From 91ee265074a71091b1faab9e3d8a20898fe9e1f6 Mon Sep 17 00:00:00 2001 From: Extra Chill Bot Date: Sun, 15 Nov 2026 13:43:14 +0000 Subject: [PATCH] fix(agent-task): record runner-workspace apply outcome and upload write evidence Runner-workspace agent writes could disappear without any trace: the workflow result never recorded what apply did, a no-op apply after successful sandbox writes passed silently, and the uploaded transcript dropped every tool call because the agent runtime result is a JSON-encoded string in the canonical execution's parsed.output. - Sandbox workspace executor keeps a content-free mutation ledger (tool, status, error type, target paths) that the runtime package executor attaches to the run metadata. - The workflow result gains workspace_apply (wp-codebox/runner-workspace-apply-outcome/v1): applied paths, rejected paths with reasons, unapplied paths, and write-call counts. Successful writes with a no-op apply now fail at stage "apply" with status writes-not-applied instead of a vacuous no_changes. - Host apply validation reports every rejected path with its reason. - Host and sandbox writable_paths matching now share one glob semantics (`**` spans directories, `*`/`?`/`[...]` stay within a segment), so the host never rejects a nested path the sandbox accepted. - The upload projection decodes parsed.output so tool observability and the write ledger (names plus workspace paths, no contents) reach the uploaded transcript, and workspace_apply is kept in the uploaded result. Refs #2567 AI assistance: Extra Chill Bot (Claude), via a Roadie subagent. --- .../execute-native-agent-task.mjs | 14 +- .../prepare-agent-task-upload.mjs | 34 +++- .../runner-workspace-apply-outcome.mjs | 91 +++++++++++ .../src/runner-workspace-apply.ts | 100 +++++++++++- ...ss-wp-codebox-runtime-package-executor.php | 8 +- ...-wp-codebox-sandbox-workspace-executor.php | 150 +++++++++++++++++- .../php-sandbox-workspace-executor-smoke.php | 59 +++++++ ...e-native-agent-task-playground-e2e.test.ts | 14 ++ tests/runner-workspace-apply-outcome.test.mjs | 99 ++++++++++++ tests/runner-workspace-apply.test.ts | 65 +++++++- tests/runtime-sources-materialization.test.ts | 31 ++++ 11 files changed, 653 insertions(+), 12 deletions(-) create mode 100644 .github/scripts/run-agent-task/runner-workspace-apply-outcome.mjs create mode 100644 tests/runner-workspace-apply-outcome.test.mjs diff --git a/.github/scripts/run-agent-task/execute-native-agent-task.mjs b/.github/scripts/run-agent-task/execute-native-agent-task.mjs index 9c1da3879..960bffcf7 100644 --- a/.github/scripts/run-agent-task/execute-native-agent-task.mjs +++ b/.github/scripts/run-agent-task/execute-native-agent-task.mjs @@ -10,6 +10,7 @@ import { readNativeResult } from "./native-result-file.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" +import { runnerWorkspaceApplyOutcome, sandboxWorkspaceMutations } from "./runner-workspace-apply-outcome.mjs" import { createTrustedArtifactApplyChannel, trustedArtifactApplyRefs } from "./trusted-artifact-snapshot.mjs" import { artifactSourcePathCategory, assertNoSeedSnapshotPaths, containsRuntimeSourceContent, sanitizeSeedSnapshotJson } from "./artifact-upload-policy.mjs" import { publishProcessMarker } from "../../../scripts/process-marker.mjs" @@ -806,6 +807,7 @@ if (toolObservability) { } assertNoRuntimeSourcePaths(runtimeResult, privateRuntimeSourceRootForSanitization) let workspaceApply = { status: "no-op", changedFiles: [] } +let applyError let workspaceEvidence let runnerWorkspaceCore = null let downstreamFailure = null @@ -819,9 +821,18 @@ if (execution.code === 0 && runtimeResult.success === true && request.runner_wor const trustedArtifacts = await trustedArtifactApplyRefs(trustedApplyArtifactRoot, refs) workspaceApply = await runnerWorkspaceCore.applyRunnerWorkspacePatch({ artifactRoot: trustedArtifacts.root, artifactRefs: trustedArtifacts.refs, workspaceRoot: workspace, writablePaths, seedIdentity: runnerWorkspaceSeedSnapshot?.provenance.identity }) } catch (error) { - downstreamFailure = { stage: "apply", message: bounded(error instanceof Error ? error.message : String(error), MAX_WORKFLOW_OUTPUT_BYTES), ...(error?.evidence ? { evidence: error.evidence } : {}) } + applyError = error + downstreamFailure = { stage: "apply", message: bounded(error instanceof Error ? error.message : String(error), MAX_WORKFLOW_OUTPUT_BYTES), ...(Array.isArray(error?.rejectedPaths) ? { rejected_paths: error.rejectedPaths } : {}), ...(error?.evidence ? { evidence: error.evidence } : {}) } } } +const workspaceApplyOutcome = request.runner_workspace?.enabled && request.run_agent && !request.dry_run + ? runnerWorkspaceApplyOutcome({ workspaceApply, applyError, bound: (value) => bounded(value, MAX_WORKFLOW_OUTPUT_BYTES), attempted: Boolean(runnerWorkspaceCore) || Boolean(applyError), mutations: sandboxWorkspaceMutations(nativeRuntimeResult), toolObservability }) + : undefined +if (workspaceApplyOutcome?.status === "writes-not-applied") { + // Never let successful agent writes vanish behind a vacuous no-op: the + // canonical patch declared nothing even though the sandbox accepted writes. + downstreamFailure ??= { stage: "apply", message: workspaceApplyOutcome.message, unapplied_paths: workspaceApplyOutcome.write_tool_calls.paths } +} if (trustedApplyArtifactRoot) { await rm(trustedApplyArtifactRoot, { recursive: true, force: true }) trustedApplyArtifactRoot = "" @@ -937,6 +948,7 @@ const result = { } : {}), }, runtime_result: redact(runtimeRecord), + ...(workspaceApplyOutcome ? { workspace_apply: workspaceApplyOutcome } : {}), ...(reviewerEvidence ? { reviewer_evidence: reviewerEvidence } : {}), verification, publication, diff --git a/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs b/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs index 81a859cf2..4b4a31200 100644 --- a/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs +++ b/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs @@ -181,6 +181,7 @@ function projectWorkflowResult(value) { execution: Object.keys(execution).length ? { stdout_truncated: execution.stdout_truncated, stderr_truncated: execution.stderr_truncated } : undefined, reviewer_evidence: reviewerEvidence.transcript === undefined ? undefined : { transcript: reviewerEvidence.transcript }, verification, + workspace_apply: result.workspace_apply, publication: result.publication, transcript: result.transcript, artifacts: result.artifacts, @@ -238,15 +239,45 @@ function projectToolCall(value) { return Object.fromEntries(Object.entries({ tool, paths: paths.length ? paths : undefined, status: boundedText(entry.status), arguments: Object.keys(args).length ? args : undefined, result: Object.keys(resultSummary).length ? resultSummary : undefined, error_code: boundedText(record(entry.error).code ?? entry.error_code), error: boundedText(record(entry.error).message ?? entry.error) }).filter(([, item]) => item !== undefined)) } +// The canonical `wordpress.run-php` execution carries the agent runtime result +// as a JSON-encoded string in `parsed.output`; decode it so tool calls survive. +function decodedParsedOutput(parsed) { + if (typeof parsed.output !== "string" || Buffer.byteLength(parsed.output) > MAX_UPLOAD_FILE_BYTES) return record(parsed.output) + try { + return record(JSON.parse(parsed.output)) + } catch { + return {} + } +} + +// Content-free ledger written by the sandbox workspace executor: tool, outcome, +// error type and target paths only. File contents are never part of it. +function projectWorkspaceMutations(value) { + const ledger = record(value) + if (ledger.schema !== "wp-codebox/sandbox-workspace-mutations/v1" || !Array.isArray(ledger.calls)) return undefined + const calls = ledger.calls.slice(0, MAX_TRANSCRIPT_EXECUTIONS).flatMap((value) => { + const call = record(value) + if (!["workspace_write", "workspace_edit", "workspace_apply_patch"].includes(call.tool) || !["succeeded", "failed"].includes(call.status)) return [] + const paths = (Array.isArray(call.paths) ? call.paths : []).map(safeTargetPath).filter(Boolean).slice(0, 32) + return [Object.fromEntries(Object.entries({ tool: call.tool, status: call.status, paths, error_type: safeToolIdentifier(call.error_type) ? call.error_type : undefined }).filter(([, item]) => item !== undefined))] + }) + return { schema: ledger.schema, calls, dropped: Number.isSafeInteger(ledger.dropped) && ledger.dropped >= 0 ? ledger.dropped : 0 } +} + function projectParsed(value) { const parsed = record(value) + const decoded = decodedParsedOutput(parsed) + const runtimeMetadata = record(record(record(parsed.agent_runtime ?? decoded.agent_runtime).result).metadata) const messages = Array.isArray(parsed.messages) ? parsed.messages : Array.isArray(parsed.model_messages) ? parsed.model_messages : [] const tools = Array.isArray(parsed.tool_calls) ? parsed.tool_calls : Array.isArray(parsed.toolCalls) ? parsed.toolCalls : [] const results = Array.isArray(parsed.tool_results) ? parsed.tool_results : Array.isArray(parsed.toolResults) ? parsed.toolResults : [] const errors = Array.isArray(parsed.errors) ? parsed.errors : parsed.error ? [parsed.error] : [] const agent = record(parsed.agent ?? parsed.agent_metadata) const toolObservability = canonicalToolObservability(parsed.metadata) - ?? canonicalToolObservability(record(parsed.agent_runtime).result?.metadata) + ?? canonicalToolObservability(runtimeMetadata) + ?? canonicalToolObservability(decoded.metadata) + const workspaceMutations = projectWorkspaceMutations(runtimeMetadata.sandbox_workspace_mutations) + ?? projectWorkspaceMutations(record(decoded.metadata).sandbox_workspace_mutations) return Object.fromEntries(Object.entries({ agent: Object.fromEntries(["id", "name", "status"].flatMap((key) => boundedText(agent[key]) ? [[key, boundedText(agent[key])]] : [])), model_messages: messages.slice(0, MAX_TRANSCRIPT_EXECUTIONS).flatMap((message) => boundedText(record(message).content ?? record(message).text ?? message) ? [{ role: boundedText(record(message).role), content: boundedText(record(message).content ?? record(message).text ?? message) }] : []), @@ -254,6 +285,7 @@ function projectParsed(value) { tool_results: results.slice(0, MAX_TRANSCRIPT_EXECUTIONS).map(projectToolCall), errors: errors.slice(0, MAX_TRANSCRIPT_EXECUTIONS).flatMap((error) => boundedText(record(error).message ?? error) ? [boundedText(record(error).message ?? error)] : []), tool_observability: toolObservability, + workspace_mutations: workspaceMutations, }).filter(([, item]) => item !== undefined && (Array.isArray(item) ? item.length > 0 : Object.keys(item).length > 0))) } diff --git a/.github/scripts/run-agent-task/runner-workspace-apply-outcome.mjs b/.github/scripts/run-agent-task/runner-workspace-apply-outcome.mjs new file mode 100644 index 000000000..3cd527688 --- /dev/null +++ b/.github/scripts/run-agent-task/runner-workspace-apply-outcome.mjs @@ -0,0 +1,91 @@ +/** + * Explicit runner-workspace apply outcome for the agent-task workflow result. + * + * Kept free of side effects so the projection is unit-testable without running + * the executor entrypoint. + */ + +function record(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : {} +} + +const WORKSPACE_MUTATION_TOOLS = new Set(["workspace_write", "workspace_edit", "workspace_apply_patch"]) +const MAX_APPLY_OUTCOME_PATHS = 100 + +/** Finds the content-free sandbox workspace mutation ledger in the runtime result. */ +export function sandboxWorkspaceMutations(value) { + let found + const visit = (entry, depth) => { + if (found || depth > 10) return + if (Array.isArray(entry)) return entry.forEach((item) => visit(item, depth + 1)) + const item = record(entry) + if (item.schema === "wp-codebox/sandbox-workspace-mutations/v1" && Array.isArray(item.calls)) { + found = item + return + } + Object.values(item).forEach((child) => visit(child, depth + 1)) + } + visit(value, 0) + return found +} + +function workspaceToolBase(name) { + const value = typeof name === "string" ? name : "" + return value.includes("/") ? value.slice(value.lastIndexOf("/") + 1) : value +} + +/** + * Projects the explicit runner-workspace apply outcome recorded in the workflow + * result: which paths reached the host workspace, which were rejected and why, + * and whether successful sandbox writes produced no host change at all. + */ +export function runnerWorkspaceApplyOutcome({ workspaceApply, applyError, attempted, mutations, toolObservability, bound = (value) => value.slice(0, 8192) }) { + const ledgerCalls = Array.isArray(record(mutations).calls) ? record(mutations).calls.map(record).filter((call) => WORKSPACE_MUTATION_TOOLS.has(call.tool)) : [] + const observedCalls = Array.isArray(record(toolObservability).calls) ? record(toolObservability).calls.map(record).filter((call) => WORKSPACE_MUTATION_TOOLS.has(workspaceToolBase(call.tool_name))) : [] + const source = ledgerCalls.length || mutations ? "sandbox-ledger" : observedCalls.length ? "tool-observability" : "none" + const calls = source === "sandbox-ledger" + ? ledgerCalls.map((call) => ({ tool: call.tool, status: call.status, paths: Array.isArray(call.paths) ? call.paths.filter((path) => typeof path === "string") : [], ...(typeof call.error_type === "string" ? { error_type: call.error_type } : {}) })) + : observedCalls.map((call) => ({ tool: workspaceToolBase(call.tool_name), status: call.status, paths: [] })) + const succeeded = calls.filter((call) => call.status === "succeeded") + const writePaths = [...new Set(succeeded.flatMap((call) => call.paths))].slice(0, MAX_APPLY_OUTCOME_PATHS) + const writeToolCalls = { + source, + attempted: calls.length, + succeeded: succeeded.length, + failed: calls.length - succeeded.length, + paths: writePaths, + ...(calls.some((call) => call.status !== "succeeded") ? { failures: calls.filter((call) => call.status !== "succeeded").slice(0, MAX_APPLY_OUTCOME_PATHS).map((call) => ({ tool: call.tool, paths: call.paths, error_type: call.error_type || "tool_call_failed" })) } : {}), + ...(Number.isSafeInteger(record(mutations).dropped) && record(mutations).dropped > 0 ? { dropped: record(mutations).dropped } : {}), + } + const appliedPaths = workspaceApply?.status === "applied" && Array.isArray(workspaceApply.changedFiles) ? workspaceApply.changedFiles.slice(0, MAX_APPLY_OUTCOME_PATHS) : [] + const rejectedPaths = Array.isArray(applyError?.rejectedPaths) ? applyError.rejectedPaths.slice(0, MAX_APPLY_OUTCOME_PATHS) : [] + const unappliedPaths = writePaths.filter((path) => !appliedPaths.includes(path) && !rejectedPaths.some((rejected) => rejected.path === path)) + let status + let message + if (applyError) { + status = rejectedPaths.length ? "rejected" : "failed" + message = bound(applyError instanceof Error ? applyError.message : String(applyError)) + } else if (!attempted) { + status = "skipped" + message = "Runner workspace apply did not run because the agent runtime did not succeed." + } else if (workspaceApply?.status === "applied") { + status = "applied" + message = `Applied ${appliedPaths.length} changed path(s) to the runner workspace.` + } else if (succeeded.length > 0) { + status = "writes-not-applied" + message = `The agent made ${succeeded.length} successful workspace write call(s)${writePaths.length ? ` (${writePaths.slice(0, 5).join(", ")}${writePaths.length > 5 ? ", ..." : ""})` : ""} but the canonical sandbox patch declared no changes, so nothing reached the runner workspace.` + } else { + status = "no-op" + message = calls.length ? "Every workspace write call failed; no changes were applied." : "The agent made no workspace write calls; no changes were applied." + } + return { + schema: "wp-codebox/runner-workspace-apply-outcome/v1", + status, + message, + applied_paths: appliedPaths, + rejected_paths: rejectedPaths, + ...(status !== "applied" && unappliedPaths.length ? { unapplied_paths: unappliedPaths } : {}), + ...(Number.isSafeInteger(workspaceApply?.declaredChanges) ? { declared_changes: workspaceApply.declaredChanges } : {}), + write_tool_calls: writeToolCalls, + } +} diff --git a/packages/runtime-core/src/runner-workspace-apply.ts b/packages/runtime-core/src/runner-workspace-apply.ts index 74356a7db..4594160a3 100644 --- a/packages/runtime-core/src/runner-workspace-apply.ts +++ b/packages/runtime-core/src/runner-workspace-apply.ts @@ -3,7 +3,7 @@ import { readFile, lstat, realpath, readdir } from "node:fs/promises" import { isAbsolute, resolve, relative } from "node:path" import { promisify } from "node:util" import { createHash } from "node:crypto" -import { pathIsWithinRoot, relativePathMatchesExcludePattern } from "./file-tree-policy.js" +import { normalizeRelativePath, pathIsWithinRoot } from "./file-tree-policy.js" const execFileAsync = promisify(execFile) const MAX_PATCH_BYTES = 5 * 1024 * 1024 @@ -44,10 +44,17 @@ export interface RunnerWorkspaceApplyFailureEvidence { changed_files: { artifact_path: string; sha256: string } } +export interface RunnerWorkspaceRejectedPath { + path: string + reason: "denied-path" | "unsupported-mode" | "outside-writable-paths" +} + export interface RunnerWorkspaceApplyResult { schema: "wp-codebox/runner-workspace-apply-result/v1" status: "applied" | "no-op" changedFiles: string[] + /** Number of change entries the canonical sandbox manifest declared. */ + declaredChanges: number patchSha256?: string integrity?: RunnerWorkspaceIntegritySnapshot publicationFiles?: RunnerWorkspacePublicationFile[] @@ -104,7 +111,7 @@ export async function applyRunnerWorkspacePatch(request: RunnerWorkspaceApplyReq } if (changed.length === 0) { if (patch.trim()) throw new Error("Canonical patch is non-empty but changed-files declares no changes.") - return { schema: "wp-codebox/runner-workspace-apply-result/v1", status: "no-op", changedFiles: [] } + return { schema: "wp-codebox/runner-workspace-apply-result/v1", status: "no-op", changedFiles: [], declaredChanges: 0 } } if (!patch.trim()) throw new Error("Canonical changed-files declares changes but patch is empty.") validatePatchPaths(patch, changed) @@ -123,6 +130,7 @@ export async function applyRunnerWorkspacePatch(request: RunnerWorkspaceApplyReq schema: "wp-codebox/runner-workspace-apply-result/v1", status: "applied", changedFiles: changed.map((file) => file.relativePath), + declaredChanges: changed.length, patchSha256: createHash("sha256").update(patch).digest("hex"), integrity: { workspaceRoot, files, baseline }, publicationFiles: changed.map((change) => { @@ -231,14 +239,96 @@ function parseChangedFiles(raw: string): RunnerWorkspaceChangedFile[] { }) } +/** + * Validates every declared change before anything is applied. All rejections + * are collected so the failure names each dropped path and why, instead of + * stopping at the first one. + */ function validateChangedFiles(files: RunnerWorkspaceChangedFile[], writablePaths: string[]): void { if (writablePaths.length === 0) throw new Error("A non-empty writable path policy is required.") + const rejected: RunnerWorkspaceRejectedPath[] = [] for (const file of files) { const path = file.relativePath.replaceAll("\\", "/") - if (!path || path.startsWith("/") || path.split("/").some((part) => part === "" || part === "." || part === ".." || part === ".git" || part === ".codebox")) throw new Error(`Changed file has a denied path: ${file.relativePath}`) - if (![file.beforeMode, file.afterMode].filter(Boolean).every((mode) => mode === "100644" || mode === "100755")) throw new Error(`Changed file has an unsupported mode: ${file.relativePath}`) - if (!writablePaths.some((pattern) => relativePathMatchesExcludePattern(path, pattern))) throw new Error(`Changed file is outside writable_paths: ${file.relativePath}`) + if (!path || path.startsWith("/") || path.split("/").some((part) => part === "" || part === "." || part === ".." || part === ".git" || part === ".codebox")) { + rejected.push({ path: file.relativePath, reason: "denied-path" }) + } else if (![file.beforeMode, file.afterMode].filter(Boolean).every((mode) => mode === "100644" || mode === "100755")) { + rejected.push({ path: file.relativePath, reason: "unsupported-mode" }) + } else if (!writablePaths.some((pattern) => writablePathMatches(path, pattern))) { + rejected.push({ path: file.relativePath, reason: "outside-writable-paths" }) + } + } + if (rejected.length === 0) return + const [first] = rejected + const message = first.reason === "denied-path" + ? `Changed file has a denied path: ${first.path}` + : first.reason === "unsupported-mode" + ? `Changed file has an unsupported mode: ${first.path}` + : `Changed file is outside writable_paths: ${first.path}` + const error = new Error(rejected.length > 1 ? `${message} (${rejected.length} paths rejected)` : message) as Error & { rejectedPaths?: RunnerWorkspaceRejectedPath[] } + error.rejectedPaths = rejected.slice(0, 100) + throw error +} + +/** + * Matches a workspace-relative path against one `writable_paths` entry. + * + * Semantics intentionally mirror the sandbox workspace tools so the host never + * drops a change the sandbox accepted: a leading `./` or `/` is ignored, a + * trailing `/**` (or a bare directory) grants the whole subtree, `**` as a + * path segment spans zero or more directories, and `*`, `?` and `[...]` match + * within a single segment. + */ +export function writablePathMatches(relativePath: string, pattern: string): boolean { + const path = normalizeRelativePath(relativePath).replace(/^\/+/, "") + const normalized = normalizeRelativePath(pattern.trim()).replace(/^\/+/, "").replace(/\/+$/, "") + if (!path || !normalized || normalized === ".") return false + if (path === normalized) return true + if (normalized.endsWith("/**")) { + const prefix = normalized.slice(0, -3) + if (!/[*?[]/.test(prefix)) return path === prefix || path.startsWith(`${prefix}/`) + } + if (!/[*?[]/.test(normalized)) return path.startsWith(`${normalized}/`) + return globRegExp(normalized).test(path) +} + +function globRegExp(pattern: string): RegExp { + const segments = pattern.split("/") + let source = "" + for (const [index, segment] of segments.entries()) { + const last = index === segments.length - 1 + if (segment === "**") { + // `a/**/b` matches `a/b` and `a/x/y/b`; a trailing `**` matches any descendant. + source += last ? "(?:[^/]+(?:/[^/]+)*)" : "(?:[^/]+/)*" + continue + } + source += globSegment(segment) + (last ? "" : "/") + } + return new RegExp(`^${source}$`) +} + +function globSegment(segment: string): string { + let source = "" + for (let index = 0; index < segment.length; index++) { + const character = segment[index] + if (character === "*") { + source += "[^/]*" + } else if (character === "?") { + source += "[^/]" + } else if (character === "[") { + const close = segment.indexOf("]", index + 2) + if (close === -1) { + source += "\\[" + continue + } + const raw = segment.slice(index + 1, close).replace(/\\/g, "\\\\") + // A class never spans a path separator, including negated classes. + source += raw.startsWith("!") || raw.startsWith("^") ? `[^/${raw.slice(1)}]` : `[${raw}]` + index = close + } else { + source += character.replace(/[.+^${}()|\\\]]/g, "\\$&") + } } + return source } function validatePatchPaths(patch: string, changed: RunnerWorkspaceChangedFile[]): void { diff --git a/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php b/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php index 2657c3d05..5513cc221 100644 --- a/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php +++ b/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php @@ -149,6 +149,7 @@ private function execute_workflow( array $task ): array|WP_Error { add_filter( 'agents_api_runtime_tool_declarations', $runtime_tool_declarations, 20, 3 ); add_filter( 'agents_api_tool_executors', $tool_executors, 20, 2 ); } + WP_Codebox_Sandbox_Workspace_Executor::reset_mutation_ledger(); try { $result = $ability_object->execute( $input ); } finally { @@ -167,8 +168,11 @@ private function execute_workflow( array $task ): array|WP_Error { $result['metadata'] = array_merge( is_array( $result['metadata'] ?? null ) ? $result['metadata'] : array(), array( - 'workflow_ability' => $ability, - 'workflow_id' => $ability, + 'workflow_ability' => $ability, + 'workflow_id' => $ability, + // Content-free write-attempt ledger so hosts can tell a lost + // sandbox write from a rejected or never-attempted one. + 'sandbox_workspace_mutations' => WP_Codebox_Sandbox_Workspace_Executor::mutation_ledger(), ) ); 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 51e607829..afe167158 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 @@ -34,6 +34,20 @@ final class WP_Codebox_Sandbox_Workspace_Executor { private const MAX_WRITE_BYTES = 5242880; // 5 MB write cap. private const MAX_GREP_RESULTS = 500; private const MAX_CONTEXT_LINES = 10; + 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; + + /** + * Content-free record of workspace mutation attempts for the current run. + * + * Hosts read it after the agent finishes so a sandbox write that never + * reaches the host workspace is attributable (accepted, rejected, or lost). + * + * @var array> + */ + private static array $mutation_ledger = array(); + private static int $mutation_ledger_dropped = 0; /** * Tool declarations keyed by Agents API client tool name. @@ -369,6 +383,7 @@ public function executeWP_Agent_Tool_Call( array $tool_call, array $tool_definit $root = self::resolve_workspace_root( $context, $parameters ); if ( is_string( $root ) && '' === $root ) { + self::record_mutation( (string) $config['base'], $parameters, self::tool_error( 'workspace_root_unavailable', 'Sandbox working root is not configured or does not exist.' ) ); return self::error_result( $tool_name, 'Sandbox working root is not configured or does not exist.', 'workspace_root_unavailable', $config, $started_at ); } @@ -377,6 +392,7 @@ public function executeWP_Agent_Tool_Call( array $tool_call, array $tool_definit $parameters['_wp_codebox_writable_paths'] = self::writable_paths( $context ); $parameters['_wp_codebox_baseline_root'] = self::baseline_root( $context ); $result = self::dispatch( $config['base'], $root, $parameters ); + self::record_mutation( (string) $config['base'], $parameters, $result ); if ( is_array( $result ) && false === ( $result['success'] ?? true ) ) { return self::error_result( $tool_name, @@ -396,6 +412,72 @@ public function executeWP_Agent_Tool_Call( array $tool_call, array $tool_definit ); } + /** Clears the per-run mutation ledger. Hosts call this before a run starts. */ + public static function reset_mutation_ledger(): void { + self::$mutation_ledger = array(); + self::$mutation_ledger_dropped = 0; + } + + /** + * Content-free summary of workspace mutation attempts since the last reset. + * + * Entries hold the tool, outcome, error type, and workspace-relative target + * paths only; file contents and patches are never recorded. + * + * @return array{schema:string,calls:array>,dropped:int} + */ + public static function mutation_ledger(): array { + return array( + 'schema' => 'wp-codebox/sandbox-workspace-mutations/v1', + 'calls' => self::$mutation_ledger, + 'dropped' => self::$mutation_ledger_dropped, + ); + } + + /** + * @param array $parameters Tool parameters. + * @param array $result Dispatch result. + */ + private static function record_mutation( string $base, array $parameters, array $result ): void { + if ( ! in_array( $base, self::MUTATION_TOOLS, true ) ) { + return; + } + if ( count( self::$mutation_ledger ) >= self::MAX_MUTATION_LEDGER_ENTRIES ) { + ++self::$mutation_ledger_dropped; + return; + } + $succeeded = false !== ( $result['success'] ?? true ); + $paths = array(); + if ( $succeeded && is_array( $result['changed_files'] ?? null ) ) { + $paths = $result['changed_files']; + } elseif ( $succeeded && is_string( $result['path'] ?? null ) && '' !== $result['path'] ) { + $paths = array( $result['path'] ); + } elseif ( '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 ) { + $paths[] = is_array( $file ) ? ( $file['target'] ?? $file['source'] ?? '' ) : ''; + } + } else { + $paths = array( $parameters['path'] ?? '' ); + } + $normalized = array(); + foreach ( $paths as $path ) { + $relative = self::relative_param( $path ); + if ( is_string( $relative ) && ! in_array( $relative, $normalized, true ) ) { + $normalized[] = $relative; + } + } + $entry = array( + 'tool' => $base, + 'status' => $succeeded ? 'succeeded' : 'failed', + 'paths' => array_slice( $normalized, 0, self::MAX_MUTATION_LEDGER_PATHS ), + ); + if ( ! $succeeded ) { + $entry['error_type'] = is_string( $result['error_type'] ?? null ) ? $result['error_type'] : 'sandbox_workspace_error'; + } + self::$mutation_ledger[] = $entry; + } + /** * Resolve a tool config by Agents API name, tolerating an absent source prefix. * @@ -1155,14 +1237,78 @@ private static function writable_path( string $relative, array $parameters ) { return self::tool_error( 'writable_path_denied', 'No writable_paths policy permits this mutation.' ); } foreach ( $patterns as $pattern ) { - $pattern = ltrim( str_replace( '\\', '/', $pattern ), '/' ); - if ( $relative === $pattern || fnmatch( $pattern, $relative, FNM_PATHNAME ) || ( str_ends_with( $pattern, '/**' ) && str_starts_with( $relative . '/', substr( $pattern, 0, -2 ) ) ) ) { + if ( self::writable_pattern_matches( $relative, (string) $pattern ) ) { return true; } } return self::tool_error( 'writable_path_denied', 'Sandbox workspace mutation is outside workflow writable_paths.' ); } + /** + * Match a workspace-relative path against one writable_paths entry. + * + * Mirrors the host apply gate (`writablePathMatches` in runtime-core) so a + * change accepted here is never silently dropped on the host: `./` and `/` + * prefixes are ignored, a trailing `/**` or bare directory grants the whole + * subtree, a `**` segment spans zero or more directories, and `*`, `?` and + * `[...]` match within one segment. + */ + public static function writable_pattern_matches( string $relative, string $pattern ): bool { + $pattern = trim( str_replace( '\\', '/', $pattern ) ); + while ( str_starts_with( $pattern, './' ) ) { + $pattern = substr( $pattern, 2 ); + } + $pattern = rtrim( ltrim( $pattern, '/' ), '/' ); + if ( '' === $relative || '' === $pattern || '.' === $pattern ) { + return false; + } + if ( $relative === $pattern ) { + return true; + } + if ( str_ends_with( $pattern, '/**' ) && 1 !== preg_match( '/[*?\[]/', substr( $pattern, 0, -3 ) ) ) { + return str_starts_with( $relative . '/', substr( $pattern, 0, -2 ) ); + } + if ( 1 !== preg_match( '/[*?\[]/', $pattern ) ) { + return str_starts_with( $relative, $pattern . '/' ); + } + $segments = explode( '/', $pattern ); + $last = count( $segments ) - 1; + $regex = ''; + foreach ( $segments as $index => $segment ) { + if ( '**' === $segment ) { + $regex .= $index === $last ? '(?:[^/]+(?:/[^/]+)*)' : '(?:[^/]+/)*'; + continue; + } + $regex .= self::glob_segment_regex( $segment ) . ( $index === $last ? '' : '/' ); + } + return 1 === preg_match( '#^' . $regex . '$#', $relative ); + } + + private static function glob_segment_regex( string $segment ): string { + $regex = ''; + $length = strlen( $segment ); + for ( $i = 0; $i < $length; $i++ ) { + $character = $segment[ $i ]; + if ( '*' === $character ) { + $regex .= '[^/]*'; + } elseif ( '?' === $character ) { + $regex .= '[^/]'; + } elseif ( '[' === $character ) { + $close = $i + 2 <= $length ? strpos( $segment, ']', $i + 2 ) : false; + if ( false === $close ) { + $regex .= '\\['; + continue; + } + $body = str_replace( array( '\\', '#' ), array( '\\\\', '\\#' ), substr( $segment, $i + 1, $close - $i - 1 ) ); + $regex .= ( str_starts_with( $body, '!' ) || str_starts_with( $body, '^' ) ) ? '[^/' . substr( $body, 1 ) . ']' : '[' . $body . ']'; + $i = $close; + } else { + $regex .= preg_quote( $character, '#' ); + } + } + return $regex; + } + /** * Validate and resolve a relative path contained within the working root. * diff --git a/scripts/php-sandbox-workspace-executor-smoke.php b/scripts/php-sandbox-workspace-executor-smoke.php index 4e735102a..d30712cc7 100644 --- a/scripts/php-sandbox-workspace-executor-smoke.php +++ b/scripts/php-sandbox-workspace-executor-smoke.php @@ -90,6 +90,8 @@ function assert_true( bool $condition, string $message ): void { ); }; + WP_Codebox_Sandbox_Workspace_Executor::reset_mutation_ledger(); + // --- write ------------------------------------------------------- $write = $call( 'workspace_write', array( 'path' => 'notes/todo.txt', 'content' => "line1\nline2\n" ) ); assert_true( true === $write['success'], 'write succeeds' ); @@ -227,6 +229,63 @@ function assert_true( bool $condition, string $message ): void { assert_true( isset( $tool['parameters']['properties'] ), "{$tool_name} includes a parameter schema" ); } + // --- mutation ledger (issue #2567) ------------------------------- + // Content-free record of write attempts lets the host tell a lost write + // from a rejected or never-attempted one. + $ledger = WP_Codebox_Sandbox_Workspace_Executor::mutation_ledger(); + assert_true( 'wp-codebox/sandbox-workspace-mutations/v1' === $ledger['schema'], 'ledger carries its schema' ); + $ledger_tools = array_values( array_unique( array_column( $ledger['calls'], 'tool' ) ) ); + assert_true( array() === array_diff( $ledger_tools, array( 'workspace_write', 'workspace_edit', 'workspace_apply_patch' ) ), 'ledger records mutation tools only' ); + assert_true( array( 'tool' => 'workspace_write', 'status' => 'succeeded', 'paths' => array( 'notes/todo.txt' ) ) === $ledger['calls'][0], 'ledger records a successful write with its path' ); + $denied = array_values( array_filter( $ledger['calls'], static fn( array $entry ): bool => 'writable_path_denied' === ( $entry['error_type'] ?? '' ) ) ); + assert_true( 1 <= count( $denied ) && 'failed' === $denied[0]['status'] && array( 'README.md' ) === $denied[0]['paths'], 'ledger records a rejected write with its path and reason' ); + $patched = array_values( array_filter( $ledger['calls'], static fn( array $entry ): bool => 'workspace_apply_patch' === $entry['tool'] && 'succeeded' === $entry['status'] ) ); + assert_true( array( 'patch-target.txt' ) === $patched[0]['paths'], 'ledger records apply-patch changed files' ); + assert_true( ! str_contains( (string) json_encode( $ledger ), 'line1' ), 'ledger never records file contents' ); + WP_Codebox_Sandbox_Workspace_Executor::reset_mutation_ledger(); + assert_true( array() === WP_Codebox_Sandbox_Workspace_Executor::mutation_ledger()['calls'], 'ledger resets between runs' ); + + // --- nested writable globs (issue #2567) -------------------------- + $nested_context = array( 'workspace_root' => $root_real, 'writable_paths' => array( 'plugins/extrachill-shop/docs/user/**' ) ); + $nested_write = $executor->executeWP_Agent_Tool_Call( + array( 'tool_name' => 'workspace_write', 'parameters' => array( 'path' => 'plugins/extrachill-shop/docs/user/getting-started.md', 'content' => "nested\n" ) ), + array( 'name' => 'workspace_write' ), + $nested_context + ); + assert_true( true === $nested_write['success'] && is_file( $root_real . '/plugins/extrachill-shop/docs/user/getting-started.md' ), 'nested writable glob accepts a new file in a new directory' ); + $nested_sibling = $executor->executeWP_Agent_Tool_Call( + array( 'tool_name' => 'workspace_write', 'parameters' => array( 'path' => 'plugins/extrachill-shop/docs/admin.md', 'content' => 'x' ) ), + array( 'name' => 'workspace_write' ), + $nested_context + ); + assert_true( false === $nested_sibling['success'] && 'writable_path_denied' === $nested_sibling['error_type'], 'nested writable glob rejects siblings outside the subtree' ); + + // Writable-path matching mirrors runtime-core writablePathMatches so the + // host apply gate never drops a change the sandbox accepted. + foreach ( array( + array( 'plugins/extrachill-shop/docs/user/a.md', 'plugins/extrachill-shop/docs/user/**', true ), + array( 'plugins/extrachill-shop/docs/user/x/a.md', 'plugins/extrachill-shop/docs/user/**', true ), + array( 'plugins/extrachill-shop/docs/user', 'plugins/extrachill-shop/docs/user/**', true ), + array( 'plugins/extrachill-shop/docs/a.md', 'plugins/extrachill-shop/docs/user/**', false ), + array( 'plugins/extrachill-shop/docs/userx/a.md', 'plugins/extrachill-shop/docs/user/**', false ), + array( 'docs/user/a.md', './docs/user/**', true ), + array( 'docs/user/a.md', '/docs/user/', true ), + array( 'docs/a.md', 'docs/**/*.md', true ), + array( 'docs/x/y/a.md', 'docs/**/*.md', true ), + array( 'docs/x/y/a.txt', 'docs/**/*.md', false ), + array( 'plugins/foo/docs/user/a.md', 'plugins/*/docs/user/**', true ), + array( 'plugins/foo/bar/docs/user/a.md', 'plugins/*/docs/user/**', false ), + array( 'docs/user/a.md', 'docs/user/*.md', true ), + array( 'docs/user/x/a.md', 'docs/user/*.md', false ), + array( 'docs/a.md', 'docs/[!b]*.md', true ), + array( 'docs/b.md', 'docs/[!b]*.md', false ), + array( 'README.md', 'README.md', true ), + array( 'README.md.bak', 'README.md', false ), + array( 'anything.md', '.', false ), + ) as list( $path, $pattern, $expected ) ) { + assert_true( $expected === WP_Codebox_Sandbox_Workspace_Executor::writable_pattern_matches( $path, $pattern ), "writable pattern parity: {$path} vs {$pattern}" ); + } + // Cleanup. $rrmdir = static function ( string $dir ) use ( &$rrmdir ): void { foreach ( scandir( $dir ) ?: array() as $entry ) { diff --git a/tests/execute-native-agent-task-playground-e2e.test.ts b/tests/execute-native-agent-task-playground-e2e.test.ts index 3371b27f4..bc704d55d 100644 --- a/tests/execute-native-agent-task-playground-e2e.test.ts +++ b/tests/execute-native-agent-task-playground-e2e.test.ts @@ -97,6 +97,14 @@ add_filter( 'pre_http_request', static function( $preempt, $args, $url ) { assert.equal(result.runtime_result.agent_task_run_result.refs.changed_files.length, 1) assert.equal(result.runtime_result.agent_task_run_result.refs.patches.length, 1) assert.equal(result.runtime_result.metadata.runner_workspace_publication.pull_request.url, "https://github.com/owner/repo/pull/1") + // Issue #2567: the workflow result records an explicit apply outcome, joined to + // the sandbox's content-free write ledger. + assert.equal(result.workspace_apply?.schema, "wp-codebox/runner-workspace-apply-outcome/v1") + assert.equal(result.workspace_apply.status, "applied") + assert.deepEqual(result.workspace_apply.applied_paths, ["README.md"]) + assert.deepEqual(result.workspace_apply.rejected_paths, []) + assert.equal(result.workspace_apply.declared_changes, 1) + assert.deepEqual(result.workspace_apply.write_tool_calls, { source: "sandbox-ledger", attempted: 1, succeeded: 1, failed: 0, paths: ["README.md"] }) const serialized = JSON.stringify(result) for (const privateValue of ["e2e-github-secret", "e2e-openai-secret", "PRIVATE_WORKSPACE_SENTINEL", "PRIVATE_NPM_SENTINEL", "PRIVATE_NETRC_SENTINEL", "PRIVATE_KEY_SENTINEL", "PRIVATE_CODEBOX_SENTINEL", "PRIVATE_NODE_MODULES_SENTINEL", sources.root, workspace]) assert.doesNotMatch(serialized, new RegExp(privateValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))) await execFileAsync(process.execPath, [uploader], { cwd: workspace, env: { ...process.env, AGENT_TASK_WORKSPACE: workspace, AGENT_TASK_REQUEST_PATH: join(workspace, ".codebox", "agent-task-request.json"), AGENT_TASK_UPLOAD_PATH: join(workspace, ".codebox", "agent-task-upload"), GITHUB_TOKEN: "e2e-github-secret", OPENAI_API_KEY: "e2e-openai-secret" } }) @@ -105,6 +113,12 @@ add_filter( 'pre_http_request', static function( $preempt, $args, $url ) { assert.match(exclusions.canonical_transcripts[0].provenance.artifact_path, /^runtime-[a-z0-9-]+\/files\/transcript\.json$/) const staged = JSON.stringify(await Promise.all((await readdir(join(workspace, ".codebox", "agent-task-upload"), { recursive: true })).map((path) => readFile(join(workspace, ".codebox", "agent-task-upload", path), "utf8").catch(() => "")))) assert.doesNotMatch(staged, /"tool_observability"/, "absent optional tool observability is omitted during upload staging") + const uploadedTranscript = JSON.parse(await readFile(join(workspace, ".codebox", "agent-task-upload", ".codebox", "agent-task-artifacts", "transcript.json"), "utf8")) + assert.deepEqual(uploadedTranscript.executions.map((execution: { parsed?: { workspace_mutations?: unknown } }) => execution.parsed?.workspace_mutations).filter(Boolean), [ + { schema: "wp-codebox/sandbox-workspace-mutations/v1", dropped: 0, calls: [{ tool: "workspace_edit", status: "succeeded", paths: ["workspace/README.md"] }] }, + ], "write tool names and paths reach the uploaded transcript") + const uploadedResult = JSON.parse(await readFile(join(workspace, ".codebox", "agent-task-upload", ".codebox", "agent-task-workflow-result.json"), "utf8")) + assert.equal(uploadedResult.workspace_apply.status, "applied", "the apply outcome is uploaded") for (const privateValue of ["wp-codebox-runner-workspace-seed-", workspace, "PRIVATE_WORKSPACE_SENTINEL", "PRIVATE_NPM_SENTINEL", "PRIVATE_NETRC_SENTINEL", "PRIVATE_KEY_SENTINEL"]) assert.doesNotMatch(staged, new RegExp(privateValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))) const stagedInput = JSON.parse(await readFile(join(workspace, ".codebox", "agent-task-upload", ".codebox", "native-agent-task-input.json"), "utf8")) assert.deepEqual(stagedInput.task_input.workspaces[0].seed, { kind: "runner-workspace-seed", digest: seedProvenance.digest.sha256, files: 2, bytes: seedProvenance.bytes, excludes: seedProvenance.excludes, excluded: seedProvenance.excluded }) diff --git a/tests/runner-workspace-apply-outcome.test.mjs b/tests/runner-workspace-apply-outcome.test.mjs new file mode 100644 index 000000000..31f135769 --- /dev/null +++ b/tests/runner-workspace-apply-outcome.test.mjs @@ -0,0 +1,99 @@ +import assert from "node:assert/strict" + +import { runnerWorkspaceApplyOutcome, sandboxWorkspaceMutations } from "../.github/scripts/run-agent-task/runner-workspace-apply-outcome.mjs" + +const ledger = (calls, dropped = 0) => ({ schema: "wp-codebox/sandbox-workspace-mutations/v1", calls, dropped }) + +// The ledger is discovered wherever the runtime nests the agent result metadata. +{ + const mutations = ledger([{ tool: "workspace_write", status: "succeeded", paths: ["docs/a.md"] }]) + const runtime = { agent_task_result: { raw: { agent_runtime: { result: { metadata: { sandbox_workspace_mutations: mutations } } } } } } + assert.deepEqual(sandboxWorkspaceMutations(runtime), mutations) + assert.equal(sandboxWorkspaceMutations({ metadata: {} }), undefined) +} + +// Applied: every applied path is listed. +{ + const outcome = runnerWorkspaceApplyOutcome({ + workspaceApply: { status: "applied", changedFiles: ["plugins/x/docs/user/a.md"], declaredChanges: 1 }, + attempted: true, + mutations: ledger([{ tool: "workspace_write", status: "succeeded", paths: ["plugins/x/docs/user/a.md"] }]), + }) + assert.equal(outcome.schema, "wp-codebox/runner-workspace-apply-outcome/v1") + assert.equal(outcome.status, "applied") + assert.deepEqual(outcome.applied_paths, ["plugins/x/docs/user/a.md"]) + assert.deepEqual(outcome.rejected_paths, []) + assert.equal(outcome.declared_changes, 1) + assert.equal(outcome.unapplied_paths, undefined) + assert.deepEqual(outcome.write_tool_calls, { source: "sandbox-ledger", attempted: 1, succeeded: 1, failed: 0, paths: ["plugins/x/docs/user/a.md"] }) +} + +// Issue #2567: successful sandbox writes with a no-op apply are surfaced, never a silent no_changes. +{ + const outcome = runnerWorkspaceApplyOutcome({ + workspaceApply: { status: "no-op", changedFiles: [], declaredChanges: 0 }, + attempted: true, + mutations: ledger([ + { tool: "workspace_write", status: "succeeded", paths: ["plugins/x/docs/user/a.md"] }, + { tool: "workspace_edit", status: "succeeded", paths: ["plugins/x/docs/user/b.md"] }, + { tool: "workspace_read", status: "succeeded", paths: ["README.md"] }, + ]), + }) + assert.equal(outcome.status, "writes-not-applied") + assert.match(outcome.message, /2 successful workspace write call\(s\) \(plugins\/x\/docs\/user\/a\.md, plugins\/x\/docs\/user\/b\.md\)/) + assert.deepEqual(outcome.unapplied_paths, ["plugins/x/docs/user/a.md", "plugins/x/docs/user/b.md"]) + assert.deepEqual(outcome.applied_paths, []) + assert.equal(outcome.write_tool_calls.attempted, 2, "read tools are not write calls") +} + +// Without the ledger, Agents API tool observability still detects write calls. +{ + const outcome = runnerWorkspaceApplyOutcome({ + workspaceApply: { status: "no-op", changedFiles: [] }, + attempted: true, + toolObservability: { version: 1, calls: [{ tool_name: "client/workspace_apply_patch", status: "succeeded" }, { tool_name: "client/workspace_read", status: "succeeded" }] }, + }) + assert.equal(outcome.status, "writes-not-applied") + assert.equal(outcome.write_tool_calls.source, "tool-observability") + assert.equal(outcome.write_tool_calls.succeeded, 1) +} + +// Rejected writes report each path and its reason. +{ + const error = Object.assign(new Error("Changed file is outside writable_paths: README.md (2 paths rejected)"), { + rejectedPaths: [{ path: "README.md", reason: "outside-writable-paths" }, { path: ".git/config", reason: "denied-path" }], + }) + const outcome = runnerWorkspaceApplyOutcome({ + workspaceApply: { status: "no-op", changedFiles: [] }, + applyError: error, + attempted: true, + mutations: ledger([{ tool: "workspace_write", status: "succeeded", paths: ["README.md", "docs/a.md"] }]), + }) + assert.equal(outcome.status, "rejected") + assert.match(outcome.message, /outside writable_paths/) + assert.deepEqual(outcome.rejected_paths, error.rejectedPaths) + assert.deepEqual(outcome.unapplied_paths, ["docs/a.md"]) +} + +// Failed write calls and a genuine no-op stay distinguishable. +{ + const failed = runnerWorkspaceApplyOutcome({ + workspaceApply: { status: "no-op", changedFiles: [] }, + attempted: true, + mutations: ledger([{ tool: "workspace_write", status: "failed", paths: ["/etc/passwd"], error_type: "path_not_writable" }], 3), + }) + assert.equal(failed.status, "no-op") + assert.match(failed.message, /Every workspace write call failed/) + assert.deepEqual(failed.write_tool_calls.failures, [{ tool: "workspace_write", paths: ["/etc/passwd"], error_type: "path_not_writable" }]) + assert.equal(failed.write_tool_calls.dropped, 3) + + const none = runnerWorkspaceApplyOutcome({ workspaceApply: { status: "no-op", changedFiles: [] }, attempted: true, mutations: ledger([]) }) + assert.equal(none.status, "no-op") + assert.match(none.message, /no workspace write calls/) + assert.equal(none.write_tool_calls.source, "sandbox-ledger") + + const skipped = runnerWorkspaceApplyOutcome({ workspaceApply: { status: "no-op", changedFiles: [] }, attempted: false }) + assert.equal(skipped.status, "skipped") +} + +console.log("runner workspace apply outcome ok") diff --git a/tests/runner-workspace-apply.test.ts b/tests/runner-workspace-apply.test.ts index a260a9188..4ec952201 100644 --- a/tests/runner-workspace-apply.test.ts +++ b/tests/runner-workspace-apply.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { promisify } from "node:util" import { createHash } from "node:crypto" -import { applyRunnerWorkspacePatch, runnerWorkspaceIdentity, verifyRunnerWorkspaceIntegrity } from "../packages/runtime-core/src/runner-workspace-apply.js" +import { applyRunnerWorkspacePatch, runnerWorkspaceIdentity, verifyRunnerWorkspaceIntegrity, writablePathMatches } from "../packages/runtime-core/src/runner-workspace-apply.js" const exec = promisify(execFile) @@ -191,4 +191,67 @@ const files = [{ path: "/workspace/README.md", relativePath: "README.md", status await assert.rejects(() => applyRunnerWorkspacePatch({ artifactRoot: input.artifacts, artifactRefs: input.refs, workspaceRoot: input.workspace, writablePaths: ["README.md"] }), /bounded regular file/) } +{ + // Nested writable globs (issue #2567): a new file under a nested docs tree is + // applied, and the result reports exactly what reached the workspace. + const nestedPatch = "--- /dev/null\n+++ b/plugins/extrachill-shop/docs/user/getting-started.md\n@@ -0,0 +1 @@\n+nested\n" + const nestedFiles = [{ path: "/workspace/plugins/extrachill-shop/docs/user/getting-started.md", relativePath: "plugins/extrachill-shop/docs/user/getting-started.md", status: "added", afterMode: "100644" }] + for (const writablePaths of [["plugins/extrachill-shop/docs/user/**"], ["./plugins/extrachill-shop/docs/user/"], ["plugins/*/docs/user/**"], ["plugins/**/*.md"]]) { + const input = await fixture(nestedPatch, nestedFiles) + const result = await applyRunnerWorkspacePatch({ artifactRoot: input.artifacts, artifactRefs: input.refs, workspaceRoot: input.workspace, writablePaths }) + assert.equal(result.status, "applied", `nested path applies for ${writablePaths.join(",")}`) + assert.deepEqual(result.changedFiles, ["plugins/extrachill-shop/docs/user/getting-started.md"]) + assert.equal(result.declaredChanges, 1) + assert.equal(await readFile(join(input.workspace, "plugins/extrachill-shop/docs/user/getting-started.md"), "utf8"), "nested\n") + } +} + +{ + // Every rejected path is reported with its reason instead of only the first. + const twoPatch = "--- a/README.md\n+++ b/README.md\n@@ -1 +1 @@\n-before\n+after\n--- /dev/null\n+++ b/docs/other.md\n@@ -0,0 +1 @@\n+x\n" + const twoFiles = [...files, { path: "/workspace/docs/other.md", relativePath: "docs/other.md", status: "added", afterMode: "100644" }] + const input = await fixture(twoPatch, twoFiles) + await assert.rejects( + () => applyRunnerWorkspacePatch({ artifactRoot: input.artifacts, artifactRefs: input.refs, workspaceRoot: input.workspace, writablePaths: ["plugins/x/docs/user/**"] }), + (error: Error & { rejectedPaths?: unknown }) => { + assert.match(error.message, /outside writable_paths: README\.md \(2 paths rejected\)/) + assert.deepEqual(error.rejectedPaths, [{ path: "README.md", reason: "outside-writable-paths" }, { path: "docs/other.md", reason: "outside-writable-paths" }]) + return true + }, + ) + assert.equal(await readFile(join(input.workspace, "README.md"), "utf8"), "before\n", "rejection happens before any change is applied") +} + +{ + const input = await fixture("", []) + const result = await applyRunnerWorkspacePatch({ artifactRoot: input.artifacts, artifactRefs: input.refs, workspaceRoot: input.workspace, writablePaths: ["README.md"] }) + assert.equal(result.status, "no-op") + assert.equal(result.declaredChanges, 0) +} + +// Host writable-path matching mirrors the sandbox workspace tools. +for (const [path, pattern, expected] of [ + ["plugins/extrachill-shop/docs/user/a.md", "plugins/extrachill-shop/docs/user/**", true], + ["plugins/extrachill-shop/docs/user/x/a.md", "plugins/extrachill-shop/docs/user/**", true], + ["plugins/extrachill-shop/docs/user", "plugins/extrachill-shop/docs/user/**", true], + ["plugins/extrachill-shop/docs/a.md", "plugins/extrachill-shop/docs/user/**", false], + ["plugins/extrachill-shop/docs/userx/a.md", "plugins/extrachill-shop/docs/user/**", false], + ["docs/user/a.md", "./docs/user/**", true], + ["docs/user/a.md", "/docs/user/", true], + ["docs/a.md", "docs/**/*.md", true], + ["docs/x/y/a.md", "docs/**/*.md", true], + ["docs/x/y/a.txt", "docs/**/*.md", false], + ["plugins/foo/docs/user/a.md", "plugins/*/docs/user/**", true], + ["plugins/foo/bar/docs/user/a.md", "plugins/*/docs/user/**", false], + ["docs/user/a.md", "docs/user/*.md", true], + ["docs/user/x/a.md", "docs/user/*.md", false], + ["docs/a.md", "docs/[!b]*.md", true], + ["docs/b.md", "docs/[!b]*.md", false], + ["README.md", "README.md", true], + ["README.md.bak", "README.md", false], + ["anything.md", ".", false], +] as const) { + assert.equal(writablePathMatches(path, pattern), expected, `${path} vs ${pattern}`) +} + console.log("runner workspace apply ok") diff --git a/tests/runtime-sources-materialization.test.ts b/tests/runtime-sources-materialization.test.ts index 5aa0f2c8e..1334d5cb3 100644 --- a/tests/runtime-sources-materialization.test.ts +++ b/tests/runtime-sources-materialization.test.ts @@ -195,6 +195,37 @@ await withTempDir("wp-codebox-runtime-source-upload-", async (directory) => { const transcriptExclusions = await readFile(join(upload, ".codebox", "agent-task-artifacts", "exclusions.json"), "utf8") assert.match(transcriptExclusions, /canonical_transcripts/) assert.match(transcriptExclusions, /codebox-transcript/) + { + // Issue #2567: the real `wordpress.run-php` execution carries the agent runtime + // result as a JSON-encoded string in parsed.output. The projection must decode + // it so tool-call names and paths reach the uploaded transcript. + const decodedOutput = JSON.stringify({ agent_runtime: { success: true, result: { metadata: { + agents_api: { tool_observability: { version: 1, calls: [{ sequence: 1, turn: 1, tool_call_id: "write-1", tool_name: "client/workspace_write", status: "succeeded", arguments: { keys: ["path", "content"], count: 2, redacted: true } }] } }, + sandbox_workspace_mutations: { schema: "wp-codebox/sandbox-workspace-mutations/v1", dropped: 0, calls: [ + { tool: "workspace_write", status: "succeeded", paths: ["plugins/extrachill-shop/docs/user/getting-started.md"], content: "secret-transcript-value" }, + { tool: "workspace_write", status: "failed", paths: ["../escape.md"], error_type: "writable_path_denied" }, + { tool: "workspace_read", status: "succeeded", paths: ["README.md"] }, + ] }, + } } } }) + const runPhpSource = JSON.stringify({ schema: "wp-codebox/agent-transcript/v1", executions: [{ executionIndex: 4, command: "wordpress.run-php", exitCode: 0, parsed: { command: "wp-codebox.agent-sandbox-run", wp_loaded: true, output: decodedOutput } }] }) + await writeFile(join(artifacts, "files", "transcript.json"), runPhpSource) + const runPhpDigest = createHash("sha256").update(runPhpSource).digest("hex") + const workspaceApply = { schema: "wp-codebox/runner-workspace-apply-outcome/v1", status: "writes-not-applied", message: "The agent made 1 successful workspace write call(s).", applied_paths: [], rejected_paths: [], unapplied_paths: ["plugins/extrachill-shop/docs/user/getting-started.md"], write_tool_calls: { source: "sandbox-ledger", attempted: 1, succeeded: 1, failed: 0, paths: ["plugins/extrachill-shop/docs/user/getting-started.md"] } } + await writeFile(join(workspace, ".codebox", "agent-task-workflow-result.json"), JSON.stringify({ schema: "wp-codebox/agent-task-workflow-result/v1", status: "failed", success: false, workspace_apply: workspaceApply, reviewer_evidence: { transcript: { schema: "wp-codebox/agent-transcript/v1", kind: "codebox-transcript", path: "files/transcript.json", source_sha256: runPhpDigest, size_bytes: Buffer.byteLength(runPhpSource) } } })) + await execFileAsync(process.execPath, [script.pathname], { env: { ...process.env, AGENT_TASK_WORKSPACE: workspace, AGENT_TASK_UPLOAD_PATH: upload, WP_CODEBOX_RUNTIME_SOURCE_ROOT: privateRoot, OPENAI_API_KEY: "secret-transcript-value" } }) + const runPhpTranscript = JSON.parse(await readFile(join(upload, ".codebox", "agent-task-artifacts", "transcript.json"), "utf8")) + const parsed = runPhpTranscript.executions[0].parsed + assert.equal(parsed.tool_observability.calls[0].tool_name, "client/workspace_write", "tool-call names survive the string-encoded runtime output") + assert.deepEqual(parsed.workspace_mutations, { schema: "wp-codebox/sandbox-workspace-mutations/v1", dropped: 0, calls: [ + { tool: "workspace_write", status: "succeeded", paths: ["workspace/plugins/extrachill-shop/docs/user/getting-started.md"] }, + { tool: "workspace_write", status: "failed", paths: [], error_type: "writable_path_denied" }, + ] }, "write paths survive; unsafe paths, contents and read tools do not") + assert.doesNotMatch(JSON.stringify(runPhpTranscript), /secret-transcript-value|escape\.md/) + const stagedApply = JSON.parse(await readFile(join(upload, ".codebox", "agent-task-workflow-result.json"), "utf8")).workspace_apply + assert.equal(stagedApply.status, "writes-not-applied", "the explicit apply outcome is uploaded with the workflow result") + assert.deepEqual(stagedApply.unapplied_paths, ["plugins/extrachill-shop/docs/user/getting-started.md"]) + await writeFile(join(workspace, ".codebox", "agent-task-workflow-result.json"), JSON.stringify({ schema: "wp-codebox/agent-task-workflow-result/v1", status: "succeeded", success: true, reviewer_evidence: reviewerEvidence })) + } await writeFile(join(artifacts, "files", "transcript.json"), `${transcriptSource}\n`) await assert.rejects(execFileAsync(process.execPath, [script.pathname], { env: { ...process.env, AGENT_TASK_WORKSPACE: workspace, AGENT_TASK_UPLOAD_PATH: upload, WP_CODEBOX_RUNTIME_SOURCE_ROOT: privateRoot } }), /digest does not match/, "Uploader rejects stale reviewer evidence digests") await writeFile(join(artifacts, "files", "transcript.json"), transcriptSource)