Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/scripts/run-agent-task/build-codebox-task-request.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { mkdirSync, writeFileSync, appendFileSync } from "node:fs"
import { normalizeExternalPackageSource, normalizeRuntimeSources, parseExternalPackageSourcePolicy } from "./materialize-external-native-package.mjs"
import { parseProductSiteInput } from "./product-site-request.mjs"

function parseJson(name, fallback, expected) {
const raw = process.env[name]
Expand Down Expand Up @@ -127,6 +128,8 @@ const request = {
run_agent: booleanEnv("RUN_AGENT"),
dry_run: booleanEnv("DRY_RUN"),
}
const productSite = parseProductSiteInput(process.env.PRODUCT_SITE)
if (productSite) request.product_site = productSite

if (request.access.allowed_repos.some((repository) => typeof repository !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository))) {
throw new Error("ALLOWED_REPOS must be a JSON array of OWNER/REPO values.")
Expand Down
6 changes: 6 additions & 0 deletions .github/scripts/run-agent-task/execute-native-agent-task.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { spawn } from "node:child_process"
import { createHash } from "node:crypto"
import { canonicalExternalNativeAgentIdentity, materializeExternalNativePackage, materializeRuntimeSources, normalizeExternalPackageSource, normalizeRuntimeSources, parseExternalPackageSourcePolicy, sha256BytesV1, validateRuntimeSourceModel } from "./materialize-external-native-package.mjs"
import { readNativeResult } from "./native-result-file.mjs"
import { normalizeProductSiteRequest } from "./product-site-request.mjs"
import { assertNoRuntimeSourcePaths, sanitizeArtifactUploadText, sanitizeRuntimeSourceJson, sanitizeRuntimeSourceText, sanitizeRuntimeSourceValue } from "./runtime-source-sanitizer.mjs"
import { publishRunnerWorkspace } from "./runner-workspace-publisher.mjs"
import { createRunnerWorkspaceSeedSnapshot, RUNNER_WORKSPACE_SEED_EXCLUDES } from "./runner-workspace-seed-snapshot.mjs"
Expand Down Expand Up @@ -739,9 +740,12 @@ const runtimeInputPath = join(workspace, ".codebox", "native-agent-task-input.js
const resultPath = join(workspace, ".codebox", "agent-task-workflow-result.json")
const controlledCodeboxPath = resolve(requestPath, "..")
const nativeResultPath = join(controlledCodeboxPath, "native-agent-task-result.json")
const productSite = normalizeProductSiteRequest(request.product_site)
const runnerWorkspaceTools = [
"workspace_read", "workspace_ls", "workspace_grep", "workspace_write", "workspace_edit", "workspace_apply_patch",
"workspace_show", "workspace_git_status", "workspace_git_diff",
// Read-only product page viewer; only declared when product_site is set.
...(productSite ? ["product_page_view"] : []),
]

function runtimeMetadataForExecutionLocation(executionLocation) {
Expand Down Expand Up @@ -836,6 +840,8 @@ const taskInput = {
metadata: { workload: request.workload, ...(materializedPackage ? { imported_agent: materializedPackage.identity } : {}), runtime_sources: materializedRuntimeSources?.descriptors ?? [], ...(runnerWorkspaceSeedSnapshot ? { runner_workspace_seed: runnerWorkspaceSeedSnapshot.provenance } : {}) },
},
},
// The CLI boots this site before the agent turn and tears it down after.
...(productSite ? { product_site: productSite } : {}),
// agent-task-run unwraps task_input before building the recipe. The
// external snapshot prevents the recipe from ever mounting the checkout.
workspaces: runnerWorkspaceSeedSnapshot ? [{ target: "/workspace", mode: "readwrite", sourceMode: "repo-backed", seed: { type: "directory", source: runnerWorkspaceSeedSnapshot.source, excludePaths: RUNNER_WORKSPACE_SEED_EXCLUDES } }] : [],
Expand Down
39 changes: 39 additions & 0 deletions .github/scripts/run-agent-task/prepare-agent-task-upload.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,44 @@ async function stageTextFile(source, destination, options = {}) {
return true
}

const PRODUCT_SITE_SCREENSHOT_DIRECTORY = "product-site/screenshots"
const PRODUCT_SITE_SCREENSHOT_NAME = /^page-\d{3}\.png$/
const PRODUCT_SITE_MAX_SCREENSHOTS = 50
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])

