oficina / equipo Public

Merge branch 'merge-error-detail' into main

Merge merge-error-detail: keep the hub's answer on a failed merge

The runner logs merge and merge-tip error messages, redacted and
bounded, not their types, and a failed merge's report carries the
hub's status, code and message in log_tail (capped at 500 bytes). No
wire change. Hosted CI passed on daa3118.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 55a424a993c6945f68ac68ab03cad7909cf6a787 parent 7140df3parent daa3118
11 files changed, +454 −17
  • .rastrillo/budgets.txt +1 −1
  • internal/equipo/work_views_test.go +20 −0
  • internal/runner/forge/merge.go +85 −10
  • internal/runner/forge/merge_detail_test.go +93 −0
  • internal/runner/thin/engineer.go +9 −0
  • internal/runner/thin/judge.go +3 −1
  • internal/runner/thin/merge.go +9 −3
  • internal/runner/thin/mergedetail_test.go +112 −0
  • internal/runner/thin/mergestep.go +5 −2
  • internal/runnerproto/redact_detail.go +64 −0
  • internal/runnerproto/redact_detail_test.go +53 −0

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index d8ea8bf4..48b650aa 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -34,7 +34,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions.
-size internal/runner/thin 17869 9489 Release previews merged with the first merge into an empty repository (previews move to protocol 9, empty-repository merge keeps 8): measured 17869 source and 9489 test lines. The first merge into an empty repository: merge inspection reads an unborn default (Heads, inspectMerge), a task branch at HEAD is never the default, the merge step says merge_unborn_default and kicks the index after a merge (about 36 lines); their test (TestUnbornDefaultForMerge, about 53 lines): measured 17201/8971. Release previews Astra round 2 adds the credential file checks (no link, exactly 0600, owned, never inside a mounted root, errors without content), the empty account listing and the cancelled reconcile (about 55 lines) and their tests (about 90); measured 17833 source and 9436 test lines. Release previews add the preview step (preview.go: the strict config from git objects, the export from git objects with its caps and digest, the fixed carlos commands each behind a publish check, the marker check that follows no redirect, the restart reconcile, about 560 lines) and its tests (preview_test.go, about 430 lines); measured 17777 source and 9347 test lines. Mac pending cleanup: the warm waits while an attempt's cleanup is pending (5 lines, test 4); measured 17165/8918. Mac simulators before T: quietSimulators shuts every simulator down (bounded) before a T cleanup and logs what is left (about 43 lines), and its test with a hung simctl (about 45 lines); measured 17160/8914. Mac user temp: the Mac host resolves the user's T and refuses an untrusted one (macUserTemp, why in words), gives every gate one turn across the worker and the probe command, and warms Xcode's plugin cache once per Xcode outside the sandbox (warm, warmNow; about 71 lines); its tests pin T on the srt gates, a refused T and the warm's once, retry and turn (about 46 lines); measured 17117/8869. Engineering in an empty repository: the step starts from no base and tells Engineering so, the push names an unborn default, Review reads an initial commit against the empty tree (changeDiff), checks list its files, and a repository whose only branches are task branches stays empty (onlyTaskBranches; about 60 lines); their tests (the task-branch, review diff and prompt tests in index_empty_test.go, about 92 lines): measured 17046/8823. Mac checks wait for the sandbox: macChecks.Run refuses unproven without the dispatch's consent, the consent context, the worker's refusal report and the link's protocol 7 gate (about 38 lines), and their tests (sandbox_consent_test.go, about 131 lines); measured 16986/8731. Mac Xcode scratch: the Mac host test pins the gate's environment (the runner user's HOME kept, no scratch home; 6 lines); measured 16948/8600. Empty repositories merged onto main: measured 16948/8594. Empty repositories: the index lists a reachable repository with no commits as empty, DefaultBranch tells that from no access (lsRemote), reads of it say so, and the handshake hello keeps empty entries back until a protocol 6 welcome (about 52 lines); their tests (index_empty_test.go, the handshake hello at protocols 5 and 6, startLinkWith; about 183 lines). Token row facts merged onto main: measured 16896/8411. Token row facts read the check's rate limit and record it as a turn's (TokenCheck, the Verify wiring, about 40 lines); measured 16614. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. Mac P2 diagnostics hand the probes' host runner.log's WARN (macHost.warn, 8 lines) and pin it with a test (12 lines): measured 16854/8411. Mac probe deadlines bound the booted simctl list, move the worker's wait for the probes out of its lock (hold) and warn when a probe run reaches its limit (about 24 lines); their tests (mac_stall_test.go: a fake xcrun that never answers, probes stalled while an update applies, about 270 lines) beside the Mac host they drive: measured 16846/8399. Release slice 1 merged onto main: measured 16822/8130. Release slice 1 (hosted checks) adds the hub's hosted CI verdict for checks: the deferred one-read poll with its persisted deadline, the one-snapshot verdict, the failing units and the restart case (judge_hosted.go, about 200 lines) and the forge's CI reads (forge.go, about 40); measured 16821. Its tests (judge_hosted_test.go, about 270 lines) take the package's tests to 8113, beside the step engine they drive. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. The paste box house rule merged onto the runner logs: measured 16573. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path.
+size internal/runner/thin 17889 9601 Merge error detail: the merge step reports the hub's status, code and message in its log tail, merge and merge watch errors log their redacted words instead of their type, and ls-remote keeps git's stderr (logDetail, about 20 lines; the merge step and watch tests, about 110); measured 17889 source and 9601 test lines. Release previews merged with the first merge into an empty repository (previews move to protocol 9, empty-repository merge keeps 8): measured 17869 source and 9489 test lines. The first merge into an empty repository: merge inspection reads an unborn default (Heads, inspectMerge), a task branch at HEAD is never the default, the merge step says merge_unborn_default and kicks the index after a merge (about 36 lines); their test (TestUnbornDefaultForMerge, about 53 lines): measured 17201/8971. Release previews Astra round 2 adds the credential file checks (no link, exactly 0600, owned, never inside a mounted root, errors without content), the empty account listing and the cancelled reconcile (about 55 lines) and their tests (about 90); measured 17833 source and 9436 test lines. Release previews add the preview step (preview.go: the strict config from git objects, the export from git objects with its caps and digest, the fixed carlos commands each behind a publish check, the marker check that follows no redirect, the restart reconcile, about 560 lines) and its tests (preview_test.go, about 430 lines); measured 17777 source and 9347 test lines. Mac pending cleanup: the warm waits while an attempt's cleanup is pending (5 lines, test 4); measured 17165/8918. Mac simulators before T: quietSimulators shuts every simulator down (bounded) before a T cleanup and logs what is left (about 43 lines), and its test with a hung simctl (about 45 lines); measured 17160/8914. Mac user temp: the Mac host resolves the user's T and refuses an untrusted one (macUserTemp, why in words), gives every gate one turn across the worker and the probe command, and warms Xcode's plugin cache once per Xcode outside the sandbox (warm, warmNow; about 71 lines); its tests pin T on the srt gates, a refused T and the warm's once, retry and turn (about 46 lines); measured 17117/8869. Engineering in an empty repository: the step starts from no base and tells Engineering so, the push names an unborn default, Review reads an initial commit against the empty tree (changeDiff), checks list its files, and a repository whose only branches are task branches stays empty (onlyTaskBranches; about 60 lines); their tests (the task-branch, review diff and prompt tests in index_empty_test.go, about 92 lines): measured 17046/8823. Mac checks wait for the sandbox: macChecks.Run refuses unproven without the dispatch's consent, the consent context, the worker's refusal report and the link's protocol 7 gate (about 38 lines), and their tests (sandbox_consent_test.go, about 131 lines); measured 16986/8731. Mac Xcode scratch: the Mac host test pins the gate's environment (the runner user's HOME kept, no scratch home; 6 lines); measured 16948/8600. Empty repositories merged onto main: measured 16948/8594. Empty repositories: the index lists a reachable repository with no commits as empty, DefaultBranch tells that from no access (lsRemote), reads of it say so, and the handshake hello keeps empty entries back until a protocol 6 welcome (about 52 lines); their tests (index_empty_test.go, the handshake hello at protocols 5 and 6, startLinkWith; about 183 lines). Token row facts merged onto main: measured 16896/8411. Token row facts read the check's rate limit and record it as a turn's (TokenCheck, the Verify wiring, about 40 lines); measured 16614. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. Mac P2 diagnostics hand the probes' host runner.log's WARN (macHost.warn, 8 lines) and pin it with a test (12 lines): measured 16854/8411. Mac probe deadlines bound the booted simctl list, move the worker's wait for the probes out of its lock (hold) and warn when a probe run reaches its limit (about 24 lines); their tests (mac_stall_test.go: a fake xcrun that never answers, probes stalled while an update applies, about 270 lines) beside the Mac host they drive: measured 16846/8399. Release slice 1 merged onto main: measured 16822/8130. Release slice 1 (hosted checks) adds the hub's hosted CI verdict for checks: the deferred one-read poll with its persisted deadline, the one-snapshot verdict, the failing units and the restart case (judge_hosted.go, about 200 lines) and the forge's CI reads (forge.go, about 40); measured 16821. Its tests (judge_hosted_test.go, about 270 lines) take the package's tests to 8113, beside the step engine they drive. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. The paste box house rule merged onto the runner logs: measured 16573. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path.
time internal/thintest 180s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts, and Astra round 1 eight transition contracts (about 15s; the package measured 126s locally under load). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing a waiting test two seconds after it starts. About 6s alone; loaded CI measured 12.5s.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom.
diff --git a/internal/equipo/work_views_test.go b/internal/equipo/work_views_test.go
index 4bd38e21..8cb09819 100644
--- a/internal/equipo/work_views_test.go
+++ b/internal/equipo/work_views_test.go
@@ -31,6 +31,26 @@ func TestTaskSummaryWords(t *testing.T) {
}
}
+// A merge the hub refused shows the person why: the stopped merge's
+// details carry the hub's status, code and message from the runner's
+// report, as written (the runner redacts and bounds them).
+func TestStoppedMergeShowsTheHubAnswer(t *testing.T) {
+ now := time.Now()
+ tail := "status: 409\ncode: archived\nmessage: this branch is archived; unarchive it before merging"
+ task := wire.Task{ID: "tk1", Creator: "a@example.com", Stage: wire.StageReadyToMerge, Steps: []wire.Step{{Specialist: wire.SpecialistMerge, State: wire.StepFailed, Reason: "merge_failed", Attempt: 1, Terminated: true, LogTail: tail, FinishedAt: &now}}}
+ v := taskLineOf(task, "a@example.com")
+ v.richOf(task, "a@example.com", nil, now)
+ for _, it := range timelineOf(task, v) {
+ if it.Kind == "stopped" && it.Headline == "Amadan did not merge it." {
+ if html := string(pasteBox.Render(it.Markdown)); !strings.Contains(html, "code: archived") || !strings.Contains(html, "message: this branch is archived; unarchive it before merging") {
+ t.Fatalf("details %q", html)
+ }
+ return
+ }
+ }
+ t.Fatalf("no stopped merge in %+v", timelineOf(task, v))
+}
+
// A timeline entry leads with one plain sentence: the specialist's own
// headline when it wrote one, else the first sentence that names no file;
// never a path, cut at a word.
diff --git a/internal/runner/forge/merge.go b/internal/runner/forge/merge.go
index 933f7355..c6f0cc9f 100644
--- a/internal/runner/forge/merge.go
+++ b/internal/runner/forge/merge.go
@@ -7,15 +7,21 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
+ "html"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
+ "regexp"
"slices"
+ "strconv"
"strings"
"syscall"
"time"
+
+ "amadan.net/oficina/equipo/internal/runnerproto"
)
// Merge errors. ErrMergeUncertain is settled by the next MergeBranch for
@@ -35,6 +41,67 @@ var (
ErrMergeUnbornDefault = errors.New("forge: the hub cannot make the first merge into an empty repository")
)
+// HubError is the hub's answer to a merge it did not make: its HTTP
+// status, its machine-readable reason (the JSON "reason") and its
+// sentence (the JSON "error", or a page's text), both redacted and
+// bounded. It wraps the outcome the answer means (ErrMergeConflict,
+// ErrMergeFailed, ErrMergeUncertain, ...), which still decides the
+// step's reason.
+type HubError struct {
+ Status int
+ Code, Message string
+ Err error
+}
+
+func (e *HubError) Error() string {
+ return fmt.Sprintf("%v (hub %s: %s)", e.Err, strings.TrimSpace(strconv.Itoa(e.Status)+" "+e.Code), e.Message)
+}
+
+func (e *HubError) Unwrap() error { return e.Err }
+
+func hubError(res HubMergeResult, err error) error {
+ return &HubError{Status: res.Status, Code: runnerproto.RedactDetail(res.Reason, 64), Message: runnerproto.RedactDetail(res.Message, runnerproto.DetailLimit), Err: err}
+}
+
+// uncertain is ErrMergeUncertain with what is known of why: the hub's
+// answer when it gave one, else the cause's words. Only the words: a
+// cause's own identity (a local refusal, say) never decides the outcome.
+func uncertain(res HubMergeResult, cause error) error {
+ switch {
+ case res.Status != 0:
+ return hubError(res, ErrMergeUncertain)
+ case cause == nil:
+ return ErrMergeUncertain
+ case errors.Is(cause, ErrMergeUncertain):
+ return cause
+ }
+ return fmt.Errorf("%w: %v", ErrMergeUncertain, cause)
+}
+
+// MergeDetail is a failed merge for the step report, a few lines: the
+// hub's status, code and message when it answered, else the error's own
+// words; redacted and bounded either way.
+func MergeDetail(err error) string {
+ var h *HubError
+ switch {
+ case err == nil:
+ return ""
+ case !errors.As(err, &h):
+ return "error: " + runnerproto.RedactDetail(err.Error(), runnerproto.DetailLimit)
+ }
+ out := "status: " + strconv.Itoa(h.Status)
+ if code := runnerproto.RedactDetail(h.Code, 64); code != "" {
+ out += "\ncode: " + code
+ }
+ if msg := runnerproto.RedactDetail(h.Message, runnerproto.DetailLimit); msg != "" {
+ out += "\nmessage: " + msg
+ }
+ return out
+}
+
+// pageTag is markup in an answer that is not JSON (a proxy's error page).
+var pageTag = regexp.MustCompile(`(?s)<(?:script|style)\b.*?</(?:script|style)>|<[^>]*>`)
+
// HubMergeRequest is the hub's merge API body (POST /api/v1/repos/{ns}/
// {repo}/branches/{name}/merge). ExpectSHA is the commit that was judged:
// the hub's instance compares it with the branch under its git lock, so a
@@ -57,7 +124,8 @@ type AgentMeta struct {
// HubMergeResult is the hub's answer: merged with the new commit on Into,
// or a refusal with its machine-readable reason (conflicts, moved,
-// ci_not_green with CIState, up_to_date, no_such_branch, ...).
+// ci_not_green with CIState, up_to_date, no_such_branch, ...) and its
+// sentence (Message, redacted and bounded).
type HubMergeResult struct {
Status int
Merged bool
@@ -66,6 +134,7 @@ type HubMergeResult struct {
BranchClosed bool
Reason string
CIState string
+ Message string
}
type hubMergeBody struct {
@@ -75,6 +144,7 @@ type hubMergeBody struct {
BranchClosed bool `json:"branch_closed"`
Reason string `json:"reason"`
CIState string `json:"ci_state"`
+ Error string `json:"error"`
}
// HubMerge sends one merge request to the hub with the agent's bearer.
@@ -95,21 +165,23 @@ func HubMerge(ctx context.Context, client *http.Client, hub string, cred Credent
hr.Header.Set("Accept", "application/json")
res, err := client.Do(hr)
if err != nil {
- return HubMergeResult{}, ErrMergeUncertain
+ return HubMergeResult{}, fmt.Errorf("%w: %v", ErrMergeUncertain, err)
}
defer res.Body.Close()
var out hubMergeBody
raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
if err != nil || json.Unmarshal(raw, &out) != nil {
+ // Not JSON (a proxy's page, say): its text is the sentence.
+ out = hubMergeBody{Error: html.UnescapeString(pageTag.ReplaceAllString(string(raw), " "))}
if res.StatusCode == http.StatusOK || res.StatusCode >= 500 {
- return HubMergeResult{Status: res.StatusCode}, ErrMergeUncertain
+ return HubMergeResult{Status: res.StatusCode, Message: runnerproto.RedactDetail(out.Error, runnerproto.DetailLimit)}, ErrMergeUncertain
}
- out = hubMergeBody{}
}
// Merged only on a 200 that says so with a commit: anything else is a
// refusal, never a success.
merged := res.StatusCode == http.StatusOK && out.Merged && object.MatchString(out.SHA)
- return HubMergeResult{Status: res.StatusCode, Merged: merged, SHA: out.SHA, Into: out.Into, BranchClosed: out.BranchClosed, Reason: out.Reason, CIState: out.CIState}, nil
+ return HubMergeResult{Status: res.StatusCode, Merged: merged, SHA: out.SHA, Into: out.Into, BranchClosed: out.BranchClosed, Reason: out.Reason, CIState: out.CIState,
+ Message: runnerproto.RedactDetail(out.Error, runnerproto.DetailLimit)}, nil
}
// RemoteState is the repository as the runner reads it: the task
@@ -308,7 +380,7 @@ func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) {
}
st, err := m.Inspect(ctx)
if err != nil {
- return MergeOutcome{}, ErrMergeUncertain
+ return MergeOutcome{}, fmt.Errorf("%w: reading the repository: %v", ErrMergeUncertain, err)
}
if st.Landed {
// Already on the default branch: a request that reached the hub
@@ -330,7 +402,7 @@ func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) {
}
}
if err := m.Confirm(ctx); err != nil {
- return MergeOutcome{}, ErrMergeUncertain
+ return MergeOutcome{}, fmt.Errorf("%w: confirming the lease: %v", ErrMergeUncertain, err)
}
rec.Phase = mergeRequested
if err := m.save(rec); err != nil {
@@ -361,7 +433,7 @@ func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) {
return m.landed(rec, again, true)
}
if rerr != nil || res.Status >= 500 || err != nil {
- return MergeOutcome{}, ErrMergeUncertain
+ return MergeOutcome{}, uncertain(res, rerr)
}
if again.Head != m.Commit {
return MergeOutcome{}, m.refused(rec, res, ErrMergeMoved)
@@ -391,9 +463,12 @@ func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) {
func (m BranchMerge) refused(rec mergeRecord, res HubMergeResult, err error) error {
rec.Phase, rec.Reason = mergeRefusedPh, res.Reason
if serr := m.save(rec); serr != nil {
- return ErrMergeUncertain
+ return uncertain(res, nil)
+ }
+ if res.Status == 0 {
+ return err
}
- return err
+ return hubError(res, err)
}
// SweepMerges removes merge records older than keep.
diff --git a/internal/runner/forge/merge_detail_test.go b/internal/runner/forge/merge_detail_test.go
new file mode 100644
index 00000000..e4c6789e
--- /dev/null
+++ b/internal/runner/forge/merge_detail_test.go
@@ -0,0 +1,93 @@
+package forge
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// The hub's answer to a merge it did not make keeps its status, its
+// machine-readable reason and its sentence, read from its JSON (error,
+// reason) or, for a page, the page's text.
+func TestHubMergeKeepsTheAnswer(t *testing.T) {
+ status, body := 0, ""
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(status)
+ w.Write([]byte(body))
+ }))
+ defer srv.Close()
+ cred := Credential{Agent: "equipo~p@example.com", Bearer: "token-1"}
+ req := HubMergeRequest{ExpectSHA: strings.Repeat("a", 40), Message: "Fix typo", Strategy: "merge", Agent: AgentMeta{Session: "equipo-tk1", Harness: "equipo", Host: "test"}}
+ for _, c := range []struct {
+ status int
+ body string
+ err error
+ reason, message string
+ }{
+ {409, `{"error":"this branch is archived; unarchive it before merging","reason":"archived"}`, nil, "archived", "this branch is archived; unarchive it before merging"},
+ {403, `{"error":"you must be a writer on this repo to do that"}`, nil, "", "you must be a writer on this repo to do that"},
+ {500, "<html><head><title>500</title></head><body><h1>Internal Server Error</h1><p>upstream &amp; down</p></body></html>", ErrMergeUncertain, "", "500 Internal Server Error upstream & down"},
+ } {
+ status, body = c.status, c.body
+ res, err := HubMerge(context.Background(), srv.Client(), srv.URL, cred, "amadan.net/oficina/sample", "equipo/tk1-fix-typo", req)
+ if !errors.Is(err, c.err) || res.Status != c.status || res.Reason != c.reason || res.Message != c.message {
+ t.Fatalf("%d %s: %+v %v", c.status, c.body, res, err)
+ }
+ }
+}
+
+// A refusal or a failure carries the hub's answer (redacted, bounded)
+// and still says which outcome it is; a cause that is not the hub's
+// answer is kept in words only, never as an outcome of its own.
+func TestMergeBranchKeepsTheHubAnswer(t *testing.T) {
+ secret := "Bearer s3cr3t-hub-token at https://agent:s3cr3t-pw@amadan.net/x"
+ for _, c := range []struct {
+ res HubMergeResult
+ want error
+ }{
+ {HubMergeResult{Status: 409, Reason: "archived", Message: "archived; " + secret}, ErrMergeFailed},
+ {HubMergeResult{Status: 409, Reason: "conflicts", Message: "conflicts in README"}, ErrMergeConflict},
+ {HubMergeResult{Status: 502, Reason: "internal", Message: "could not reach the repo instance; " + secret}, ErrMergeUncertain},
+ {HubMergeResult{Status: 409, Reason: "archived", Message: strings.Repeat("long ", 400)}, ErrMergeFailed},
+ } {
+ h := &fakeHub{head: strings.Repeat("a", 40), answer: func(*fakeHub, HubMergeRequest) (HubMergeResult, error) { return c.res, nil }}
+ _, err := MergeBranch(context.Background(), newMerge(t, h))
+ var he *HubError
+ if !errors.Is(err, c.want) || !errors.As(err, &he) || he.Status != c.res.Status || he.Code != c.res.Reason {
+ t.Fatalf("%+v: %v", c.res, err)
+ }
+ detail := MergeDetail(err)
+ if strings.Contains(he.Message, "s3cr3t") || strings.Contains(err.Error(), "s3cr3t") || strings.Contains(detail, "s3cr3t") || len(he.Message) > 500 {
+ t.Fatalf("not redacted or bounded: %q / %q / %q", he.Message, err, detail)
+ }
+ lead, _, _ := strings.Cut(c.res.Message, ";")
+ if !strings.HasPrefix(detail, "status: "+strconv.Itoa(c.res.Status)+"\ncode: "+c.res.Reason+"\nmessage: "+lead[:min(len(lead), 20)]) {
+ t.Fatalf("detail %q", detail)
+ }
+ }
+ // No answer at all: the cause in words, redacted; its own identity
+ // (here a local refusal) never decides the outcome.
+ h := &fakeHub{head: strings.Repeat("a", 40), answer: func(*fakeHub, HubMergeRequest) (HubMergeResult, error) {
+ return HubMergeResult{}, errors.Join(ErrMergeRefused, errors.New(secret))
+ }}
+ _, err := MergeBranch(context.Background(), newMerge(t, h))
+ if !errors.Is(err, ErrMergeUncertain) || errors.Is(err, ErrMergeRefused) || !strings.Contains(err.Error(), "refused by validation") {
+ t.Fatalf("no answer: %v", err)
+ }
+ if d := MergeDetail(err); !strings.HasPrefix(d, "error: ") || strings.Contains(d, "s3cr3t") {
+ t.Fatalf("no answer detail %q", d)
+ }
+ // The remote could not be read: nothing was asked, and the reason says
+ // why.
+ m := newMerge(t, &fakeHub{head: strings.Repeat("a", 40)})
+ m.Inspect = func(context.Context) (RemoteState, error) {
+ return RemoteState{}, errors.New("ls-remote: fatal: repository not found")
+ }
+ if _, err := MergeBranch(context.Background(), m); !errors.Is(err, ErrMergeUncertain) || !strings.Contains(MergeDetail(err), "repository not found") {
+ t.Fatalf("inspect: %v", err)
+ }
+}
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index 1e5dabbe..27319514 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -23,6 +23,7 @@ import (
"amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runner/provider/claude"
"amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/wire"
)
@@ -458,6 +459,14 @@ func (e *Engineer) log(msg string, err error) {
}
}
+// logDetail logs err's own words, redacted and bounded, where log keeps
+// only its type (merges: forge's and git's words, never a provider's).
+func (e *Engineer) logDetail(msg string, err error) {
+ if e.O.Logger != nil && err != nil {
+ e.O.Logger.Warn(msg, "err", runnerproto.RedactDetail(err.Error(), runnerproto.DetailLimit))
+ }
+}
+
func firstNonEmpty(a, b string) string {
if a != "" {
return a
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go
index ae6b48dc..aad97eb3 100644
--- a/internal/runner/thin/judge.go
+++ b/internal/runner/thin/judge.go
@@ -859,7 +859,9 @@ func treeDiff(ctx context.Context, git, gitDir, from, to string, limit int) (str
// past that it stops the command and reports clipped. Nothing beyond
// limit is held in memory.
func boundedOutput(cmd *exec.Cmd, limit int) ([]byte, bool, error) {
- cmd.Stderr = io.Discard
+ if cmd.Stderr == nil {
+ cmd.Stderr = io.Discard
+ }
pipe, err := cmd.StdoutPipe()
if err != nil {
return nil, false, err
diff --git a/internal/runner/thin/merge.go b/internal/runner/thin/merge.go
index 115de307..cfbbd468 100644
--- a/internal/runner/thin/merge.go
+++ b/internal/runner/thin/merge.go
@@ -6,6 +6,7 @@ import (
"database/sql"
"encoding/base64"
"errors"
+ "fmt"
"log/slog"
"os/exec"
"path/filepath"
@@ -14,6 +15,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/wire"
)
@@ -177,7 +179,7 @@ func (m *MergeWatch) Check(ctx context.Context) {
}
if err != nil {
cancel()
- m.log("merge tip", err)
+ m.log("merge tip", fmt.Errorf("%s: %w", repo, err))
continue
}
moved := false
@@ -265,9 +267,11 @@ func (m *MergeWatch) merged(ctx context.Context, repo, branch string, w watch) b
return true
}
+// log says err in its own words, redacted and bounded: git's and the
+// state's, never a provider's.
func (m *MergeWatch) log(msg string, err error) {
if m.Logger != nil && err != nil {
- m.Logger.Warn(msg, "err", sanitize(err))
+ m.Logger.Warn(msg, "err", runnerproto.RedactDetail(err.Error(), runnerproto.DetailLimit))
}
}
@@ -299,9 +303,11 @@ func (c *Clones) Heads(ctx context.Context, repo string, branches []string) (str
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
+ var stderr bytes.Buffer
+ cmd.Stderr = &limitWriter{w: &stderr, n: 2 << 10}
out, clipped, err := boundedOutput(cmd, 1<<20)
if err != nil || clipped {
- return "", "", nil, errors.Join(err, errors.New("ls-remote"))
+ return "", "", nil, errors.Join(err, fmt.Errorf("ls-remote: %s", strings.TrimSpace(stderr.String())))
}
branch, tip, heads := "", "", map[string]string{}
for _, line := range strings.Split(string(out), "\n") {
diff --git a/internal/runner/thin/mergedetail_test.go b/internal/runner/thin/mergedetail_test.go
new file mode 100644
index 00000000..a883dae1
--- /dev/null
+++ b/internal/runner/thin/mergedetail_test.go
@@ -0,0 +1,112 @@
+package thin
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/forge"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// httpHub sends the merge to a fake hub over HTTP, as the runner does.
+type httpHub struct {
+ *hubForge
+ url string
+ client *http.Client
+}
+
+func (h httpHub) Merge(ctx context.Context, repo, branch string, req forge.HubMergeRequest) (forge.HubMergeResult, error) {
+ return forge.HubMerge(ctx, h.client, h.url, forge.Credential{Bearer: "agent-bearer"}, repo, branch, req)
+}
+
+// brokenRemote cannot be read: its error names credentials.
+type brokenRemote struct{ *hubForge }
+
+func (brokenRemote) Remote(context.Context, string) (workspace.Remote, error) {
+ return workspace.Remote{}, errors.New("dial https://agent:s3cr3t-pw@amadan.net/x: Authorization: Bearer s3cr3t-hub-token refused")
+}
+
+// TestMergeStepKeepsTheHubAnswer: when the hub refuses or fails a merge,
+// the runner's log line has the hub's words and the step report has its
+// status, code and message (the log tail the task page shows for a
+// stopped step), redacted and bounded in both; the reason is as before.
+// When the repository cannot be read the hub is never asked, and the
+// report says why.
+func TestMergeStepKeepsTheHubAnswer(t *testing.T) {
+ old := mergeBackoff
+ mergeBackoff = time.Millisecond
+ t.Cleanup(func() { mergeBackoff = old })
+ e, f, r, _ := hubRig(t)
+ logs := &lockedBuffer{}
+ e.O.Logger = slog.New(slog.NewTextHandler(logs, nil))
+ status, body := 0, ""
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(status)
+ w.Write([]byte(body))
+ }))
+ defer srv.Close()
+ e.Forge = httpHub{hubForge: f, url: srv.URL, client: srv.Client()}
+ secret := "Authorization: Bearer s3cr3t-hub-token; see https://agent:s3cr3t-pw@amadan.net/x"
+ long := strings.Repeat("word ", 1000) + "END"
+ for _, c := range []struct {
+ status int
+ body string
+ tail, log string
+ }{
+ {409, `{"error":"this branch is archived; ` + secret + `","reason":"archived"}`, "status: 409\ncode: archived\nmessage: this branch is archived; Authorization: ***; see https://***@amadan.net/x", "hub 409 archived: this branch is archived; Authorization: ***"},
+ {500, "<html><body><h1>Internal Server Error</h1><p>" + secret + "</p></body></html>", "status: 500\nmessage: Internal Server Error Authorization: ***", "hub 500: Internal Server Error Authorization: ***"},
+ {409, `{"error":"` + long + `","reason":"archived"}`, "status: 409\ncode: archived\nmessage: word word", "hub 409 archived: word word"},
+ } {
+ status, body = c.status, c.body
+ before := len(logs.Bytes())
+ rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
+ line := string(logs.Bytes()[before:])
+ if rep.State != wire.StepFailed || rep.Reason != "merge_failed" || !strings.HasPrefix(rep.LogTail, c.tail) {
+ t.Fatalf("%d: report %+v", c.status, rep)
+ }
+ if !strings.Contains(line, "msg=merge") || !strings.Contains(line, c.log) {
+ t.Fatalf("%d: log %q", c.status, line)
+ }
+ if strings.Contains(rep.LogTail+line, "s3cr3t") || strings.Contains(rep.LogTail+line, "END") || len(rep.LogTail) > 600 || len(line) > 800 {
+ t.Fatalf("%d: not redacted or bounded: %q / %q", c.status, rep.LogTail, line)
+ }
+ }
+ f.requests = 0
+ e.Clones.Forge = brokenRemote{f}
+ before := len(logs.Bytes())
+ rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
+ line := string(logs.Bytes()[before:])
+ want := "reading the repository: dial https://***@amadan.net/x: Authorization: *** refused"
+ if rep.Reason != "merge_failed" || !strings.HasPrefix(rep.LogTail, "error: ") || !strings.Contains(rep.LogTail, want) || !strings.Contains(line, want) || f.requests != 0 {
+ t.Fatalf("unreadable: %+v %q (%d requests)", rep, line, f.requests)
+ }
+ if strings.Contains(rep.LogTail+line, "s3cr3t") {
+ t.Fatalf("unreadable, not redacted: %q / %q", rep.LogTail, line)
+ }
+}
+
+// TestMergeWatchLogsWhy: a default branch that cannot be read is logged
+// with the repository and git's own words, not the error's type.
+func TestMergeWatchLogsWhy(t *testing.T) {
+ e, f, r, cand := hubRig(t)
+ ctx := context.Background()
+ if err := e.O.State.AcceptWatch(ctx, "w1", wire.WatchMergeCommand{Person: "p@x", TaskID: "tk1", Repo: r.Repo, Branch: r.Branch, CandidateSHA: cand}); err != nil {
+ t.Fatal(err)
+ }
+ f.dir = filepath.Join(t.TempDir(), "missing.git")
+ logs := &lockedBuffer{}
+ w := &MergeWatch{State: e.O.State, Clones: e.Clones, Git: "/usr/bin/git", Logger: slog.New(slog.NewTextHandler(logs, nil))}
+ w.Check(ctx)
+ got := string(logs.Bytes())
+ if !strings.Contains(got, `msg="merge tip"`) || !strings.Contains(got, r.Repo) || !strings.Contains(got, "does not appear to be a git repository") {
+ t.Fatalf("log %q", got)
+ }
+}
diff --git a/internal/runner/thin/mergestep.go b/internal/runner/thin/mergestep.go
index 2bcfcd69..52a01521 100644
--- a/internal/runner/thin/mergestep.go
+++ b/internal/runner/thin/mergestep.go
@@ -100,6 +100,9 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire.
}
time.Sleep(time.Duration(uncertain+1) * mergeBackoff)
}
+ // Why it did not merge, for the person (the stopped step's log tail):
+ // the hub's status, code and message, or the error's words.
+ rep.LogTail = forge.MergeDetail(err)
if notAuthorized && err != nil {
return fail("merge_not_authorized")
}
@@ -116,7 +119,7 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire.
case err == nil:
// Done: the merge watch for this candidate ends here, so only this
// report says it landed (with the commit and how).
- e.log("merge watch", e.O.State.endWatch(context.WithoutCancel(ctx), r.TaskID, r.CandidateSHA))
+ e.logDetail("merge watch", e.O.State.endWatch(context.WithoutCancel(ctx), r.TaskID, r.CandidateSHA))
rep.State, rep.MergeSHA, rep.Into, rep.Strategy = wire.StepDone, out.SHA, out.Into, out.Strategy
// Where the SHA came from, and its parents when the hub said it: the
// instance offers Undo only for a merge commit the hub named whose
@@ -146,7 +149,7 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire.
case errors.Is(err, forge.ErrMergeRefused):
return fail("policy_rejected")
}
- e.log("merge", err)
+ e.logDetail("merge", err)
return fail("merge_failed")
}
diff --git a/internal/runnerproto/redact_detail.go b/internal/runnerproto/redact_detail.go
new file mode 100644
index 00000000..7d88f013
--- /dev/null
+++ b/internal/runnerproto/redact_detail.go
@@ -0,0 +1,64 @@
+package runnerproto
+
+import (
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// DetailLimit bounds an error's words in a log line or a step report.
+const DetailLimit = 500
+
+var (
+ // A header that carries a credential, its value (and scheme) gone.
+ detailHeader = regexp.MustCompile(`(?i)\b((?:proxy-)?authorization|set-cookie|cookie|x-api-key|private-token)(["']?\s*[:=]\s*["']?)(?:(?:bearer|basic|token|digest|negotiate)\s+)?[^\s,;"']+`)
+ // A URL's userinfo (user:password@).
+ detailUserinfo = regexp.MustCompile(`(?i)\b([a-z][a-z0-9+.-]*://)[^/\s@?#'"]+@`)
+ // A JSON member whose name says it holds a credential.
+ detailJSONKey = regexp.MustCompile(`(?i)("[a-z0-9_-]*(?:token|secret|password|passwd|api[_-]?key|authorization|credentials?)"\s*:\s*")[^"]*"`)
+ // A JSON web token, and any long opaque run (a hub token is 64 hex;
+ // a commit SHA-1, 40, is kept).
+ detailJWT = regexp.MustCompile(`\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*`)
+ detailOpaque = regexp.MustCompile(`\b[A-Za-z0-9_+]{41,}=*`)
+ detailSpace = regexp.MustCompile(`\s+`)
+)
+
+// RedactDetail is an error's words made safe to log or report: no
+// credential (bearer and basic values, Authorization and cookie headers,
+// URL userinfo, credential-named JSON members, known token prefixes,
+// JSON web tokens, long opaque runs), one line without control or
+// format characters, backticks as quotes (it may sit in a code block),
+// and at most limit bytes, the cut marked. Redaction runs before the
+// cut, so a credential across the bound is never half shown.
+func RedactDetail(s string, limit int) string {
+ s = strings.ToValidUTF8(s, "?")
+ s = strings.Map(func(r rune) rune {
+ if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
+ return ' '
+ }
+ if r == '`' {
+ return '\''
+ }
+ return r
+ }, s)
+ s = detailHeader.ReplaceAllString(s, "${1}${2}***")
+ s = detailUserinfo.ReplaceAllString(s, "${1}***@")
+ s = detailJSONKey.ReplaceAllString(s, `${1}***"`)
+ s = detailJWT.ReplaceAllString(s, "***")
+ s = RedactText(s, nil)
+ s = detailOpaque.ReplaceAllString(s, "***")
+ s = strings.TrimSpace(detailSpace.ReplaceAllString(s, " "))
+ if len(s) <= limit {
+ return s
+ }
+ mark := "…"
+ if limit < len(mark) {
+ mark = ""
+ }
+ s = s[:max(limit-len(mark), 0)]
+ for !utf8.ValidString(s) {
+ s = s[:len(s)-1]
+ }
+ return s + mark
+}
diff --git a/internal/runnerproto/redact_detail_test.go b/internal/runnerproto/redact_detail_test.go
new file mode 100644
index 00000000..9efe1093
--- /dev/null
+++ b/internal/runnerproto/redact_detail_test.go
@@ -0,0 +1,53 @@
+package runnerproto_test
+
+import (
+ "strings"
+ "testing"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+// An error's words for a log line or a step report: every credential
+// shape gone, one line, no control characters, never past the bound.
+func TestRedactDetail(t *testing.T) {
+ hex64 := strings.Repeat("ab12", 16)
+ for _, c := range []struct{ in, gone, kept string }{
+ {"Authorization: Bearer s3cr3t-T0ken and more", "s3cr3t-T0ken", "Authorization: *** and more"},
+ {"authorization=token s3cr3t-T0ken", "s3cr3t-T0ken", "authorization=***"},
+ {"proxy-authorization: Basic eDpzM2NyM3Q=", "eDpzM2NyM3Q", "proxy-authorization: ***"},
+ {"bearer s3cr3t-T0ken was refused", "s3cr3t-T0ken", "was refused"},
+ {`fatal: unable to access 'https://x:s3cr3t-pw@amadan.net/ns/repo/': 403`, "s3cr3t-pw", "https://***@amadan.net/ns/repo/"},
+ {`{"error":"no","access_token":"s3cr3t-T0ken"}`, "s3cr3t-T0ken", `"access_token":"***"`},
+ {"cookie: session=s3cr3t-T0ken", "s3cr3t-T0ken", "cookie: ***"},
+ {"token " + hex64 + " rejected", hex64, "rejected"},
+ {"key sk-ant-s3cr3tT0kenValue here", "s3cr3tT0kenValue", "here"},
+ {"jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ4In0.c2lnbmF0dXJl", "eyJzdWIiOiJ4In0", "jwt ***"},
+ // A commit SHA, a task branch and a path are not credentials.
+ {"tip " + strings.Repeat("a", 40) + " on equipo/tk5fen4uajpn-the-first-merge-into-an-empty-one", "", strings.Repeat("a", 40) + " on equipo/tk5fen4uajpn-the-first-merge-into-an-empty-one"},
+ } {
+ got := runnerproto.RedactDetail(c.in, 500)
+ if c.gone != "" && strings.Contains(got, c.gone) || !strings.Contains(got, c.kept) {
+ t.Fatalf("RedactDetail(%q) = %q", c.in, got)
+ }
+ }
+ // Control characters (a forged log line, a terminal escape, a bidi
+ // override) become spaces; backticks cannot close a code block.
+ got := runnerproto.RedactDetail("first\nlevel=ERROR msg=forged\r\x1b[31mred\u202e ```done```", 500)
+ if strings.ContainsAny(got, "\n\r\x1b\u202e`") || got != "first level=ERROR msg=forged [31mred '''done'''" {
+ t.Fatalf("control characters: %q", got)
+ }
+ // Bounded, at a rune, with the cut marked; redaction happens before
+ // the cut, so a credential across the bound is never half shown.
+ long := strings.Repeat("é", 235) + " https://x:s3cr3t-pw@amadan.net/" + strings.Repeat("x ", 100)
+ got = runnerproto.RedactDetail(long, 500)
+ if len(got) > 500 || !utf8.ValidString(got) || !strings.HasSuffix(got, "…") || strings.Contains(got, "s3cr3t") {
+ t.Fatalf("bounded: %d %q", len(got), got)
+ }
+ if got := runnerproto.RedactDetail("x:"+strings.Repeat("y", 300)+"@", 10); len(got) > 10 {
+ t.Fatalf("tiny bound: %q", got)
+ }
+ if got := runnerproto.RedactDetail(string([]byte{0xff, 'o', 'k'}), 500); !utf8.ValidString(got) {
+ t.Fatalf("invalid UTF-8: %q", got)
+ }
+}