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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .github/scripts/run-agent-task/execute-native-agent-task.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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 = ""
Expand Down Expand Up @@ -937,6 +948,7 @@ const result = {
} : {}),
},
runtime_result: redact(runtimeRecord),
...(workspaceApplyOutcome ? { workspace_apply: workspaceApplyOutcome } : {}),
...(reviewerEvidence ? { reviewer_evidence: reviewerEvidence } : {}),
verification,
publication,
Expand Down
34 changes: 33 additions & 1 deletion .github/scripts/run-agent-task/prepare-agent-task-upload.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -238,22 +239,53 @@ 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) }] : []),
tool_calls: tools.slice(0, MAX_TRANSCRIPT_EXECUTIONS).map(projectToolCall),
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)))
}

Expand Down
91 changes: 91 additions & 0 deletions .github/scripts/run-agent-task/runner-workspace-apply-outcome.mjs
Original file line number Diff line number Diff line change
@@ -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,
}
}
Loading
Loading