// product_site screenshots are the only binary upload: bounded, non-symlink
// PNG files with the exact names the page viewer writes, copied byte-for-byte.
async function stageProductSiteScreenshots(request) {
const staged = new Set()
if (!record(request.product_site).start_url) return staged
const directory = join(artifactsPath, PRODUCT_SITE_SCREENSHOT_DIRECTORY)
const directoryMetadata = await lstat(directory).catch(() => null)
if (!directoryMetadata?.isDirectory()) return staged
const names = (await readdir(directory, { withFileTypes: true }).catch(() => []))
.filter((entry) => entry.isFile() && PRODUCT_SITE_SCREENSHOT_NAME.test(entry.name))
.map((entry) => entry.name)
.sort()
.slice(0, PRODUCT_SITE_MAX_SCREENSHOTS)
for (const name of names) {
const path = `${PRODUCT_SITE_SCREENSHOT_DIRECTORY}/${name}`
const source = join(directory, name)
if (sourceCategory(path, source)) continue
const metadata = await lstat(source).catch(() => null)
if (!metadata?.isFile() || metadata.size > MAX_UPLOAD_FILE_BYTES) continue
const handle = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => null)
if (!handle) continue
const openedMetadata = await handle.stat()
const bytes = openedMetadata.isFile() && openedMetadata.size <= MAX_UPLOAD_FILE_BYTES ? await readBoundedFile(handle, MAX_UPLOAD_FILE_BYTES) : null
await handle.close()
if (!bytes || bytes.length > MAX_UPLOAD_FILE_BYTES || !bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) continue
const destination = join(uploadPath, ".codebox", "agent-task-artifacts", path)
await mkdir(resolve(destination, ".."), { recursive: true })
await writeFile(destination, bytes)
staged.add(path)
}
return staged
}

function canonicalTranscript(result) {
const descriptor = record(record(result).reviewer_evidence).transcript
if (descriptor === undefined) return undefined
Expand Down Expand Up @@ -558,6 +596,7 @@ for (const [path, reference] of workflowOutputArtifactsToStage) {
}
await stageTextFile(source, join(uploadPath, ".codebox", "agent-task-artifacts", path))
}
for (const path of await stageProductSiteScreenshots(request)) declaredPaths.add(path)
const transcript = await stageCanonicalTranscript(result)
if (transcript?.provenance?.source_sha256) {
const stagedResultPath = join(uploadPath, ".codebox", "agent-task-workflow-result.json")
Expand Down
66 changes: 66 additions & 0 deletions .github/scripts/run-agent-task/product-site-request.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Validates the optional `product_site` workflow input. An empty value keeps the
// run unchanged; a declared site is booted read-only beside the agent runtime.
const MAX_PRODUCT_SITE_BYTES = 64 * 1024
const ROLE_PATTERN = /^[a-z0-9_-]{1,64}$/
const SLUG_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
const ALLOWED_FIELDS = new Set(["blueprint", "plugins", "start_url", "login_role", "wp"])

function isRecord(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value)
}

function workspaceRelativePath(value, field) {
if (typeof value !== "string" || !value.trim()) throw new Error(`${field} must be a non-empty workspace-relative path.`)
const path = value.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "")
if (!path || path.startsWith("/") || /^[A-Za-z]:/.test(path) || path.split("/").some((part) => !part || part === "." || part === "..")) {
throw new Error(`${field} must be a workspace-relative path without traversal.`)
}
return path
}

function siteRelativePath(value, field) {
if (typeof value !== "string") throw new Error(`${field} must be a string.`)
const path = value.trim() || "/"
if (path.length > 2048 || /[\u0000-\u001f\u007f\\]/.test(path) || /^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) {
throw new Error(`${field} must be a site-relative path such as /about/.`)
}
return path.startsWith("/") ? path : `/${path}`
}

export function parseProductSiteInput(raw) {
const text = typeof raw === "string" ? raw.trim() : ""
if (!text) return undefined
if (Buffer.byteLength(text) > MAX_PRODUCT_SITE_BYTES) throw new Error("PRODUCT_SITE exceeds 64 KiB.")
return normalizeProductSiteRequest(JSON.parse(text))
}

