oficina / equipo Public

Merge branch 'release-s1-hosted-checks' into main

Merge release slice 1: hosted checks on the exact candidate

Checks take hosted CI's verdict for the exact candidate on projects
with hosted CI (protocol 5, migration 0062 chat_steps.hosted_ci).
Spec, one Astra round with six findings folded in, tests that failed
first and 28 mutations. Hosted CI passed on ee52d11.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3ef45d1a0901d591b302d536b13f34a05502a32e parent d096dfcparent ee52d11
21 files changed, +1,329 −20
  • .rastrillo/budgets.txt +4 −4
  • docs/superpowers/specs/2026-11-11-equipo-release-s1-hosted-checks.md +206 −0
  • docs/superpowers/specs/CODEX-FINDINGS-RELEASE-S1-HOSTED-CHECKS.md +27 −0
  • internal/equipo/chat/merge.go +3 −1
  • internal/equipo/chat/review.go +11 −1
  • internal/equipo/chat/tasks.go +57 −4
  • internal/equipo/migrations/0062_thin_hosted_checks.sql +1 −0
  • internal/equipo/migrations/schema.sql +1 −1
  • internal/runner/forge/ci.go +128 −0
  • internal/runner/forge/ci_test.go +105 −0
  • internal/runner/thin/engineer.go +3 −0
  • internal/runner/thin/forge.go +38 −0
  • internal/runner/thin/judge.go +18 −5
  • internal/runner/thin/judge_hosted.go +191 −0
  • internal/runner/thin/judge_hosted_test.go +270 −0
  • internal/runner/thin/run.go +1 −1
  • internal/runner/thin/step.go +4 −0
  • internal/thintest/hosted_checks_contract_test.go +138 −0
  • internal/wire/runners.go +38 −3
  • internal/wire/runners_test.go +48 −0
  • internal/wire/tasks.go +37 −0

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 269a9bf4..6408f8dd 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 16822 8130 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 14100 - 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 14160 - 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 - 13685 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 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 - 13823 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/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/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/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/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 (