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
36 changes: 31 additions & 5 deletions .github/scripts/run-agent-task/runner-workspace-publisher.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,34 @@
function string(value) { return typeof value === "string" ? value.trim() : "" }
function record(value) { return value && typeof value === "object" && !Array.isArray(value) ? value : {} }

// The publication head branch. An explicit `branch` (or `head_branch`) is the
// caller's branch and is used exactly as given. Otherwise the head is
// `branch_prefix` + run id, joined with a `-` unless the prefix already ends in a
// separator (`/`, `-`, `_`, `.`), so a prefix such as `docs/upkeep` yields
// `docs/upkeep-run-1` rather than `docs/upkeeprun-1`. The base-SHA fresh-branch
// rule appends `-<base-sha-12>` to whichever head this returns.
export function publicationHeadBranch(config, request = {}) {
const explicit = string(config.branch) || string(config.head_branch)
if (explicit) return { prefix: "", head: explicit }
const prefix = string(config.branch_prefix || "wp-codebox/agent-task/")
const runId = string(config.run_id || request.workload?.id || "agent-task").replace(/[^A-Za-z0-9._/-]+/g, "-")
const separator = !prefix || /[/_.-]$/.test(prefix) ? "" : "-"
return { prefix, head: `${prefix}${separator}${runId}` }
}

// Pull request body: the caller's body plus a reviewer-facing list of the
// files this publication changed.
export function publicationPullBody(config, publicationFiles) {
const callerBody = string(config.body)
const files = (Array.isArray(publicationFiles) ? publicationFiles : [])
.map((file) => ({ path: string(file?.path), deleted: Boolean(file?.deleted) }))
.filter((file) => file.path)
if (!files.length) return callerBody
const shown = files.slice(0, 100).map((file) => `- \`${file.path}\`${file.deleted ? " (deleted)" : ""}`)
if (files.length > shown.length) shown.push(`- …and ${files.length - shown.length} more`)
return [callerBody, `### Changed files (${files.length})\n\n${shown.join("\n")}`].filter(Boolean).join("\n\n")
}