export function normalizeProductSiteRequest(value) {
if (value === undefined || value === null) return undefined
if (!isRecord(value)) throw new Error("product_site must be a JSON object.")
if (Object.keys(value).length === 0) return undefined
const unknown = Object.keys(value).filter((key) => !ALLOWED_FIELDS.has(key))
if (unknown.length) throw new Error(`product_site has unsupported fields: ${unknown.join(", ")}.`)
if (value.blueprint !== undefined && !isRecord(value.blueprint)) throw new Error("product_site.blueprint must be a Playground blueprint object.")
if (value.plugins !== undefined && !Array.isArray(value.plugins)) throw new Error("product_site.plugins must be an array.")
const plugins = (value.plugins ?? []).map((entry, index) => {
const field = `product_site.plugins[${index}]`
if (typeof entry === "string") return workspaceRelativePath(entry, field)
if (!isRecord(entry)) throw new Error(`${field} must be a path string or {path, slug, activate}.`)
const extra = Object.keys(entry).filter((key) => !["path", "slug", "activate"].includes(key))
if (extra.length) throw new Error(`${field} has unsupported fields: ${extra.join(", ")}.`)
if (entry.slug !== undefined && (typeof entry.slug !== "string" || !SLUG_PATTERN.test(entry.slug))) throw new Error(`${field}.slug must be a plugin directory slug.`)
if (entry.activate !== undefined && typeof entry.activate !== "boolean") throw new Error(`${field}.activate must be a boolean.`)
return Object.fromEntries(Object.entries({ path: workspaceRelativePath(entry.path, `${field}.path`), slug: entry.slug, activate: entry.activate }).filter(([, item]) => item !== undefined))
})
if (value.login_role !== undefined && value.login_role !== "" && (typeof value.login_role !== "string" || !ROLE_PATTERN.test(value.login_role))) {
throw new Error("product_site.login_role must be a WordPress role slug.")
}
if (value.wp !== undefined && (typeof value.wp !== "string" || !/^[A-Za-z0-9._-]{1,32}$/.test(value.wp))) throw new Error("product_site.wp must be a WordPress version.")
return Object.fromEntries(Object.entries({
blueprint: value.blueprint ?? {},
plugins,
start_url: siteRelativePath(value.start_url ?? "/", "product_site.start_url"),
login_role: value.login_role || undefined,
wp: value.wp,
}).filter(([, item]) => item !== undefined))
}
10 changes: 10 additions & 0 deletions .github/workflows/run-agent-task.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ name: Run Agent Task (reusable)
description: JSON runner-owned workspace publication request.
type: string
default: '{}'
product_site:
description: "Optional JSON read-only product site {blueprint, plugins, start_url, login_role}. When set, the site boots before the agent turn and the agent gets the product_page_view tool; plugin paths are relative to the target workspace."
type: string
default: ""
validation_dependencies:
description: Optional validation dependency install command.
type: string
Expand Down Expand Up @@ -229,6 +233,11 @@ jobs:
working-directory: .wp-codebox-workflow
run: npm ci

- name: Install product site browser
if: inputs.product_site != '' && inputs.product_site != '{}'
working-directory: .wp-codebox-workflow
run: npx playwright install --with-deps chromium

