# Runners progress: Mac runners groundwork (slices A and B)

Branch `thin-v1-runners` from `thin-v1-slice4c` (2d1edaf), with
`design-mac-runner` (b5f7259) merged so the spec is on the branch, then
`thin-v1-composer` (0797ad0: connections slice 1, inner screens,
housekeeping slice 1, attachments) merged at 23b0b31. Spec:
`docs/superpowers/specs/2026-11-07-equipo-mac-runners.md` rev 4
(accepted), slices A and B, Linux only. No Darwin code and no Mac probe:
those need tito-studio and a person (slice C onwards). Conventions and
scripts as in `SLICE1-PROGRESS.md` to `SLICE4C-PROGRESS.md`.

## Done

1. Wire, protocol 2 (`internal/wire/runners.go`): `Protocol1`,
   `Protocol2`; roles `primary`, `worker`; sandboxes; the fixed tag set;
   `Platform`, `Capabilities` (xcode, simulators, toolchains, harness,
   tags) with `ValidCapabilities` (40 simulators, 300 bytes a string,
   8 KB in all, no path separator, newline, `~` or `=` in any string);
   `Covers`; placement, publication and termination kinds; transfers
   (`TransferHeader`, `Blob`, `SendPackCommand`), `PublishCommand`,
   `PublishedReport`, `Refused`. `hello` gained `protocol`, `platform`,
   `label`, `sandbox`, `capabilities`; `welcome` `protocol`, `role`,
   `release`; `dispatch` `needs`, `runner_id`; `lease` `step_id`,
   `attempt`; `step` `termination_kind`, `have`, `phase`. Every new field
   is `omitempty`, so a protocol 1 frame is byte for byte the slice 4
   frame. `wire.Encode(frame, protocol)` clears the protocol 2 fields and
   refuses protocol 2 frame types at protocol 1. New step reasons
   `placement_refused`, `withdrawn`, `transfer_refused`,
   `runner_offline`. Fixtures `frames/hello-mac.json`,
   `welcome-worker.json`, `dispatch-needs.json`, `lease-step.json`,
   `blob.json`, `send_pack.json`, `publish.json`, `published.json`,
   `refused.json`, `step-process-group.json`. Tests:
   `TestEncodeProtocol1IsTheSlice4Wire` (each new frame at protocol 1 has
   the slice 4 fixture's keys and parses; the slice 4 fixtures pass
   through byte for byte), `TestEncodeProtocol1RefusesNewFrames`,
   `TestProtocolNegotiation`, `TestDurableRunnerFrames`,
   `TestCapabilitiesGuard`, `TestCovers`. Mutations: Encode without the
   downgrade, and without the protocol 2 frame refusal, each failed a
   test.

2. Migration 0054 (renumbered from 0047 at the composer merge):
   `runners.role`, `runner_commands.runner_id`, `chat_steps.runner_id`
   (indexed), placement, publication and termination columns,
   `chat_tasks.engineering_runner`, `runner_sessions.protocol`,
   `runner_transfers`. In one transaction: every runner primary, every
   command and step in every state bound to the person's primary (the
   primaryRunner query, then fallbacks), runnerless open steps waiting.
   `chat.UnboundSteps` is the schema check. Tests:
   `TestRunnersMigrationBindsSlice4Rows` (SQL over an older database:
   running, pending termination, queued, unacked commands);
   `TestContractMigrationOverSlice4Work` (live work, schema stripped
   back, restart migrates, the same runner carries on, Retry still
   waits for termination).
3. Per-runner scoping: Pending, ack, step reports and syncSteps by
   runner; turns stay primary-only; a wrong-runner report is refused
   without closing the connection (`ErrRefused`, acked, logged).
   `TestContractWorkerScoping`; four mutations each failed it.
