Skip to content

Commit d0ce90f

Browse files
authored
fix(agent-task): use the caller's publication branch as given and make workspace git status/diff work (#2592)
Publication branch: the head was always `branch_prefix` + workload id with no separator, so callers passing their branch as the prefix got doubled names such as `docs-agent/extrachill-shop-user-docsdocs-agent-user-maintenance`. An explicit `runner_workspace.branch` (or `head_branch`) is now used exactly; otherwise the prefix and run id are joined with `-` unless the prefix already ends in a separator. The fresh-branch rule still appends `-<base-sha-12>` once. PR body: WP Codebox appends a "Changed files" list to the caller body. Git tools: workspace_git_status/workspace_git_diff required a host-supplied `workspace_baseline_root` that no production caller provided (the seeded snapshot also excludes `.git`), so every call failed with baseline_unavailable -> tool_call_failed. The sandbox executor now records each path's seed content before its first mutation and compares against that; the diff is a real context-hunk unified diff that round-trips through workspace_apply_patch. Closes #2591 AI assistance: Extra Chill Bot (Claude), via a Roadie subagent.
1 parent 4875fb1 commit d0ce90f

7 files changed

Lines changed: 523 additions & 38 deletions

File tree

‎.github/scripts/run-agent-task/runner-workspace-publisher.mjs‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,34 @@
22
function string(value) { return typeof value === "string" ? value.trim() : "" }
33
function record(value) { return value && typeof value === "object" && !Array.isArray(value) ? value : {} }
44

5+
// The publication head branch. An explicit `branch` (or `head_branch`) is the
6+
// caller's branch and is used exactly as given. Otherwise the head is
7+
// `branch_prefix` + run id, joined with a `-` unless the prefix already ends in a
8+
// separator (`/`, `-`, `_`, `.`), so a prefix such as `docs/upkeep` yields
9+
// `docs/upkeep-run-1` rather than `docs/upkeeprun-1`. The base-SHA fresh-branch
10+
// rule appends `-<base-sha-12>` to whichever head this returns.
11+
export function publicationHeadBranch(config, request = {}) {
12+
const explicit = string(config.branch) || string(config.head_branch)
13+
if (explicit) return { prefix: "", head: explicit }
14+
const prefix = string(config.branch_prefix || "wp-codebox/agent-task/")
15+
const runId = string(config.run_id || request.workload?.id || "agent-task").replace(/[^A-Za-z0-9._/-]+/g, "-")
16+
const separator = !prefix || /[/_.-]$/.test(prefix) ? "" : "-"
17+
return { prefix, head: `${prefix}${separator}${runId}` }
18+
}
19+
20+
// Pull request body: the caller's body plus a reviewer-facing list of the
21+
// files this publication changed.
22+
export function publicationPullBody(config, publicationFiles) {
23+
const callerBody = string(config.body)
24+
const files = (Array.isArray(publicationFiles) ? publicationFiles : [])
25+
.map((file) => ({ path: string(file?.path), deleted: Boolean(file?.deleted) }))
26+
.filter((file) => file.path)
27+
if (!files.length) return callerBody
28+
const shown = files.slice(0, 100).map((file) => `- \`${file.path}\`${file.deleted ? " (deleted)" : ""}`)
29+
if (files.length > shown.length) shown.push(`- …and ${files.length - shown.length} more`)
30+
return [callerBody, `### Changed files (${files.length})\n\n${shown.join("\n")}`].filter(Boolean).join("\n\n")
31+
}
32+
533
export async function publishRunnerWorkspace({ request, changedFiles, publicationFiles, workspace, token, fetchImpl = fetch }) {
634
const targetRepo = string(request.target_repo).toLowerCase()
735
const config = record(request.runner_workspace)
@@ -11,17 +39,15 @@ export async function publishRunnerWorkspace({ request, changedFiles, publicatio
1139
if (!targetRepo || targetRepo !== configuredRepo || !allowed.includes(targetRepo)) throw new Error("Runner workspace publication repository is not authorized.")
1240
let base = string(config.base) || string(config.base_branch)
1341
const hasConfiguredBase = Boolean(base)
14-
const prefix = string(config.branch_prefix || "wp-codebox/agent-task/")
15-
const runId = string(config.run_id || request.workload?.id || "agent-task").replace(/[^A-Za-z0-9._/-]+/g, "-")
16-
const configuredHead = `${prefix}${runId}`
42+
const { prefix, head: configuredHead } = publicationHeadBranch(config, request)
1743
const api = async (method, path, body) => {
1844
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) } : {}) })
1945
const payload = await response.json().catch(() => ({}))
2046
if (!response.ok) throw new Error(`GitHub API ${method} ${path} failed with ${response.status}.`)
2147
return payload
2248
}
2349
if (!base) base = string((await api("GET", "")).default_branch)
24-
if (!/^[A-Za-z0-9._/-]+$/.test(prefix) || !configuredHead.startsWith(prefix) || configuredHead.includes("..") || !/^[A-Za-z0-9._/-]+$/.test(base)) {
50+
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)) {
2551
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.")
2652
}
2753
const refPath = (name) => `/git/ref/heads/${name.split("/").map(encodeURIComponent).join("/")}`
@@ -86,7 +112,7 @@ export async function publishRunnerWorkspace({ request, changedFiles, publicatio
86112
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] })
87113
if (pull) await api("PATCH", `/git/refs/heads/${head.split("/").map(encodeURIComponent).join("/")}`, { sha: string(commit.sha), force: false })
88114
else await api("POST", "/git/refs", { ref: `refs/heads/${head}`, sha: string(commit.sha) })
89-
pull ||= await api("POST", "/pulls", { title: string(config.title || request.workload?.label || "Apply agent task changes"), head, base, body: string(config.body || "") })
115+
pull ||= await api("POST", "/pulls", { title: string(config.title || request.workload?.label || "Apply agent task changes"), head, base, body: publicationPullBody(config, captured) })
90116
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.")
91117
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 } }
92118
}

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ a recipe. They cover:
106106
| `recipe-run` | Repeatable JSON recipes: mounts, workspaces, seeds, steps, assertions, artifacts. `--dry-run` resolves the plan without booting. | [Recipe contract](docs/recipe-contract.md) |
107107
| `bench` and `artifacts bench-*` | Benchmark matrices and baseline-versus-candidate comparison. | [Benchmark contract](docs/benchmark-contract.md) |
108108
| `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) |
109+
| `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) |
109110
| `run-wordpress-workload`, `run-fuzz-suite`, `adversarial` | Workloads, fuzz suites, and adversarial campaigns with replay. | [Adversarial runtime](docs/adversarial-runtime.md) |
110111
| `artifacts`, `runs` | Verify, inspect, and recover bundles; poll or cancel recipe runs. | [Artifact bundles](docs/artifact-bundles.md) |
111112
| TypeScript packages | Embed the runtime: `wp-codebox-workspace/core`, `/playground`, `/cli`, and friends. | [Public API contract](docs/public-api-contract.md) |

‎docs/agent-task-reusable-workflow.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,30 @@ Publication results record the effective head branch and resolved base SHA. An
135135
existing branch is extended only for an exact open pull request that descends
136136
from that base; otherwise publication starts a base-SHA-suffixed fresh branch.
137137

138+
### Publication branch, title, and body
139+
140+
`runner_workspace` controls what the published pull request looks like:
141+
142+
- `branch` (alias `head_branch`): the head branch, used **exactly as given**.
143+
The workload id is never appended to it.
144+
- `branch_prefix`: used only when `branch` is absent. The head is
145+
`branch_prefix` + run id (`run_id`, else `workload_id`). The two are joined
146+
with `-` unless the prefix already ends in `/`, `-`, `_`, or `.`. The default
147+
prefix is `wp-codebox/agent-task/`.
148+
- Fresh-branch rule: if the head branch exists but has no exact open pull request
149+
for the base, publication uses `<head>-<base-sha-12>` instead. The suffix is
150+
added once, to whichever head the rules above produced.
151+
- `title`: pull request title. Defaults to `workload_label`. Set it; generic
152+
labels such as "Run Docs Agent" make poor PR titles.
153+
- `commit_message`: commit message. Defaults to `workload_label`.
154+
- `body`: pull request body. WP Codebox appends a `### Changed files (N)` list
155+
of the published paths, marking deletions, when it opens the pull request.
156+
157+
Before v0.33.7 the head was always `branch_prefix` + workload id with no
158+
separator, so a caller passing its branch as the prefix got names such as
159+
`docs-agent/upkeepdocs-agent-user-maintenance`
160+
([#2591](https://github.com/Automattic/wp-codebox/issues/2591)).
161+
138162
## Outputs
139163

140164
- `job_status`: normalized terminal status.

‎docs/sandbox-workspace-contract.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,32 @@ the mounted workspace. Read-only source-host abilities may be exposed for contex
2929
Push, deploy, worktree lifecycle, source sync, PR creation, issue mutation, comments,
3030
merge, cleanup, and apply-back operations stay parent-only. The sandbox produces
3131
artifacts; the parent site decides whether and how to apply them.
32+
33+
## Workspace status and diff tools
34+
35+
The seeded runner workspace is a filtered snapshot: `.git/**` is excluded (see
36+
[Runner Workspace Seed Policy](runner-workspace-seed-policy.md)), and the sandbox
37+
tools never invoke `git` or a shell. `workspace_git_status` and
38+
`workspace_git_diff` therefore compare the workspace against its **seed
39+
baseline**, not a git `HEAD`:
40+
41+
- Before a mutation tool (`workspace_write`, `workspace_edit`,
42+
`workspace_apply_patch`) first touches a path, the executor records that path's
43+
seed content (or that it did not exist). Mutation tools are the only way an
44+
agent can change the sandbox, so this overlay is a complete record of the run's
45+
changes. `reset_mutation_ledger()` clears it at the start of each run.
46+
- When the host supplies a filesystem baseline (`workspace_baseline_root` in the
47+
executor context), that full tree is used instead.
48+
- `workspace_git_status` returns `files` (sorted paths), `changes`
49+
(`{path, status}` with `added`, `modified`, or `deleted`), a `summary` count,
50+
and `baseline: "seed"` or `"filesystem"`. A file rewritten with identical
51+
content is clean.
52+
- `workspace_git_diff` returns a unified diff with git-style `a/`/`b/` headers,
53+
`/dev/null` for adds and deletes, and 3-line context hunks, so it applies with
54+
`workspace_apply_patch`. An optional `path` limits it to one file. Output is
55+
capped at 256 KB; files past the cap or with binary content are listed in
56+
`skipped` and `truncated` is set.
57+
58+
Before v0.33.7 neither tool had a baseline in runtime-package runs, so every
59+
call failed with `tool_call_failed` (`baseline_unavailable`)
60+
([#2591](https://github.com/Automattic/wp-codebox/issues/2591)).

0 commit comments

Comments
 (0)