export async function publishRunnerWorkspace({ request, changedFiles, publicationFiles, workspace, token, fetchImpl = fetch }) {
const targetRepo = string(request.target_repo).toLowerCase()
const config = record(request.runner_workspace)
Expand All @@ -11,17 +39,15 @@ export async function publishRunnerWorkspace({ request, changedFiles, publicatio
if (!targetRepo || targetRepo !== configuredRepo || !allowed.includes(targetRepo)) throw new Error("Runner workspace publication repository is not authorized.")
let base = string(config.base) || string(config.base_branch)
const hasConfiguredBase = Boolean(base)
const prefix = string(config.branch_prefix || "wp-codebox/agent-task/")
const runId = string(config.run_id || request.workload?.id || "agent-task").replace(/[^A-Za-z0-9._/-]+/g, "-")
const configuredHead = `${prefix}${runId}`
const { prefix, head: configuredHead } = publicationHeadBranch(config, request)
const api = async (method, path, body) => {
const response = await fetchImpl(`https://api.github.com/repos/${targetRepo}${path}`, { method, headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${token}`, "X-GitHub-Api-Version": "2022-11-28", ...(body ? { "Content-Type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) })
const payload = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(`GitHub API ${method} ${path} failed with ${response.status}.`)
return payload
}
if (!base) base = string((await api("GET", "")).default_branch)
if (!/^[A-Za-z0-9._/-]+$/.test(prefix) || !configuredHead.startsWith(prefix) || configuredHead.includes("..") || !/^[A-Za-z0-9._/-]+$/.test(base)) {
if (!/^[A-Za-z0-9._/-]*$/.test(prefix) || !/^[A-Za-z0-9._/-]+$/.test(configuredHead) || !configuredHead.startsWith(prefix) || configuredHead.includes("..") || configuredHead.startsWith("/") || configuredHead.endsWith("/") || !/^[A-Za-z0-9._/-]+$/.test(base)) {
throw new Error(hasConfiguredBase ? "Runner workspace branch configuration is invalid." : "Runner workspace branch configuration is invalid: repository metadata must provide a valid default branch when base is omitted.")
}
const refPath = (name) => `/git/ref/heads/${name.split("/").map(encodeURIComponent).join("/")}`
Expand Down Expand Up @@ -86,7 +112,7 @@ export async function publishRunnerWorkspace({ request, changedFiles, publicatio
const commit = await api("POST", "/git/commits", { message: string(config.commit_message || request.workload?.label || "Apply agent task changes"), tree: string(nextTree.sha), parents: [parent] })
if (pull) await api("PATCH", `/git/refs/heads/${head.split("/").map(encodeURIComponent).join("/")}`, { sha: string(commit.sha), force: false })
else await api("POST", "/git/refs", { ref: `refs/heads/${head}`, sha: string(commit.sha) })
pull ||= await api("POST", "/pulls", { title: string(config.title || request.workload?.label || "Apply agent task changes"), head, base, body: string(config.body || "") })
pull ||= await api("POST", "/pulls", { title: string(config.title || request.workload?.label || "Apply agent task changes"), head, base, body: publicationPullBody(config, captured) })
if (!isExactPull(pull, head) || !/^https:\/\/github\.com\//.test(string(pull.html_url))) throw new Error("GitHub publication response did not match the requested repository and branches.")
return { schema: "wp-codebox/runner-workspace-publication-result/v1", success: true, status: "published", backend: "github-rest", branch: { base, base_sha: baseSha, head, name: head }, commit: { sha: string(commit.sha), parent_sha: parent }, pull_request: { number: pull.number, url: pull.html_url, reused: reusedPull, opened: !reusedPull } }
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ a recipe. They cover:
| `recipe-run` | Repeatable JSON recipes: mounts, workspaces, seeds, steps, assertions, artifacts. `--dry-run` resolves the plan without booting. | [Recipe contract](docs/recipe-contract.md) |
| `bench` and `artifacts bench-*` | Benchmark matrices and baseline-versus-candidate comparison. | [Benchmark contract](docs/benchmark-contract.md) |
| `agent-task-run` | One natural-language task through a mounted agent stack, returning a patch and preview. | [Agent runtime contract](docs/agent-runtime-contract.md) |
| `run-agent-task.yml` | Reusable GitHub Actions workflow: run an agent package against a repository and publish a pull request. Branch, title, and body rules are under *Publication branch, title, and body*; the agent's git-less `workspace_git_status` / `workspace_git_diff` tools are described in the sandbox workspace contract. | [Agent task reusable workflow](docs/agent-task-reusable-workflow.md), [Sandbox workspace contract](docs/sandbox-workspace-contract.md#workspace-status-and-diff-tools) |
| `run-wordpress-workload`, `run-fuzz-suite`, `adversarial` | Workloads, fuzz suites, and adversarial campaigns with replay. | [Adversarial runtime](docs/adversarial-runtime.md) |
| `artifacts`, `runs` | Verify, inspect, and recover bundles; poll or cancel recipe runs. | [Artifact bundles](docs/artifact-bundles.md) |
| TypeScript packages | Embed the runtime: `wp-codebox-workspace/core`, `/playground`, `/cli`, and friends. | [Public API contract](docs/public-api-contract.md) |
Expand Down
24 changes: 24 additions & 0 deletions docs/agent-task-reusable-workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,30 @@ Publication results record the effective head branch and resolved base SHA. An
existing branch is extended only for an exact open pull request that descends
from that base; otherwise publication starts a base-SHA-suffixed fresh branch.

### Publication branch, title, and body

`runner_workspace` controls what the published pull request looks like:

- `branch` (alias `head_branch`): the head branch, used **exactly as given**.
The workload id is never appended to it.
- `branch_prefix`: used only when `branch` is absent. The head is
`branch_prefix` + run id (`run_id`, else `workload_id`). The two are joined
with `-` unless the prefix already ends in `/`, `-`, `_`, or `.`. The default
prefix is `wp-codebox/agent-task/`.
- Fresh-branch rule: if the head branch exists but has no exact open pull request
for the base, publication uses `<head>-<base-sha-12>` instead. The suffix is
added once, to whichever head the rules above produced.
- `title`: pull request title. Defaults to `workload_label`. Set it; generic
labels such as "Run Docs Agent" make poor PR titles.
- `commit_message`: commit message. Defaults to `workload_label`.
- `body`: pull request body. WP Codebox appends a `### Changed files (N)` list
of the published paths, marking deletions, when it opens the pull request.

Before v0.33.7 the head was always `branch_prefix` + workload id with no
separator, so a caller passing its branch as the prefix got names such as
`docs-agent/upkeepdocs-agent-user-maintenance`
([#2591](https://github.com/Automattic/wp-codebox/issues/2591)).

## Outputs

- `job_status`: normalized terminal status.
Expand Down
29 changes: 29 additions & 0 deletions docs/sandbox-workspace-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,32 @@ the mounted workspace. Read-only source-host abilities may be exposed for contex
Push, deploy, worktree lifecycle, source sync, PR creation, issue mutation, comments,
merge, cleanup, and apply-back operations stay parent-only. The sandbox produces
artifacts; the parent site decides whether and how to apply them.

## Workspace status and diff tools

The seeded runner workspace is a filtered snapshot: `.git/**` is excluded (see
[Runner Workspace Seed Policy](runner-workspace-seed-policy.md)), and the sandbox
tools never invoke `git` or a shell. `workspace_git_status` and
`workspace_git_diff` therefore compare the workspace against its **seed
baseline**, not a git `HEAD`:

- Before a mutation tool (`workspace_write`, `workspace_edit`,
`workspace_apply_patch`) first touches a path, the executor records that path's
seed content (or that it did not exist). Mutation tools are the only way an
agent can change the sandbox, so this overlay is a complete record of the run's
changes. `reset_mutation_ledger()` clears it at the start of each run.
- When the host supplies a filesystem baseline (`workspace_baseline_root` in the
executor context), that full tree is used instead.
- `workspace_git_status` returns `files` (sorted paths), `changes`
(`{path, status}` with `added`, `modified`, or `deleted`), a `summary` count,
and `baseline: "seed"` or `"filesystem"`. A file rewritten with identical
content is clean.
- `workspace_git_diff` returns a unified diff with git-style `a/`/`b/` headers,
`/dev/null` for adds and deletes, and 3-line context hunks, so it applies with
`workspace_apply_patch`. An optional `path` limits it to one file. Output is
capped at 256 KB; files past the cap or with binary content are listed in
`skipped` and `truncated` is set.

Before v0.33.7 neither tool had a baseline in runtime-package runs, so every
call failed with `tool_call_failed` (`baseline_unavailable`)
([#2591](https://github.com/Automattic/wp-codebox/issues/2591)).
Loading
Loading