4. Roles: first enrolment primary, later ones workers (replace a
   primary by revoking it first); a connecting primary rebinds orphans
   (no primary at write time, a revoked primary's). Negotiation: hello
   offers protocol 2; the instance speaks the lower and encodes every
   frame per connection; a protocol 1 worker is refused; the runner
   falls back once on a strict-decode refusal and logs it; a worker
   never does (`ErrInstanceTooOld`) and will not enrol with an instance
   lacking `GET /api/runner/protocol`. `TestContractRunnerRoles`,
   `TestLinkFallsBackToProtocol1`, `TestWorkerRefusesAnOlderInstance`,
   `TestLinkSpeaksProtocol2`, `TestWorkerEnrolRefusesAnOlderInstance`.
5. Capabilities (Linux probe; the test build's fixture Mac), cleaned
   on the instance (out of bounds dropped, label one line). Index
   reports `needs_macos` (gate) and `ios_simulator` (shared scheme);
   Engineering reports `apple`.
6. Placement (`chat/runners.go`): checks needing a Mac go to a worker
   whose tags cover them (primary first, then fewest running steps,
   enrolment order); offline fitting worker: waiting; after 30 minutes
   checks resolve `cannot_run/runner_offline` and review goes on;
   nobody fits or the primary is protocol 1: the primary judges as
   before (`needs_macos`). The runner picks a connection among its own.
   Engineering is pinned per task; questions go to the step's runner.
   Start authorization (`lease{step_id, attempt}`) and withdrawal in
   one serialised write: not started, the next attempt is placed at
   once and the old one can never start; started, `cancel_step` and
   the next attempt only after termination; a 2-minute grace before
   withdrawing from a worker that dropped. `placement_refused`
   re-places. `GET /api/v1/runners`, `snapshot.runners`, per-runner
   events (the chat's offline line follows the primary only).
   Contracts: `TestContractChecksPlacedOnTheWorker`,
   `TestContractChecksWithoutAWorker`, `TestContractChecksWaitForTheWorker`,
   `TestContractPlacementRefused`, `TestContractWithdrawal`, delayed
   older-SHA checks and review cases in `TestContractReviewAndChecks`.
7. Transfers: rows authorise every chunk (sender, open, header, current
   attempt, bounds, order); blobs relay as commands; oversize ends
   checks `checks_unavailable`; last ack closes; 24 h TTL.
   `TestContractTransferAuthorization`, `TestContractTransferTooLarge`.
   Worker side: header against its step row, digest, exactly the
   candidate with a complete tree (`TestWorkerRefusesTamperedPacks`).
8. Publication: only the primary's `published` sets Pushed for a
   worker's commit; the primary indexes the pack beside its clone,
   checks the parent is the base, confirms the publication right
   before the push and pushes through forge (record then reconcile).
   `TestContractPublication`, `TestContractCancelBeforePublication`,
   `TestRelayRetryAfterPushFailure`, `TestRelayCrashes` (after
   indexing; after the push), `TestRelayCancelledBeforePush`,
   `TestRelayRefusesAWrongCommit`.
9. Fake worker (`-tags testbuild` only): process group, no sandbox;
   `make release-runner` runs `scripts/no-fake-worker.sh`;
   `TestReleaseRunnerHasNoFakeWorker` fails if it is compiled in.
   Headless `TestMacWorker`: M1, M5, M2 (and the 30-minute rule with a
   fake clock), M4 (SIGKILL, process group proven gone, Retry).
10. M8 `TestMixedVersions` against the staging line 0797ad0 built from
   git history: older runner against this instance (protocol 1, task
   done, every frame unchanged by `Encode(f, 1)`); this runner against
   the older instance (one fallback, task done); a worker refused at
   enrolment, nothing created.

Mutations: about 25, each observed failing a test (listed in the
commits); defence in depth noted where one survived first.

11. Astra round 1 (REQUEST CHANGES at 1b89bd1, 7 Important, 1 Minor),
    each fix with a test that failed first:
    1. A revoked primary keeps its attempts: only conversation commands
       move to the replacement; dispatches, cancels, asks, transfers and
       publications stay with the runner that may still run them, and the
       replacement's empty sync settles none of its steps
       (`TestContractRevokedPrimaryKeepsItsAttempts`).
    2. Withdrawal comes first in a step report and in sync: a withdrawn
       attempt's results never count; only its termination proof does,
       whenever it arrives, and places the next attempt; Retry clears the
       withdrawal (`TestContractWithdrawnAttemptReports`,
       `TestContractWithdrawnProofAfterFailure`).
    3. A waiting, never-dispatched step ends locally on Cancel, and
       nothing is ever sent to an empty runner id
       (`TestContractCancelWaitingSteps`).
    4. The Engineering pin is set on the task value the transaction
       saves (`TestContractEngineeringPinKept`).
    5. A worker's role is kept in its state: it never falls back to
       protocol 1 and never serves under a primary welcome, whatever its
       OS (`TestWorkerIdentityPersists`, `TestWorkerRefusesAPrimaryWelcome`).
    6. A worker's report never clears the primary's `Pushed` or
       publication (`TestContractPublishedBeforeWorkerDone`).
    7. Oversize is declared by a chunk count past `wire.MaxTransferChunks`,
       refused at once by the instance (checks `checks_unavailable`) and
       by a receiver (`TestContractTransferDeclaredTooLarge`,
       `TestRelayDeclaresOversize`).
    8. Asking a step whose runner is offline answers 409 `runner_offline`
       at once (`TestContractAskOfflineRunner`).

12. Astra round 2 (7 of 8 resolved; three items), each with a test that
    failed first:
    1. Worker identity before connecting: enrolment keeps the role from
       the credential the instance returns (`role` only for a worker;
       absent means primary, as an older instance's credential is) in a
       `role` file beside `credentials.json`, which stays what older
       runner binaries read. A runner with no known role (enrolled before
       roles) never falls back to protocol 1 and never serves a protocol 1
       welcome until a protocol 2 welcome tells it, which it keeps
       (`TestEnrolKeepsTheRole`, `TestContractEnrolmentNamesAWorker`,
       `TestEnrolledWorkerNeverFallsBack`, `TestUnknownRoleWaitsForTheInstance`,
       `TestUnknownRoleLearnsFromProtocol2`).
    2. Cancel after withdrawal: the proof finishes the cancellation and
       places nothing (`TestContractCancelAfterWithdrawal`).
    3. Removal is two-phase: the runner is marked removing first (no new
       work, not a primary); never-started protocol 2 attempts are
       withdrawn and placed elsewhere in the same transaction;
       possibly-started ones (or any on a protocol 1 runner) are
       cancelled, and the runner is revoked when the last proof arrives.
       Nothing else settles them: no timeout, no other runner's sync.
       Remove now revokes at once and quarantines possibly-started steps
       (`machine_removed`, no termination, Needs you); the creator's
       Recover (audited `task.recover`) settles them `unverified` and
       allows Retry. Runners page: "Removing: waiting for it to stop its
       work" and Remove now; the card and Needs you: "Stopped: the
       machine was removed mid-step. Make sure it's switched off, then
       Recover" with Recover (`TestContractRemovalWaitsForProof`,
       `TestContractRemoveNowQuarantines`, `TestPagesRemovalAndRecover`;
       `TestContractRevokedPrimaryKeepsItsAttempts` updated: the never-
       started dispatch now moves to the replacement and its old attempt
       can never start).

## Decisions

- New wire fields are `omitempty` rather than always present: the slice
  4 fixtures stay byte-identical, and `Encode` at protocol 1 only has to
  clear fields.
- `refused{id, reason}` answers a start authorization the instance will
  not grant; the spec names the refusal but no frame for it.
- `send_pack` (instance to primary, durable) asks the primary to upload
  an inbound transfer's pack; the spec says the primary sends the pack
  but not how it is asked.
- Blob frames carry the whole transfer header, so the receiver checks
  repository, task, step, attempt, base, candidate and direction against
  its own step row on every chunk; `sha256` is the whole pack's digest.
- The capability report keeps accounts where they are (hello's
  connections since the composer merge).
- Protocol 1 is the composer wire. M8 runs against 0797ad0 rather than
  the spec's ca0a65c, whose wire predates 4b, 4c and connections.
- Only checks are placed by needs in this release; Engineering, Review
  and merges stay on the primary until slice F.
- The worker's connections are not recorded yet (checks need none).
- Blob transfers use their own row and blob commands rather than the
  attachments' chunk frames: they bind to a step attempt and a
  direction, which attachments do not need.

## Open issues

- A runner that never comes back while removing stays removing; Remove
  now is the way out (quarantine, then Recover).
- `have`/thin packs are on the wire but packs are whole one-commit packs.
- Copy for the runner lines (waiting, offline, Runners) is not written;
  slice D/E, with Luna's pass.
- 4c_rebase failed once in a loaded full headless run, passed alone.

## Blockers

None.

## Copy for review (round 2, accepted for now)

- `runner.removing` "Removing: waiting for it to stop its work"
- `runner.remove_now` "Remove now"
- `work.needs.machine_removed` "Stopped: the machine was removed
  mid-step. Make sure it's switched off, then Recover"
- `work.reason.machine_removed` "the machine was removed mid-step"
- `work.recover` "Recover"
