From c0371f2acabb1fba2ed975190e7b8cf3f2d0f175 Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Sun, 15 Nov 2026 17:29:14 +0000 Subject: [PATCH] fix(agent-task): use the caller's publication branch as given and make workspace git status/diff work 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 `-` 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. --- .../runner-workspace-publisher.mjs | 36 +- README.md | 1 + docs/agent-task-reusable-workflow.md | 24 ++ docs/sandbox-workspace-contract.md | 29 ++ ...-wp-codebox-sandbox-workspace-executor.php | 354 ++++++++++++++++-- .../php-sandbox-workspace-executor-smoke.php | 80 ++++ tests/runner-workspace-publisher.test.mjs | 37 +- 7 files changed, 523 insertions(+), 38 deletions(-) diff --git a/.github/scripts/run-agent-task/runner-workspace-publisher.mjs b/.github/scripts/run-agent-task/runner-workspace-publisher.mjs index 5dea594d5..af4467fc0 100644 --- a/.github/scripts/run-agent-task/runner-workspace-publisher.mjs +++ b/.github/scripts/run-agent-task/runner-workspace-publisher.mjs @@ -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 `-` 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) @@ -11,9 +39,7 @@ 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(() => ({})) @@ -21,7 +47,7 @@ export async function publishRunnerWorkspace({ request, changedFiles, publicatio 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("/")}` @@ -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 } } } diff --git a/README.md b/README.md index 03041d037..e64366ded 100644 --- a/README.md +++ b/README.md @@ -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) | diff --git a/docs/agent-task-reusable-workflow.md b/docs/agent-task-reusable-workflow.md index a9227a654..874fec79a 100644 --- a/docs/agent-task-reusable-workflow.md +++ b/docs/agent-task-reusable-workflow.md @@ -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 `-` 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. diff --git a/docs/sandbox-workspace-contract.md b/docs/sandbox-workspace-contract.md index 689f7de33..429da044d 100644 --- a/docs/sandbox-workspace-contract.md +++ b/docs/sandbox-workspace-contract.md @@ -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)). diff --git a/packages/wordpress-plugin/src/class-wp-codebox-sandbox-workspace-executor.php b/packages/wordpress-plugin/src/class-wp-codebox-sandbox-workspace-executor.php index afe167158..cba5b1f0c 100644 --- a/packages/wordpress-plugin/src/class-wp-codebox-sandbox-workspace-executor.php +++ b/packages/wordpress-plugin/src/class-wp-codebox-sandbox-workspace-executor.php @@ -37,6 +37,10 @@ final class WP_Codebox_Sandbox_Workspace_Executor { private const MUTATION_TOOLS = array( 'workspace_write', 'workspace_edit', 'workspace_apply_patch' ); private const MAX_MUTATION_LEDGER_ENTRIES = 64; private const MAX_MUTATION_LEDGER_PATHS = 32; + private const MAX_SEED_PREIMAGES = 512; + private const MAX_DIFF_BYTES = 262144; // 256 KB diff output cap. + private const MAX_DIFF_LCS_CELLS = 4000000; // Line-diff work bound before whole-file fallback. + private const DIFF_CONTEXT_LINES = 3; /** * Content-free record of workspace mutation attempts for the current run. @@ -49,6 +53,20 @@ final class WP_Codebox_Sandbox_Workspace_Executor { private static array $mutation_ledger = array(); private static int $mutation_ledger_dropped = 0; + /** + * Seed pre-images for every path a mutation tool touched this run. + * + * Keyed by workspace-relative path; the value is the file content the path + * held before its first mutation, or null when it did not exist. The seeded + * sandbox snapshot deliberately excludes `.git`, so workspace_git_status and + * workspace_git_diff compare against these pre-images when the host supplies + * no filesystem baseline. Mutation tools are the only way the agent can change + * the sandbox, so the overlay is a complete record of its changes. + * + * @var array + */ + private static array $seed_preimages = array(); + /** * Tool declarations keyed by Agents API client tool name. * @@ -220,16 +238,24 @@ final class WP_Codebox_Sandbox_Workspace_Executor { 'client/workspace_git_status' => array( 'base' => 'workspace_git_status', 'capability' => 'workspace.files.read', - 'description' => 'Compare the sandbox workspace to its captured baseline without invoking git or a shell.', + 'description' => 'List files added, modified, or deleted in the sandbox workspace since the run started (seed baseline). Git-less: the sandbox has no .git directory.', 'side_effects' => array(), 'parameters' => array( 'type' => 'object', 'properties' => array() ), ), 'client/workspace_git_diff' => array( 'base' => 'workspace_git_diff', 'capability' => 'workspace.files.read', - 'description' => 'Return a bounded baseline-versus-current unified diff without invoking git or a shell.', + 'description' => 'Return a bounded unified diff of sandbox workspace changes since the run started (seed baseline). Git-less: the sandbox has no .git directory. Optionally limit to one path.', 'side_effects' => array(), - 'parameters' => array( 'type' => 'object', 'properties' => array() ), + 'parameters' => array( + 'type' => 'object', + 'properties' => array( + 'path' => array( + 'type' => 'string', + 'description' => 'Optional workspace-relative file path to limit the diff to.', + ), + ), + ), ), ); @@ -391,6 +417,7 @@ public function executeWP_Agent_Tool_Call( array $tool_call, array $tool_definit // from arbitrary ambient tool arguments. $parameters['_wp_codebox_writable_paths'] = self::writable_paths( $context ); $parameters['_wp_codebox_baseline_root'] = self::baseline_root( $context ); + self::capture_seed_preimages( (string) $config['base'], $root, $parameters ); $result = self::dispatch( $config['base'], $root, $parameters ); self::record_mutation( (string) $config['base'], $parameters, $result ); if ( is_array( $result ) && false === ( $result['success'] ?? true ) ) { @@ -416,6 +443,48 @@ public function executeWP_Agent_Tool_Call( array $tool_call, array $tool_definit public static function reset_mutation_ledger(): void { self::$mutation_ledger = array(); self::$mutation_ledger_dropped = 0; + self::$seed_preimages = array(); + } + + /** + * Record the pre-mutation content of every path a mutation tool may touch. + * + * Only the first observation of a path is kept, so the recorded content is the + * seed state. Invalid or escaping paths are skipped; the tool itself rejects them. + * + * @param array $parameters Tool parameters. + */ + private static function capture_seed_preimages( string $base, string $root, array $parameters ): void { + if ( ! in_array( $base, self::MUTATION_TOOLS, true ) ) { + return; + } + $candidates = array(); + if ( 'workspace_apply_patch' === $base ) { + $files = is_scalar( $parameters['patch'] ?? null ) ? self::parse_unified_diff( (string) $parameters['patch'] ) : array(); + foreach ( is_array( $files ) && ! isset( $files['error'] ) ? $files : array() as $file ) { + foreach ( array( 'source', 'target' ) as $key ) { + if ( is_array( $file ) && is_string( $file[ $key ] ?? null ) ) { + $candidates[] = $file[ $key ]; + } + } + } + } else { + $candidates[] = $parameters['path'] ?? ''; + } + foreach ( $candidates as $candidate ) { + $relative = self::relative_param( $candidate ); + if ( ! is_string( $relative ) || array_key_exists( $relative, self::$seed_preimages ) ) { + continue; + } + if ( count( self::$seed_preimages ) >= self::MAX_SEED_PREIMAGES ) { + return; + } + $path = self::contained_path( $root, $relative, false ); + if ( is_array( $path ) ) { + continue; + } + self::$seed_preimages[ $relative ] = is_file( $path ) ? self::read_raw( $path ) : null; + } } /** @@ -1128,45 +1197,266 @@ private static function workspace_show( string $root, array $parameters ): array ); } - /** @param array $parameters @return array */ + /** + * Changed paths since the run started. + * + * Uses the host-supplied filesystem baseline when present, otherwise the seed + * pre-images recorded before each mutation. The seeded sandbox carries no .git + * directory, so neither path invokes git or a shell. + * + * @param array $parameters Tool parameters. + * @return array + */ private static function workspace_status( string $root, array $parameters ): array { - $baseline = self::baseline_from_parameters( $parameters ); - if ( '' === $baseline ) { - return self::tool_error( 'baseline_unavailable', 'Sandbox workspace baseline is unavailable.' ); - } - $current = self::workspace_file_map( $root ); - $before = self::workspace_file_map( $baseline ); - $changed = array(); - foreach ( array_unique( array_merge( array_keys( $before ), array_keys( $current ) ) ) as $path ) { - if ( ! isset( $before[ $path ] ) || ! isset( $current[ $path ] ) || ! hash_equals( $before[ $path ], $current[ $path ] ) ) { - $changed[] = $path; - } + $changes = self::workspace_changes( $root, $parameters ); + $files = array_keys( $changes['entries'] ); + $counts = array( 'added' => 0, 'modified' => 0, 'deleted' => 0 ); + $list = array(); + foreach ( $changes['entries'] as $path => $entry ) { + ++$counts[ $entry['status'] ]; + $list[] = array( 'path' => $path, 'status' => $entry['status'] ); } - sort( $changed ); - return array( 'success' => true, 'changed' => ! empty( $changed ), 'files' => $changed, 'dirty' => count( $changed ), 'baseline' => 'filesystem' ); + return array( + 'success' => true, + 'changed' => ! empty( $files ), + 'files' => $files, + 'changes' => $list, + 'dirty' => count( $files ), + 'summary' => $counts, + 'baseline' => $changes['baseline'], + ); } /** @param array $parameters @return array */ private static function workspace_diff( string $root, array $parameters ): array { - $status = self::workspace_status( $root, $parameters ); - if ( empty( $status['success'] ) ) { - return $status; + $filter = null; + if ( isset( $parameters['path'] ) && '' !== trim( (string) $parameters['path'] ) ) { + $filter = self::relative_param( $parameters['path'] ); + if ( is_array( $filter ) ) { + return $filter; + } + } + $changes = self::workspace_changes( $root, $parameters ); + $patch = ''; + $files = array(); + $skipped = array(); + $truncated = false; + foreach ( $changes['entries'] as $relative => $entry ) { + if ( null !== $filter && $relative !== $filter ) { + continue; + } + $files[] = $relative; + $before = $entry['before']; + $after = $entry['after']; + if ( self::looks_binary( (string) $before ) || self::looks_binary( (string) $after ) ) { + $skipped[] = array( 'path' => $relative, 'reason' => 'binary' ); + continue; + } + $file_patch = self::unified_diff( $relative, $before, $after ); + if ( strlen( $patch ) + strlen( $file_patch ) > self::MAX_DIFF_BYTES ) { + $truncated = true; + $skipped[] = array( 'path' => $relative, 'reason' => 'diff_size_limit' ); + continue; + } + $patch .= $file_patch; } + return array( + 'success' => true, + 'changed' => ! empty( $files ), + 'files' => $files, + 'diff' => $patch, + 'truncated' => $truncated, + 'skipped' => $skipped, + 'baseline' => $changes['baseline'], + ); + } + + /** + * Resolve changed entries with their before/after content. + * + * @param array $parameters Tool parameters. + * @return array{baseline:string,entries:array} + */ + private static function workspace_changes( string $root, array $parameters ): array { + $entries = array(); $baseline = self::baseline_from_parameters( $parameters ); - $patch = ''; - foreach ( $status['files'] as $relative ) { - $before = is_file( $baseline . '/' . $relative ) ? self::read_raw( $baseline . '/' . $relative ) : ''; - $after = is_file( $root . '/' . $relative ) ? self::read_raw( $root . '/' . $relative ) : ''; - if ( null === $before || null === $after || self::looks_binary( $before ) || self::looks_binary( $after ) ) { - return self::tool_error( 'binary_content', 'Workspace diff cannot represent binary content.' ); + if ( '' !== $baseline ) { + $current = self::workspace_file_map( $root ); + $before = self::workspace_file_map( $baseline ); + $paths = array_unique( array_merge( array_keys( $before ), array_keys( $current ) ) ); + foreach ( $paths as $path ) { + if ( isset( $before[ $path ], $current[ $path ] ) && hash_equals( $before[ $path ], $current[ $path ] ) ) { + continue; + } + $entries[ $path ] = array( + 'before' => isset( $before[ $path ] ) ? self::read_raw( $baseline . '/' . $path ) : null, + 'after' => isset( $current[ $path ] ) ? self::read_raw( $root . '/' . $path ) : null, + ); + } + $kind = 'filesystem'; + } else { + foreach ( self::$seed_preimages as $path => $original ) { + $file = $root . '/' . $path; + $current = is_file( $file ) ? self::read_raw( $file ) : null; + if ( $current === $original ) { + continue; + } + $entries[ $path ] = array( 'before' => $original, 'after' => $current ); + } + $kind = 'seed'; + } + ksort( $entries, SORT_STRING ); + foreach ( $entries as $path => $entry ) { + $entries[ $path ]['status'] = null === $entry['before'] ? 'added' : ( null === $entry['after'] ? 'deleted' : 'modified' ); + } + return array( 'baseline' => $kind, 'entries' => $entries ); + } + + /** + * Unified diff for one file with context hunks (git-style headers). + */ + private static function unified_diff( string $relative, ?string $before, ?string $after ): string { + $from = null === $before ? '/dev/null' : 'a/' . $relative; + $to = null === $after ? '/dev/null' : 'b/' . $relative; + $old = self::diff_lines( (string) $before ); + $new = self::diff_lines( (string) $after ); + $ops = self::diff_ops( $old, $new ); + + $out = "--- {$from}\n+++ {$to}\n"; + $context = self::DIFF_CONTEXT_LINES; + $count = count( $ops ); + $index = 0; + while ( $index < $count ) { + if ( ' ' === $ops[ $index ][0] ) { + ++$index; + continue; + } + // Hunk spans from $context lines before the first change through + // $context lines after the last change that is within 2*$context. + $start = max( 0, $index - $context ); + $end = $index; + $scan = $index; + while ( $scan < $count ) { + if ( ' ' !== $ops[ $scan ][0] ) { + $end = $scan; + ++$scan; + continue; + } + $run = $scan; + while ( $run < $count && ' ' === $ops[ $run ][0] ) { + ++$run; + } + if ( $run >= $count || $run - $scan > 2 * $context ) { + break; + } + $scan = $run; + } + $stop = min( $count - 1, $end + $context ); + + $old_start = 1; + $new_start = 1; + for ( $k = 0; $k < $start; ++$k ) { + if ( '+' !== $ops[ $k ][0] ) { + ++$old_start; + } + if ( '-' !== $ops[ $k ][0] ) { + ++$new_start; + } + } + $old_len = 0; + $new_len = 0; + $body = ''; + for ( $k = $start; $k <= $stop; ++$k ) { + if ( '+' !== $ops[ $k ][0] ) { + ++$old_len; + } + if ( '-' !== $ops[ $k ][0] ) { + ++$new_len; + } + $body .= $ops[ $k ][0] . $ops[ $k ][1] . "\n"; + } + $out .= sprintf( "@@ -%d,%d +%d,%d @@\n", 0 === $old_len ? $old_start - 1 : $old_start, $old_len, 0 === $new_len ? $new_start - 1 : $new_start, $new_len ); + $out .= $body; + $index = $stop + 1; + } + return $out; + } + + /** @return array */ + private static function diff_lines( string $content ): array { + if ( '' === $content ) { + return array(); + } + return explode( "\n", str_ends_with( $content, "\n" ) ? substr( $content, 0, -1 ) : $content ); + } + + /** + * Line edit script (LCS). Falls back to delete-all/add-all past the work bound. + * + * @param array $old Old lines. + * @param array $new New lines. + * @return array + */ + private static function diff_ops( array $old, array $new ): array { + // Trim the common prefix and suffix so the LCS table only covers the changed core. + $prefix = 0; + $n = count( $old ); + $m = count( $new ); + while ( $prefix < $n && $prefix < $m && $old[ $prefix ] === $new[ $prefix ] ) { + ++$prefix; + } + $suffix = 0; + while ( $suffix < $n - $prefix && $suffix < $m - $prefix && $old[ $n - 1 - $suffix ] === $new[ $m - 1 - $suffix ] ) { + ++$suffix; + } + $ops = array(); + for ( $i = 0; $i < $prefix; ++$i ) { + $ops[] = array( ' ', $old[ $i ] ); + } + $a = array_slice( $old, $prefix, $n - $prefix - $suffix ); + $b = array_slice( $new, $prefix, $m - $prefix - $suffix ); + $x = count( $a ); + $y = count( $b ); + if ( $x * $y > self::MAX_DIFF_LCS_CELLS ) { + foreach ( $a as $line ) { + $ops[] = array( '-', $line ); + } + foreach ( $b as $line ) { + $ops[] = array( '+', $line ); + } + } else { + $lcs = array_fill( 0, $x + 1, array_fill( 0, $y + 1, 0 ) ); + for ( $i = $x - 1; $i >= 0; --$i ) { + for ( $j = $y - 1; $j >= 0; --$j ) { + $lcs[ $i ][ $j ] = $a[ $i ] === $b[ $j ] ? $lcs[ $i + 1 ][ $j + 1 ] + 1 : max( $lcs[ $i + 1 ][ $j ], $lcs[ $i ][ $j + 1 ] ); + } } - $from = is_file( $baseline . '/' . $relative ) ? 'a/' . $relative : '/dev/null'; - $to = is_file( $root . '/' . $relative ) ? 'b/' . $relative : '/dev/null'; - $patch .= "--- {$from}\n+++ {$to}\n@@ -1," . substr_count( $before, "\n" ) . " +1," . substr_count( $after, "\n" ) . " @@\n"; - foreach ( explode( "\n", rtrim( $before, "\n" ) ) as $line ) { if ( '' !== $line || '' !== $before ) { $patch .= '-' . $line . "\n"; } } - foreach ( explode( "\n", rtrim( $after, "\n" ) ) as $line ) { if ( '' !== $line || '' !== $after ) { $patch .= '+' . $line . "\n"; } } + $i = 0; + $j = 0; + while ( $i < $x && $j < $y ) { + if ( $a[ $i ] === $b[ $j ] ) { + $ops[] = array( ' ', $a[ $i ] ); + ++$i; + ++$j; + } elseif ( $lcs[ $i + 1 ][ $j ] >= $lcs[ $i ][ $j + 1 ] ) { + $ops[] = array( '-', $a[ $i ] ); + ++$i; + } else { + $ops[] = array( '+', $b[ $j ] ); + ++$j; + } + } + for ( ; $i < $x; ++$i ) { + $ops[] = array( '-', $a[ $i ] ); + } + for ( ; $j < $y; ++$j ) { + $ops[] = array( '+', $b[ $j ] ); + } + } + for ( $i = $n - $suffix; $i < $n; ++$i ) { + $ops[] = array( ' ', $old[ $i ] ); } - return array( 'success' => true, 'changed' => ! empty( $status['files'] ), 'files' => $status['files'], 'diff' => $patch, 'baseline' => 'filesystem' ); + return $ops; } /** @return array */ diff --git a/scripts/php-sandbox-workspace-executor-smoke.php b/scripts/php-sandbox-workspace-executor-smoke.php index d30712cc7..e25dfc556 100644 --- a/scripts/php-sandbox-workspace-executor-smoke.php +++ b/scripts/php-sandbox-workspace-executor-smoke.php @@ -286,6 +286,84 @@ function assert_true( bool $condition, string $message ): void { assert_true( $expected === WP_Codebox_Sandbox_Workspace_Executor::writable_pattern_matches( $path, $pattern ), "writable pattern parity: {$path} vs {$pattern}" ); } + // ----------------------------------------------------------------- + // Production shape: the seeded sandbox snapshot excludes .git and the host + // supplies no filesystem baseline. Status/diff must still work against the + // seed state, captured before each file's first mutation (wp-codebox#2591). + // ----------------------------------------------------------------- + $seed_root = sys_get_temp_dir() . '/wp-codebox-sandbox-seed-' . bin2hex( random_bytes( 6 ) ); + mkdir( $seed_root . '/docs', 0755, true ); + $guide_lines = array(); + for ( $line = 1; $line <= 40; ++$line ) { + $guide_lines[] = "Line {$line} of the guide."; + } + $guide = implode( "\n", $guide_lines ) . "\n"; + file_put_contents( $seed_root . '/docs/guide.md', $guide ); + file_put_contents( $seed_root . '/docs/old.md', "# Old\n" ); + file_put_contents( $seed_root . '/docs/untouched.md', "# Untouched\n" ); + $seed_real = (string) realpath( $seed_root ); + $seed_context = array( 'workspace_root' => $seed_real, 'writable_paths' => array( 'docs/**' ) ); + $seed_call = static function ( string $tool_name, array $parameters ) use ( $executor, $seed_context ): array { + return $executor->executeWP_Agent_Tool_Call( array( 'tool_name' => $tool_name, 'parameters' => $parameters ), array( 'name' => $tool_name ), $seed_context ); + }; + WP_Codebox_Sandbox_Workspace_Executor::reset_mutation_ledger(); + + $clean = $seed_call( 'workspace_git_status', array() ); + assert_true( true === $clean['success'], 'seed status succeeds without .git or a filesystem baseline' ); + assert_true( false === $clean['result']['changed'] && array() === $clean['result']['files'], 'seed status is clean before any mutation' ); + assert_true( 'seed' === $clean['result']['baseline'], 'seed status reports the seed baseline' ); + $clean_diff = $seed_call( 'workspace_git_diff', array() ); + assert_true( true === $clean_diff['success'] && '' === $clean_diff['result']['diff'], 'seed diff is empty before any mutation' ); + + $seed_call( 'workspace_edit', array( 'path' => 'docs/guide.md', 'old_string' => 'Line 20 of the guide.', 'new_string' => 'Line twenty of the guide.' ) ); + $seed_call( 'workspace_edit', array( 'path' => 'docs/guide.md', 'old_string' => 'Line 21 of the guide.', 'new_string' => "Line 21 of the guide.\nAn added line." ) ); + $seed_call( 'workspace_write', array( 'path' => 'docs/new.md', 'content' => "# New\n" ) ); + $seed_call( 'workspace_apply_patch', array( 'patch' => "--- a/docs/old.md\n+++ /dev/null\n@@ -1,1 +0,0 @@\n-# Old\n" ) ); + $seed_call( 'workspace_write', array( 'path' => 'docs/untouched.md', 'content' => "# Untouched\n" ) ); + $failed_edit = $seed_call( 'workspace_edit', array( 'path' => 'docs/untouched.md', 'old_string' => 'missing', 'new_string' => 'x' ) ); + assert_true( false === $failed_edit['success'], 'failed edit stays failed' ); + + $seed_status = $seed_call( 'workspace_git_status', array() ); + assert_true( true === $seed_status['success'], 'seed status succeeds after mutations' ); + assert_true( array( 'docs/guide.md', 'docs/new.md', 'docs/old.md' ) === $seed_status['result']['files'], 'seed status lists modified, added, and deleted files; rewrites with identical content are clean' ); + assert_true( + array( + array( 'path' => 'docs/guide.md', 'status' => 'modified' ), + array( 'path' => 'docs/new.md', 'status' => 'added' ), + array( 'path' => 'docs/old.md', 'status' => 'deleted' ), + ) === $seed_status['result']['changes'], + 'seed status classifies each change' + ); + assert_true( array( 'added' => 1, 'modified' => 1, 'deleted' => 1 ) === $seed_status['result']['summary'], 'seed status summarizes change counts' ); + + $seed_diff = $seed_call( 'workspace_git_diff', array() ); + assert_true( true === $seed_diff['success'], 'seed diff succeeds after mutations' ); + $diff_text = $seed_diff['result']['diff']; + assert_true( str_contains( $diff_text, "--- a/docs/guide.md\n+++ b/docs/guide.md\n@@ -17,8 +17,9 @@\n" ), 'seed diff emits a context hunk, not a whole-file rewrite' ); + assert_true( str_contains( $diff_text, "-Line 20 of the guide.\n+Line twenty of the guide.\n Line 21 of the guide.\n+An added line.\n" ), 'seed diff shows the exact changed lines' ); + assert_true( ! str_contains( $diff_text, 'Line 1 of the guide.' ) && ! str_contains( $diff_text, 'Line 40 of the guide.' ), 'seed diff omits unchanged lines outside context' ); + assert_true( str_contains( $diff_text, "--- /dev/null\n+++ b/docs/new.md\n@@ -0,0 +1,1 @@\n+# New\n" ), 'seed diff shows added files' ); + assert_true( str_contains( $diff_text, "--- a/docs/old.md\n+++ /dev/null\n@@ -1,1 +0,0 @@\n-# Old\n" ), 'seed diff shows deleted files' ); + + $one_diff = $seed_call( 'workspace_git_diff', array( 'path' => 'docs/new.md' ) ); + assert_true( array( 'docs/new.md' ) === $one_diff['result']['files'] && ! str_contains( $one_diff['result']['diff'], 'guide.md' ), 'seed diff honors the optional path filter' ); + + // The seed diff is a valid patch: reverting it onto a fresh seed copy reproduces the edited workspace. + $replay_root = sys_get_temp_dir() . '/wp-codebox-sandbox-replay-' . bin2hex( random_bytes( 6 ) ); + mkdir( $replay_root . '/docs', 0755, true ); + file_put_contents( $replay_root . '/docs/guide.md', $guide ); + file_put_contents( $replay_root . '/docs/old.md', "# Old\n" ); + $replay_real = (string) realpath( $replay_root ); + $replay_context = array( 'workspace_root' => $replay_real, 'writable_paths' => array( 'docs/**' ) ); + $replayed = $executor->executeWP_Agent_Tool_Call( array( 'tool_name' => 'workspace_apply_patch', 'parameters' => array( 'patch' => $diff_text ) ), array( 'name' => 'workspace_apply_patch' ), $replay_context ); + assert_true( true === $replayed['success'], 'seed diff applies cleanly as a patch' ); + assert_true( file_get_contents( $seed_real . '/docs/guide.md' ) === file_get_contents( $replay_real . '/docs/guide.md' ), 'replayed seed diff reproduces the edited file' ); + assert_true( is_file( $replay_real . '/docs/new.md' ) && ! is_file( $replay_real . '/docs/old.md' ), 'replayed seed diff reproduces adds and deletes' ); + + WP_Codebox_Sandbox_Workspace_Executor::reset_mutation_ledger(); + $after_reset = $seed_call( 'workspace_git_status', array() ); + assert_true( false === $after_reset['result']['changed'], 'reset clears the seed baseline for the next run' ); + // Cleanup. $rrmdir = static function ( string $dir ) use ( &$rrmdir ): void { foreach ( scandir( $dir ) ?: array() as $entry ) { @@ -299,6 +377,8 @@ function assert_true( bool $condition, string $message ): void { }; $rrmdir( $root_real ); $rrmdir( $baseline ); + $rrmdir( $seed_real ); + $rrmdir( $replay_real ); fwrite( STDOUT, "OK php-sandbox-workspace-executor-smoke\n" ); } diff --git a/tests/runner-workspace-publisher.test.mjs b/tests/runner-workspace-publisher.test.mjs index 7ed31c119..1aa12efb3 100644 --- a/tests/runner-workspace-publisher.test.mjs +++ b/tests/runner-workspace-publisher.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict" -import { publishRunnerWorkspace } from "../.github/scripts/run-agent-task/runner-workspace-publisher.mjs" +import { publicationHeadBranch, publicationPullBody, publishRunnerWorkspace } from "../.github/scripts/run-agent-task/runner-workspace-publisher.mjs" const request = { target_repo: "owner/repo", workload: { id: "run-1", label: "Update" }, runner_workspace: { enabled: true, repo: "owner/repo", base: "main", branch_prefix: "wp-codebox/agent-task/" }, access: { allowed_repos: ["owner/repo"] } } const publicationFiles = [{ path: "README.md", mode: "100644", content: Buffer.from("changed\n").toString("base64"), deleted: false }] @@ -119,4 +119,39 @@ await assert.rejects(() => publishRunnerWorkspace({ request, changedFiles: ["REA await publishRunnerWorkspace({ request, changedFiles: ["README.md"], publicationFiles: [{ path: "README.md", mode: "100755", content: Buffer.from("changed\n").toString("base64"), deleted: false }], token: "secret", fetchImpl: mock.fetch }) assert(mock.calls.some(([url]) => url.endsWith("/git/trees"))) } +// Branch naming (wp-codebox#2591): the caller's branch is used as given and +// a prefix is joined to the run id with a separator only when it lacks one. +assert.deepEqual(publicationHeadBranch({ branch: "docs-agent/extrachill-shop-user-docs", branch_prefix: "docs-agent/extrachill-shop-user-docs" }, { workload: { id: "docs-agent-user-maintenance" } }).head, "docs-agent/extrachill-shop-user-docs", "an explicit branch is used exactly, never with the workload id appended") +assert.equal(publicationHeadBranch({ head_branch: "release/notes" }, { workload: { id: "w" } }).head, "release/notes", "head_branch is an explicit branch alias") +assert.equal(publicationHeadBranch({ branch_prefix: "wp-codebox/agent-task/" }, { workload: { id: "run-1" } }).head, "wp-codebox/agent-task/run-1", "a prefix ending in / is joined directly") +assert.equal(publicationHeadBranch({ branch_prefix: "docs/upkeep-" }, { workload: { id: "run-1" } }).head, "docs/upkeep-run-1", "a prefix ending in - is joined directly") +assert.equal(publicationHeadBranch({ branch_prefix: "docs/upkeep" }, { workload: { id: "run-1" } }).head, "docs/upkeep-run-1", "a prefix without a trailing separator gets exactly one - separator") +assert.equal(publicationHeadBranch({}, { workload: { id: "run 1" } }).head, "wp-codebox/agent-task/run-1", "the default prefix and sanitized run id remain unchanged") +{ + const explicitRequest = { ...request, workload: { id: "docs-agent-user-maintenance", label: "Run Docs Agent" }, runner_workspace: { ...request.runner_workspace, branch: "wp-codebox/agent-task/run-1", branch_prefix: "wp-codebox/agent-task/run-1" } } + const mock = fetchMock(false) + const result = await publishRunnerWorkspace({ request: explicitRequest, changedFiles: ["README.md"], publicationFiles, token: "secret", fetchImpl: mock.fetch }) + assert.equal(result.branch.head, "wp-codebox/agent-task/run-1", "first publication on an explicit branch uses it unchanged") + const refCreate = mock.calls.find(([url, method]) => new URL(url).pathname.endsWith("/git/refs") && method === "POST") + assert.equal(refCreate?.[2]?.ref, "refs/heads/wp-codebox/agent-task/run-1", "the created ref is the caller branch") +} +{ + const explicitRequest = { ...request, workload: { id: "docs-agent-user-maintenance", label: "Run Docs Agent" }, runner_workspace: { ...request.runner_workspace, branch: "wp-codebox/agent-task/run-1" } } + const reused = await publishRunnerWorkspace({ request: explicitRequest, changedFiles: ["README.md"], publicationFiles, token: "secret", fetchImpl: fetchMock(true).fetch }) + assert.equal(reused.branch.head, "wp-codebox/agent-task/run-1", "an explicit branch with an exact open PR is reused unchanged") + assert.equal(reused.pull_request.reused, true) + const fresh = await publishRunnerWorkspace({ request: explicitRequest, changedFiles: ["README.md"], publicationFiles, token: "secret", fetchImpl: fetchMock(true, "main", undefined, false).fetch }) + assert.equal(fresh.branch.head, "wp-codebox/agent-task/run-1-base", "an explicit branch without an open PR gets the base-SHA suffix exactly once") +} +// Pull request title and body. +{ + const titledRequest = { ...request, runner_workspace: { ...request.runner_workspace, title: "docs(shop): user docs maintenance", body: "Summary." } } + const mock = fetchMock(false) + await publishRunnerWorkspace({ request: titledRequest, changedFiles: ["docs/a.md", "docs/b.md"], publicationFiles: [...publicationFiles, { path: "docs/old.md", deleted: true }], token: "secret", fetchImpl: mock.fetch }) + const pullCreate = mock.calls.find(([url, method]) => new URL(url).pathname.endsWith("/pulls") && method === "POST") + assert.equal(pullCreate?.[2]?.title, "docs(shop): user docs maintenance", "a caller title wins over the workload label") + assert.equal(pullCreate?.[2]?.body, "Summary.\n\n### Changed files (2)\n\n- `README.md`\n- `docs/old.md` (deleted)", "the PR body appends the changed files to the caller body") +} +assert.equal(publicationPullBody({}, []), "", "no files and no caller body yields an empty body") +assert.equal(publicationPullBody({ body: "Only body" }, []), "Only body") console.log("runner workspace publisher ok")