- name: Prepare GitHub App token configuration
id: access-app-config
env:
Expand Down Expand Up @@ -308,6 +317,7 @@ jobs:
# value set under it is ignored and the script receives the runner's
# workspace path instead of this JSON config.
RUNNER_WORKSPACE_CONFIG: ${{ inputs.runner_workspace }}
PRODUCT_SITE: ${{ inputs.product_site }}
VALIDATION_DEPENDENCIES: ${{ inputs.validation_dependencies }}
VERIFICATION_COMMANDS: ${{ inputs.verification_commands }}
DRIFT_CHECKS: ${{ inputs.drift_checks }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"max_turns": { "required": false, "type": "number", "default": 12 },
"time_budget_ms": { "required": false, "type": "number", "default": 600000 },
"output_projections": { "required": false, "type": "string", "default": "{}" },
"product_site": { "required": false, "type": "string", "default": "" },
"transcript_artifact_name": { "required": false, "type": "string", "default": "agent-task-transcript" },
"replay_bundle_artifact_name": { "required": false, "type": "string", "default": "" },
"expected_artifacts": { "required": false, "type": "string", "default": "[]" },
Expand Down
3 changes: 2 additions & 1 deletion docs/agent-task-reusable-workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ This release-coherence contract fixes [#1759](https://github.com/Automattic/wp-c
- `target_repo`: `OWNER/REPO` target repository.
- `prompt`, `writable_paths`, provider/model, `max_turns`, `time_budget_ms`, callback data, and artifact declarations: native task inputs.
- `runner_workspace`: JSON runner-workspace publication request owned by the package.
- `product_site`: optional JSON read-only product site, `{ "blueprint": {...}, "plugins": ["path/to/plugin"], "start_url": "/", "login_role": "subscriber" }`. Empty (the default) leaves the run unchanged. When set, the workflow installs Playwright Chromium, the runner boots the site from the Playground `blueprint` with each plugin directory (relative to the target workspace, or `{path, slug, activate}`) mounted read-only and activated, and tears it down after the agent turn. The agent gets one extra tool, `product_page_view({ path })`, which loads a site-relative path in Chromium and returns the title, bounded visible text, heading outline, links/buttons/form labels, and the artifact path of a PNG screenshot staged under `product-site/screenshots/`. Navigation is GET-only: non-GET requests, form submissions, and requests to other origins are blocked, and the only credential is an optional fixture user with the declared `login_role`.
- `validation_dependencies`: optional shell command that installs validation dependencies in the target workspace.
- `verification_commands` and `drift_checks`: JSON arrays of non-empty command strings or `{command, description}` objects. Every entry runs and must pass. An object may declare one output as `artifact: {name, type, path}`. All three artifact fields are required, `path` is relative to `.codebox/agent-task-artifacts`, and the exact name/type pair must also be an output in `artifact_declarations`. After an exit-zero command, the workflow accepts only an existing regular UTF-8 file of at most 4 MiB without path traversal or symlinks. It adds a canonical `wp-codebox/typed-artifact/v1` reference to that verification record so declared-artifact upload staging collects the file. Artifact validation fails that verification before publication; failed commands never accept an artifact. Strings and command/description-only objects retain their existing behavior.
- `success_requires_pr`: require a successful, published runner-workspace pull request for `target_repo`.
Expand Down Expand Up @@ -246,6 +247,6 @@ workflow itself cannot inspect the caller's `uses:` declaration at runtime.

## Upload safety limits

The reusable workflow stages every uploaded file through a fail-closed policy. Only regular UTF-8 files of 4 MiB or less are uploaded, after configured secret values are redacted. Symlinks, special files, binary files, and files larger than 4 MiB are excluded from the upload staging directory. This applies to task artifacts and workflow request, input, and result files.
The reusable workflow stages every uploaded file through a fail-closed policy. Only regular UTF-8 files of 4 MiB or less are uploaded, after configured secret values are redacted. The one binary exception is `product_site` screenshots: regular, non-symlink PNG files named `product-site/screenshots/page-NNN.png` of 4 MiB or less are copied byte-for-byte after their PNG signature is verified. Symlinks, special files, binary files, and files larger than 4 MiB are excluded from the upload staging directory. This applies to task artifacts and workflow request, input, and result files.

Native task execution, validation-dependency installation, verification, drift checks, and GitHub pull-request validation retain at most 32 KiB from each stdout and stderr stream while continuing to drain both streams. Command results expose `stdout_truncated` and `stderr_truncated` when retained output is incomplete. Native `agent-task-run` structured output is instead read from a controlled `.codebox/native-agent-task-result.json` file outside the agent-writable target checkout. The executor accepts only a regular, non-symlink JSON file up to 1 MiB with the required result schemas, rejects configured secret values, redacts the accepted record before persistence, and removes the transient native result file after reading it.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
"test:runtime-package-boundaries": "node --test tests/derive-cloudflare-core-contract-atomic.test.mjs && node tests/runtime-package-boundaries.test.mjs",
"test:agent-task-contracts": "tsx tests/agent-task-contracts.test.ts && tsx tests/agent-task-canonical-evidence.test.ts && npm run test:agent-task-workflow-interface && npm run test:runtime-sources-materialization && tsx tests/agent-task-reusable-workflow.test.ts",
"test:agent-task-workflow-interface": "tsx tests/run-agent-task-reusable-workflow-interface.test.ts",
"test:product-site": "tsx tests/product-site-workflow.test.ts && php scripts/php-product-site-executor-smoke.php && tsx --test tests/product-site-page-view.browser.test.ts",
"test:agent-task-runtime-package-staging": "tsx tests/agent-task-runtime-package-staging.test.ts",
"test:external-native-package-materialization": "tsx tests/external-native-package-materialization.test.ts",
"test:runtime-sources-materialization": "tsx tests/runtime-sources-materialization.test.ts",
Expand Down
Loading
Loading