Merge main into duplicate-keep-decided
Brings in release slice 1 and the Mac probe fixes (b87bdec) before hosted CI. budgets.txt resolved at measured values.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
33 files changed,
+2,473
−83
.rastrillo/budgets.txt+4 −4docs/superpowers/specs/2026-11-11-equipo-release-s1-hosted-checks.md+206 −0docs/superpowers/specs/CODEX-FINDINGS-RELEASE-S1-HOSTED-CHECKS.md+27 −0internal/equipo/chat/merge.go+3 −1internal/equipo/chat/review.go+11 −1internal/equipo/chat/tasks.go+57 −4internal/equipo/migrations/0062_thin_hosted_checks.sql+1 −0internal/equipo/migrations/schema.sql+1 −1internal/runner/forge/ci.go+128 −0internal/runner/forge/ci_test.go+105 −0internal/runner/mac/caps.go+1 −2internal/runner/mac/gate.go+10 −1internal/runner/mac/gate_test.go+16 −2internal/runner/mac/p2why.go+285 −0internal/runner/mac/p2why_test.go+208 −0internal/runner/mac/probe.go+232 −35internal/runner/mac/probe_test.go+72 −16internal/runner/thin/engineer.go+3 −0internal/runner/thin/forge.go+38 −0internal/runner/thin/judge.go+18 −5internal/runner/thin/judge_hosted.go+191 −0internal/runner/thin/judge_hosted_test.go+270 −0internal/runner/thin/mac.go+17 −2internal/runner/thin/mac_stall_test.go+269 −0internal/runner/thin/run.go+1 −1internal/runner/thin/startup_logs_test.go+12 −0internal/runner/thin/step.go+4 −0internal/runner/thin/worker.go+20 −3internal/thintest/hosted_checks_contract_test.go+138 −0internal/wire/runners.go+38 −3internal/wire/runners_test.go+48 −0internal/wire/tasks.go+37 −0scripts/runner-reference-allowlist.json+2 −2
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index be78fd1a..7e51dfbf 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 16573 - 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 16854 8411 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. |
| @@ -49,7 +49,7 @@ perf GET /api/v1/notebook skip Thin v1 person API: bearer-only JSON for devices; |
| perf GET /api/v1/thinking skip Thin v1 person API: bearer-only JSON for devices; the browser reads thinking words on /settings/thinking. |
| perf GET /api/v1/tasks skip Thin v1 person API: bearer-only JSON for devices; the browser reads tasks through /tasks. |
| perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads a task through /tasks/{id}. |
| -size internal/equipo/chat 14110 - The duplicate combine keeps the decided task: the housekeeping view reads each task's newest merge card and marks it Decided (about 12 lines); measured 14110. Turn batching adds turnText, the frame fit (fitTail, batchFull) and the stranded-turn recovery in sync (about 115 lines); measured 14095. The re-run ruling (recheckMayMerge, refreshAfterRecheck, about 70 lines); measured 13981. Merge authority thin v1 adds the gate's store side (mergeauth.go: authorizeMerge before dispatch and at each hub request, the fence for runners below the merge-facts protocol, the ask card in Equipo's words, the ships question, receipts with Undo, the policy tool and API, about 1000 lines); the gate is pure, in internal/equipo/mergegate, but its inputs and audit must be read and written inside the store's transactions. Measured 13204. Mac recheck runs a waiting task's needs_macos checks again when a Mac that fits arrives (macrecheck.go, about 90 lines); measured 12485. Spend 1 merged onto Projects UX: measured 12376 with both. Spend 1 adds a task's spend from its usage rows (TaskSpend, about 60 lines) and the usage rows' round; measured 12047. Projects UX adds per-person project stars with the auto-star reconciliation, the person's and the coordinator's star_project (stars.go, about 210 lines) and the project's own repository in its view; measured 12206. Claude's sign-in by a link adds the code route beside the token's in SendSecret, the sign-in prompt and the kind it becomes (about 40 lines); measured 11933. Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1100 lines). Composer attachments add uploads, the message link, the mailbox relay with chunk frames hydrated from the stored file, and serving (attachments.go, attachments_http.go, about 330 lines); the link and relay run inside the send and dispatch transactions, so they live beside them; sniffing and stripping are pure, in internal/attach. Measured 10292. Merged with UX1 thinking words (f2602d3), measured 9801. Housekeeping slice 1 adds the loop's ledger and state machine, the housekeeping principal's checks inside the shared store functions, reservations, Pause, quiet hours, the digest, claim recovery and the API (housekeeping.go, housekeeping_control.go, housekeeping_http.go, about 1,350 lines); the checks must run inside the store's transactions, so they live beside them; the detectors themselves are pure, in internal/equipo/housekeeping. Measured 9637. Thin v1 UX1 thinking words adds the per-person set and its API (thinking.go, about 100 lines); measured 8305. Connections slice 1 review round 2: the mutation ledger matches record_task by subject only and refuses an ambiguous call with the earlier operations, the preference and forget (about 120 lines); measured 8236. Thin v1 UX1 round 3 adds Equipo combining duplicate tasks reversibly (duplicates.go: detection, the in-transaction fold checks, fold, Undo, about 400 lines) and headlines on findings and steps (headline.go); measured 7898. Connections slice 1 adds connection records from hello and attempts, the connect mailbox, the API, usage rows and the turn's mutation ledger (connections.go and tools.go, about 600 lines); measured 7400 after merging UX1. Thin v1 UX1 adds step activity lines, duplicates and their fold, the coordinator at work on a task, project facts from the runner catalog and open merge cards for the pages (inner.go, about 330 lines); measured 6610 with slice 4c's review fixes. Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep. |
| +size internal/equipo/chat 14175 - The duplicate keep rule merged onto main: measured 14175. The duplicate combine keeps the decided task: the housekeeping view reads each task's newest merge card and marks it Decided (about 12 lines); measured 14110. Turn batching adds turnText, the frame fit (fitTail, batchFull) and the stranded-turn recovery in sync (about 115 lines); measured 14095. The re-run ruling (recheckMayMerge, refreshAfterRecheck, about 70 lines); measured 13981. Merge authority thin v1 adds the gate's store side (mergeauth.go: authorizeMerge before dispatch and at each hub request, the fence for runners below the merge-facts protocol, the ask card in Equipo's words, the ships question, receipts with Undo, the policy tool and API, about 1000 lines); the gate is pure, in internal/equipo/mergegate, but its inputs and audit must be read and written inside the store's transactions. Measured 13204. Mac recheck runs a waiting task's needs_macos checks again when a Mac that fits arrives (macrecheck.go, about 90 lines); measured 12485. Spend 1 merged onto Projects UX: measured 12376 with both. Spend 1 adds a task's spend from its usage rows (TaskSpend, about 60 lines) and the usage rows' round; measured 12047. Projects UX adds per-person project stars with the auto-star reconciliation, the person's and the coordinator's star_project (stars.go, about 210 lines) and the project's own repository in its view; measured 12206. Claude's sign-in by a link adds the code route beside the token's in SendSecret, the sign-in prompt and the kind it becomes (about 40 lines); measured 11933. Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1100 lines). Composer attachments add uploads, the message link, the mailbox relay with chunk frames hydrated from the stored file, and serving (attachments.go, attachments_http.go, about 330 lines); the link and relay run inside the send and dispatch transactions, so they live beside them; sniffing and stripping are pure, in internal/attach. Measured 10292. Merged with UX1 thinking words (f2602d3), measured 9801. Housekeeping slice 1 adds the loop's ledger and state machine, the housekeeping principal's checks inside the shared store functions, reservations, Pause, quiet hours, the digest, claim recovery and the API (housekeeping.go, housekeeping_control.go, housekeeping_http.go, about 1,350 lines); the checks must run inside the store's transactions, so they live beside them; the detectors themselves are pure, in internal/equipo/housekeeping. Measured 9637. Thin v1 UX1 thinking words adds the per-person set and its API (thinking.go, about 100 lines); measured 8305. Connections slice 1 review round 2: the mutation ledger matches record_task by subject only and refuses an ambiguous call with the earlier operations, the preference and forget (about 120 lines); measured 8236. Thin v1 UX1 round 3 adds Equipo combining duplicate tasks reversibly (duplicates.go: detection, the in-transaction fold checks, fold, Undo, about 400 lines) and headlines on findings and steps (headline.go); measured 7898. Connections slice 1 adds connection records from hello and attempts, the connect mailbox, the API, usage rows and the turn's mutation ledger (connections.go and tools.go, about 600 lines); measured 7400 after merging UX1. Thin v1 UX1 adds step activity lines, duplicates and their fold, the coordinator at work on a task, project facts from the runner catalog and open merge cards for the pages (inner.go, about 330 lines); measured 6610 with slice 4c's review fixes. Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep. Release slice 1 (hosted checks) adds the hosted CI offer, the binding's acceptance inside the step report's transaction, the hosted sandbox rule and the fix round's failing units (about 65 lines); measured 14160. Turn batching adds turnText, the frame fit (fitTail, batchFull) and the stranded-turn recovery in sync (about 115 lines); measured 14095. The re-run ruling (recheckMayMerge, refreshAfterRecheck, about 70 lines); measured 13981. Merge authority thin v1 adds the gate's store side (mergeauth.go: authorizeMerge before dispatch and at each hub request, the fence for runners below the merge-facts protocol, the ask card in Equipo's words, the ships question, receipts with Undo, the policy tool and API, about 1000 lines); the gate is pure, in internal/equipo/mergegate, but its inputs and audit must be read and written inside the store's transactions. Measured 13204. Mac recheck runs a waiting task's needs_macos checks again when a Mac that fits arrives (macrecheck.go, about 90 lines); measured 12485. Spend 1 merged onto Projects UX: measured 12376 with both. Spend 1 adds a task's spend from its usage rows (TaskSpend, about 60 lines) and the usage rows' round; measured 12047. Projects UX adds per-person project stars with the auto-star reconciliation, the person's and the coordinator's star_project (stars.go, about 210 lines) and the project's own repository in its view; measured 12206. Claude's sign-in by a link adds the code route beside the token's in SendSecret, the sign-in prompt and the kind it becomes (about 40 lines); measured 11933. Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1100 lines). Composer attachments add uploads, the message link, the mailbox relay with chunk frames hydrated from the stored file, and serving (attachments.go, attachments_http.go, about 330 lines); the link and relay run inside the send and dispatch transactions, so they live beside them; sniffing and stripping are pure, in internal/attach. Measured 10292. Merged with UX1 thinking words (f2602d3), measured 9801. Housekeeping slice 1 adds the loop's ledger and state machine, the housekeeping principal's checks inside the shared store functions, reservations, Pause, quiet hours, the digest, claim recovery and the API (housekeeping.go, housekeeping_control.go, housekeeping_http.go, about 1,350 lines); the checks must run inside the store's transactions, so they live beside them; the detectors themselves are pure, in internal/equipo/housekeeping. Measured 9637. Thin v1 UX1 thinking words adds the per-person set and its API (thinking.go, about 100 lines); measured 8305. Connections slice 1 review round 2: the mutation ledger matches record_task by subject only and refuses an ambiguous call with the earlier operations, the preference and forget (about 120 lines); measured 8236. Thin v1 UX1 round 3 adds Equipo combining duplicate tasks reversibly (duplicates.go: detection, the in-transaction fold checks, fold, Undo, about 400 lines) and headlines on findings and steps (headline.go); measured 7898. Connections slice 1 adds connection records from hello and attempts, the connect mailbox, the API, usage rows and the turn's mutation ledger (connections.go and tools.go, about 600 lines); measured 7400 after merging UX1. Thin v1 UX1 adds step activity lines, duplicates and their fold, the coordinator at work on a task, project facts from the runner catalog and open merge cards for the pages (inner.go, about 330 lines); measured 6610 with slice 4c's review fixes. Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
| @@ -61,6 +61,6 @@ perf GET /conversation/attachments/{id} skip Composer attachments: the bytes of |
| perf GET /conversation/attachments/{id}/preview skip Composer attachments: an image thumbnail inside the conversation; a file, not a screen. |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s Mac runners slice B: TestReleaseRunnerHasNoFakeWorker builds the release runner exactly as make release-runner does and the thin package under the testbuild tag (measured 11.9s locally with a warm cache). |
| -size internal/headless - 8679 The draft stream drive records each draw and the commit (about 27 lines) merged onto the paste box: measured 8679. The paste box merged onto turn batching: measured 8652. The paste box adds its browser drive (browser_paste_test.go, about 130 lines: streaming, copy text, keyboard, scripts off); measured 8464. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. Turn batching merged onto the browser lane: measured 8523. Turn batching adds TestHeadlessTurnBatching (three messages behind a slow turn through the real runner and fake CLI: the one next turn, its input, the bubbles and note, the usage rows and the spend lines) and TestHeadlessBatchAfterRefusedReply (the real runner reconnects after a refused reply), about 190 lines; measured 8518. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. |
| -size internal/thintest - 13747 The duplicate combine keeps the decided task adds staging's Woodstar pair as a contract through the real store (TestContractCombineKeepsDecided, about 60 lines); measured 13747. The InnerScreens transition wait merged onto main: measured 13685. The inner screens drive waits for the row menu's opacity transition to end before it reads the menu at rest (about 7 lines); measured 13251. Turn batching merged onto the ThinkingCycles clock fix (the drive takes a still clock and the page's record of each phrase, about 50 lines): measured 13678. Turn batching merged onto the browser lane: measured 13631. Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch, the note clearing, batches split to fit one frame and the failed batch's note; about 430 lines); measured 13630 with the ship buttons merged. The ship buttons add their contract and browser tests (ships_buttons_test.go, ships_buttons_browser_test.go, about 190 lines); measured 13196. Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness. |
| +size internal/headless - 8679 The duplicate keep rule merged onto main: measured 8679. The draft stream drive records each draw and the commit (about 27 lines) merged onto the paste box: measured 8679. The paste box merged onto turn batching: measured 8652. The paste box adds its browser drive (browser_paste_test.go, about 130 lines: streaming, copy text, keyboard, scripts off); measured 8464. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. Turn batching merged onto the browser lane: measured 8523. Turn batching adds TestHeadlessTurnBatching (three messages behind a slow turn through the real runner and fake CLI: the one next turn, its input, the bubbles and note, the usage rows and the spend lines) and TestHeadlessBatchAfterRefusedReply (the real runner reconnects after a refused reply), about 190 lines; measured 8518. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. Release slice 1 merged onto main: measured 8679. Turn batching merged onto the browser lane: measured 8523. Turn batching adds TestHeadlessTurnBatching (three messages behind a slow turn through the real runner and fake CLI: the one next turn, its input, the bubbles and note, the usage rows and the spend lines) and TestHeadlessBatchAfterRefusedReply (the real runner reconnects after a refused reply), about 190 lines; measured 8518. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. The draft stream drive records each draw and the commit (about 27 lines) merged onto the paste box: measured 8679. The paste box merged onto turn batching: measured 8652. The paste box adds its browser drive (browser_paste_test.go, about 130 lines: streaming, copy text, keyboard, scripts off); measured 8464. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. Turn batching merged onto the browser lane: measured 8523. Turn batching adds TestHeadlessTurnBatching (three messages behind a slow turn through the real runner and fake CLI: the one next turn, its input, the bubbles and note, the usage rows and the spend lines) and TestHeadlessBatchAfterRefusedReply (the real runner reconnects after a refused reply), about 190 lines; measured 8518. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. |
| +size internal/thintest - 13885 The duplicate keep rule merged onto main: measured 13885. The duplicate combine keeps the decided task adds staging's Woodstar pair as a contract through the real store (TestContractCombineKeepsDecided, about 60 lines); measured 13747. The InnerScreens transition wait merged onto main: measured 13685. The inner screens drive waits for the row menu's opacity transition to end before it reads the menu at rest (about 7 lines); measured 13251. Turn batching merged onto the ThinkingCycles clock fix (the drive takes a still clock and the page's record of each phrase, about 50 lines): measured 13678. Turn batching merged onto the browser lane: measured 13631. Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch, the note clearing, batches split to fit one frame and the failed batch's note; about 430 lines); measured 13630 with the ship buttons merged. The ship buttons add their contract and browser tests (ships_buttons_test.go, ships_buttons_browser_test.go, about 190 lines); measured 13196. Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness. Release slice 1 merged onto main: measured 13823. Release slice 1 (hosted checks) adds its contracts (hosted_checks_contract_test.go: the pass that asks, the failure's fix round, every binding rule, the protocol 4 runner; about 140 lines); measured 13816. Turn batching merged onto the ThinkingCycles clock fix (the drive takes a still clock and the page's record of each phrase, about 50 lines): measured 13678. Turn batching merged onto the browser lane: measured 13631. Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch, the note clearing, batches split to fit one frame and the failed batch's note; about 430 lines); measured 13630 with the ship buttons merged. The ship buttons add their contract and browser tests (ships_buttons_test.go, ships_buttons_browser_test.go, about 190 lines); measured 13196. Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness. The InnerScreens transition wait merged onto main: measured 13685. The inner screens drive waits for the row menu's opacity transition to end before it reads the menu at rest (about 7 lines); measured 13251. Turn batching merged onto the ThinkingCycles clock fix (the drive takes a still clock and the page's record of each phrase, about 50 lines): measured 13678. Turn batching merged onto the browser lane: measured 13631. Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch, the note clearing, batches split to fit one frame and the failed batch's note; about 430 lines); measured 13630 with the ship buttons merged. The ship buttons add their contract and browser tests (ships_buttons_test.go, ships_buttons_browser_test.go, about 190 lines); measured 13196. Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness. |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
diff --git a/docs/superpowers/specs/2026-11-11-equipo-release-s1-hosted-checks.md b/docs/superpowers/specs/2026-11-11-equipo-release-s1-hosted-checks.md| new file mode 100644 |
| index 00000000..555a61da |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-11-equipo-release-s1-hosted-checks.md |
| @@ -0,0 +1,206 @@ |
| +# Release slice 1: hosted checks |
| + |
| +Status: 2026-11-11, revision 2. Drafted by Claude (Opus 5.5) on |
| +`release-s1-hosted-checks` from main 577e24c. This is slice 1 of |
| +`2026-11-11-equipo-release.md` (§2.7), approved by Paul as D2. |
| +- Revision 1 (1d7b90d) drew READY AFTER FIXES from Astra, in one round. |
| + The findings are in `CODEX-FINDINGS-RELEASE-S1-HOSTED-CHECKS.md` |
| + beside this spec. |
| +- Revision 2 folds all six findings in, marked **(astra N)**. Where it |
| + could, it cut scope instead of adding machinery. |
| +- Revision 2.1 adds the amadan request number (§5). |
| + |
| +## 0. Why, and the finish line |
| + |
| +A checks step on the primary runs the repository's gate offline in |
| +bubblewrap. Equipo's own gate is written for hosted CI: it pulls an |
| +image, Chromium and tools, and govulncheck needs vuln.go.dev. So on |
| +oficina/equipo every checks step ends `cannot_run needs_network`, even |
| +though hosted CI has already judged the exact commit. |
| + |
| +**Finish line:** |
| +- For a repository with hosted CI on, the checks step reports hosted CI's |
| + own verdict on the exact candidate SHA. The verdict is bound to the |
| + repository, the branch, the SHA and the run's report time. |
| +- A runner restart while the step waits no longer ends it |
| + `runner_restarted`. |
| +- The rename task (`tkataquuxfrw`) on Retry ends `failed`, with hosted |
| + CI's failing steps in its fix round. |
| + |
| +## 1. Rules |
| + |
| +1. **No new credential, no new grant.** The primary reads the hub's bearer |
| + API with the agent credential it already holds for the repository, as |
| + `fileForge.Merge` does. Redirects are refused, and reads are capped. |
| + Workers hold no forge credential and never take this path. |
| +2. **Who decides.** The instance offers hosted checks on every checks |
| + dispatch to the primary (`DispatchCommand.HostedChecks`). |
| + - The runner takes the offer only when `GET .../ci/hosted` answers |
| + `on` and the change does not need macOS (`needsMacOS`). |
| + - Anything else, a read error included, means today's local gate, |
| + unchanged. |
| + - Once taken, the attempt's phase becomes `hosted`, which is |
| + persisted. |
| +3. **Polling is deferred, not held (astra 5).** |
| + - Each run of the attempt confirms the lease, makes one status read |
| + (`GET .../ci/status?branch=<task branch>&logs=none`, 30 s request |
| + timeout, again every 15 s: the engine's deferral interval, as for |
| + merges), and returns `stepDeferred` when there is no verdict yet, |
| + as a merge waiting for CI does. The queue moves on meanwhile. |
| + - The deadline is 60 minutes from the first deferral |
| + (`deferred_since`, persisted), so neither a restart nor a reconnect |
| + resets it. |
| + - Cancel and withdrawal end it at the next run, through the lease. |
| + - Restart recovery runs a `hosted`-phase checks attempt again, as it |
| + does a merge, instead of failing it `runner_restarted`. |
| + - A read error counts as no verdict yet. At the deadline the step |
| + ends `cannot_run checks_timeout`. |
| +4. **One snapshot (astra 2).** A verdict comes only from a response whose |
| + `ns`, `repo` and `branch` equal the request and whose `sha` is the |
| + candidate. |
| + - On `failure`, one `logs=failed` read adds the logs only if its sha, |
| + state and `updated_at` equal the first response's. Otherwise the |
| + report carries the first snapshot's names and summary without logs. |
| + - Another tip, `queued`, `running` and `unknown` all mean no verdict |
| + yet. |
| +5. **Verdicts.** |
| + |
| +| Hub state on the candidate | Checks | Gate | Exit | Reason | `Hosted` | |
| +|---|---|---|---|---|---| |
| +| `success` | `passed` | `hosted CI` | 0 | | yes | |
| +| `failure` | `failed` | `hosted CI` | 1 | | yes | |
| +| `skipped` (no CI script) | `none` | | | | yes | |
| +| `lost`, `stale` | `cannot_run` | | | `checks_unavailable` | yes | |
| +| deadline | `cannot_run` | | | `checks_timeout` | no | |
| + |
| + The output lists the failing unit names first, then the hub's summary, |
| + then the failing logs' tail. It is bounded by `wire.MaxChecksOutput`. |
| +6. **Binding, bounded (astra 2, 6).** `StepReport.Hosted` holds `repo`, |
| + `branch`, `sha`, `state`, `reported_at` (the hub's `updated_at`; the |
| + hub exposes no run id) and `failed` (at most 20 names of 120 bytes, |
| + which the runner truncates). The instance counts a report that carries |
| + `Hosted`, or names gate `hosted CI`, only when all of these hold: |
| + - it comes from the primary, on a connection at protocol 5; |
| + - the step is checks, and `Hosted` is present; |
| + - the repository is the project's own; |
| + - the branch is the task's; |
| + - the SHA is the step's candidate; |
| + - `reported_at` is greater than 0; |
| + - `failed` is within its bounds; |
| + - the state maps to the outcome as in rule 5. |
| + |
| + Anything else is ignored, as a judgement on another SHA is today. The |
| + instance stores the binding in `chat_steps.hosted_ci` (JSON) and sets |
| + `checks_sandbox = hosted`. |
| +7. **Merge authority: checks that ran, not yet sandboxed (astra 1).** A |
| + hosted `passed` or `failed` is a real result: Review gets it, a |
| + failure starts the fix round, and "checks couldn't run" is no longer |
| + the reason. |
| + - **Why not sandboxed:** the hub's status API does not say where a |
| + verdict was produced. `on` is the desired setting, and a verdict |
| + from an ordinary runner survives enabling hosted CI. The hub's own |
| + merge gate on CI is off by default. |
| + - **So:** `checksOutsideSandbox` counts `hosted` as outside the |
| + sandbox. A hosted pass is asked about ("its checks ran outside the |
| + sandbox", existing copy) and never merged on its own. `mergegate` |
| + does not change. |
| + - **Later:** once the hub reports execution provenance and a run id |
| + (an amadan request, §5), hosted can count as sandboxed in its own |
| + change. |
| +8. **Fix round.** For a hosted failure, the feedback first names the |
| + failing units from the stored binding, for example "The repository's |
| + hosted CI failed on 4d28994 in: compile; check shard 5 of 23", then |
| + gives the output's tail. |
| + |
| +## 2. Wire and versions |
| + |
| +- **Protocol 5,** `wire.ProtocolHostedChecks`, becomes |
| + `ProtocolCurrent`. It adds `DispatchCommand.hosted_checks` and |
| + `StepReport.hosted`, both `omitempty`. |
| +- **Downgrade, `downgradeHostedChecks` (astra 3):** |
| + - It drops the offer for any peer below 5. |
| + - It turns a hosted-derived report into `cannot_run |
| + checks_unavailable`, with no gate, no exit code and no `hosted`. A |
| + stripped report never keeps a `passed` an old instance would accept |
| + unbound. |
| + - It runs first, and the later steps keep the accumulated flag. |
| + |
| +| Combination | Behaviour | |
| +|---|---| |
| +| new instance, runner at 4 | no offer, so the local gate as today | |
| +| old instance, new runner | spoken 4, so no offer. A hosted report still in flight from before reaches the old instance as `cannot_run` | |
| +| new runner rolled back to an old binary (astra 4) | not transparent. The old binary fails held checks `runner_restarted`, and an unacknowledged report with `hosted` in the outbox would be refused by a protocol 4 instance's strict decoder. Rule: roll a runner back below protocol 5 only after it has delivered its outbox, as for every earlier bump that added report fields (merge facts' `change`). The release plan's runner-state proof (§2.6 item 4) will test it | |
| + |
| +## 3. Changes |
| + |
| +- **`wire`:** `ProtocolHostedChecks`, the two fields, `HostedResult` |
| + with its bounds, `GateHosted`, `SandboxHosted`, and the semantic |
| + downgrade. |
| +- **`runner/forge`:** `HubCIHosted` and `HubCIStatus`. They send the |
| + bearer, escape the path, refuse redirects, cap the read (64 KiB and |
| + 4 MiB), and check the answer's identity. |
| +- **`runner/thin`:** |
| + - an optional `HostedCI` interface, met by `fileForge`; |
| + - `hostedChecks`, which runs in deferred steps; |
| + - `phaseHosted`, and its case in restart recovery. |
| +- **`equipo/chat`:** |
| + - dispatch sets the flag for checks on the primary; |
| + - `stepReport` validates and stores the binding; |
| + - `checksOutsideSandbox` counts `hosted`; |
| + - `feedback` names the failing units. |
| +- **Migration** `0062_thin_hosted_checks.sql`: `chat_steps.hosted_ci` |
| + text. It is additive, and the model and snapshot are updated. |
| +- **Budgets:** the sizes for `internal/runner/thin`, |
| + `internal/equipo/chat` and the touched test packages, with reasons. |
| +- **No new UI copy.** |
| + |
| +## 4. Tests, failing first |
| + |
| +- **wire:** below 5, `Encode` drops the offer, and turns a hosted |
| + `passed` into `cannot_run`. The result decodes strictly at protocols 4, |
| + 3, 2 and 1. At 5 it passes through unchanged. |
| +- **forge:** |
| + - the bearer and the path; |
| + - an answer for another branch, ns or repo is refused; |
| + - a malformed sha; |
| + - caps; |
| + - a redirect is refused and not followed; |
| + - a refusal, a bad repository, another logs mode, and a bearer with a |
| + newline. |
| +- **thin**, with a fake `HostedCI`: |
| + - pending defers, and unrelated work runs meanwhile; |
| + - a pass and a failure, each from one snapshot; a failure whose |
| + enrichment moved keeps no logs; |
| + - `skipped`, `lost`, and the deadline, measured from `deferred_since`; |
| + - hosted off, a read error on `hosted`, or no offer gives the local |
| + gate, as does a macOS change; |
| + - after a restart the step runs again, without `runner_restarted`; |
| + - cancel ends it; |
| + - the names are bounded. |
| +- **thintest contracts:** |
| + - a hosted pass leads to review and approval, and the merge then asks |
| + with the sandbox reason and does not act; |
| + - a hosted failure starts a fix round that names the units; |
| + - every binding rule is checked on its own, and the report is ignored; |
| + - a protocol 4 rig gets no offer. |
| +- **Mutations:** every rule 6 guard, the identity check in rule 4, the |
| + deadline, the downgrade and the sandbox rule is broken once, and its |
| + test is seen to fail. |
| + |
| +## 5. Out of scope, and follow-ups |
| + |
| +- Hosted checks on Mac workers. |
| +- Retrying steps already ended `runner_restarted`. Retry stays a person's |
| + tap. |
| + |
| +### v2: automatic merge on hosted passes |
| + |
| +Filed as amadan/amadan#136, which cross-references #131. It asks for a |
| +status read by commit SHA that returns the run id and the run's executor: |
| +`hosted` (one of amadan's single-use VMs, with the job credential scoped |
| +as today) or `runner`. |
| + |
| +Once it lands, a hosted verdict binds to the run id instead of the report |
| +time. Hosted CI then counts as sandboxed only when the executor is |
| +`hosted`, and a pass may merge on its own under merge authority. That |
| +change is a spec of its own. |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-RELEASE-S1-HOSTED-CHECKS.md b/docs/superpowers/specs/CODEX-FINDINGS-RELEASE-S1-HOSTED-CHECKS.md| new file mode 100644 |
| index 00000000..c916629a |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-RELEASE-S1-HOSTED-CHECKS.md |
| @@ -0,0 +1,27 @@ |
| +READY AFTER FIXES |
| + |
| +All findings are **Important**, ordered by impact. Hub citations refer to the locally inspected `origin/main`. |
| + |
| +1. **Hosted enablement does not prove that a verdict came from hosted execution.** Rule 2 checks only `on`, but that field is `DesiredOn` (Hub `internal/hub/hosted_optin.go:152`). Enabling hosted CI leaves existing verdicts intact (`internal/repod/store_ci_hosted.go:102`). The status endpoint returns the general commit verdict without execution provenance (`internal/hub/ci_status_api.go:215`). An earlier ordinary runner’s success can therefore become `SandboxHosted`, enabling automatic merge through [gate.go:225](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/equipo/mergegate/gate.go:225). The claimed backup is also conditional: Hub `internal/repod/git_merge.go:443` bypasses the green check when disabled, and `internal/repod/store_merge.go:38` defaults it off. |
| + |
| + **Fix:** Require trustworthy hosted-run provenance before granting sandboxed-check treatment; otherwise require confirmation. Add a contract covering an ordinary green result followed by hosted enablement, with the hub merge gate disabled. |
| + |
| +2. **The response-to-report binding and second-read consistency rules are incomplete.** Rules 4 and 7 require matching SHA and report metadata, but never explicitly require comparing the hub response’s namespace, repository and branch with the request before constructing that metadata. The hub supplies those fields (`internal/hub/ci_status_api.go:215`). Rule 6’s second `logs=failed` request resolves the branch tip again (`internal/hub/ci_status_api.go:191`), so a branch move or rerun can attach another result’s names and logs to the first failure. `reported_at` is carried but has no validation rule. |
| + |
| + **Fix:** Validate response identity before constructing `Hosted`; define and validate the timestamp. Build verdict, binding, names and logs from one validated response snapshot. If enrichment fails or changes identity, retain only evidence from the original snapshot or continue polling. Test wrong-response identity, branch movement, same-SHA reruns and failed enrichment. Validate bindings for hosted `skipped`, `lost` and `stale` reports too, rather than conditioning validation solely on a nonempty gate. |
| + |
| +3. **Downgrading only the new fields can silently discard the authority evidence.** A v5 runner may already hold a hosted dispatch or completed report when it reconnects to a v4 instance. Clearing `hosted` preserves `passed`, exit zero and gate `hosted CI`. The old [judgement validator at tasks.go:1125](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/equipo/chat/tasks.go:1125) accepts that result without binding validation. The compatibility table covers fresh dispatches only. |
| + |
| + **Fix:** Specify a semantic downgrade for existing hosted results, such as `cannot_run/checks_unavailable`, rather than stripping their evidence alone. Test queued and completed v5 work reconnecting at v4, plus strict decoding at every supported lower protocol. Preserve the accumulated downgrade-change flag when modifying [runners.go:377](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/wire/runners.go:377). |
| + |
| +4. **Runner state rollback is not transparent.** Although dispatch bodies use `json.Unmarshal`, startup recovery marks checks attempts `runner_restarted`; it does not execute the local gate ([step.go:380](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/runner/thin/step.go:380)). Completed reports pose another problem: unacknowledged outbox bodies remain raw JSON ([state.go:194](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/runner/thin/state.go:194)). An old runner sending to a v4 peer returns those frames unchanged from [Encode at runners.go:366](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/wire/runners.go:366); the old receiver rejects `hosted` through [frames.go:174](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/wire/frames.go:174). |
| + |
| + **Fix:** Define a tested drain or conversion procedure before reusing v5 state with an old binary, or explicitly prohibit that rollback. Correct the recovery promise. Cover both persisted dispatches and unacknowledged hosted reports using the actual old reader. |
| + |
| +5. **An hour-long polling call would monopolize the runner’s step queue.** Engineering, review and specialist questions execute serially ([step.go:553](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/runner/thin/step.go:553)). Existing CI merge waits deliberately defer and release that queue ([mergestep.go:106](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/runner/thin/mergestep.go:106)). |
| + |
| + **Fix:** Specify deferred hosted polling with a persistent start/deadline, bounded requests and cancellation-aware waits. Define status-read error behavior after opting into hosted checks. Add tests proving unrelated work proceeds, cancellation and withdrawal stop polling, and reconnects do not reset the timeout. Explicitly test the chosen restart behavior. |
| + |
| +6. **The new binding has no size budget.** Bounding `Output` does not bound `Hosted.failed[]`. A permitted 4 MiB response can produce a report exceeding the 256 KiB frame limit ([api.go:452](/home/paulca/amadan.net/oficina/equipo-release-s1/internal/wire/api.go:452)), causing repeated rejection of a durable report. |
| + |
| + **Fix:** Bound failed-unit count, individual names and total serialized binding size before enqueueing and when accepting reports. Reserve frame space for existing fields. Test oversized names/lists and verify truncated feedback still identifies failures without breaking delivery. |
| \ No newline at end of file |
diff --git a/internal/equipo/chat/merge.go b/internal/equipo/chat/merge.go| index bbe7ed8a..8635a631 100644 |
| --- a/internal/equipo/chat/merge.go |
| +++ b/internal/equipo/chat/merge.go |
| @@ -41,7 +41,9 @@ func (p progress) mergeAllowed(withoutChecks bool) bool { |
| // (passed only for repositories the creator owns, spec §4.3), Equipo |
| // never merges those on its own: the creator is asked, "Merge <title>?". |
| func (p progress) checksOutsideSandbox() bool { |
| - return p.checks != nil && p.checks.ChecksSandbox == wire.SandboxNone |
| + // Hosted CI's verdict counts as checks that ran, but the hub cannot |
| + // yet say where it ran (release slice 1), so it is never sandboxed. |
| + return p.checks != nil && (p.checks.ChecksSandbox == wire.SandboxNone || p.checks.ChecksSandbox == wire.SandboxHosted) |
| } |
| // startMerge dispatches the merge step for the judged candidate, decided |
diff --git a/internal/equipo/chat/review.go b/internal/equipo/chat/review.go| index c019a211..760fd271 100644 |
| --- a/internal/equipo/chat/review.go |
| +++ b/internal/equipo/chat/review.go |
| @@ -270,7 +270,17 @@ func (t *txn) fixRound(k *taskRecord, p progress, steps []stepRecord) error { |
| // Engineering fix round's brief. |
| func feedback(p progress) string { |
| var b strings.Builder |
| - if c := p.checks; c != nil && c.Checks == wire.ChecksFailed { |
| + if c := p.checks; c != nil && c.Checks == wire.ChecksFailed && c.ChecksSandbox == wire.SandboxHosted { |
| + var h wire.HostedResult |
| + _ = json.Unmarshal([]byte(c.HostedCI), &h) |
| + fmt.Fprintf(&b, "The repository's hosted CI failed on %s", short(p.candidate)) |
| + if len(h.Failed) > 0 { |
| + b.WriteString(" in: " + strings.Join(h.Failed, "; ")) |
| + } |
| + b.WriteString(". The end of its output:\n") |
| + lines := strings.Split(strings.TrimRight(c.Output, "\n"), "\n") |
| + b.WriteString(strings.Join(lines[max(0, len(lines)-60):], "\n") + "\n") |
| + } else if c != nil && c.Checks == wire.ChecksFailed { |
| code := -1 |
| if c.ExitCode != nil { |
| code = *c.ExitCode |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index e6fd158a..17cd2316 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -187,6 +187,9 @@ type stepRecord struct { |
| // RecheckBy is the runner whose arrival ran these checks again, after |
| // they waited for a Mac (macrecheck.go). Set only at creation. |
| RecheckBy string |
| + // HostedCI is the binding of a checks verdict taken from the hub's |
| + // hosted CI (wire.HostedResult JSON; ChecksSandbox is then hosted). |
| + HostedCI string |
| } |
| func (stepRecord) TableName() string { return "chat_steps" } |
| @@ -500,7 +503,7 @@ func (t *txn) saveStep(s *stepRecord, k *taskRecord) error { |
| } |
| s.Revision++ |
| s.UpdatedAt = t.now() |
| - if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents").Updates(s).Error; err != nil { |
| + if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci").Updates(s).Error; err != nil { |
| return err |
| } |
| members, err := t.members() |
| @@ -796,6 +799,9 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error { |
| return err |
| } |
| cmd.RunnerID = s.RunnerID |
| + // The primary may take the hub's hosted CI verdict for checks (a |
| + // protocol 5 runner; Encode drops the offer for older ones). |
| + cmd.HostedChecks = s.Specialist == wire.SpecialistChecks && s.RunnerID == primary |
| if s.RunnerID != primary { |
| // Placed on a worker: what it needs, and the candidate relayed |
| // from the primary as a pack in an inbound transfer. |
| @@ -1043,6 +1049,14 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| if !judgement(s.Specialist, v) || v.CandidateSHA != s.CandidateSHA || !v.Termination { |
| return nil |
| } |
| + var pr projectRecord |
| + if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil { |
| + return err |
| + } |
| + hosted, ok := acceptHosted(l, role, s, pr.Repo, k.Branch, v) |
| + if !ok { |
| + return nil |
| + } |
| s.Reason, s.Verdict, s.ReviewLabel, s.Checks, s.Gate, s.ExitCode = v.Reason, v.Verdict, v.ReviewLabel, v.Checks, v.Gate, v.ExitCode |
| if s.Specialist == wire.SpecialistChecks && role == wire.RoleWorker { |
| // A worker's word on how its checks were confined; |
| @@ -1065,9 +1079,8 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| } |
| } |
| s.Output = clipText(v.Output, wire.MaxChecksOutput) |
| - var pr projectRecord |
| - if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil { |
| - return err |
| + if hosted != "" { |
| + s.HostedCI, s.ChecksSandbox = hosted, wire.SandboxHosted |
| } |
| // Merge authority: the review's measured change, kept only |
| // when it is exactly this attempt's, whole, from the primary. |
| @@ -1118,6 +1131,46 @@ func firstSet(a, b string) string { |
| // judgement reports whether a done report carries a whole result for a |
| // checks or review step. |
| +// acceptHosted judges a checks report's hosted CI binding (release slice |
| +// 1): none, and no hosted gate, is an ordinary report (ok, ""). With one, |
| +// it counts only from the primary on a protocol 5 connection, for exactly |
| +// the project's repository, the task's branch and the step's candidate, |
| +// with a report time, its failing units within bounds and its state |
| +// matching the outcome; then ok and the binding to store. |
| +func acceptHosted(l Lease, role string, s stepRecord, repo, branch string, v *wire.StepReport) (string, bool) { |
| + h := v.Hosted |
| + if h == nil { |
| + return "", v.Gate != wire.GateHosted |
| + } |
| + if s.Specialist != wire.SpecialistChecks || role != wire.RolePrimary || l.Protocol < wire.ProtocolHostedChecks { |
| + return "", false |
| + } |
| + if h.Repo != repo || h.Branch != branch || h.SHA != s.CandidateSHA || h.ReportedAt <= 0 || len(h.Failed) > wire.MaxHostedFailed { |
| + return "", false |
| + } |
| + for _, name := range h.Failed { |
| + if _, ok := cleanText(name, wire.MaxHostedName); !ok || strings.ContainsAny(name, "\n\r") { |
| + return "", false |
| + } |
| + } |
| + var fits bool |
| + switch h.State { |
| + case wire.HostedSuccess: |
| + fits = v.Checks == wire.ChecksPassed && v.Gate == wire.GateHosted |
| + case wire.HostedFailure: |
| + fits = v.Checks == wire.ChecksFailed && v.Gate == wire.GateHosted |
| + case "skipped": |
| + fits = v.Checks == wire.ChecksNone |
| + case "lost", "stale": |
| + fits = v.Checks == wire.ChecksCannotRun && v.Reason == "checks_unavailable" |
| + } |
| + if !fits { |
| + return "", false |
| + } |
| + raw, _ := json.Marshal(wire.HostedResult{Repo: h.Repo, Branch: h.Branch, SHA: h.SHA, State: h.State, ReportedAt: h.ReportedAt, Failed: append([]string{}, h.Failed...)}) |
| + return string(raw), true |
| +} |
| + |
| func judgement(specialist string, v *wire.StepReport) bool { |
| switch specialist { |
| case wire.SpecialistChecks: |
diff --git a/internal/equipo/migrations/0062_thin_hosted_checks.sql b/internal/equipo/migrations/0062_thin_hosted_checks.sql| new file mode 100644 |
| index 00000000..ec07a5ea |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0062_thin_hosted_checks.sql |
| @@ -0,0 +1 @@ |
| +ALTER TABLE chat_steps ADD COLUMN hosted_ci text; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index d1a49444..4dee3a6d 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -598,7 +598,7 @@ CREATE INDEX chat_card_task ON chat_cards(task_id); |
| CREATE TABLE chat_project_attachments (project_id text, kind text, ref text, name text, created_at datetime, PRIMARY KEY (project_id, kind, ref)); |
| CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text, folded_into text, folded_stage text, folded_at datetime, engineering_runner text, merge_hold text, merge_verified numeric, revert_of text, revert_sha text); |
| CREATE INDEX chat_task_project ON chat_tasks(project_id); |
| -CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text); |
| +CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text, hosted_ci text); |
| CREATE INDEX chat_step_task ON chat_steps(task_id); |
| CREATE TABLE chat_task_entries (id text PRIMARY KEY, task_id text, idempotency_key text, kind text, author text, text text, repo text, path text, line integer, created_at datetime, headline text, folded_from text); |
| CREATE INDEX chat_entry_task ON chat_task_entries(task_id); |
diff --git a/internal/runner/forge/ci.go b/internal/runner/forge/ci.go| new file mode 100644 |
| index 00000000..d98b1c7e |
| --- /dev/null |
| +++ b/internal/runner/forge/ci.go |
| @@ -0,0 +1,128 @@ |
| +package forge |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| +) |
| + |
| +// ErrCIRead means the hub's CI answer could not be read: a refused or |
| +// failed request, a redirect, an oversized or unreadable body. Callers |
| +// treat it as "not known", never as a verdict. |
| +var ErrCIRead = errors.New("forge: the hub's CI answer could not be read") |
| + |
| +// CI status logs modes the hub knows: none for a poll, failed for the |
| +// logs of the units that failed. |
| +const ( |
| + CILogsNone = "none" |
| + CILogsFailed = "failed" |
| +) |
| + |
| +// CIStatus is the hub's verdict on a branch's tip, as GET /api/v1/repos/ |
| +// {ns}/{repo}/ci/status?branch= reports it (amadan discussion #8): the tip |
| +// it judged, the run's state, when the hub recorded it, its one-line |
| +// summary of what failed, and the workflow's steps and shards. |
| +type CIStatus struct { |
| + NS string `json:"ns"` |
| + Repo string `json:"repo"` |
| + Branch string `json:"branch"` |
| + SHA string `json:"sha"` |
| + State string `json:"state"` |
| + Summary string `json:"summary"` |
| + UpdatedAt int64 `json:"updated_at"` |
| + Log string `json:"log"` |
| + Steps []CIStep `json:"steps"` |
| +} |
| + |
| +// CIStep is one step of a run, with its shards when it is sharded. |
| +type CIStep struct { |
| + Name string `json:"name"` |
| + State string `json:"state"` |
| + Log string `json:"log"` |
| + Shards []CIShard `json:"shards"` |
| +} |
| + |
| +// CIShard is one shard of a sharded step. |
| +type CIShard struct { |
| + Name string `json:"name"` |
| + State string `json:"state"` |
| + Log string `json:"log"` |
| +} |
| + |
| +// Read caps: the hosted answer is a handful of fields; a status with the |
| +// failing units' logs is bounded by the hub's own log budget. |
| +const ( |
| + maxCIHostedBody = 64 << 10 |
| + maxCIStatusBody = 4 << 20 |
| +) |
| + |
| +// HubCIHosted asks the hub whether it runs repo's CI on its own machines |
| +// (GET /api/v1/repos/{ns}/{repo}/ci/hosted, any member). |
| +func HubCIHosted(ctx context.Context, client *http.Client, hub string, cred Credential, repo string) (bool, error) { |
| + var out struct { |
| + On *bool `json:"on"` |
| + } |
| + if err := ciGet(ctx, client, hub, cred, repo, "/ci/hosted", nil, maxCIHostedBody, &out); err != nil { |
| + return false, err |
| + } |
| + if out.On == nil { |
| + return false, ErrCIRead |
| + } |
| + return *out.On, nil |
| +} |
| + |
| +// HubCIStatus reads the hub's CI verdict on branch's tip, with logs |
| +// (CILogsNone or CILogsFailed). |
| +func HubCIStatus(ctx context.Context, client *http.Client, hub string, cred Credential, repo, branch, logs string) (CIStatus, error) { |
| + if !validRef(branch) || logs != CILogsNone && logs != CILogsFailed { |
| + return CIStatus{}, ErrCIRead |
| + } |
| + var out CIStatus |
| + if err := ciGet(ctx, client, hub, cred, repo, "/ci/status", url.Values{"branch": {branch}, "logs": {logs}}, maxCIStatusBody, &out); err != nil { |
| + return CIStatus{}, err |
| + } |
| + // The answer must be about exactly what was asked. |
| + parts := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") |
| + if out.NS != parts[0] || out.Repo != parts[1] || out.Branch != branch || out.State == "" || out.SHA != "" && !object.MatchString(out.SHA) { |
| + return CIStatus{}, ErrCIRead |
| + } |
| + return out, nil |
| +} |
| + |
| +func ciGet(ctx context.Context, client *http.Client, hub string, cred Credential, repo, suffix string, q url.Values, limit int64, out any) error { |
| + if !validRepository(repo) || cred.Bearer == "" || strings.ContainsAny(cred.Bearer, "\r\n") { |
| + return ErrCIRead |
| + } |
| + parts := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") |
| + endpoint := strings.TrimRight(hub, "/") + "/api/v1/repos/" + url.PathEscape(parts[0]) + "/" + url.PathEscape(parts[1]) + suffix |
| + if len(q) > 0 { |
| + endpoint += "?" + q.Encode() |
| + } |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) |
| + if err != nil { |
| + return ErrCIRead |
| + } |
| + req.Header.Set("Authorization", "Bearer "+cred.Bearer) |
| + req.Header.Set("Accept", "application/json") |
| + // The bearer goes to the hub only: a redirect is refused, not followed. |
| + c := *client |
| + c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| + res, err := c.Do(req) |
| + if err != nil { |
| + return fmt.Errorf("%w: %v", ErrCIRead, err) |
| + } |
| + defer res.Body.Close() |
| + if res.StatusCode != http.StatusOK { |
| + return fmt.Errorf("%w: status %d", ErrCIRead, res.StatusCode) |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(res.Body, limit+1)) |
| + if err != nil || int64(len(raw)) > limit || json.Unmarshal(raw, out) != nil { |
| + return ErrCIRead |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/forge/ci_test.go b/internal/runner/forge/ci_test.go| new file mode 100644 |
| index 00000000..95349ddd |
| --- /dev/null |
| +++ b/internal/runner/forge/ci_test.go |
| @@ -0,0 +1,105 @@ |
| +package forge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// TestHubCIReads: both reads send the agent's bearer to the hub's path |
| +// for the repository, ask for the branch and logs given, and decode the |
| +// verdict. Anything the hub did not plainly answer (a refusal, a redirect, |
| +// an oversized or unreadable body, another branch) is ErrCIRead, never a |
| +// verdict. |
| +func TestHubCIReads(t *testing.T) { |
| + sha := strings.Repeat("2", 40) |
| + var got, stolen []string |
| + elsewhere := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + stolen = append(stolen, r.Header.Get("Authorization")) |
| + _, _ = w.Write([]byte(`{"ns":"oficina","repo":"sample","branch":"equipo/tk1-fix-teh","state":"success"}`)) |
| + })) |
| + defer elsewhere.Close() |
| + body := map[string]string{} |
| + status := map[string]int{} |
| + hub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + got = append(got, r.Method+" "+r.URL.Path+"?"+r.URL.RawQuery+" "+r.Header.Get("Authorization")) |
| + if code := status[r.URL.Path]; code != 0 { |
| + if code == http.StatusFound { |
| + w.Header().Set("Location", elsewhere.URL+"/steal") |
| + } |
| + w.WriteHeader(code) |
| + return |
| + } |
| + _, _ = w.Write([]byte(body[r.URL.Path])) |
| + })) |
| + defer hub.Close() |
| + cred := Credential{Bearer: "agent-token"} |
| + ctx := context.Background() |
| + const repo, branch = "amadan.net/oficina/sample", "equipo/tk1-fix-teh" |
| + |
| + body["/api/v1/repos/oficina/sample/ci/hosted"] = `{"available":true,"on":true,"vcpu":32}` |
| + if on, err := HubCIHosted(ctx, hub.Client(), hub.URL, cred, repo); err != nil || !on { |
| + t.Fatalf("hosted %v %v", on, err) |
| + } |
| + body["/api/v1/repos/oficina/sample/ci/status"] = `{"ns":"oficina","repo":"sample","branch":"equipo/tk1-fix-teh","sha":"` + sha + `","state":"failure","label":"CI failed","summary":"step \"compile\" failed","updated_at":1794402264,"steps":[{"name":"compile","state":"failure","log":"budget size: 1 problem"},{"name":"check","state":"success","shards":[{"index":0,"name":"shard 0 of 2","state":"success"}]}]}` |
| + st, err := HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, CILogsFailed) |
| + if err != nil || st.SHA != sha || st.State != "failure" || st.UpdatedAt != 1794402264 || len(st.Steps) != 2 || st.Steps[0].Log != "budget size: 1 problem" || st.Steps[1].Shards[0].Name != "shard 0 of 2" { |
| + t.Fatalf("status %+v %v", st, err) |
| + } |
| + want := []string{ |
| + "GET /api/v1/repos/oficina/sample/ci/hosted? Bearer agent-token", |
| + "GET /api/v1/repos/oficina/sample/ci/status?branch=equipo%2Ftk1-fix-teh&logs=failed Bearer agent-token", |
| + } |
| + if strings.Join(got, "\n") != strings.Join(want, "\n") { |
| + t.Fatalf("requests\n%s", strings.Join(got, "\n")) |
| + } |
| + |
| + refused := func(name string, err error) { |
| + t.Helper() |
| + if !errors.Is(err, ErrCIRead) { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, "equipo/other", CILogsNone) |
| + refused("another branch's answer", err) |
| + for _, other := range []string{`"ns":"elsewhere","repo":"sample"`, `"ns":"oficina","repo":"other"`, `"repo":"sample"`} { |
| + body["/api/v1/repos/oficina/sample/ci/status"] = `{` + other + `,"branch":"equipo/tk1-fix-teh","sha":"` + sha + `","state":"success"}` |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, CILogsNone) |
| + refused("an answer about "+other, err) |
| + } |
| + body["/api/v1/repos/oficina/sample/ci/hosted"] = `{"available":true}` |
| + _, err = HubCIHosted(ctx, hub.Client(), hub.URL, cred, repo) |
| + refused("no on field", err) |
| + body["/api/v1/repos/oficina/sample/ci/status"] = `{"ns":"oficina","repo":"sample","branch":"equipo/tk1-fix-teh","sha":"not-a-sha","state":"success"}` |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, CILogsNone) |
| + refused("a malformed tip", err) |
| + body["/api/v1/repos/oficina/sample/ci/status"] = `{"ns":"oficina","repo":"sample","branch":"equipo/tk1-fix-teh","sha":"` + sha + `","state":"success","log":"` + strings.Repeat("x", maxCIStatusBody) + `"}` |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, CILogsNone) |
| + refused("an oversized body", err) |
| + body["/api/v1/repos/oficina/sample/ci/status"] = `{"branch":` |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, CILogsNone) |
| + refused("an unreadable body", err) |
| + status["/api/v1/repos/oficina/sample/ci/status"] = http.StatusFound |
| + got = nil |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, CILogsNone) |
| + refused("a redirect", err) |
| + if len(got) != 1 || len(stolen) != 0 { |
| + t.Fatalf("the redirect was followed: %v %v", got, stolen) |
| + } |
| + status["/api/v1/repos/oficina/sample/ci/status"] = http.StatusForbidden |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, CILogsNone) |
| + refused("a refusal", err) |
| + got = nil |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, "amadan.net/oficina/../x", branch, CILogsNone) |
| + refused("a bad repository", err) |
| + _, err = HubCIStatus(ctx, hub.Client(), hub.URL, cred, repo, branch, "all") |
| + refused("another logs mode", err) |
| + _, err = HubCIHosted(ctx, hub.Client(), hub.URL, Credential{Bearer: "a\nb"}, repo) |
| + refused("a bearer with a newline", err) |
| + if len(got) != 0 { |
| + t.Fatalf("asked the hub anyway: %v", got) |
| + } |
| +} |
diff --git a/internal/runner/mac/caps.go b/internal/runner/mac/caps.go| index a73ac20a..8e589263 100644 |
| --- a/internal/runner/mac/caps.go |
| +++ b/internal/runner/mac/caps.go |
| @@ -7,7 +7,6 @@ import ( |
| "sort" |
| "strconv" |
| "strings" |
| - "time" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -28,7 +27,7 @@ func Capabilities(ctx context.Context, x Exec, t Tools) wire.Capabilities { |
| if name == "" { |
| return "" |
| } |
| - c, cancel := context.WithTimeout(ctx, 30*time.Second) |
| + c, cancel := context.WithTimeout(ctx, QueryLimit) |
| defer cancel() |
| out, err := x(c, name, args...) |
| if err != nil { |
diff --git a/internal/runner/mac/gate.go b/internal/runner/mac/gate.go| index 3d4f3026..7545f8c8 100644 |
| --- a/internal/runner/mac/gate.go |
| +++ b/internal/runner/mac/gate.go |
| @@ -37,7 +37,8 @@ type Gate struct { |
| // Settings writes the attempt's srt settings for a tree and scratch. |
| Settings func(tree, attempt string) ([]byte, error) |
| // Env is the gate's whole environment but TMPDIR, EQUIPO_ATTEMPT and |
| - // EQUIPO_GATE_STATUS, which the run adds. |
| + // EQUIPO_GATE_STATUS (and under srt CLAUDE_CODE_TMPDIR), which the |
| + // run adds. |
| Env []string |
| // Caffeinate keeps the Mac awake while a gate runs |
| // (/usr/bin/caffeinate); "" does not. |
| @@ -109,6 +110,14 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi |
| cmd := exec.Command(cmdline[0], cmdline[1:]...) |
| cmd.Dir = dir |
| cmd.Env = append(append([]string{}, g.Env...), "TMPDIR="+scratch, "EQUIPO_ATTEMPT="+attempt, "EQUIPO_GATE_STATUS="+status) |
| + if g.SRT != "" { |
| + // srt 0.0.81 sets the command's TMPDIR to CLAUDE_CODE_TMPDIR, else |
| + // to its own /tmp/claude (generateProxyEnvVars in sandbox-utils), |
| + // a directory every srt user on the Mac shares and none cleans: |
| + // keep it this attempt's scratch, which the profile already lets |
| + // the gate write and the run removes. |
| + cmd.Env = append(cmd.Env, "CLAUDE_CODE_TMPDIR="+scratch) |
| + } |
| if g.ScratchHome { |
| cmd.Env = append(cmd.Env, "HOME="+scratch) |
| } |
diff --git a/internal/runner/mac/gate_test.go b/internal/runner/mac/gate_test.go| index e37a68fe..51075be4 100644 |
| --- a/internal/runner/mac/gate_test.go |
| +++ b/internal/runner/mac/gate_test.go |
| @@ -17,13 +17,16 @@ import ( |
| ) |
| // fakeSRT stands in for srt on Linux: it needs --settings <file> -- and a |
| -// readable JSON file, runs the command through a shell as srt does, and |
| -// exits 0 when the command dies of SIGTERM, as srt's cli does. |
| +// readable JSON file, runs the command through a shell as srt does, |
| +// sets its TMPDIR as srt 0.0.81 does (CLAUDE_CODE_TMPDIR, else |
| +// CLAUDE_TMPDIR, else /tmp/claude), and exits 0 when the command dies of |
| +// SIGTERM, as srt's cli does. |
| const fakeSRT = `#!/bin/bash |
| [ "$1" = --settings ] && [ "$3" = -- ] || exit 97 |
| python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$2" || exit 98 |
| cp "$2" "$FAKE_SRT_SEEN" |
| shift 3 |
| +export TMPDIR="${CLAUDE_CODE_TMPDIR:-${CLAUDE_TMPDIR:-/tmp/claude}}" |
| "$@" |
| s=$? |
| [ "$s" = 143 ] && exit 0 |
| @@ -119,6 +122,17 @@ func TestGateEnvironmentFromScratch(t *testing.T) { |
| } |
| } |
| +// Under srt TMPDIR is still the attempt's own scratch, not srt's shared |
| +// /tmp/claude: what a check leaves there goes with the attempt, and no |
| +// other user's /tmp/claude decides whether it can write. |
| +func TestGateKeepsTMPDIRUnderSRT(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + res, _ := run(g, dir, "checks-c-2", time.Minute, `echo "$TMPDIR"`) |
| + if res.Code != 0 || !strings.HasPrefix(res.Output, filepath.Dir(dir)+"/attempt-") { |
| + t.Fatalf("TMPDIR under srt: %+v", res) |
| + } |
| +} |
| + |
| // Cancel and timeout: SIGTERM to the group, SIGKILL after the grace, a |
| // sweep of marked processes (a child that ignores SIGTERM and one that |
| // left the group but kept its marker), and the proof: the group gone |
diff --git a/internal/runner/mac/p2why.go b/internal/runner/mac/p2why.go| new file mode 100644 |
| index 00000000..e23de64d |
| --- /dev/null |
| +++ b/internal/runner/mac/p2why.go |
| @@ -0,0 +1,285 @@ |
| +package mac |
| + |
| +import ( |
| + "path" |
| + "regexp" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "unicode/utf8" |
| +) |
| + |
| +// Why P2's srt run did not fully succeed: the step that failed, its |
| +// exit, whether the run timed out, and the first error lines, bounded |
| +// and with nothing secret in them. The probe's detail carries the short |
| +// form; runner.log the excerpt, once per probe run. |
| + |
| +// p2Phases are the steps of P2's srt run in the order they run. The |
| +// script build stands alone; each package step needs the one before. |
| +var p2Phases = []struct{ key, label string }{ |
| + {"script-build", "script build"}, |
| + {"package-resolve", "package resolve"}, |
| + {"test-build", "test build"}, |
| + {"simulator-boot", "simulator boot"}, |
| + {"test-run", "test run"}, |
| +} |
| + |
| +// p2Succeeded are xcodebuild's own last lines for its three steps that |
| +// build or test (build, build-for-testing, test-without-building). |
| +var p2Succeeded = []string{"** BUILD SUCCEEDED **", "** TEST BUILD SUCCEEDED **", "** TEST EXECUTE SUCCEEDED **"} |
| + |
| +const ( |
| + // p2AttemptLines bounds the report lines kept (15 are expected; the |
| + // first for each attempt counts). |
| + p2AttemptLines = 64 |
| + // p2ErrorLines and p2ExcerptBytes bound the excerpt; p2ShortBytes its |
| + // first line in the probe's detail. |
| + p2ErrorLines = 5 |
| + p2ExcerptBytes = 400 |
| + p2ShortBytes = 120 |
| +) |
| + |
| +var ( |
| + phaseLine = regexp.MustCompile(`^EQUIPO-PHASE (script-build|package-resolve|test-build|simulator-boot|test-run) ([0-9]{1,3})$`) |
| + // failureLine: xcodebuild's and the compilers' error lines, srt's own |
| + // ("Error: ...", a refused settings file), a nested sandbox that |
| + // could not be applied, a denial a tool printed, a write Unix |
| + // permissions refused, and the fixture finding no targets. |
| + failureLine = regexp.MustCompile(`(?i)\berror:|^refusing to run|^failed to execute|sandbox_apply|sandbox-exec:|\bdeny\(\d+\)|operation not permitted|permission denied|^EQUIPO-PROBE \w+ targets missing`) |
| + ansiEscape = regexp.MustCompile("\x1b\\[[0-9;?]*[ -/]*[@-~]") |
| +) |
| + |
| +// p2Watch reads the whole of P2's output as it comes, so what decides P2 |
| +// does not depend on the gate's last 200 lines: a full build and test |
| +// prints more than that, and the script build's lines come first. |
| +type p2Watch struct { |
| + mu sync.Mutex |
| + attempts []string |
| + phases map[string]int |
| + succeeded map[string]bool |
| + errors []string |
| +} |
| + |
| +func newP2Watch() *p2Watch { |
| + return &p2Watch{phases: map[string]int{}, succeeded: map[string]bool{}} |
| +} |
| + |
| +func (w *p2Watch) line(l string) { |
| + t := strings.TrimSpace(l) |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if attemptLine.MatchString(t) { |
| + if len(w.attempts) < p2AttemptLines { |
| + w.attempts = append(w.attempts, t) |
| + } |
| + return |
| + } |
| + if m := phaseLine.FindStringSubmatch(t); m != nil { |
| + if _, seen := w.phases[m[1]]; !seen { |
| + w.phases[m[1]], _ = strconv.Atoi(m[2]) |
| + } |
| + return |
| + } |
| + for _, s := range p2Succeeded { |
| + if t == s { |
| + w.succeeded[s] = true |
| + } |
| + } |
| + if len(w.errors) < p2ErrorLines && failureLine.MatchString(t) { |
| + for _, e := range w.errors { |
| + if e == t { |
| + return |
| + } |
| + } |
| + w.errors = append(w.errors, t) |
| + } |
| +} |
| + |
| +// attemptsSeen is the report lines, one per line, for ParseAttempts. |
| +func (w *p2Watch) attemptsSeen() string { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + return strings.Join(w.attempts, "\n") |
| +} |
| + |
| +// ran: the run exited 0, every step said it exited 0, and xcodebuild |
| +// said each build and test succeeded. |
| +func (w *p2Watch) ran(res Result) bool { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if res.Code != 0 { |
| + return false |
| + } |
| + for _, p := range p2Phases { |
| + if c, ok := w.phases[p.key]; !ok || c != 0 { |
| + return false |
| + } |
| + } |
| + for _, s := range p2Succeeded { |
| + if !w.succeeded[s] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// p2Failure is why the srt run did not fully succeed. |
| +type p2Failure struct { |
| + // Phase is the first step that failed, else the first that did not |
| + // finish: "srt start" when no step reported, "gate start" when the |
| + // gate could not start, "run end" when every step exited 0 and the |
| + // run still did not succeed. Failed is every step that failed, with |
| + // its exit ("script build exit 65"); Unfinished the step the run was |
| + // stopped in ("test build timed out"). |
| + Phase string |
| + Failed []string |
| + Unfinished string |
| + Exit int |
| + TimedOut bool |
| + // Excerpt is up to p2ErrorLines redacted lines, at most |
| + // p2ExcerptBytes; First the first of them, at most p2ShortBytes. |
| + Excerpt, First string |
| +} |
| + |
| +// failure says why a run that did not fully succeed failed. |
| +func (w *p2Watch) failure(res Result, r redactor) p2Failure { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + f := p2Failure{Exit: res.Code, TimedOut: res.Reason == "checks_timeout"} |
| + stopped := f.TimedOut || res.Reason == "cancelled" |
| + missing := "" |
| + for _, p := range p2Phases { |
| + c, ok := w.phases[p.key] |
| + if ok && c != 0 { |
| + f.Failed = append(f.Failed, p.label+" exit "+strconv.Itoa(c)) |
| + if f.Phase == "" { |
| + f.Phase, f.Exit = p.label, c |
| + } |
| + } |
| + if !ok && missing == "" { |
| + missing = p.label |
| + } |
| + } |
| + switch { |
| + case len(w.phases) == 0 && res.Reason == "checks_unavailable": |
| + missing = "gate start" |
| + case len(w.phases) == 0 && !stopped: |
| + missing = "srt start" |
| + } |
| + if stopped && missing != "" { |
| + f.Unfinished = missing + map[bool]string{true: " timed out", false: " stopped"}[f.TimedOut] |
| + } |
| + if f.Phase == "" { |
| + f.Phase = firstNonEmpty(missing, "run end") |
| + } |
| + var lines []string |
| + size := 0 |
| + for _, e := range w.errors { |
| + if e = cut(r.line(e), p2ExcerptBytes-size); e == "" { |
| + continue |
| + } |
| + lines = append(lines, e) |
| + if size += len(e) + len(" | "); size >= p2ExcerptBytes { |
| + break |
| + } |
| + } |
| + f.Excerpt = cut(strings.Join(lines, " | "), p2ExcerptBytes) |
| + if len(lines) > 0 { |
| + f.First = cut(lines[0], p2ShortBytes) |
| + } |
| + return f |
| +} |
| + |
| +// short is the failure for the probe's detail ("test build exit 65: |
| +// error: ..."); clean then keeps it inside the capability string rules. |
| +func (f p2Failure) short() string { |
| + parts := append([]string{}, f.Failed...) |
| + if f.Unfinished != "" { |
| + parts = append(parts, f.Unfinished) |
| + } |
| + if len(parts) == 0 { |
| + if f.Exit < 0 { |
| + parts = append(parts, f.Phase+" failed") |
| + } else { |
| + parts = append(parts, f.Phase+" exit "+strconv.Itoa(f.Exit)) |
| + } |
| + } |
| + s := strings.Join(parts, ", ") |
| + if f.First != "" { |
| + s += ": " + f.First |
| + } |
| + return s |
| +} |
| + |
| +// redactor takes out of an output line what must never leave the Mac: |
| +// the secrets it is given (the sentinel secret and its prefixes, the |
| +// Keychain service, the targets file's lines and values) and every path |
| +// under a home, kept as its last element only. |
| +type redactor struct { |
| + secrets []string |
| + homes *regexp.Regexp |
| +} |
| + |
| +func newRedactor(secrets, homes []string) redactor { |
| + var s []string |
| + for _, x := range secrets { |
| + if x != "" { |
| + s = append(s, x) |
| + } |
| + } |
| + // Longest first: a prefix must not leave the rest of a longer one. |
| + sort.SliceStable(s, func(i, j int) bool { return len(s[i]) > len(s[j]) }) |
| + h := []string{regexp.QuoteMeta("/Users/")} |
| + for _, x := range homes { |
| + if x = strings.TrimRight(x, "/"); x != "" { |
| + h = append(h, regexp.QuoteMeta(x)) |
| + } |
| + } |
| + sort.SliceStable(h, func(i, j int) bool { return len(h[i]) > len(h[j]) }) |
| + return redactor{secrets: s, homes: regexp.MustCompile("(?:/private)?(?:" + strings.Join(h, "|") + ")[^\\s'\"`:,;()<>\\[\\]]*")} |
| +} |
| + |
| +func (r redactor) line(s string) string { |
| + s = strings.ToValidUTF8(s, "") |
| + s = ansiEscape.ReplaceAllString(s, "") |
| + s = strings.Map(func(c rune) rune { |
| + if c < 0x20 || c == 0x7f || c >= 0x80 && c < 0xa0 { |
| + return ' ' |
| + } |
| + return c |
| + }, s) |
| + s = r.redact(s) |
| + s = r.homes.ReplaceAllStringFunc(s, func(p string) string { |
| + base := path.Base(strings.TrimRight(p, "/")) |
| + if base == "." || base == "/" || base == "Users" { |
| + return "[home]" |
| + } |
| + return "[home]..." + base |
| + }) |
| + // Again after the paths: a last element keeps no part of a secret. |
| + s = r.redact(s) |
| + return strings.Join(strings.Fields(s), " ") |
| +} |
| + |
| +func (r redactor) redact(s string) string { |
| + for _, x := range r.secrets { |
| + s = strings.ReplaceAll(s, x, "[redacted]") |
| + } |
| + return s |
| +} |
| + |
| +// cut keeps at most n bytes of s, whole runes only. |
| +func cut(s string, n int) string { |
| + if n <= 0 { |
| + return "" |
| + } |
| + if len(s) <= n { |
| + return s |
| + } |
| + s = s[:n] |
| + for len(s) > 0 && !utf8.ValidString(s) { |
| + s = s[:len(s)-1] |
| + } |
| + return s |
| +} |
diff --git a/internal/runner/mac/p2why_test.go b/internal/runner/mac/p2why_test.go| new file mode 100644 |
| index 00000000..ad291225 |
| --- /dev/null |
| +++ b/internal/runner/mac/p2why_test.go |
| @@ -0,0 +1,208 @@ |
| +package mac |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// warned records what P2 said to runner.log. |
| +type warned struct { |
| + mu sync.Mutex |
| + calls [][]any |
| +} |
| + |
| +func (w *warned) warn(msg string, args ...any) { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + w.calls = append(w.calls, append([]any{msg}, args...)) |
| +} |
| + |
| +func (w *warned) attr(i int, key string) string { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + c := w.calls[i] |
| + for j := 1; j+1 < len(c); j += 2 { |
| + if c[j] == key { |
| + return fmt.Sprint(c[j+1]) |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// A real build and test prints far more than the gate keeps (its last |
| +// 200 lines), the script build's report lines and success line first: |
| +// P2 reads the whole output as it comes, so a full run is still judged. |
| +func TestP2ReadsTheWholeOutput(t *testing.T) { |
| + f := newProbeFixture(t, allLines("denied"), "FAKE_NOISE=1") |
| + var w warned |
| + f.h.Warn = w.warn |
| + p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if p.Verdict != wire.ProbeDenied || !ran || len(w.calls) != 0 { |
| + t.Fatalf("a long, complete run: %+v ran=%v warned=%v", p, ran, w.calls) |
| + } |
| +} |
| + |
| +// Each step of the srt run that fails is named in P2's detail with its |
| +// exit and first error line, and once in runner.log with the bounded |
| +// excerpt; P2 is never denied for it. |
| +func TestP2SaysWhichStepFailed(t *testing.T) { |
| + for _, c := range []struct{ env, phase, detail string }{ |
| + {"FAKE_BUILD_FAIL=1", "script build", "xcodebuild did not run in srt: script build exit 65: Sandbox: deny(1) mach-lookup com.apple.dt.example"}, |
| + {"FAKE_RESOLVE_FAIL=1", "package resolve", "xcodebuild did not run in srt: package resolve exit 74: xcodebuild: error: Could not resolve package dependencies:"}, |
| + {"FAKE_TEST_BUILD_FAIL=error: no such module 'XCTest'", "test build", "xcodebuild did not run in srt: test build exit 65: error: no such module 'XCTest'"}, |
| + {"FAKE_BOOT_FAIL=1", "simulator boot", "xcodebuild did not run in srt: simulator boot exit 149: Unable to boot device: error: launchd_sim failed"}, |
| + {"FAKE_RUN_FAIL=1", "test run", "xcodebuild did not run in srt: test run exit 65: xcodebuild: error: Failed to establish communication with the test runner."}, |
| + } { |
| + f := newProbeFixture(t, allLines("denied"), c.env) |
| + var w warned |
| + f.h.Warn = w.warn |
| + p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, c.detail) { |
| + t.Fatalf("%s: %+v ran=%v", c.phase, p, ran) |
| + } |
| + if err := wire.ValidCapabilities(wire.Capabilities{Probes: []wire.Probe{p}}); err != nil { |
| + t.Fatalf("%s: detail outside the capability rules: %v", c.phase, err) |
| + } |
| + if len(w.calls) != 1 || w.calls[0][0] != "p2 srt run failed" || w.attr(0, "phase") != c.phase || w.attr(0, "excerpt") == "" || w.attr(0, "timed_out") != "false" { |
| + t.Fatalf("%s: warned %v", c.phase, w.calls) |
| + } |
| + } |
| + // No step reported at all: srt itself did not start the command. |
| + f := newProbeFixture(t, allLines("denied")) |
| + if err := os.WriteFile(f.h.Tools.SRT, []byte("#!/bin/bash\necho 'Error: Refusing to run with the built-in defaults' >&2\nexit 1\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + var w warned |
| + f.h.Warn = w.warn |
| + p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if p.Detail != "not shown denied: all 15 attempts; xcodebuild did not run in srt: srt start exit 1: Error: Refusing to run with the built-in defaults" || w.attr(0, "phase") != "srt start" { |
| + t.Fatalf("srt did not start: %+v %v", p, w.calls) |
| + } |
| +} |
| + |
| +// What P2 says about a failure never carries the sentinel secret, the |
| +// Keychain service, the targets file's contents or a path under a home, |
| +// even when the failing tool prints all of them. |
| +func TestP2FailureIsRedacted(t *testing.T) { |
| + leak := `t=../equipo-targets.txt; echo "error: cannot read $(sed -n 's/^state=//p' $t)"; echo "error: no item $(sed -n 's/^keychain=//p' $t) in $(sed -n 's/^keychain_file=//p' $t)"; echo "error: $(tr '\n' ' ' < $t)"; printf 'error: \033[31mred\033[0m and \001bell\n'` |
| + f := newProbeFixture(t, allLines("denied")) |
| + xb, _ := os.ReadFile(f.h.Tools.Xcodebuild) |
| + patched := strings.Replace(string(xb), `[ -n "$FAKE_TEST_BUILD_FAIL" ] &&`, `{ `+leak+`; exit 65; }; [ -n "$FAKE_TEST_BUILD_FAIL" ] &&`, 1) |
| + if err := os.WriteFile(f.h.Tools.Xcodebuild, []byte(patched), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + var w warned |
| + f.h.Warn = w.warn |
| + f.h.Paths.OtherHomes = []string{"/Users/paul"} |
| + p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if len(w.calls) != 1 || w.attr(0, "phase") != "test build" { |
| + t.Fatalf("warned %v", w.calls) |
| + } |
| + excerpt := w.attr(0, "excerpt") |
| + said := p.Detail + "\n" + fmt.Sprint(w.calls) |
| + for _, bad := range []string{f.dir, "/Users/paul", "io.amadan.equipo.probe.", "probe-sentinel-", "login.keychain", "port_", "keychain=", "example.com", "\x1b", "\x01"} { |
| + if strings.Contains(said, bad) { |
| + t.Fatalf("%q left in %q", bad, said) |
| + } |
| + } |
| + if !strings.Contains(excerpt, "error: cannot read [redacted] | error: no item [redacted] in [redacted]") || !strings.Contains(excerpt, "red and bell") || len(excerpt) > p2ExcerptBytes { |
| + t.Fatalf("excerpt %q", excerpt) |
| + } |
| +} |
| + |
| +// The judge of a failure from recorded gate outputs: the step a timeout |
| +// stopped, srt or the gate not starting, every step passing yet no |
| +// success line, and the excerpt's bounds (five lines, 400 bytes, no |
| +// control characters). |
| +func TestP2FailureFromGateOutput(t *testing.T) { |
| + red := newRedactor([]string{"0123456789abcdef"}, []string{"/Users/equipo-paul"}) |
| + feed := func(lines ...string) *p2Watch { |
| + w := newP2Watch() |
| + for _, l := range lines { |
| + w.line(l) |
| + } |
| + return w |
| + } |
| + for name, c := range map[string]struct { |
| + w *p2Watch |
| + res Result |
| + phase string |
| + short string |
| + timeup bool |
| + }{ |
| + "timed out in the test build": {feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0"), Result{Code: -1, Reason: "checks_timeout"}, "test build", "test build timed out", true}, |
| + "a failure, then a timeout": {feed("EQUIPO-PHASE script-build 65", "EQUIPO-PHASE package-resolve 0"), Result{Code: -1, Reason: "checks_timeout"}, "script build", "script build exit 65, test build timed out", true}, |
| + "stopped by the run's limit": {feed(), Result{Code: -1, Reason: "cancelled"}, "script build", "script build stopped", false}, |
| + "srt refused its settings": {feed("Error: /Users/equipo-paul/.local/s.json does not exist."), Result{Code: 1}, "srt start", "srt start exit 1: Error: [home]...s.json does not exist.", false}, |
| + "the gate could not start": {feed(), Result{Code: -1, Reason: "checks_unavailable"}, "gate start", "gate start failed", false}, |
| + "no success line": {feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0", "EQUIPO-PHASE test-build 0", "EQUIPO-PHASE simulator-boot 0", "EQUIPO-PHASE test-run 0", "** BUILD SUCCEEDED **"), |
| + Result{Code: 0}, "run end", "run end exit 0", false}, |
| + } { |
| + if c.w.ran(c.res) { |
| + t.Fatalf("%s: taken as ran", name) |
| + } |
| + f := c.w.failure(c.res, red) |
| + if f.Phase != c.phase || f.short() != c.short || f.TimedOut != c.timeup { |
| + t.Fatalf("%s: %+v short %q", name, f, f.short()) |
| + } |
| + } |
| + var lines []string |
| + for i := 0; i < 9; i++ { |
| + lines = append(lines, fmt.Sprintf("/Users/equipo-paul/x/f%d.swift:1:2: error: \x1b[1m%s\x07 0123456789abcdef", i, strings.Repeat("é", 60))) |
| + } |
| + lines = append(lines, lines[0]) |
| + f := feed(lines...).failure(Result{Code: 65}, red) |
| + if n := strings.Count(f.Excerpt, " | ") + 1; n > p2ErrorLines || len(f.Excerpt) > p2ExcerptBytes || len(f.First) > p2ShortBytes || !strings.HasPrefix(f.First, "[home]...f0.swift:1:2: error: é") { |
| + t.Fatalf("bounds: %d lines, %d bytes, first %q", n, len(f.Excerpt), f.First) |
| + } |
| + for _, r := range f.Excerpt { |
| + if r < 0x20 || r == 0x7f || r == '�' { |
| + t.Fatalf("control or broken character in %q", f.Excerpt) |
| + } |
| + } |
| + if strings.Contains(f.Excerpt, "0123456789abcdef") || strings.Contains(f.Excerpt, "equipo-paul") { |
| + t.Fatalf("not redacted: %q", f.Excerpt) |
| + } |
| + // A run that did everything, by every account. |
| + all := feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0", "EQUIPO-PHASE test-build 0", "EQUIPO-PHASE simulator-boot 0", "EQUIPO-PHASE test-run 0", "** BUILD SUCCEEDED **", "** TEST BUILD SUCCEEDED **", "** TEST EXECUTE SUCCEEDED **") |
| + if !all.ran(Result{Code: 0}) || all.ran(Result{Code: 1}) { |
| + t.Fatal("ran") |
| + } |
| +} |
| + |
| +// However long the reason, the detail keeps what decides trust (the |
| +// end not proven) and stays a capability string: the reason is cut. |
| +func TestP2DetailKeepsTheEnd(t *testing.T) { |
| + unknown := []string{"script.state", "script.tcp", "script.dns", "script.keychain", "plugin.state", "plugin.tcp", "plugin.dns", "plugin.keychain", "test.state", "test.tcp", "test.dns", "test.keychain"} |
| + d := p2Detail(map[string][]string{"unknown": unknown[:11], "allowed": unknown[11:]}, 12, false, false, "test build exit 65: "+strings.Repeat("error: x ", 60)) |
| + if !strings.Contains(d, "end not proven; xcodebuild did not run in srt: test build exit 65: error") || len(d) > wire.MaxCapabilityString { |
| + t.Fatalf("detail %q", d) |
| + } |
| + if d := p2Detail(map[string][]string{"unknown": unknown}, 12, false, true, ""); d != "not shown denied: all 12 attempts; xcodebuild did not run in srt" { |
| + t.Fatalf("detail %q", d) |
| + } |
| +} |
| + |
| +// P2's script runs every step it names, in order, under the gate's |
| +// TMPDIR, with the package's plugins allowed to run unvalidated and |
| +// nothing that reaches the network. |
| +func TestP2Script(t *testing.T) { |
| + s := p2Script(quote("/usr/bin/xcodebuild"), quote("/usr/bin/xcrun"), "ABCDEF01-2345-6789-ABCD-EF0123456789") |
| + last := -1 |
| + for _, p := range p2Phases { |
| + i := strings.Index(s, "phase "+p.key+" ") |
| + if i < last { |
| + t.Fatalf("%s missing or out of order in %s", p.key, s) |
| + } |
| + last = i |
| + } |
| + if strings.Count(s, "-skipPackagePluginValidation") != 3 || strings.Count(s, `-derivedDataPath "$TMPDIR/dd"`) != 3 || strings.Contains(s, "http") { |
| + t.Fatalf("script %s", s) |
| + } |
| +} |
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go| index 0b71c3c5..68403680 100644 |
| --- a/internal/runner/mac/probe.go |
| +++ b/internal/runner/mac/probe.go |
| @@ -7,6 +7,7 @@ import ( |
| "embed" |
| "encoding/hex" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| "io/fs" |
| "net" |
| @@ -52,8 +53,28 @@ type ProbeHost struct { |
| Listen func() (net.Listener, error) |
| // Wait bounds P6's wait for its test to start (8 minutes). |
| Wait time.Duration |
| + // Limit bounds the whole run (ProbeLimit). |
| + Limit time.Duration |
| + // Warn hears why P2's srt run did not fully succeed, once per run, |
| + // redacted (runner.log); nil says nothing. |
| + Warn func(msg string, args ...any) |
| + // late notes the queries that did not answer in time (RunProbes). |
| + late *queries |
| } |
| +// QueryLimit bounds each query the probes and the capability report |
| +// make (simctl list, xcodebuild -version, launchctl, pmset, a tool's |
| +// version): a command that has not answered by then is killed and taken |
| +// as unavailable. Only the gates the probes run (a real build and test) |
| +// and srt's own start take longer, each with a bound of its own. |
| +var QueryLimit = 30 * time.Second |
| + |
| +// ProbeLimit bounds a whole probe run, whatever hangs inside it. It is |
| +// above the bounds of the probes' own gates (P2's 20 minutes, P6's 8), |
| +// so it never cuts a slow but healthy first build short: it is the |
| +// backstop for a wait nothing else bounds. |
| +const ProbeLimit = 30 * time.Minute |
| + |
| // Report is what the probes found, kept in the state dir and sent in the |
| // capability report. |
| type Report struct { |
| @@ -67,6 +88,9 @@ type Report struct { |
| // SRT fingerprints the srt, Node and ripgrep the probes ran with |
| // (set by the worker that made the report). |
| SRT string `json:"srt"` |
| + // Unfinished are the probes the run's limit cut short: each says |
| + // not proven. |
| + Unfinished []string `json:"unfinished,omitempty"` |
| } |
| // Probe is the result of one probe ("" verdict when it did not run). |
| @@ -101,22 +125,131 @@ func ProfileDigest() string { |
| } |
| // RunProbes runs P1 to P7 (spec §6) and reports each. None needs a |
| -// person: P3 and P5 say what they could not do and why. |
| +// person: P3 and P5 say what they could not do and why. Every command |
| +// is bounded (QueryLimit, or a gate's own limit) and so is the run |
| +// (h.Limit): when that passes the run ends with what it has, the |
| +// probes it did not finish not proven and listed in Unfinished. |
| func RunProbes(ctx context.Context, h ProbeHost) Report { |
| + limit := h.Limit |
| + if limit <= 0 { |
| + limit = ProbeLimit |
| + } |
| + run, cancel := context.WithTimeout(ctx, limit) |
| + defer cancel() |
| r := Report{Version: h.Version, Profile: ProfileDigest(), At: time.Now().UTC()} |
| - caps := Capabilities(ctx, h.Exec, h.Tools) |
| - r.Probes = append(r.Probes, probeP1(ctx, h, caps)) |
| - p2, srtRan, keychain := probeP2(ctx, h, caps) |
| + h.late = &queries{run: run, exec: h.Exec, late: map[string]bool{}} |
| + h.Exec = h.late.do |
| + var mu sync.Mutex |
| + got := map[string]wire.Probe{} |
| + srtRan := false |
| + // A result that comes once the run's limit has passed is left out: |
| + // the cancellation, not the Mac, may have decided it. |
| + put := func(p wire.Probe, ran ...bool) { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if run.Err() == nil { |
| + got[p.ID] = p |
| + if len(ran) > 0 { |
| + srtRan = ran[0] |
| + } |
| + } |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + caps := Capabilities(run, h.Exec, h.Tools) |
| + put(probeP1(run, h, caps)) |
| + p2, ran, keychain := probeP2(run, h, caps) |
| + put(p2, ran) |
| + put(wire.Probe{ID: "P3", Verdict: wire.ProbeSkipped, Detail: clean("sign-in needs a person (slice F); Keychain from the sandbox: " + keychain)}) |
| + put(probeP4(run, h)) |
| + put(wire.Probe{ID: "P5", Verdict: wire.ProbeSkipped, Detail: "Codex on the Mac is parked (slice G)"}) |
| + put(probeP6(run, h, caps, ran)) |
| + put(probeP7(run, h)) |
| + }() |
| + select { |
| + case <-done: |
| + case <-run.Done(): |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| r.SRTRanXcode = srtRan |
| - r.Probes = append(r.Probes, p2) |
| - r.Probes = append(r.Probes, wire.Probe{ID: "P3", Verdict: wire.ProbeSkipped, Detail: clean("sign-in needs a person (slice F); Keychain from the sandbox: " + keychain)}) |
| - r.Probes = append(r.Probes, probeP4(ctx, h)) |
| - r.Probes = append(r.Probes, wire.Probe{ID: "P5", Verdict: wire.ProbeSkipped, Detail: "Codex on the Mac is parked (slice G)"}) |
| - r.Probes = append(r.Probes, probeP6(ctx, h, caps, srtRan)) |
| - r.Probes = append(r.Probes, probeP7(ctx, h)) |
| + for _, id := range wire.ProbeIDs { |
| + p, ok := got[id] |
| + if !ok { |
| + p = wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: clean("not proven: the probe run reached its limit of " + limit.String())} |
| + r.Unfinished = append(r.Unfinished, id) |
| + } |
| + r.Probes = append(r.Probes, p) |
| + } |
| return r |
| } |
| +// queries runs the probes' commands and notes each that did not answer |
| +// in time: its own deadline passed while the run's had not. |
| +type queries struct { |
| + run context.Context |
| + exec Exec |
| + mu sync.Mutex |
| + late map[string]bool |
| +} |
| + |
| +func (q *queries) do(ctx context.Context, name string, args ...string) (string, error) { |
| + out, err := q.exec(ctx, name, args...) |
| + if errors.Is(ctx.Err(), context.DeadlineExceeded) && q.run.Err() == nil { |
| + q.mu.Lock() |
| + q.late[queryKey(name, args)] = true |
| + q.mu.Unlock() |
| + } |
| + return out, err |
| +} |
| + |
| +// queryKey names a command by its program, or xcrun's by its tool |
| +// ("simctl"). |
| +func queryKey(name string, args []string) string { |
| + if path.Base(name) == "xcrun" && len(args) > 0 { |
| + return args[0] |
| + } |
| + return path.Base(name) |
| +} |
| + |
| +// said is why a tool cannot be relied on when a query to it did not |
| +// answer ("simctl did not answer in 30s"), else "". |
| +func (h ProbeHost) said(tool string) string { |
| + if h.late == nil { |
| + return "" |
| + } |
| + h.late.mu.Lock() |
| + defer h.late.mu.Unlock() |
| + if h.late.late[tool] { |
| + return tool + " did not answer in " + QueryLimit.String() |
| + } |
| + return "" |
| +} |
| + |
| +// noXcode and noSimulator say why a probe that needs Xcode or a |
| +// simulator cannot run: a query that did not answer, or none found. |
| +func (h ProbeHost) noXcode() string { |
| + if why := h.said("xcodebuild"); why != "" { |
| + return "Xcode unavailable: " + why |
| + } |
| + return "no Xcode" |
| +} |
| + |
| +func (h ProbeHost) noSimulator() string { |
| + if why := h.said("simctl"); why != "" { |
| + return "simulator unavailable: " + why |
| + } |
| + return "" |
| +} |
| + |
| +// query runs one probe command bounded by limit. |
| +func (h ProbeHost) query(ctx context.Context, limit time.Duration, name string, args ...string) (string, error) { |
| + c, cancel := context.WithTimeout(ctx, limit) |
| + defer cancel() |
| + return h.Exec(c, name, args...) |
| +} |
| + |
| func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Probe { |
| name := ComputerName(ctx, h.Exec) |
| ios := 0 |
| @@ -126,9 +259,12 @@ func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Prob |
| } |
| } |
| if caps.Xcode.Version == "" { |
| - return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean("no Xcode; " + name)} |
| + return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean(h.noXcode() + "; " + name)} |
| } |
| detail := fmt.Sprintf("Xcode %s (%s); %d iOS simulators; %s", caps.Xcode.Version, caps.Xcode.Build, ios, name) |
| + if why := h.noSimulator(); why != "" { |
| + detail = fmt.Sprintf("Xcode %s (%s); %s; %s", caps.Xcode.Version, caps.Xcode.Build, why, name) |
| + } |
| if ios == 0 { |
| return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean(detail)} |
| } |
| @@ -137,6 +273,8 @@ func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Prob |
| // ComputerName is the Mac's name as people see it ("Tito Studio"). |
| func ComputerName(ctx context.Context, x Exec) string { |
| + ctx, cancel := context.WithTimeout(ctx, QueryLimit) |
| + defer cancel() |
| out, err := x(ctx, "/usr/sbin/scutil", "--get", "ComputerName") |
| if err != nil { |
| return "" |
| @@ -210,24 +348,57 @@ func JudgeP2(got map[string]string, f P2Facts) (verdict string, groups map[strin |
| return verdict, groups |
| } |
| -func p2Detail(groups map[string][]string, total int, srtRan bool) string { |
| +// p2Detail says what P2 found and whether the run's end was proven; why |
| +// is the short form of a failed srt run, last, so the capability |
| +// string's limit cuts it before the rest. |
| +func p2Detail(groups map[string][]string, total int, srtRan, ended bool, why string) string { |
| var parts []string |
| for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"unknown", "not shown denied"}, {"unix", "Unix permissions only"}} { |
| - if len(groups[g.key]) > 0 { |
| + switch n := len(groups[g.key]); { |
| + case n > 0 && n == total && n > len(probePlaces): |
| + // Every attempt alike (none reported, say): the count, which |
| + // leaves room for why. |
| + parts = append(parts, fmt.Sprintf("%s: all %d attempts", g.label, n)) |
| + case n > 0: |
| parts = append(parts, g.label+": "+strings.Join(groups[g.key], " ")) |
| } |
| } |
| if len(parts) == 0 { |
| parts = append(parts, fmt.Sprintf("all %d attempts denied", total)) |
| } |
| - if srtRan { |
| + if !ended { |
| + parts = append(parts, "end not proven") |
| + } |
| + switch { |
| + case srtRan: |
| parts = append(parts, "xcodebuild ran in srt") |
| - } else { |
| + case why != "": |
| + parts = append(parts, "xcodebuild did not run in srt: "+why) |
| + default: |
| parts = append(parts, "xcodebuild did not run in srt") |
| } |
| return clean(strings.Join(parts, "; ")) |
| } |
| +// p2Script is P2's run under srt, one step at a time, each reporting |
| +// its exit (EQUIPO-PHASE <step> <exit>) so a failure names its step: the |
| +// hostile script phase's build, then the package's resolve, test build, |
| +// the simulator's boot and the hostile test on it. |
| +func p2Script(xb, xcrun, udid string) string { |
| + dest := quote("platform=iOS Simulator,id=" + udid) |
| + pkg := ` -scheme "$s" -derivedDataPath "$TMPDIR/dd" -skipPackagePluginValidation` |
| + return `phase() { p=$1; shift; "$@"; c=$?; echo "EQUIPO-PHASE $p $c"; return $c; } |
| +(cd project && phase script-build ` + xb + ` -project Hostile.xcodeproj -target HostileScript -configuration Debug build SYMROOT="$TMPDIR/sym" OBJROOT="$TMPDIR/obj"); a=$? |
| +cd package || exit 1 |
| +s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hostile-Package || s=Hostile |
| +phase package-resolve ` + xb + ` -resolvePackageDependencies` + pkg + ` && |
| +phase test-build ` + xb + ` build-for-testing -destination ` + dest + pkg + ` && |
| +phase simulator-boot ` + xcrun + ` simctl bootstatus ` + quote(udid) + ` -b && |
| +phase test-run ` + xb + ` test-without-building -destination ` + dest + ` -only-testing:HostileTests/HostileTests/testHostile` + pkg + ` |
| +b=$? |
| +[ "$a" = 0 ] && [ "$b" = 0 ]` |
| +} |
| + |
| // probeP2 runs the hostile fixture under the checks profile. |
| func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Probe, bool, string) { |
| fail := func(verdict, why string) (wire.Probe, bool, string) { |
| @@ -237,7 +408,10 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro |
| return fail(wire.ProbeUnavailable, "srt is not installed") |
| } |
| if caps.Xcode.Version == "" { |
| - return fail(wire.ProbeUnavailable, "no Xcode") |
| + return fail(wire.ProbeUnavailable, clean(h.noXcode())) |
| + } |
| + if why := h.noSimulator(); why != "" { |
| + return fail(wire.ProbeUnavailable, clean(why)) |
| } |
| // The hostile test runs where production checks run: on an iOS |
| // simulator, through CoreSimulator and the test services. |
| @@ -285,13 +459,15 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro |
| }(place, l) |
| targets = append(targets, "port_"+place+"="+strconv.Itoa(l.Addr().(*net.TCPAddr).Port)) |
| } |
| - facts.DNS = h.Resolve(ctx, "example.com") |
| + resolve, cancel := context.WithTimeout(ctx, QueryLimit) |
| + facts.DNS = h.Resolve(resolve, "example.com") |
| + cancel() |
| targets = append(targets, "dns=example.com") |
| service := "io.amadan.equipo.probe." + secret[:12] |
| - if _, err := h.Exec(ctx, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil { |
| + if _, err := h.query(ctx, QueryLimit, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil { |
| facts.Keychain = true |
| defer func() { |
| - _, _ = h.Exec(context.WithoutCancel(ctx), "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service) |
| + _, _ = h.query(context.WithoutCancel(ctx), QueryLimit, "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service) |
| }() |
| } |
| // On a simulator the Keychain API is the simulator's own: the test |
| @@ -300,15 +476,30 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro |
| if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0600); err != nil { |
| return fail(wire.ProbeUnavailable, "the fixture could not be prepared") |
| } |
| - xb := quote(h.Tools.Xcodebuild) |
| - script := `cd project && ` + xb + ` -project Hostile.xcodeproj -target HostileScript -configuration Debug build SYMROOT="$TMPDIR/sym" OBJROOT="$TMPDIR/obj" |
| -cd ../package && s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hostile-Package || s=Hostile |
| -` + xb + ` test -scheme "$s" -destination ` + quote("platform=iOS Simulator,id="+sim.UDID) + ` -only-testing:HostileTests/HostileTests/testHostile -derivedDataPath "$TMPDIR/dd" -skipPackagePluginValidation` |
| - res := h.Gate(true).Run(ctx, "probe-p2-"+secret[:8], root, []string{"/bin/bash", "-c", script}, 20*time.Minute, func(string) error { return nil }) |
| + script := p2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) |
| + g, watch := h.Gate(true), newP2Watch() |
| + g.Watch = watch.line |
| + res := g.Run(ctx, "probe-p2-"+secret[:8], root, []string{"/bin/bash", "-c", script}, 20*time.Minute, func(string) error { return nil }) |
| mu.Lock() |
| defer mu.Unlock() |
| - srtRan := res.Code == 0 && strings.Contains(res.Output, "** BUILD SUCCEEDED **") && strings.Contains(res.Output, "** TEST SUCCEEDED **") |
| - verdict, groups := JudgeP2(ParseAttempts(res.Output), facts) |
| + srtRan := watch.ran(res) |
| + verdict, groups := JudgeP2(ParseAttempts(watch.attemptsSeen()), facts) |
| + why := "" |
| + if !srtRan { |
| + // Never the secret, the service, the targets file's contents or a |
| + // path under a home. |
| + secrets := []string{service, secret, secret[:12], secret[:8]} |
| + for _, t := range targets { |
| + _, v, _ := strings.Cut(t, "=") |
| + secrets = append(secrets, t, v) |
| + } |
| + red := newRedactor(secrets, append([]string{h.Paths.Home, h.Paths.StateDir, h.Scratch}, h.Paths.OtherHomes...)) |
| + f := watch.failure(res, red) |
| + why = f.short() |
| + if h.Warn != nil { |
| + h.Warn("p2 srt run failed", "phase", f.Phase, "failed", strings.Join(f.Failed, ", "), "unfinished", f.Unfinished, "exit", f.Exit, "timed_out", f.TimedOut, "gate_reason", res.Reason, "excerpt", f.Excerpt) |
| + } |
| + } |
| // Denied counts only for a run that did everything and was proven |
| // to end: the hostile build and test completed under srt, and nothing |
| // of them is left. |
| @@ -327,10 +518,7 @@ cd ../package && s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hosti |
| if !facts.Home { |
| total -= len(probePlaces) |
| } |
| - detail := p2Detail(groups, total, srtRan) |
| - if !res.Terminated { |
| - detail = clean(detail + "; end not proven") |
| - } |
| + detail := p2Detail(groups, total, srtRan, res.Terminated, why) |
| return wire.Probe{ID: "P2", Verdict: verdict, Detail: detail}, srtRan, keychain |
| } |
| @@ -351,9 +539,9 @@ func probeP4(ctx context.Context, h ProbeHost) wire.Probe { |
| for _, home := range ExposedHomes(h.Paths.OtherHomes, h.Exposed) { |
| readable = append(readable, path.Base(home)) |
| } |
| - _, err := h.Exec(ctx, "/bin/launchctl", "print", "gui/"+strconv.Itoa(h.UID)+"/"+AgentLabel) |
| + _, err := h.query(ctx, QueryLimit, "/bin/launchctl", "print", "gui/"+strconv.Itoa(h.UID)+"/"+AgentLabel) |
| loaded := err == nil |
| - pm, _ := h.Exec(ctx, "/usr/bin/pmset", "-g", "custom") |
| + pm, _ := h.query(ctx, QueryLimit, "/usr/bin/pmset", "-g", "custom") |
| sleep, known := ACSleep(pm) |
| var parts []string |
| switch { |
| @@ -404,7 +592,13 @@ func ACSleep(out string) (int, bool) { |
| // the end takes to prove, what is left, and whether the tree goes. |
| func probeP6(ctx context.Context, h ProbeHost, caps wire.Capabilities, srtRan bool) wire.Probe { |
| if caps.Xcode.Version == "" { |
| - return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: "no Xcode"} |
| + return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: clean(h.noXcode())} |
| + } |
| + // A simctl that does not answer means CoreSimulator is stuck, and |
| + // xcodebuild test asks it for destinations even for macOS: the probe |
| + // would only wait out its whole limit. |
| + if why := h.noSimulator(); why != "" { |
| + return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: clean(why)} |
| } |
| root, err := copyFixture(h.Scratch) |
| if err != nil { |
| @@ -477,6 +671,8 @@ exec ` + xb + ` test -scheme "$s" -destination ` + quote(destination) + ` -only- |
| // processNames are this user's processes by name (basename), counted. |
| func processNames(ctx context.Context, x Exec) map[string]int { |
| + ctx, cancel := context.WithTimeout(ctx, QueryLimit) |
| + defer cancel() |
| out, err := x(ctx, "/bin/ps", "-x", "-o", "comm=") |
| names := map[string]int{} |
| if err != nil { |
| @@ -509,7 +705,7 @@ func probeP7(ctx context.Context, h ProbeHost) wire.Probe { |
| if tool == "" { |
| return "" |
| } |
| - out, err := h.Exec(ctx, tool, args...) |
| + out, err := h.query(ctx, QueryLimit, tool, args...) |
| if err != nil { |
| return "" |
| } |
| @@ -538,7 +734,8 @@ func probeP7(ctx context.Context, h ProbeHost) wire.Probe { |
| ok = false |
| } else { |
| defer os.Remove(file) |
| - if _, err := h.Exec(ctx, h.Tools.SRT, "--settings", file, "--", "/usr/bin/true"); err != nil { |
| + // srt starts its own runtime before the command: a minute, not a query's 30 s. |
| + if _, err := h.query(ctx, time.Minute, h.Tools.SRT, "--settings", file, "--", "/usr/bin/true"); err != nil { |
| parts, ok = append(parts, "srt could not run a command"), false |
| } |
| } |
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go| index 2c7e8294..0bfa13c8 100644 |
| --- a/internal/runner/mac/probe_test.go |
| +++ b/internal/runner/mac/probe_test.go |
| @@ -17,27 +17,46 @@ import ( |
| // fakeXcodebuild plays xcodebuild for the fixture: it really reads the |
| // targets file the probe wrote, prints the report lines a scenario |
| -// gives, and with FAKE_CONNECT connects to the test's loopback port |
| -// while saying "denied" (the probe's listener must catch the lie). |
| +// gives (the plugin's while the test target builds), and with |
| +// FAKE_CONNECT connects to the test's loopback port while saying |
| +// "denied" (the probe's listener must catch the lie). FAKE_NOISE prints |
| +// what a real build does: far more than the gate's last 200 lines. |
| +// FAKE_*_FAIL fails a step the way it fails on a Mac. |
| const fakeXcodebuild = `#!/bin/bash |
| +noise() { [ -n "$FAKE_NOISE" ] && for i in $(seq 1 300); do echo "CompileSwift normal arm64 step $i"; done; true; } |
| case "$*" in |
| *-list*) echo " Schemes:"; echo " Hostile-Package"; exit 0 ;; |
| *HostileScript*) |
| [ -r ../equipo-targets.txt ] || { echo "no targets"; exit 3; } |
| + case "$TMPDIR" in "$FAKE_DIR"/scratch/*) ;; *) echo "error: unable to create directory $TMPDIR/sym (Permission denied)"; echo "** BUILD FAILED **"; exit 65 ;; esac |
| [ -n "$FAKE_BUILD_FAIL" ] && { echo "Sandbox: deny(1) mach-lookup com.apple.dt.example"; echo "** BUILD FAILED **"; exit 65; } |
| [ -n "$FAKE_LINES_THEN_FAIL" ] && { cat "$FAKE_DIR/script.out"; echo "** BUILD FAILED **"; exit 65; } |
| - cat "$FAKE_DIR/script.out"; echo "** BUILD SUCCEEDED **"; exit 0 ;; |
| + cat "$FAKE_DIR/script.out"; noise; echo "** BUILD SUCCEEDED **"; exit 0 ;; |
| +*-resolvePackageDependencies*) |
| + [ -n "$FAKE_RESOLVE_FAIL" ] && { echo "xcodebuild: error: Could not resolve package dependencies:"; echo " sandbox-exec: sandbox_apply: Operation not permitted"; exit 74; } |
| + echo "resolved source packages:"; exit 0 ;; |
| +*build-for-testing*) |
| + [ -n "$FAKE_TEST_BUILD_FAIL" ] && { printf '%s\n' "$FAKE_TEST_BUILD_FAIL"; echo "** TEST BUILD FAILED **"; exit 65; } |
| + cat "$FAKE_DIR/plugin.out"; noise; echo "** TEST BUILD SUCCEEDED **"; exit 0 ;; |
| *testHostile*) |
| - case "$*" in *"platform=iOS Simulator,id="*) ;; *) echo "testHostile not on an iOS simulator"; exit 70 ;; esac |
| + case "$*" in *test-without-building*"platform=iOS Simulator,id="*) ;; *) echo "testHostile not on an iOS simulator"; exit 70 ;; esac |
| + [ -n "$FAKE_RUN_FAIL" ] && { echo "xcodebuild: error: Failed to establish communication with the test runner."; echo "** TEST EXECUTE FAILED **"; exit 65; } |
| t=../equipo-targets.txt |
| if [ -n "$FAKE_READ_STATE" ] && cat "$(sed -n 's/^state=//p' $t)" >/dev/null 2>&1; then echo "EQUIPO-PROBE test state allowed"; fi |
| if [ -n "$FAKE_CONNECT" ]; then exec 3<>"/dev/tcp/127.0.0.1/$(sed -n 's/^port_test=//p' $t)"; fi |
| - cat "$FAKE_DIR/test.out"; echo "** TEST SUCCEEDED **"; exit 0 ;; |
| + cat "$FAKE_DIR/test.out"; noise; echo "** TEST EXECUTE SUCCEEDED **"; exit 0 ;; |
| *testWait*) echo "EQUIPO-PROBE wait started"; exec sleep 600 ;; |
| esac |
| exit 64 |
| ` |
| +// fakeXcrun plays xcrun simctl bootstatus for P2's simulator boot. |
| +const fakeXcrun = `#!/bin/bash |
| +[ "$1 $2 $4" = "simctl bootstatus -b" ] || exit 64 |
| +[ -n "$FAKE_BOOT_FAIL" ] && { echo "An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):"; echo "Unable to boot device: error: launchd_sim failed"; exit 149; } |
| +echo "Device already booted, nothing to do." |
| +` |
| + |
| func allLines(result string) map[string]string { |
| out := map[string]string{} |
| for _, place := range []string{"script", "plugin", "test"} { |
| @@ -62,18 +81,18 @@ func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *prob |
| f := &probeFixture{dir: root} |
| xb := filepath.Join(root, "xcodebuild") |
| srt := filepath.Join(root, "srt") |
| - for p, body := range map[string]string{xb: fakeXcodebuild, srt: fakeSRT} { |
| + xcrun := filepath.Join(root, "xcrun") |
| + for p, body := range map[string]string{xb: fakeXcodebuild, srt: fakeSRT, xcrun: fakeXcrun} { |
| if err := os.WriteFile(p, []byte(body), 0700); err != nil { |
| t.Fatal(err) |
| } |
| } |
| - // The script and plugin places print through the build log; the |
| - // fake prints the plugin's beside the script's. |
| - if err := os.WriteFile(filepath.Join(root, "script.out"), []byte(lines["script"]+lines["plugin"]), 0600); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(filepath.Join(root, "test.out"), []byte(lines["test"]), 0600); err != nil { |
| - t.Fatal(err) |
| + // The script and plugin places print through the build log: the |
| + // script's in the project's build, the plugin's in the test build. |
| + for name, place := range map[string]string{"script.out": "script", "plugin.out": "plugin", "test.out": "test"} { |
| + if err := os.WriteFile(filepath.Join(root, name), []byte(lines[place]), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| } |
| state := filepath.Join(root, "state") |
| if err := os.MkdirAll(state, 0700); err != nil { |
| @@ -91,7 +110,7 @@ func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *prob |
| key := strings.Join(append([]string{name}, args...), " ") |
| f.execLog = append(f.execLog, key) |
| switch { |
| - case key == "xcrun simctl list -j devices available": |
| + case key == xcrun+" simctl list -j devices available": |
| return string(sims), nil |
| case strings.HasPrefix(key, "/usr/bin/security "): |
| return "", nil |
| @@ -104,7 +123,7 @@ func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *prob |
| return "", errors.New("not recorded: " + key) |
| } |
| base := []string{"PATH=/usr/bin:/bin", "HOME=" + root, "FAKE_DIR=" + root, "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")} |
| - f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: "xcrun", Node: "node", SRT: srt, RG: "rg"}, |
| + f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: xcrun, Node: "node", SRT: srt, RG: "rg"}, |
| Paths: Paths{Home: root, StateDir: state, OtherHomes: []string{"/Users/Shared", "/Users/paul"}}, |
| Scratch: filepath.Join(root, "scratch"), UID: 501, Version: "abc1234", |
| Gate: func(sandboxed bool) *Gate { |
| @@ -198,7 +217,7 @@ func TestP2IsDeniedOnlyWhenEverythingIs(t *testing.T) { |
| t.Fatalf("DNS control failed outside: %+v", p) |
| } |
| f = newProbeFixture(t, allLines("denied"), "FAKE_BUILD_FAIL=1") |
| - if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, "xcodebuild did not run in srt") { |
| + if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, "xcodebuild did not run in srt: script build exit 65: Sandbox: deny(1) mach-lookup com.apple.dt.example") { |
| t.Fatalf("the fixture did not build under srt: %+v ran=%v", p, ran) |
| } |
| f = newProbeFixture(t, allLines("denied")) |
| @@ -328,3 +347,40 @@ func TestP2NeedsTheSimulatorAndAProvenEnd(t *testing.T) { |
| t.Fatalf("no simulator: %+v", p) |
| } |
| } |
| + |
| +// A wait nothing else bounds (a command that ignores its context) ends |
| +// at the run's limit: the report has every probe, the ones not finished |
| +// not proven and listed, and stays a valid capability report. |
| +func TestRunProbesLimit(t *testing.T) { |
| + stuck := make(chan struct{}) |
| + t.Cleanup(func() { close(stuck) }) |
| + h := ProbeHost{Version: "abc1234", UID: 501, Paths: Paths{HomesUnknown: true}, Exposed: func(string) bool { return false }, Limit: 300 * time.Millisecond, |
| + Exec: func(ctx context.Context, name string, args ...string) (string, error) { |
| + if name == "/bin/launchctl" { |
| + <-stuck |
| + } |
| + return "", errors.New("not recorded") |
| + }} |
| + got := make(chan Report, 1) |
| + go func() { got <- RunProbes(context.Background(), h) }() |
| + var r Report |
| + select { |
| + case r = <-got: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the probe run outlived its limit") |
| + } |
| + if !slices.Equal(r.Unfinished, []string{"P4", "P5", "P6", "P7"}) { |
| + t.Fatalf("unfinished %v %+v", r.Unfinished, r.Probes) |
| + } |
| + for _, id := range r.Unfinished { |
| + if p := r.Probe(id); p.Verdict != wire.ProbeUnavailable || p.Detail != "not proven: the probe run reached its limit of 300ms" { |
| + t.Fatalf("%s %+v", id, p) |
| + } |
| + } |
| + if p := r.Probe("P1"); p.Verdict != wire.ProbeFailed { |
| + t.Fatalf("P1 finished before the limit: %+v", p) |
| + } |
| + if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { |
| + t.Fatalf("report outside the capability rules: %v", err) |
| + } |
| +} |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index 44dd8e0d..0e24d707 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -57,6 +57,9 @@ type Engineer struct { |
| Codex CodexOptions |
| Clones *Clones |
| Forge Forge |
| + // CI is the hub's hosted CI for checks the instance offers it for |
| + // (nil: checks always run the gate here). |
| + CI HostedCI |
| // Authorize confirms the execution lease before the step starts and |
| // right before the push. |
| Authorize func(context.Context) error |
diff --git a/internal/runner/thin/forge.go b/internal/runner/thin/forge.go| index 8b18d657..93829d86 100644 |
| --- a/internal/runner/thin/forge.go |
| +++ b/internal/runner/thin/forge.go |
| @@ -292,6 +292,44 @@ func (f *fileForge) Merge(ctx context.Context, repo, branch string, req forge.Hu |
| return forge.HubMerge(ctx, f.client, f.hub, c, repo, branch, req) |
| } |
| +// CIHosted asks the hub whether it runs repo's CI on its own machines, |
| +// with the agent's credential for repo. |
| +func (f *fileForge) CIHosted(ctx context.Context, repo string) (bool, error) { |
| + c, err := f.ciCredential(ctx, repo) |
| + if err != nil { |
| + return false, err |
| + } |
| + return forge.HubCIHosted(ctx, f.client, f.hub, c, repo) |
| +} |
| + |
| +// CIStatus reads the hub's CI verdict on branch's tip in repo. |
| +func (f *fileForge) CIStatus(ctx context.Context, repo, branch, logs string) (forge.CIStatus, error) { |
| + c, err := f.ciCredential(ctx, repo) |
| + if err != nil { |
| + return forge.CIStatus{}, err |
| + } |
| + return forge.HubCIStatus(ctx, f.client, f.hub, c, repo, branch, logs) |
| +} |
| + |
| +func (f *fileForge) ciCredential(ctx context.Context, repo string) (forge.Credential, error) { |
| + if !slices.Contains(f.Reachable(ctx), repo) { |
| + return forge.Credential{}, forge.ErrCIRead |
| + } |
| + c, err := f.creds.Credential(ctx, repo) |
| + if err != nil { |
| + return forge.Credential{}, forge.ErrCIRead |
| + } |
| + return c, nil |
| +} |
| + |
| +// hostedCIOf is the forge's hosted CI reads, when it has them. |
| +func hostedCIOf(f Forge) HostedCI { |
| + if ci, ok := f.(HostedCI); ok { |
| + return ci |
| + } |
| + return nil |
| +} |
| + |
| func (f *fileForge) record(repo string) error { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go| index 6fc37cd8..5ed36e1b 100644 |
| --- a/internal/runner/thin/judge.go |
| +++ b/internal/runner/thin/judge.go |
| @@ -211,6 +211,15 @@ func needsMacOS(changed []string, gateText string) bool { |
| // checks runs the repository's gate on the candidate. |
| func (e *Engineer) checks(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| rep := judgeReport(r) |
| + if r.Phase == phaseHosted { |
| + // Waiting for hosted CI (a deferral or a restart): the lease, then |
| + // one read of the hub. |
| + if err := e.lease(ctx, r); err != nil { |
| + rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true |
| + return rep |
| + } |
| + return e.hostedChecks(ctx, r, rep) |
| + } |
| tree, reason, err := e.judgeTree(ctx, r) |
| if err != nil { |
| rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true |
| @@ -230,15 +239,19 @@ func (e *Engineer) checks(ctx context.Context, r stepRow, progress func(wire.Ste |
| return rep |
| } |
| g, ok := findGate(tree.Dir) |
| - if !ok { |
| - rep.LogTail = "No checks found: no .amadan/ci.d, .amadan/ci or make ci target." |
| - return done(wire.ChecksNone, "") |
| - } |
| var changed []string |
| if r.BaseSHA != "" { |
| changed, _ = workspace.TaskTree{Dir: tree.Dir, GitDir: tree.GitDir, Git: tree.Git, Base: r.BaseSHA}.ChangedFiles(ctx, r.CandidateSHA) |
| } |
| - if runtime.GOOS != "darwin" && needsMacOS(changed, g.text) { |
| + mac := runtime.GOOS != "darwin" && needsMacOS(changed, g.text) |
| + if e.takeHosted(ctx, r, mac) { |
| + return e.hostedChecks(ctx, r, rep) |
| + } |
| + if !ok { |
| + rep.LogTail = "No checks found: no .amadan/ci.d, .amadan/ci or make ci target." |
| + return done(wire.ChecksNone, "") |
| + } |
| + if mac { |
| rep.LogTail = "Not run: " + g.name + " needs macOS to check this change, and this runner is " + runtime.GOOS + "." |
| return done(wire.ChecksCannotRun, "needs_macos") |
| } |
diff --git a/internal/runner/thin/judge_hosted.go b/internal/runner/thin/judge_hosted.go| new file mode 100644 |
| index 00000000..ef772b94 |
| --- /dev/null |
| +++ b/internal/runner/thin/judge_hosted.go |
| @@ -0,0 +1,191 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "slices" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// HostedCI is the hub's own CI as the primary reads it with the agent's |
| +// credential (release slice 1): whether the hub runs a repository's CI on |
| +// its machines, and its verdict on a branch's tip. |
| +type HostedCI interface { |
| + CIHosted(ctx context.Context, repo string) (bool, error) |
| + CIStatus(ctx context.Context, repo, branch, logs string) (forge.CIStatus, error) |
| +} |
| + |
| +// phaseHosted marks a checks attempt that waits for the hub's hosted CI: |
| +// it runs again after a restart instead of failing runner_restarted. |
| +const phaseHosted = "hosted" |
| + |
| +// Hosted checks wait at most hostedWait from the first deferral; each |
| +// status read is bounded by hostedRead. Variables for the tests. |
| +var ( |
| + hostedWait = 60 * time.Minute |
| + hostedRead = 30 * time.Second |
| +) |
| + |
| +// takeHosted reports whether this checks attempt takes the hub's hosted |
| +// CI verdict instead of running the gate here: the instance offered it, |
| +// the change needs no Mac, and the hub says hosted CI is on. It records |
| +// the attempt's phase first, so a restart resumes the wait. |
| +func (e *Engineer) takeHosted(ctx context.Context, r stepRow, mac bool) bool { |
| + if !r.HostedChecks || mac || e.CI == nil { |
| + return false |
| + } |
| + cctx, cancel := context.WithTimeout(ctx, hostedRead) |
| + on, err := e.CI.CIHosted(cctx, r.Repo) |
| + cancel() |
| + if err != nil || !on { |
| + return false |
| + } |
| + return e.O.State.setStepPhase(ctx, r, phaseHosted, r.Base, r.Candidate) == nil |
| +} |
| + |
| +// hostedChecks makes one read of the hub's verdict on the task branch's |
| +// tip. No verdict on the candidate yet: the attempt is deferred (the |
| +// queue moves on) until hostedWait after its first deferral. |
| +func (e *Engineer) hostedChecks(ctx context.Context, r stepRow, rep wire.StepReport) wire.StepReport { |
| + if e.CI == nil { |
| + rep.State, rep.Termination, rep.Checks, rep.Reason = wire.StepDone, true, wire.ChecksCannotRun, "checks_unavailable" |
| + return rep |
| + } |
| + cctx, cancel := context.WithTimeout(ctx, hostedRead) |
| + st, err := e.CI.CIStatus(cctx, r.Repo, r.Branch, forge.CILogsNone) |
| + cancel() |
| + if ctx.Err() != nil { |
| + rep.State, rep.Reason, rep.Termination = wire.StepCancelled, "cancelled", true |
| + return rep |
| + } |
| + if err == nil && st.SHA == r.CandidateSHA && st.UpdatedAt > 0 { |
| + if out, ok := e.hostedVerdict(ctx, r, rep, st); ok { |
| + return out |
| + } |
| + } |
| + if since := e.O.State.deferredSince(context.WithoutCancel(ctx), r); !since.IsZero() && time.Since(since) >= hostedWait { |
| + rep.State, rep.Termination, rep.Checks, rep.Reason = wire.StepDone, true, wire.ChecksCannotRun, "checks_timeout" |
| + rep.LogTail = fmt.Sprintf("Hosted CI gave no verdict on %s within %d minutes.", shortSHA(r.CandidateSHA), int(hostedWait/time.Minute)) |
| + return rep |
| + } |
| + rep.State = stepDeferred |
| + return rep |
| +} |
| + |
| +// hostedVerdict is the report for a verdict the hub gave on the |
| +// candidate, from that one snapshot (its failing logs only from a second |
| +// read of the very same run). ok is false while there is no verdict. |
| +func (e *Engineer) hostedVerdict(ctx context.Context, r stepRow, rep wire.StepReport, st forge.CIStatus) (wire.StepReport, bool) { |
| + done := func(outcome, reason string) (wire.StepReport, bool) { |
| + rep.State, rep.Termination, rep.Checks, rep.Reason = wire.StepDone, true, outcome, reason |
| + rep.Hosted = &wire.HostedResult{Repo: r.Repo, Branch: r.Branch, SHA: st.SHA, State: st.State, ReportedAt: st.UpdatedAt, Failed: failedUnits(st.Steps)} |
| + return rep, true |
| + } |
| + where := "Hosted CI on " + strings.TrimPrefix(r.Repo, "amadan.net/") + " at " + shortSHA(st.SHA) |
| + switch st.State { |
| + case wire.HostedSuccess: |
| + code := 0 |
| + rep.Gate, rep.ExitCode, rep.Output = wire.GateHosted, &code, where+": passed." |
| + rep.LogTail = rep.Output |
| + return done(wire.ChecksPassed, "") |
| + case wire.HostedFailure: |
| + code := 1 |
| + logs := "" |
| + cctx, cancel := context.WithTimeout(ctx, hostedRead) |
| + full, err := e.CI.CIStatus(cctx, r.Repo, r.Branch, forge.CILogsFailed) |
| + cancel() |
| + if err == nil && full.SHA == st.SHA && full.State == st.State && full.UpdatedAt == st.UpdatedAt { |
| + logs = failedLogs(full.Steps) |
| + } |
| + head := where + ": failed.\n" |
| + if names := failedUnits(st.Steps); len(names) > 0 { |
| + head += "Failed: " + strings.Join(names, "; ") + "\n" |
| + } |
| + if s := strings.TrimSpace(st.Summary); s != "" { |
| + head += s + "\n" |
| + } |
| + rep.Gate, rep.ExitCode, rep.Output = wire.GateHosted, &code, head+tailBytes(logs, wire.MaxChecksOutput-len(head)) |
| + rep.LogTail = lastLines(rep.Output, stepTailLines, wire.MaxLogTail) |
| + return done(wire.ChecksFailed, "") |
| + case "skipped": |
| + rep.LogTail = where + ": no CI script." |
| + return done(wire.ChecksNone, "") |
| + case "lost", "stale": |
| + rep.LogTail = where + ": the run did not finish (" + st.State + ")." |
| + return done(wire.ChecksCannotRun, "checks_unavailable") |
| + } |
| + return rep, false |
| +} |
| + |
| +// failedUnits names what failed, finest first: a sharded step's failing |
| +// shards, else the step. At most wire.MaxHostedFailed names of |
| +// wire.MaxHostedName bytes. |
| +func failedUnits(steps []forge.CIStep) []string { |
| + out := []string{} |
| + add := func(name string) { |
| + if len(out) < wire.MaxHostedFailed { |
| + out = append(out, clipName(strings.Join(strings.Fields(name), " "))) |
| + } |
| + } |
| + for _, s := range steps { |
| + if s.State != wire.HostedFailure { |
| + continue |
| + } |
| + shards := slices.IndexFunc(s.Shards, func(sh forge.CIShard) bool { return sh.State == wire.HostedFailure }) >= 0 |
| + if !shards { |
| + add(s.Name) |
| + continue |
| + } |
| + for _, sh := range s.Shards { |
| + if sh.State == wire.HostedFailure { |
| + add(s.Name + " " + sh.Name) |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func failedLogs(steps []forge.CIStep) string { |
| + var b strings.Builder |
| + for _, s := range steps { |
| + if s.Log != "" { |
| + b.WriteString("=== " + s.Name + "\n" + s.Log + "\n") |
| + } |
| + for _, sh := range s.Shards { |
| + if sh.Log != "" { |
| + b.WriteString("=== " + s.Name + " " + sh.Name + "\n" + sh.Log + "\n") |
| + } |
| + } |
| + } |
| + return b.String() |
| +} |
| + |
| +func clipName(s string) string { |
| + for len(s) > wire.MaxHostedName { |
| + _, n := utf8.DecodeLastRuneInString(s) |
| + s = s[:len(s)-n] |
| + } |
| + return s |
| +} |
| + |
| +// tailBytes is the end of s within limit bytes, starting on a line. |
| +func tailBytes(s string, limit int) string { |
| + if limit <= 0 { |
| + return "" |
| + } |
| + if len(s) <= limit { |
| + return s |
| + } |
| + s = s[len(s)-limit:] |
| + if i := strings.IndexByte(s, '\n'); i >= 0 { |
| + s = s[i+1:] |
| + } |
| + return strings.ToValidUTF8(s, "") |
| +} |
| + |
| +func shortSHA(sha string) string { return sha[:min(len(sha), 7)] } |
diff --git a/internal/runner/thin/judge_hosted_test.go b/internal/runner/thin/judge_hosted_test.go| new file mode 100644 |
| index 00000000..0c8b0bb8 |
| --- /dev/null |
| +++ b/internal/runner/thin/judge_hosted_test.go |
| @@ -0,0 +1,270 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// fakeCI is the hub's hosted CI: whether it is on, then each status read |
| +// in turn (the last one repeats); failed answers the logs=failed read. |
| +type fakeCI struct { |
| + on bool |
| + onErr error |
| + statuses []forge.CIStatus |
| + failed *forge.CIStatus |
| + calls []string |
| +} |
| + |
| +func (f *fakeCI) CIHosted(_ context.Context, repo string) (bool, error) { |
| + f.calls = append(f.calls, "hosted "+repo) |
| + return f.on, f.onErr |
| +} |
| + |
| +func (f *fakeCI) CIStatus(ctx context.Context, repo, branch, logs string) (forge.CIStatus, error) { |
| + f.calls = append(f.calls, "status "+repo+" "+branch+" "+logs) |
| + if ctx.Err() != nil { |
| + return forge.CIStatus{}, ctx.Err() |
| + } |
| + if logs == forge.CILogsFailed && f.failed != nil { |
| + return *f.failed, nil |
| + } |
| + if len(f.statuses) == 0 { |
| + return forge.CIStatus{}, forge.ErrCIRead |
| + } |
| + st := f.statuses[0] |
| + if len(f.statuses) > 1 { |
| + f.statuses = f.statuses[1:] |
| + } |
| + return st, nil |
| +} |
| + |
| +// hostedRig is a checks attempt on the hub rig's candidate, accepted in |
| +// the runner's state as the instance dispatched it (with the offer). |
| +func hostedRig(t *testing.T, ci *fakeCI) (*Engineer, stepRow, string) { |
| + t.Helper() |
| + e, f, r, cand := hubRig(t) |
| + e.CI = ci |
| + r.Specialist, r.StepID, r.HostedChecks = wire.SpecialistChecks, "c1", true |
| + r.BaseSHA = gitOut(t, f.dir, "rev-parse", "main") |
| + if err := e.O.State.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + return e, heldStep(t, e), cand |
| +} |
| + |
| +// heldStep is the checks attempt as the engine would run it next. |
| +func heldStep(t *testing.T, e *Engineer) stepRow { |
| + t.Helper() |
| + if _, err := e.O.State.db.Exec("UPDATE steps SET not_before=''"); err != nil { |
| + t.Fatal(err) |
| + } |
| + r, ok, err := e.O.State.nextStep(context.Background()) |
| + if err != nil || !ok { |
| + t.Fatalf("no attempt held: %v %v", ok, err) |
| + } |
| + return r |
| +} |
| + |
| +func ciAt(sha, state string) forge.CIStatus { |
| + return forge.CIStatus{NS: "oficina", Repo: "sample", Branch: "equipo/tk1-fix-typo", SHA: sha, State: state, UpdatedAt: 1794402264} |
| +} |
| + |
| +// TestHostedChecksPass: offered and on, the attempt waits while the hub |
| +// has no verdict on the candidate (another tip, then running), deferred |
| +// so the queue moves on, its phase kept; then it reports the hub's pass, |
| +// bound to the repository, branch, SHA and run. |
| +func TestHostedChecksPass(t *testing.T) { |
| + ci := &fakeCI{on: true, statuses: []forge.CIStatus{ciAt(strings.Repeat("9", 40), "success")}} |
| + e, r, cand := hostedRig(t, ci) |
| + ctx := context.Background() |
| + if rep := e.Exec(ctx, r, func(wire.StepReport) {}); rep.State != stepDeferred { |
| + t.Fatalf("another tip's pass counted: %+v", rep) |
| + } |
| + r = heldStep(t, e) |
| + if r.Phase != phaseHosted { |
| + t.Fatalf("phase %q", r.Phase) |
| + } |
| + ci.statuses = []forge.CIStatus{ciAt(cand, "running"), ciAt(cand, "success")} |
| + if rep := e.Exec(ctx, r, func(wire.StepReport) {}); rep.State != stepDeferred { |
| + t.Fatalf("a running run counted: %+v", rep) |
| + } |
| + rep := e.Exec(ctx, heldStep(t, e), func(wire.StepReport) {}) |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || rep.Gate != wire.GateHosted || rep.ExitCode == nil || *rep.ExitCode != 0 || !rep.Termination || rep.CandidateSHA != cand { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + h := rep.Hosted |
| + if h == nil || h.Repo != "amadan.net/oficina/sample" || h.Branch != "equipo/tk1-fix-typo" || h.SHA != cand || h.State != "success" || h.ReportedAt != 1794402264 || len(h.Failed) != 0 { |
| + t.Fatalf("binding %+v", h) |
| + } |
| + if ci.calls[0] != "hosted amadan.net/oficina/sample" || strings.Count(strings.Join(ci.calls, "\n"), "hosted ") != 1 { |
| + t.Fatalf("calls %v", ci.calls) |
| + } |
| +} |
| + |
| +// TestHostedChecksFailure: a failure names its failing units first, from |
| +// the one snapshot, with the failing logs only from a second read of the |
| +// same run; if that read is of another run, the logs are left out. |
| +func TestHostedChecksFailure(t *testing.T) { |
| + for _, sameRun := range []bool{true, false} { |
| + ci := &fakeCI{on: true} |
| + e, r, cand := hostedRig(t, ci) |
| + st := ciAt(cand, "failure") |
| + st.Summary = `step "compile" failed` |
| + st.Steps = []forge.CIStep{{Name: "compile", State: "failure"}, {Name: "check", State: "failure", Shards: []forge.CIShard{{Name: "shard 4 of 23", State: "success"}, {Name: "shard 5 of 23", State: "failure"}}}, {Name: "perf", State: "success"}} |
| + full := st |
| + full.Steps = []forge.CIStep{{Name: "compile", State: "failure", Log: "rastrillo: budget size: 1 problem(s)"}, {Name: "check", State: "failure", Shards: []forge.CIShard{{Name: "shard 5 of 23", State: "failure", Log: "--- FAIL: TestHeadless/2_project"}}}} |
| + if !sameRun { |
| + full.UpdatedAt++ |
| + } |
| + ci.statuses, ci.failed = []forge.CIStatus{st}, &full |
| + rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksFailed || rep.Gate != wire.GateHosted || rep.ExitCode == nil || *rep.ExitCode == 0 { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if rep.Hosted == nil || strings.Join(rep.Hosted.Failed, "|") != "compile|check shard 5 of 23" || rep.Hosted.State != "failure" { |
| + t.Fatalf("binding %+v", rep.Hosted) |
| + } |
| + head := "Hosted CI on oficina/sample at " + cand[:7] + ": failed.\nFailed: compile; check shard 5 of 23\nstep \"compile\" failed\n" |
| + if !strings.HasPrefix(rep.Output, head) { |
| + t.Fatalf("output %q", rep.Output) |
| + } |
| + hasLogs := strings.Contains(rep.Output, "budget size: 1 problem") && strings.Contains(rep.Output, "=== check shard 5 of 23\n--- FAIL: TestHeadless/2_project") |
| + if hasLogs != sameRun { |
| + t.Fatalf("same run %v, logs %v: %q", sameRun, hasLogs, rep.Output) |
| + } |
| + } |
| +} |
| + |
| +// TestHostedChecksOtherEnds: no CI script is no checks, a run the hub |
| +// lost could not run, and no verdict within the deadline (counted from |
| +// the first deferral, which a restart keeps) is a timeout. |
| +func TestHostedChecksOtherEnds(t *testing.T) { |
| + for state, want := range map[string]string{"skipped": wire.ChecksNone, "lost": wire.ChecksCannotRun, "stale": wire.ChecksCannotRun} { |
| + ci := &fakeCI{on: true} |
| + e, r, cand := hostedRig(t, ci) |
| + ci.statuses = []forge.CIStatus{ciAt(cand, state)} |
| + rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| + if rep.State != wire.StepDone || rep.Checks != want || rep.Gate != "" || rep.ExitCode != nil || rep.Hosted == nil || rep.Hosted.State != state { |
| + t.Fatalf("%s: %+v", state, rep) |
| + } |
| + if want == wire.ChecksCannotRun && rep.Reason != "checks_unavailable" { |
| + t.Fatalf("%s reason %q", state, rep.Reason) |
| + } |
| + } |
| + ci := &fakeCI{on: true, statuses: []forge.CIStatus{ciAt(strings.Repeat("9", 40), "success")}} |
| + e, r, _ := hostedRig(t, ci) |
| + ctx := context.Background() |
| + if rep := e.Exec(ctx, r, func(wire.StepReport) {}); rep.State != stepDeferred { |
| + t.Fatalf("first %+v", rep) |
| + } |
| + if err := e.O.State.deferStep(ctx, heldStep(t, e), 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rep := e.Exec(ctx, heldStep(t, e), func(wire.StepReport) {}); rep.State != stepDeferred { |
| + t.Fatalf("within the deadline %+v", rep) |
| + } |
| + old := stamp(time.Now().Add(-hostedWait - time.Minute)) |
| + if _, err := e.O.State.db.Exec("UPDATE steps SET deferred_since=?", old); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.O.State.deferStep(ctx, heldStep(t, e), 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + rep := e.Exec(ctx, heldStep(t, e), func(wire.StepReport) {}) |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksCannotRun || rep.Reason != "checks_timeout" || rep.Hosted != nil { |
| + t.Fatalf("after the deadline %+v", rep) |
| + } |
| +} |
| + |
| +// TestHostedChecksNotTaken: without the instance's offer, with hosted CI |
| +// off, or when the hub cannot say, the runner runs its own gate as |
| +// before (this repository has none) and never asks for a verdict; a |
| +// change that needs a Mac is never offered to hosted CI. |
| +func TestHostedChecksNotTaken(t *testing.T) { |
| + for name, c := range map[string]struct { |
| + offer bool |
| + ci *fakeCI |
| + }{ |
| + "no offer": {false, &fakeCI{on: true}}, |
| + "off": {true, &fakeCI{on: false}}, |
| + "read error": {true, &fakeCI{on: true, onErr: forge.ErrCIRead}}, |
| + } { |
| + e, r, _ := hostedRig(t, c.ci) |
| + r.HostedChecks = c.offer |
| + rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksNone || rep.Hosted != nil { |
| + t.Fatalf("%s: %+v", name, rep) |
| + } |
| + if strings.Contains(strings.Join(c.ci.calls, "\n"), "status ") || !c.offer && len(c.ci.calls) != 0 { |
| + t.Fatalf("%s: calls %v", name, c.ci.calls) |
| + } |
| + if r := heldStep(t, e); r.Phase == phaseHosted { |
| + t.Fatalf("%s: phase kept", name) |
| + } |
| + } |
| + ci := &fakeCI{on: true} |
| + e, r, _ := hostedRig(t, ci) |
| + if e.takeHosted(context.Background(), r, true) || len(ci.calls) != 0 { |
| + t.Fatalf("a Mac change went to hosted CI: %v", ci.calls) |
| + } |
| +} |
| + |
| +// TestHostedChecksAfterRestart: a runner that stops while its checks wait |
| +// for hosted CI does not fail them runner_restarted; the attempt is held |
| +// and reads the hub again. Cancel and withdrawal still end it. |
| +func TestHostedChecksAfterRestart(t *testing.T) { |
| + ci := &fakeCI{on: true, statuses: []forge.CIStatus{ciAt(strings.Repeat("9", 40), "success")}} |
| + e, r, cand := hostedRig(t, ci) |
| + ctx := context.Background() |
| + if rep := e.Exec(ctx, r, func(wire.StepReport) {}); rep.State != stepDeferred { |
| + t.Fatalf("first %+v", rep) |
| + } |
| + if err := e.O.State.RecoverSteps(ctx, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if reps := outbox(t, e.O.State); len(reps) != 0 { |
| + t.Fatalf("recovery reported %+v", reps) |
| + } |
| + ci.statuses = []forge.CIStatus{ciAt(cand, "success")} |
| + if rep := e.Exec(ctx, heldStep(t, e), func(wire.StepReport) {}); rep.Checks != wire.ChecksPassed || rep.Hosted == nil { |
| + t.Fatalf("after restart %+v", rep) |
| + } |
| + |
| + e.AuthorizeStep = func(context.Context, string, int64) error { return ErrWithdrawn } |
| + if rep := e.Exec(ctx, heldStep(t, e), func(wire.StepReport) {}); rep.State != wire.StepCancelled || rep.Reason != "withdrawn" { |
| + t.Fatalf("withdrawn %+v", rep) |
| + } |
| + e.AuthorizeStep = nil |
| + cctx, cancel := context.WithCancel(ctx) |
| + cancel() |
| + if rep := e.Exec(cctx, heldStep(t, e), func(wire.StepReport) {}); rep.State != wire.StepCancelled { |
| + t.Fatalf("cancelled %+v", rep) |
| + } |
| + if !errors.Is(cctx.Err(), context.Canceled) { |
| + t.Fatal("context") |
| + } |
| +} |
| + |
| +// TestHostedFailedUnitsBounded: however many units fail, and however long |
| +// their names, the binding stays within its bounds. |
| +func TestHostedFailedUnitsBounded(t *testing.T) { |
| + var steps []forge.CIStep |
| + for i := 0; i < 40; i++ { |
| + steps = append(steps, forge.CIStep{Name: strings.Repeat("é", 200) + string(rune('a'+i%26)), State: "failure"}) |
| + } |
| + names := failedUnits(steps) |
| + if len(names) != wire.MaxHostedFailed { |
| + t.Fatalf("%d names", len(names)) |
| + } |
| + for _, n := range names { |
| + if len(n) > wire.MaxHostedName || !strings.HasPrefix(n, "é") || strings.ContainsRune(n, '�') { |
| + t.Fatalf("name %q (%d bytes)", n, len(n)) |
| + } |
| + } |
| +} |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index 4e6cf78a..9dd25d4b 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -290,6 +290,9 @@ func (p *macProbes) start(ctx context.Context, refresh func()) { |
| p.log.Log(ctx, level, "probes finished", "took", took(start), "verdicts", v) |
| said = v |
| } |
| + if len(r.Unfinished) > 0 && p.log != nil { |
| + p.log.Warn("probe run reached its limit; unfinished probes are not proven", "unfinished", strings.Join(r.Unfinished, " ")) |
| + } |
| if before && p.verified() { |
| r.SRT = srtPinned |
| } |
| @@ -572,8 +575,12 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| settings := func(tree, attempt string) ([]byte, error) { |
| return mac.ChecksSettings(mac.ChecksInput{Paths: h.paths, Tree: tree, Attempt: attempt, Mach: mac.CheckMachServices}) |
| } |
| + // Both bounded: a simctl that never answers (CoreSimulator stuck) |
| + // must not hold a gate or a probe run. |
| booted := func(ctx context.Context) []string { |
| - out, err := h.run(ctx, h.tools.Xcrun, "simctl", "list", "-j", "devices", "booted") |
| + c, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| + defer cancel() |
| + out, err := h.run(c, h.tools.Xcrun, "simctl", "list", "-j", "devices", "booted") |
| var udids []string |
| if err == nil { |
| for _, s := range mac.ParseSimulators([]byte(out)) { |
| @@ -634,6 +641,14 @@ func (h *macHost) probeHost(version string, gate func(string, string) *mac.Gate) |
| }, |
| Exposed: mac.Exposed, |
| Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, |
| + Warn: h.warn, |
| + } |
| +} |
| + |
| +// warn is runner.log at WARN, nil when there is no log. |
| +func (h *macHost) warn(msg string, args ...any) { |
| + if h.log != nil { |
| + h.log.Warn(msg, args...) |
| } |
| } |
| @@ -680,7 +695,7 @@ func serveMac(ctx context.Context, c runner.Config, o Options, h *macHost) error |
| if w.Tainted { |
| h.taint.Set() |
| } |
| - up.offer(w, func() func() { worker.mu.Lock(); return worker.mu.Unlock }, func() { stop(ErrUpdated) }, o.Logger) |
| + up.offer(w, worker.hold, func() { stop(ErrUpdated) }, o.Logger) |
| }}) |
| } |
diff --git a/internal/runner/thin/mac_stall_test.go b/internal/runner/thin/mac_stall_test.go| new file mode 100644 |
| index 00000000..6c7a4014 |
| --- /dev/null |
| +++ b/internal/runner/thin/mac_stall_test.go |
| @@ -0,0 +1,269 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/mac" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// stallXcrun plays an xcrun whose simctl never answers: the hanging |
| +// call leaves a child (sleep) holding its output, as a stuck |
| +// CoreSimulator client would. Every pid goes in PIDS so the test can |
| +// prove them gone and kill any left, by pid. |
| +const stallXcrun = `#!/bin/sh |
| +echo $$ >> PIDS |
| +case "$*" in |
| +*"devices available"*) [ -z "HANG_AVAILABLE" ] && { cat SIMS; exit 0; } ;; |
| +esac |
| +sleep 600 & |
| +echo $! >> PIDS |
| +wait |
| +` |
| + |
| +const stallXcodebuild = `#!/bin/sh |
| +case "$*" in |
| +-version) echo "Xcode 16.2"; echo "Build version 16C5032a"; exit 0 ;; |
| +esac |
| +exit 64 |
| +` |
| + |
| +// stallHost is a Mac host on Linux whose xcrun hangs: on every simctl |
| +// call (all) or only on the booted list the probes' gates ask (P6). |
| +func stallHost(t *testing.T, all bool) (*macHost, string) { |
| + t.Helper() |
| + root := t.TempDir() |
| + pids := filepath.Join(root, "pids") |
| + sims, err := filepath.Abs("../mac/testdata/simctl-devices.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hang := "" |
| + if all { |
| + hang = "1" |
| + } |
| + xcrun := strings.NewReplacer("PIDS", pids, "SIMS", sims, `"HANG_AVAILABLE"`, `"`+hang+`"`).Replace(stallXcrun) |
| + tools := mac.Tools{Xcrun: filepath.Join(root, "xcrun"), Xcodebuild: filepath.Join(root, "xcodebuild")} |
| + for p, body := range map[string]string{tools.Xcrun: xcrun, tools.Xcodebuild: stallXcodebuild} { |
| + if err := os.WriteFile(p, []byte(body), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + t.Cleanup(func() { |
| + raw, _ := os.ReadFile(pids) |
| + for _, f := range strings.Fields(string(raw)) { |
| + if pid, err := strconv.Atoi(f); err == nil && pid > 1 { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + } |
| + }) |
| + was, users := mac.QueryLimit, macUsers |
| + mac.QueryLimit, macUsers = 300*time.Millisecond, filepath.Join(root, "Users") |
| + t.Cleanup(func() { mac.QueryLimit, macUsers = was, users }) |
| + c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: filepath.Join(root, "lib", "runner")} |
| + for _, d := range []string{c.StateDir, c.ScratchRoot} { |
| + if err := os.MkdirAll(d, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + h, err := newMacHost(c, OptionsFromEnv(func(string) string { return "" })) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.tools = tools |
| + return h, pids |
| +} |
| + |
| +// alive lists the recorded pids still running after a short settle. |
| +func alive(pids string) []string { |
| + deadline := time.Now().Add(3 * time.Second) |
| + for { |
| + raw, _ := os.ReadFile(pids) |
| + var left []string |
| + for _, f := range strings.Fields(string(raw)) { |
| + if pid, err := strconv.Atoi(f); err == nil && syscall.Kill(pid, 0) == nil { |
| + if stat, _ := os.ReadFile("/proc/" + f + "/stat"); !strings.Contains(string(stat), ") Z ") { |
| + left = append(left, f) |
| + } |
| + } |
| + } |
| + if len(left) == 0 || time.Now().After(deadline) { |
| + return left |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| +} |
| + |
| +// A simctl that never answers no longer holds the probes: each query is |
| +// killed at QueryLimit with what it started, the run finishes, ready |
| +// closes, and the report says why the simulator probes could not run. |
| +// The booted list the probes' gates ask (Paul's Studio, 15:44) is |
| +// bounded as well as the capability list. |
| +func TestMacProbesFinishWhenSimctlHangs(t *testing.T) { |
| + for _, all := range []bool{true, false} { |
| + t.Run(map[bool]string{true: "every simctl", false: "the booted list"}[all], func(t *testing.T) { |
| + h, pids := stallHost(t, all) |
| + start := time.Now() |
| + h.probes.start(t.Context(), func() {}) |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + if err := h.probes.wait(ctx); err != nil { |
| + t.Fatalf("the probe run did not finish (ready never closed): %v", err) |
| + } |
| + if took := time.Since(start); took > 15*time.Second { |
| + t.Fatalf("the probe run took %s", took) |
| + } |
| + r := h.probes.report() |
| + if len(r.Probes) != len(wire.ProbeIDs) || len(r.Unfinished) != 0 { |
| + t.Fatalf("report %+v", r) |
| + } |
| + if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { |
| + t.Fatalf("report outside the capability rules: %v", err) |
| + } |
| + p1, p6 := r.Probe("P1"), r.Probe("P6") |
| + if all { |
| + why := "simulator unavailable: simctl did not answer in 300ms" |
| + if p1.Verdict != wire.ProbeFailed || !strings.Contains(p1.Detail, why) || p6.Verdict != wire.ProbeUnavailable || p6.Detail != why { |
| + t.Fatalf("P1 %+v P6 %+v", p1, p6) |
| + } |
| + } else if p6.Verdict != wire.ProbeFailed || !strings.Contains(p6.Detail, "did not start") { |
| + // The fake xcodebuild runs no test: P6 ran its gate (which |
| + // asked the booted list twice) and says so. |
| + t.Fatalf("P6 %+v", p6) |
| + } |
| + if left := alive(pids); len(left) != 0 { |
| + t.Fatalf("hung simctl processes left: %v", left) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// updateServer serves release bbb2222 with a runner whose digest its |
| +// manifest names. |
| +func updateServer(t *testing.T) (string, []byte) { |
| + newBin := []byte("#!new runner\n") |
| + sum := sha256.Sum256(newBin) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch { |
| + case r.URL.Path == "/releases/bbb2222/install-manifest.json": |
| + _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "bbb2222", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: hex.EncodeToString(sum[:])}}}) |
| + case strings.HasPrefix(r.URL.Path, "/releases/bbb2222/"+release.DarwinDir+"/"): |
| + _, _ = w.Write(newBin) |
| + default: |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + return srv.URL, newBin |
| +} |
| + |
| +// heldGate runs only once the test lets it. |
| +type heldGate struct { |
| + *stubGate |
| + started, release chan struct{} |
| +} |
| + |
| +func (g heldGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { |
| + close(g.started) |
| + <-g.release |
| + return g.stubGate.Run(ctx, a, dir, argv, l, record) |
| +} |
| + |
| +// The updater does not wait for the probes: with the probes stalled for |
| +// good and a step waiting on them, a new release is swapped in and the |
| +// worker stopped with ErrUpdated at once. A step that really runs still |
| +// holds the swap until it ends. |
| +func TestMacUpdateWhileProbesStall(t *testing.T) { |
| + origin, newBin := updateServer(t) |
| + update := func(t *testing.T, w *Worker, stop func()) (string, *macUpdater) { |
| + binary := filepath.Join(t.TempDir(), "runner") |
| + if err := os.WriteFile(binary, []byte("#!old runner\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + u := &macUpdater{origin: origin, version: "aaa1111", binary: binary, fetch: fetchLimited} |
| + u.offer(wire.Welcome{Release: "bbb2222"}, w.hold, stop, nil) |
| + return binary, u |
| + } |
| + swapped := func(binary string) bool { raw, _ := os.ReadFile(binary); return string(raw) == string(newBin) } |
| + |
| + t.Run("probes stalled", func(t *testing.T) { |
| + x := newWorkerRig(t) |
| + x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| + waiting := make(chan struct{}) |
| + x.w.Ready = func(ctx context.Context) error { |
| + close(waiting) |
| + <-ctx.Done() |
| + return ctx.Err() |
| + } |
| + ctx, stop := context.WithCancelCause(context.Background()) |
| + defer stop(nil) |
| + reps := make(chan wire.StepReport, 1) |
| + go func() { reps <- x.w.Exec(ctx, x.r, func(wire.StepReport) {}) }() |
| + <-waiting |
| + binary, u := update(t, x.w, func() { stop(ErrUpdated) }) |
| + select { |
| + case err := <-u.done: |
| + if err != nil || !swapped(binary) || !errors.Is(context.Cause(ctx), ErrUpdated) { |
| + t.Fatalf("update: %v swapped=%v cause=%v", err, swapped(binary), context.Cause(ctx)) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the update waited for probes that never finish") |
| + } |
| + select { |
| + case rep := <-reps: |
| + if rep.State != wire.StepCancelled || len(x.gate.ran) != 0 { |
| + t.Fatalf("waiting step %+v ran %v", rep, x.gate.ran) |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the waiting step did not end with the worker") |
| + } |
| + }) |
| + |
| + t.Run("step running", func(t *testing.T) { |
| + x := newWorkerRig(t) |
| + x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| + g := heldGate{stubGate: x.gate, started: make(chan struct{}), release: make(chan struct{})} |
| + x.w.Gate = g |
| + reps := make(chan wire.StepReport, 1) |
| + go func() { reps <- x.run() }() |
| + <-g.started |
| + stopped := make(chan struct{}) |
| + binary, u := update(t, x.w, func() { close(stopped) }) |
| + select { |
| + case <-u.done: |
| + t.Fatal("the update did not wait for the running step") |
| + case <-time.After(500 * time.Millisecond): |
| + } |
| + if swapped(binary) { |
| + t.Fatal("binary swapped while a step ran") |
| + } |
| + close(g.release) |
| + if rep := <-reps; rep.State != wire.StepDone { |
| + t.Fatalf("step %+v", rep) |
| + } |
| + select { |
| + case err := <-u.done: |
| + if err != nil || !swapped(binary) { |
| + t.Fatalf("update after the step: %v", err) |
| + } |
| + <-stopped |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the update never applied after the step") |
| + } |
| + }) |
| +} |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 7413aa8c..55e7911e 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -267,7 +267,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if err = engine.Start(ctx); err != nil { |
| return err |
| } |
| - engineer := &Engineer{O: o.Claude, Codex: o.Codex, Clones: clones, Forge: fg, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel} |
| + engineer := &Engineer{O: o.Claude, Codex: o.Codex, Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel} |
| link.Forget = engineer.RemoveKept |
| merges := &MergeWatch{State: state, Clones: clones, Git: c.GitPath, Notify: link.Notify, Logger: o.Logger, Every: o.MergeEvery} |
| if merges.Every <= 0 { |
diff --git a/internal/runner/thin/startup_logs_test.go b/internal/runner/thin/startup_logs_test.go| index f1bfae02..16264388 100644 |
| --- a/internal/runner/thin/startup_logs_test.go |
| +++ b/internal/runner/thin/startup_logs_test.go |
| @@ -202,3 +202,15 @@ func TestMacSlowCommandLogged(t *testing.T) { |
| t.Fatalf("a quick command logged: %v %q", err, quiet.String()) |
| } |
| } |
| + |
| +// Why P2's srt run failed reaches runner.log at WARN through the probes' |
| +// host; a host without a log says nothing and does not fail. |
| +func TestMacP2FailureLogged(t *testing.T) { |
| + logs := &syncBuffer{} |
| + h := &macHost{log: slog.New(slog.NewTextHandler(logs, nil))} |
| + h.probeHost("v1", nil).Warn("p2 srt run failed", "phase", "test build", "exit", 65) |
| + if out := logs.String(); !strings.Contains(out, `level=WARN msg="p2 srt run failed" phase="test build" exit=65`) { |
| + t.Fatalf("runner.log:\n%s", out) |
| + } |
| + (&macHost{}).probeHost("v1", nil).Warn("p2 srt run failed") |
| +} |
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go| index 984822dd..5287f62d 100644 |
| --- a/internal/runner/thin/step.go |
| +++ b/internal/runner/thin/step.go |
| @@ -384,6 +384,10 @@ func (s *State) RecoverSteps(ctx context.Context, verify func(context.Context, s |
| // A merge settles itself from its record and the default |
| // branch: it runs again and never merges twice. |
| continue |
| + case r.Specialist == wire.SpecialistChecks && r.Phase == phaseHosted && !r.Cancel: |
| + // Checks waiting for hosted CI ran nothing here: they read |
| + // the hub again, within the same deadline. |
| + continue |
| case r.Cancel: |
| rep.State, rep.Reason = wire.StepCancelled, "cancelled" |
| default: |
diff --git a/internal/runner/thin/worker.go b/internal/runner/thin/worker.go| index f26752ef..0d0e1ce1 100644 |
| --- a/internal/runner/thin/worker.go |
| +++ b/internal/runner/thin/worker.go |
| @@ -70,11 +70,21 @@ type Worker struct { |
| Ready func(context.Context) error |
| // mu is held while an attempt runs, so an update swaps the binary |
| - // only between steps; marker is that attempt's EQUIPO_ATTEMPT. |
| + // only between steps; marker is that attempt's EQUIPO_ATTEMPT. An |
| + // attempt waiting for Ready does not hold it. |
| mu sync.Mutex |
| marker string |
| } |
| +// hold waits until no attempt runs and keeps the next one from starting |
| +// until the returned release (the Mac updater swaps the binary there). |
| +// It never waits for Ready: probes that never finish must not keep the |
| +// runner on an old release. |
| +func (w *Worker) hold() func() { |
| + w.mu.Lock() |
| + return w.mu.Unlock |
| +} |
| + |
| func (w *Worker) root() string { return filepath.Join(w.Engine.O.Runner.StateDir, "worker") } |
| func (w *Worker) stepsDir() string { |
| @@ -110,13 +120,20 @@ func (w *Worker) Exec(ctx context.Context, r stepRow, progress func(wire.StepRep |
| // Only checks are placed on workers until slice F. |
| return end(wire.StepFailed, "placement_refused") |
| } |
| - w.mu.Lock() |
| - defer w.mu.Unlock() |
| + // Ready first, outside mu: a step waiting for the probes is not a |
| + // step running, and the updater's hold must not wait for it. |
| if w.Ready != nil { |
| if err := w.Ready(ctx); err != nil { |
| return end(wire.StepCancelled, "cancelled") |
| } |
| } |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + // An update may have swapped the binary and stopped the worker while |
| + // this step waited for mu. |
| + if ctx.Err() != nil { |
| + return end(wire.StepCancelled, "cancelled") |
| + } |
| // The attempt's marker is on record before anything of it runs: every |
| // process it starts (git here, the gate later) carries it, so a |
| // restarted runner can find them even if no group was recorded. |
diff --git a/internal/thintest/hosted_checks_contract_test.go b/internal/thintest/hosted_checks_contract_test.go| new file mode 100644 |
| index 00000000..37ebeb13 |
| --- /dev/null |
| +++ b/internal/thintest/hosted_checks_contract_test.go |
| @@ -0,0 +1,138 @@ |
| +package thintest |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// hostedReport is the primary's checks report with the hub's hosted CI |
| +// verdict on d's candidate, bound to the task's branch. |
| +func hostedReport(d *wire.DispatchCommand, branch, state string, failed ...string) wire.StepReport { |
| + rep := wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA, Termination: true, Findings: []wire.Finding{}, Gate: wire.GateHosted, |
| + Hosted: &wire.HostedResult{Repo: "amadan.net/oficina/sample", Branch: branch, SHA: d.CandidateSHA, State: state, ReportedAt: 1794402264, Failed: append([]string{}, failed...)}} |
| + switch state { |
| + case wire.HostedSuccess: |
| + rep.Checks, rep.ExitCode, rep.Output = wire.ChecksPassed, exit(0), "Hosted CI on oficina/sample: passed." |
| + case wire.HostedFailure: |
| + rep.Checks, rep.ExitCode = wire.ChecksFailed, exit(1) |
| + rep.Output = "Hosted CI on oficina/sample: failed.\nFailed: " + strings.Join(failed, "; ") + "\n=== compile\nrastrillo: budget size: 1 problem(s)\n" |
| + } |
| + return rep |
| +} |
| + |
| +// TestContractHostedChecksPass: a checks step on the primary is offered |
| +// hosted CI; the hub's pass on the candidate is checks that ran (Review |
| +// reads it, the task is ready to merge), recorded as hosted, but the hub |
| +// cannot say where the verdict ran, so Equipo asks rather than merging on |
| +// its own. |
| +func TestContractHostedChecksPass(t *testing.T) { |
| + r := newToolRigAt(t, wire.ProtocolHostedChecks) |
| + ctx := r.ctx |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id, _ := r.pushed("h", "Fix the README typo", base, cand) |
| + task, _ := r.client.Task(ctx, id) |
| + r.expect(wire.FrameWatchMerge) |
| + c := r.dispatched(wire.SpecialistChecks, base, cand, 0) |
| + if !c.HostedChecks { |
| + t.Fatalf("checks on the primary not offered hosted CI: %+v", c) |
| + } |
| + r.step("h-c", hostedReport(c, task.Branch, wire.HostedSuccess)) |
| + rv := r.dispatched(wire.SpecialistReview, base, cand, 0) |
| + if rv.HostedChecks || !strings.Contains(rv.Brief, "hosted CI passed.") { |
| + t.Fatalf("review dispatch %+v", rv) |
| + } |
| + k, _ := r.client.Task(ctx, id) |
| + if k.Checks != wire.ChecksPassed || k.ChecksSandbox != wire.SandboxHosted { |
| + t.Fatalf("task %+v", k) |
| + } |
| + r.verdict("h-r", rv, wire.VerdictApprove) |
| + card := r.mergeCardsWait(id) |
| + if !strings.Contains(card.Question, "its checks ran outside the sandbox") { |
| + t.Fatalf("merge card %q", card.Question) |
| + } |
| + for _, h := range r.held { |
| + if d, ok := h.body.(*wire.DispatchCommand); ok && d.Specialist == wire.SpecialistMerge { |
| + t.Fatal("merged on its own on a hosted pass") |
| + } |
| + } |
| +} |
| + |
| +// TestContractHostedChecksFailure: the hub's failure starts the fix round, |
| +// whose feedback names the failing units from the stored binding before |
| +// the output's tail. |
| +func TestContractHostedChecksFailure(t *testing.T) { |
| + r := newToolRigAt(t, wire.ProtocolHostedChecks) |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id, _ := r.pushed("f", "Fix the README typo", base, cand) |
| + task, _ := r.client.Task(r.ctx, id) |
| + r.expect(wire.FrameWatchMerge) |
| + c := r.dispatched(wire.SpecialistChecks, base, cand, 0) |
| + r.step("f-c", hostedReport(c, task.Branch, wire.HostedFailure, "compile", "check shard 5 of 23")) |
| + fix := r.dispatched(wire.SpecialistEngineering, cand, "", 1) |
| + want := "The repository's hosted CI failed on " + cand[:7] + " in: compile; check shard 5 of 23." |
| + if !strings.Contains(fix.Feedback, want) || !strings.Contains(fix.Feedback, "budget size: 1 problem") { |
| + t.Fatalf("fix round feedback %q", fix.Feedback) |
| + } |
| +} |
| + |
| +// TestContractHostedBindingRules: a hosted verdict counts only when every |
| +// part of its binding is exactly what was judged, from a protocol 5 |
| +// primary; any other report is ignored and the step waits on. |
| +func TestContractHostedBindingRules(t *testing.T) { |
| + for name, bend := range map[string]func(*wire.StepReport){ |
| + "another repository": func(v *wire.StepReport) { v.Hosted.Repo = "amadan.net/oficina/other" }, |
| + "another branch": func(v *wire.StepReport) { v.Hosted.Branch = "equipo/other" }, |
| + "another commit": func(v *wire.StepReport) { v.Hosted.SHA = strings.Repeat("9", 40) }, |
| + "state disagrees": func(v *wire.StepReport) { v.Hosted.State = wire.HostedFailure }, |
| + "no report time": func(v *wire.StepReport) { v.Hosted.ReportedAt = 0 }, |
| + "no binding": func(v *wire.StepReport) { v.Hosted = nil }, |
| + "binding, other gate": func(v *wire.StepReport) { |
| + v.Gate = "make ci" |
| + }, |
| + "too many units": func(v *wire.StepReport) { |
| + v.Hosted.Failed = make([]string, wire.MaxHostedFailed+1) |
| + for i := range v.Hosted.Failed { |
| + v.Hosted.Failed[i] = "unit" |
| + } |
| + }, |
| + "a unit too long": func(v *wire.StepReport) { v.Hosted.Failed = []string{strings.Repeat("u", wire.MaxHostedName+1)} }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + r := newToolRigAt(t, wire.ProtocolHostedChecks) |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id, _ := r.pushed("b", "Fix the README typo", base, cand) |
| + task, _ := r.client.Task(r.ctx, id) |
| + r.expect(wire.FrameWatchMerge) |
| + c := r.dispatched(wire.SpecialistChecks, base, cand, 0) |
| + rep := hostedReport(c, task.Branch, wire.HostedSuccess) |
| + bend(&rep) |
| + r.step("b-c", rep) |
| + if k, _ := r.client.Task(r.ctx, id); k.Checks != "" || k.Steps[1].State == wire.StepDone { |
| + t.Fatalf("counted: %+v", k.Steps[1]) |
| + } |
| + // The exact binding still counts afterwards. |
| + r.step("b-c-ok", hostedReport(c, task.Branch, wire.HostedSuccess)) |
| + r.dispatched(wire.SpecialistReview, base, cand, 0) |
| + }) |
| + } |
| +} |
| + |
| +// TestContractHostedChecksOldRunner: a runner at protocol 4 is never |
| +// offered hosted CI, and a hosted binding from it counts for nothing. |
| +func TestContractHostedChecksOldRunner(t *testing.T) { |
| + r := newToolRigAt(t, wire.ProtocolMergeFacts) |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id, _ := r.pushed("o", "Fix the README typo", base, cand) |
| + task, _ := r.client.Task(r.ctx, id) |
| + r.expect(wire.FrameWatchMerge) |
| + c := r.dispatched(wire.SpecialistChecks, base, cand, 0) |
| + if c.HostedChecks || strings.Contains(string(r.runner.Received[len(r.runner.Received)-1]), "hosted_checks") { |
| + t.Fatalf("offered to a protocol 4 runner: %+v", c) |
| + } |
| + r.step("o-c", hostedReport(c, task.Branch, wire.HostedSuccess)) |
| + if k, _ := r.client.Task(r.ctx, id); k.Checks != "" { |
| + t.Fatalf("a protocol 4 runner's hosted verdict counted: %+v", k) |
| + } |
| +} |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index 726dcf3e..1ae18b72 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -26,6 +26,7 @@ const ( |
| Protocol2 = 2 |
| Protocol3 = 3 |
| Protocol4 = 4 |
| + Protocol5 = 5 |
| // ProtocolSpend is the first protocol with a fix round's Feedback and |
| // a usage row's Turns; Encode drops both below it. |
| ProtocolSpend = Protocol3 |
| @@ -33,7 +34,11 @@ const ( |
| // fields; Encode drops them below it, and Equipo merges on its own |
| // only with a runner that speaks it. |
| ProtocolMergeFacts = Protocol4 |
| - ProtocolCurrent = ProtocolMergeFacts |
| + // ProtocolHostedChecks is the first protocol with hosted checks (a |
| + // checks dispatch's offer and the report's hosted binding); Encode |
| + // drops both below it, so the runner runs its own gate as before. |
| + ProtocolHostedChecks = Protocol5 |
| + ProtocolCurrent = ProtocolHostedChecks |
| ) |
| // Runner roles. A person's first runner is the primary: the coordinator, |
| @@ -51,6 +56,9 @@ const ( |
| // SandboxNone is the test-build fake worker only: it runs checks in a |
| // process group without a sandbox. |
| SandboxNone = "none" |
| + // SandboxHosted is the instance's record that a checks verdict came |
| + // from the hub's hosted CI (release slice 1); runners never report it. |
| + SandboxHosted = "hosted" |
| ) |
| // Capability tags, a fixed set. A step's needs are a subset. |
| @@ -358,7 +366,8 @@ func Speaks(protocol int, kind string) bool { return protocol >= Protocol2 || !p |
| var ErrProtocol = errors.New("wire: frame not in this protocol") |
| // Encode returns f as the given protocol speaks it. Below |
| -// ProtocolMergeFacts the merge authority fields are dropped; below |
| +// ProtocolHostedChecks the hosted checks fields are dropped; below |
| +// ProtocolMergeFacts the merge authority fields too; below |
| // ProtocolSpend the spend fields too; at protocol 1 it is exactly the |
| // slice 4 frame and field set: protocol 2 fields are dropped and a |
| // protocol 2 frame type is refused (ErrProtocol). |
| @@ -374,8 +383,11 @@ func Encode(f Frame, protocol int) (Frame, error) { |
| return Frame{}, err |
| } |
| changed := false |
| + if protocol < ProtocolHostedChecks { |
| + changed = downgradeHostedChecks(body) |
| + } |
| if protocol < ProtocolMergeFacts { |
| - changed = downgradeMergeFacts(body) |
| + changed = downgradeMergeFacts(body) || changed |
| } |
| if protocol < ProtocolSpend { |
| changed = downgradeSpend(body) || changed |
| @@ -394,6 +406,29 @@ func Encode(f Frame, protocol int) (Frame, error) { |
| return f, nil |
| } |
| +// downgradeHostedChecks clears a body's ProtocolHostedChecks fields |
| +// (omitempty). It reports whether the body had any. |
| +func downgradeHostedChecks(body any) bool { |
| + switch v := body.(type) { |
| + case *DispatchCommand: |
| + set := v.HostedChecks |
| + v.HostedChecks = false |
| + return set |
| + case *StepReport: |
| + // A hosted verdict means nothing without its binding: an older |
| + // instance gets checks that could not run, never a bare pass. |
| + if v.Hosted == nil && v.Gate != GateHosted { |
| + return false |
| + } |
| + v.Hosted, v.Gate, v.ExitCode = nil, "", nil |
| + if v.Checks != "" { |
| + v.Checks, v.Reason = ChecksCannotRun, "checks_unavailable" |
| + } |
| + return true |
| + } |
| + return false |
| +} |
| + |
| // downgradeMergeFacts clears a body's ProtocolMergeFacts fields (all |
| // omitempty). It reports whether the body has any. |
| func downgradeMergeFacts(body any) bool { |
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go| index 6f1b7324..ecf72828 100644 |
| --- a/internal/wire/runners_test.go |
| +++ b/internal/wire/runners_test.go |
| @@ -242,3 +242,51 @@ func TestEncodeProtocol2DropsProtocol3Fields(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// Protocol 5 (hosted checks) adds the dispatch's offer of hosted CI and |
| +// a checks report's hosted binding. Encoded for an older peer, whose |
| +// strict decoder knows neither, the offer is gone and a hosted verdict |
| +// becomes checks that could not run: never a pass an old instance would |
| +// take without its binding. At protocol 5 both pass through. |
| +func TestEncodeBelowProtocol5DropsHostedChecks(t *testing.T) { |
| + hosted := &wire.HostedResult{Repo: "amadan.net/oficina/sample", Branch: "equipo/tk-fix", SHA: strings.Repeat("2", 40), State: wire.HostedSuccess, ReportedAt: 1794402264, Failed: []string{}} |
| + code := 0 |
| + for _, c := range []struct { |
| + kind string |
| + new, prev any |
| + }{ |
| + {wire.FrameDispatch, wire.DispatchCommand{TaskID: "tk", Specialist: wire.SpecialistChecks, Findings: []wire.Finding{}, HostedChecks: true}, wire.DispatchCommand{TaskID: "tk", Specialist: wire.SpecialistChecks, Findings: []wire.Finding{}}}, |
| + {wire.FrameStep, wire.StepReport{TaskID: "tk", State: wire.StepDone, Findings: []wire.Finding{}, Checks: wire.ChecksPassed, Gate: wire.GateHosted, ExitCode: &code, Output: "Hosted CI passed.", Hosted: hosted}, wire.StepReport{TaskID: "tk", State: wire.StepDone, Findings: []wire.Finding{}, Checks: wire.ChecksCannotRun, Reason: "checks_unavailable", Output: "Hosted CI passed."}}, |
| + } { |
| + f, err := wire.NewFrame("f1", c.kind, c.new) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if same, err := wire.Encode(f, wire.ProtocolHostedChecks); err != nil || !bytes.Equal(same.Data, f.Data) { |
| + t.Fatalf("%s changed at protocol 5: %v", c.kind, err) |
| + } |
| + want, _ := wire.NewFrame("f1", c.kind, c.prev) |
| + for _, p := range []int{wire.ProtocolMergeFacts, wire.ProtocolSpend, wire.Protocol2, wire.Protocol1} { |
| + old, err := wire.Encode(f, p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if p >= wire.Protocol2 && !bytes.Equal(old.Data, want.Data) { |
| + t.Fatalf("%s at protocol %d:\n got %s\nwant %s", c.kind, p, old.Data, want.Data) |
| + } |
| + var body any = &wire.DispatchCommand{} |
| + if c.kind == wire.FrameStep { |
| + body = &wire.StepReport{} |
| + } |
| + if err := wire.Strict(old.Data, body); err != nil { |
| + t.Fatalf("%s at protocol %d does not decode: %v", c.kind, p, err) |
| + } |
| + if strings.Contains(string(old.Data), `"hosted"`) || strings.Contains(string(old.Data), "hosted_checks") || strings.Contains(string(old.Data), wire.GateHosted) { |
| + t.Fatalf("%s at protocol %d still says hosted: %s", c.kind, p, old.Data) |
| + } |
| + } |
| + } |
| + if wire.ProtocolCurrent != wire.ProtocolHostedChecks { |
| + t.Fatalf("current protocol %d", wire.ProtocolCurrent) |
| + } |
| +} |
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go| index c40ed437..091a7aa8 100644 |
| --- a/internal/wire/tasks.go |
| +++ b/internal/wire/tasks.go |
| @@ -632,6 +632,10 @@ type DispatchCommand struct { |
| // Protocol 3: RevertSHA is the merge commit a revert task undoes; the |
| // review measures whether the candidate reverts exactly that. |
| RevertSHA string `json:"revert_sha,omitempty"` |
| + // Protocol 5: HostedChecks offers a checks step on the primary the |
| + // hub's own CI verdict on the candidate, when the repository's hosted |
| + // CI is on (release slice 1). An older runner never gets it. |
| + HostedChecks bool `json:"hosted_checks,omitempty"` |
| } |
| // WatchMergeCommand watches a task's branch for its candidate landing on |
| @@ -726,8 +730,41 @@ type StepReport struct { |
| Change *ChangeFacts `json:"change,omitempty"` |
| MergeSource string `json:"merge_source,omitempty"` |
| MergeParents []string `json:"merge_parents,omitempty"` |
| + // Protocol 5. Hosted binds a checks verdict taken from the hub's |
| + // hosted CI (Gate GateHosted) to what it judged. |
| + Hosted *HostedResult `json:"hosted,omitempty"` |
| } |
| +// GateHosted is the gate a checks report names when its verdict is the |
| +// hub's hosted CI on the candidate, not a gate the runner ran. |
| +const GateHosted = "hosted CI" |
| + |
| +// Hosted CI states the hub reports that end a run with a verdict. |
| +const ( |
| + HostedSuccess = "success" |
| + HostedFailure = "failure" |
| +) |
| + |
| +// HostedResult is a hosted CI verdict as the hub reported it: the |
| +// repository and branch asked about, the tip it judged (the candidate), |
| +// its state, when the hub recorded the run (ReportedAt, Unix seconds; the |
| +// hub exposes no run id) and the units that failed. |
| +type HostedResult struct { |
| + Repo string `json:"repo"` |
| + Branch string `json:"branch"` |
| + SHA string `json:"sha"` |
| + State string `json:"state"` |
| + ReportedAt int64 `json:"reported_at"` |
| + Failed []string `json:"failed"` |
| +} |
| + |
| +// MaxHostedFailed bounds the failing units a hosted result names, and |
| +// MaxHostedName each name. |
| +const ( |
| + MaxHostedFailed = 20 |
| + MaxHostedName = 120 |
| +) |
| + |
| // Merge sources: the hub's answer to this request, the default branch |
| // read after an uncertain answer, or the runner's earlier record. |
| const ( |
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json| index 0e5c9420..206b29f8 100644 |
| --- a/scripts/runner-reference-allowlist.json |
| +++ b/scripts/runner-reference-allowlist.json |
| @@ -9087,14 +9087,14 @@ |
| }, |
| { |
| "path": "internal/runner/mac/probe_test.go", |
| - "line_sha256": "44950e069b32e9cac0bd1be01071e463f77784b7352d107830249ae15b225ac1", |
| + "line_sha256": "25ec48979ef44aafe04613b442250cf081684a4edf4ac97eb3ad8ce8ac9e4af1", |
| "match": "Node", |
| "count": 1, |
| "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| }, |
| { |
| "path": "internal/runner/mac/probe_test.go", |
| - "line_sha256": "44950e069b32e9cac0bd1be01071e463f77784b7352d107830249ae15b225ac1", |
| + "line_sha256": "25ec48979ef44aafe04613b442250cf081684a4edf4ac97eb3ad8ce8ac9e4af1", |
| "match": "node", |
| "count": 1, |
| "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |