oficina / equipo Public

Merge thin-v1-runners 15feb20; a Mac keeps only a worker role

Merges the runners final round (the enrolled role kept in a role file
beside credentials.json, cancel before withdrawal, two-phase removal
with Remove now and Recover). The approval's primary count also skips
runners being removed. Enrolment now checks the role the instance put
in the credential: a worker-only runner (a Mac) enrolled as anything
but a worker keeps nothing and says so (runner.enrolled_as_primary);
the Mac installer then says to add the main runner first. Budgets:
internal/equipo 15300, internal/runner 9750 and 9050.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9e407e2a2177af4ec177cd646d3d107542627ae4 parent be0f1e3parent 15feb20
46 files changed, +846 −67
  • .rastrillo/budgets.txt +2 −2
  • cmd/equipo-runner/install_mac.go +3 −0
  • cmd/equipo-runner/install_mac_test.go +11 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +5 −0
  • docs/superpowers/plans/DARWIN-PROGRESS.md +6 −1
  • docs/superpowers/plans/RUNNERS-PROGRESS.md +43 −3
  • internal/equipo/app.go +2 −0
  • internal/equipo/chat/http.go +10 −0
  • internal/equipo/chat/review.go +3 −0
  • internal/equipo/chat/runners.go +148 −11
  • internal/equipo/chat/store.go +5 −0
  • internal/equipo/chat_page.go +1 −1
  • internal/equipo/chat_wiring.go +8 −2
  • internal/equipo/copy.go +7 −0
  • internal/equipo/migrations/0054_thin_runners.sql +1 −0
  • internal/equipo/migrations/schema.sql +2 −1
  • internal/equipo/runner_handlers.go +25 −0
  • internal/equipo/runners.go +50 −5
  • internal/equipo/setup/enrolment.go +1 −1
  • internal/equipo/setup/runner_models.go +3 −0
  • internal/equipo/templates/runners.html +4 −1
  • internal/equipo/templates/task_card.html +1 −1
  • internal/equipo/templates/work_parts.html +1 −1
  • internal/equipo/work_pages.go +16 −1
  • internal/equipo/work_views.go +6 −2
  • internal/plan3test/person_api_contract_test.go +1 −1
  • internal/runner/diagnostics.go +2 −0
  • internal/runner/enrol.go +40 −1
  • internal/runner/enrol_worker_test.go +61 −0
  • internal/runner/thin/contract_test.go +4 −1
  • internal/runner/thin/link.go +25 −6
  • internal/runner/thin/protocol_test.go +54 −0
  • internal/runner/thin/run.go +14 −2
  • internal/runnerproto/types.go +4 −0
  • internal/thintest/client.go +5 −0
  • internal/thintest/instance.go +10 −1
  • internal/thintest/migration_contract_test.go +1 −1
  • internal/thintest/review1_contract_test.go +31 −17
  • internal/thintest/review2_contract_test.go +207 −0
  • internal/wire/api.go +3 −0
  • internal/wire/runners.go +3 −0
  • internal/wire/tasks.go +6 −0
  • internal/wire/wiretest/testdata/api/event-runner.json +1 −1
  • internal/wire/wiretest/testdata/api/runners.json +1 −1
  • internal/wire/wiretest/testdata/api/snapshot.json +1 −1
  • scripts/runner-reference-allowlist.json +8 −1

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index b28f8cea..acff89de 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,13 +14,13 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 15100 - Mac runners (Darwin worker) add the one-tap enrolment link, the runners view's self-probes, /install.sh, the outside-the-sandbox label and their copy (about 90 lines); measured 15058. Mac runners add the runner role, the protocol route and the placement minute (about 40 lines). Housekeeping slice 1 adds the Housekeeping view beside the Notebook, the digest line and their copy (housekeeping_page.go, about 170 lines); measured 14513. Thin v1 UX1 thinking words adds the settings page and the set registry wiring (thinking_words.go) and 55 strings of phrases; measured 14411. The Connections page to Paul's approved mockup (connections_view.go: what is answering, the preference, rows with headroom, roles, usage and the recovery action, about 300 lines); measured 14268. Merged with UX1 round 3 (duplicate combining with Undo, timeline headlines) beside the Connections page; measured 13895. Connections slice 1 adds the Connections page, the switched line and the no_connection card and their copy (chat_connections.go, about 220 lines). Measured 12269. Thin v1 UX1 adds the inner screens' view model (work_views.go: stage track, badges, timeline, decisions, project facts, about 830 lines), the rich page handlers and their copy (about 170 lines); measured 13263. Thin v1 slice 4c adds the merged line, the merge card and its copy (about 60 lines). Thin v1 slice 4 adds the thin sidebar (rail.go), review and checks lines on the task card and pages, and their copy (about 190 lines). Thin v1 slice 3 adds the task card, the thin Tasks and Projects pages and their actions over the chat store, and their copy (about 280 lines). Thin v1 slice 2 adds activity labels, card copy and card rendering on the chat page (about 250 lines); slice 1 added the chat wiring and page (about 180 lines) beside code its slice 7 sweep deletes (the live hub, the old coordinator); lower then. Task 7 keeps the existing ceiling by moving transaction-bound event lookup into conversation. Measured 10796 source and 437 test lines; roster, database, pending copy and execution wiring remain here.
+size internal/equipo 15300 - Mac runners (Darwin worker) add the one-tap enrolment link, the runners view's self-probes, /install.sh, the outside-the-sandbox label and their copy (about 90 lines); measured 15058. Mac runners add the runner role, the protocol route and the placement minute, then two-phase removal, Remove now and Recover (about 110 lines). Housekeeping slice 1 adds the Housekeeping view beside the Notebook, the digest line and their copy (housekeeping_page.go, about 170 lines); measured 14513. Thin v1 UX1 thinking words adds the settings page and the set registry wiring (thinking_words.go) and 55 strings of phrases; measured 14411. The Connections page to Paul's approved mockup (connections_view.go: what is answering, the preference, rows with headroom, roles, usage and the recovery action, about 300 lines); measured 14268. Merged with UX1 round 3 (duplicate combining with Undo, timeline headlines) beside the Connections page; measured 13895. Connections slice 1 adds the Connections page, the switched line and the no_connection card and their copy (chat_connections.go, about 220 lines). Measured 12269. Thin v1 UX1 adds the inner screens' view model (work_views.go: stage track, badges, timeline, decisions, project facts, about 830 lines), the rich page handlers and their copy (about 170 lines); measured 13263. Thin v1 slice 4c adds the merged line, the merge card and its copy (about 60 lines). Thin v1 slice 4 adds the thin sidebar (rail.go), review and checks lines on the task card and pages, and their copy (about 190 lines). Thin v1 slice 3 adds the task card, the thin Tasks and Projects pages and their actions over the chat store, and their copy (about 280 lines). Thin v1 slice 2 adds activity labels, card copy and card rendering on the chat page (about 250 lines); slice 1 added the chat wiring and page (about 180 lines) beside code its slice 7 sweep deletes (the live hub, the old coordinator); lower then. Task 7 keeps the existing ceiling by moving transaction-bound event lookup into conversation. Measured 10796 source and 437 test lines; roster, database, pending copy and execution wiring remain here.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); 60s gives 34 percent headroom. Shared baseline capture reduces repeated Go runs; retain the CI allowance for sandbox sentinels, timeout and child cleanup. 2026-11-07: loaded CI (host load about 24) measured 66.5s with the package unchanged by thin v1 slice 4 beyond optional check mounts; 90s keeps 35 percent headroom.
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). Parallel plan graphs and removal of repeated progress floods reduced their local targeted run from 146.920s to 30.784s; the original bug graph retains volume coverage. Keep 330s for journal, proxy, recovery and namespace integration, with 13 percent headroom.
perf GET /api/runner/v2/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory.
-size internal/runner 9650 8950 Mac runners (slices A and B) add the worker enrolment check (enrol.go) and its test. Thin v1 slice 1 exports helpers for internal/runner/thin beside the old runtime its slice 7 sweep deletes; lower then. Task 17 fix round 1 adds authenticated terminal-login composition and saved-report recovery beside the existing runner journal and state lock. Measured 9421 source and 8719 test lines. Login lifecycle, subprocess handling and environment parsing stay in setup/provider; the 100-line source raise retains only production HTTP/config wiring here. Existing test and 330s time ceilings are unchanged.
+size internal/runner 9750 9050 Mac runners (Darwin worker) add the darwin clock, peer credential and walk shims, the worker-only enrolment flag and its role check, and their tests; measured 9689 source and 8960 test lines. Mac runners (slices A and B) add the worker enrolment check (enrol.go) and its test. Thin v1 slice 1 exports helpers for internal/runner/thin beside the old runtime its slice 7 sweep deletes; lower then. Task 17 fix round 1 adds authenticated terminal-login composition and saved-report recovery beside the existing runner journal and state lock. Measured 9421 source and 8719 test lines. Login lifecycle, subprocess handling and environment parsing stay in setup/provider; the 100-line source raise retains only production HTTP/config wiring here. Existing test and 330s time ceilings are unchanged.
time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner.
time internal/runner/provider/codex 35s Plan 3 CI repair measured 24.464s for the full package (controller CI 27.908s). Independent policy subtests now run in parallel; 35s leaves 25 percent above the loaded CI measurement for schema, native approval and fsynced capture fixtures.
diff --git a/cmd/equipo-runner/install_mac.go b/cmd/equipo-runner/install_mac.go
index fb9a2d46..efca8293 100644
--- a/cmd/equipo-runner/install_mac.go
+++ b/cmd/equipo-runner/install_mac.go
@@ -164,6 +164,9 @@ func installMac(ctx context.Context, args []string, h macInstallHost, out, errou
cfg := runner.Config{Origin: *origin, InstanceID: *instance, StateDir: values["EQUIPO_RUNNER_STATE_DIR"], WorkspaceRoot: values["EQUIPO_WORKSPACE_ROOT"], ScratchRoot: values["EQUIPO_SCRATCH_ROOT"], GitPath: values["EQUIPO_GIT_PATH"], MachineLabel: label, Executable: binary, WorkerOnly: true}
say("runner.mac.tap")
if err := h.enrol(ctx, cfg, out); err != nil {
+ if errors.Is(err, runner.ErrEnrolledAsPrimary) {
+ return fail("runner.needs_primary")
+ }
return fail("runner.install.unavailable")
}
plist := filepath.Join(agents, mac.AgentLabel+".plist")
diff --git a/cmd/equipo-runner/install_mac_test.go b/cmd/equipo-runner/install_mac_test.go
index 9fcf4d7f..839673b7 100644
--- a/cmd/equipo-runner/install_mac_test.go
+++ b/cmd/equipo-runner/install_mac_test.go
@@ -286,3 +286,14 @@ func TestInstallMacAgain(t *testing.T) {
held.Close()
}
}
+
+// The instance's role decides: a Mac it enrolled as a primary stops the
+// installer, which says why and loads no agent.
+func TestInstallMacEnrolledAsPrimary(t *testing.T) {
+ x := newMacRig(t)
+ x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolledAsPrimary }
+ code, _, errout := x.install()
+ if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.needs_primary")) || slices.Contains(x.calls, "launchctl bootstrap gui/502 "+filepath.Join(x.home, "Library/LaunchAgents/io.amadan.equipo-runner.plist")) {
+ t.Fatalf("%d %q %v", code, errout, x.calls)
+ }
+}
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 3705f402..79ddce74 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -4862,6 +4862,11 @@ records remain unchanged.
| `work.reason.amadan_ci_failed` | Amadan's own CI did not pass | Thin v1 slice 4c the coordinator merges (Stopped line) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `work.reason.merge_forbidden` | Equipo may not merge in this repository | Thin v1 slice 4c the coordinator merges (Stopped line) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `work.reason.merge_failed` | Amadan did not merge it | Thin v1 slice 4c the coordinator merges (Stopped line) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `runner.removing` | Removing: waiting for it to stop its work | Mac runners: a runner removed while work it may have started is still running (runners page) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `runner.remove_now` | Remove now | Mac runners: remove a lost or compromised machine at once (runners page) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `work.needs.machine_removed` | Stopped: the machine was removed mid-step. Make sure it's switched off, then Recover | Mac runners: a step quarantined by Remove now (task card, Needs you) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `work.reason.machine_removed` | the machine was removed mid-step | Mac runners: Stopped line reason | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `work.recover` | Recover | Mac runners: settle a quarantined step after the machine is off (task card, Needs you) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `chat.card.merge_question` | Merge %s without checks? | Thin v1 slice 4c the coordinator merges (merge card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `chat.card.merge` | Merge | Thin v1 slice 4c the coordinator merges (merge card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `chat.card.wait` | Wait for checks | Thin v1 slice 4c the coordinator merges (merge card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/docs/superpowers/plans/DARWIN-PROGRESS.md b/docs/superpowers/plans/DARWIN-PROGRESS.md
index f1a07e96..e65f5488 100644
--- a/docs/superpowers/plans/DARWIN-PROGRESS.md
+++ b/docs/superpowers/plans/DARWIN-PROGRESS.md
@@ -155,7 +155,12 @@ primary, seatbelt default, task label); views (label, probes); config
tool it runs gets the runner's Node and ripgrep first on PATH.
`TestMacHostPaths`.
Also: Linux-only tests carry a linux build tag and `make vet` vets the
-runner for darwin/arm64. Merged thin-v1-runners d7c803b.
+runner for darwin/arm64. Merged thin-v1-runners d7c803b, then 15feb20
+(enrolled role file, cancel before withdrawal, two-phase removal). A
+Mac also checks the role the instance put in its enrolment credential:
+anything but worker keeps nothing (`ErrEnrolledAsPrimary`) and the
+installer says to add the main runner first (`TestEnrolKeepsTheRole`,
+`TestInstallMacEnrolledAsPrimary`).
## Decisions
diff --git a/docs/superpowers/plans/RUNNERS-PROGRESS.md b/docs/superpowers/plans/RUNNERS-PROGRESS.md
index 434308c3..722ebd9a 100644
--- a/docs/superpowers/plans/RUNNERS-PROGRESS.md
+++ b/docs/superpowers/plans/RUNNERS-PROGRESS.md
@@ -144,6 +144,38 @@ commits); defence in depth noted where one survived first.
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
@@ -170,9 +202,8 @@ commits); defence in depth noted where one survived first.
## Open issues
-- Revoking a runner with a started step or an unacked dispatch leaves
- that attempt unproven: nothing else may supply its proof, so the task
- waits (Cancel is accepted, the step stays with the revoked runner).
+- 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.
@@ -181,3 +212,12 @@ commits); defence in depth noted where one survived first.
## 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"
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 9e5ea898..aad779ed 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -221,6 +221,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Post("/tasks/{id}/ask", a.workAsk)
r.Post("/conversation/tasks/{id}/retry", a.workTaskAction(true))
r.Post("/conversation/tasks/{id}/cancel", a.workTaskAction(false))
+ r.Post("/conversation/tasks/{id}/recover", a.workTaskRecover)
r.Post("/tasks/{id}/duplicate", a.workDuplicate)
r.Post("/tasks/{id}/uncombine", a.workUncombine)
r.Post("/conversation/tasks/{id}/merge", a.workTaskMerge)
@@ -284,6 +285,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Post("/tasks/{id}/questions/{question}/answer", a.answerQuestion)
r.Post("/runners/enrol", a.approveEnrolment)
r.Post("/runners/{id}/revoke", a.revokeRunner)
+ r.Post("/runners/{id}/remove-now", a.removeRunnerNow)
r.Post("/projects/{id}/connections", a.saveConnectionChoice)
r.Get("/settings/thinking", a.thinkingPage)
r.Post("/settings/thinking", a.thinkingSave)
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 5e08a101..57f4d5f1 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -78,6 +78,7 @@ func (h *HTTP) Mount(r chi.Router) {
r.Get("/tasks/{id}", h.thinOr("GET /tasks/{id}", thinTask, h.bearer(h.task)))
r.Post("/tasks/{id}/cancel", h.thinOr("POST /tasks/{id}/cancel", thinTask, h.bearer(h.cancelTask)))
r.Post("/tasks/{id}/retry", h.bearer(h.retryTask))
+ r.Post("/tasks/{id}/recover", h.bearer(h.recoverTask))
r.Post("/tasks/{id}/duplicate", h.bearer(h.markDuplicate))
r.Post("/tasks/{id}/merge", h.bearer(h.mergeTask))
r.Post("/tasks/{id}/uncombine", h.bearer(h.uncombineTask))
@@ -559,6 +560,15 @@ func (h *HTTP) resetNotebook(w http.ResponseWriter, r *http.Request, p personapi
writeJSON(w, http.StatusAccepted, out)
}
+func (h *HTTP) recoverTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ attempt, err := h.Store.RecoverTask(r.Context(), p.Address, chi.URLParam(r, "id"))
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 202, wire.TaskAccepted{Attempt: attempt})
+}
+
func (h *HTTP) runners(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
out, err := h.Store.RunnerList(r.Context(), p.Address)
if err != nil {
diff --git a/internal/equipo/chat/review.go b/internal/equipo/chat/review.go
index fdb3136f..de7919b3 100644
--- a/internal/equipo/chat/review.go
+++ b/internal/equipo/chat/review.go
@@ -98,6 +98,9 @@ func (p progress) needsYou(k taskRecord) string {
if wire.FinalStage(k.Stage) || k.CancelRequested || p.last == nil {
return ""
}
+ if p.last.State == wire.StepFailed && p.last.Reason == "machine_removed" && !p.last.Terminated {
+ return wire.NeedsMachineRemoved
+ }
if p.last.Specialist == wire.SpecialistEngineering && p.last.State == wire.StepDone && p.last.Publication == wire.PublicationFailed {
return wire.NeedsRetry
}
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index d8060423..f5e156c4 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -54,6 +54,24 @@ func (t *txn) rebind(p RunnerPrincipal) error {
// it ends as not run when it was withdrawn for that (a pack too large to
// relay), else the next attempt is placed.
func (t *txn) withdrawnEnded(k *taskRecord, s *stepRecord) error {
+ runner := s.RunnerID
+ if err := t.withdrawnSettle(k, s); err != nil {
+ return err
+ }
+ return t.removalProgress(runner)
+}
+
+func (t *txn) withdrawnSettle(k *taskRecord, s *stepRecord) error {
+ if k.CancelRequested || wire.FinalStage(k.Stage) {
+ // Cancelled meanwhile: the proof finishes the cancellation and
+ // nothing is placed.
+ now := t.now()
+ s.State, s.Reason, s.Terminated, s.FinishedAt, s.Withdrawn = wire.StepCancelled, "cancelled", true, &now, false
+ if !wire.FinalStage(k.Stage) {
+ k.Stage = wire.StageCancelled
+ }
+ return t.saveStep(s, k)
+ }
if s.Reason != "" {
s.Terminated = true
return t.resolveNotRun(k, s, s.Reason)
@@ -64,6 +82,122 @@ func (t *txn) withdrawnEnded(k *taskRecord, s *stepRecord) error {
return t.saveStep(s, k)
}
+// removalProgress revokes a runner being removed once nothing it may
+// have started is left unproven.
+func (t *txn) removalProgress(runner string) error {
+ if runner == "" || t.s.authority.FinishRemoval == nil {
+ return nil
+ }
+ var removing int64
+ if err := t.db.Raw(`SELECT count(*) FROM runners WHERE id = ? AND removing_at IS NOT NULL AND revoked_at IS NULL`, runner).Scan(&removing).Error; err != nil || removing == 0 {
+ return err
+ }
+ var open int64
+ if err := t.db.Model(&stepRecord{}).Where("runner_id = ? AND state IN ?", runner, []string{wire.StepQueued, wire.StepRunning}).Count(&open).Error; err != nil || open != 0 {
+ return err
+ }
+ return t.s.authority.FinishRemoval(t.db, runner)
+}
+
+// RemoveRunner takes a runner's work back for its removal, in the
+// caller's transaction. An attempt that never started (protocol 2: no
+// start authorization granted) is withdrawn and placed elsewhere at once.
+// One that may have started (authorized, or on a protocol 1 runner whose
+// start is not known) is cancelled and counted uncertain: the caller
+// keeps the runner removing until its proof arrives. With now, the
+// runner is revoked at once instead, so those attempts are quarantined:
+// stopped (machine_removed) with no proof until the creator recovers them.
+func (s *Store) RemoveRunner(tx *gorm.DB, person, runner string, now bool) (uncertain int, err error) {
+ t := &txn{s: s, ctx: context.Background(), db: tx, touched: map[string]bool{}}
+ defer func() {
+ for p := range t.touched {
+ s.hub.Wake(p)
+ }
+ }()
+ var proto int
+ _ = tx.Raw(`SELECT coalesce(protocol, 1) FROM runner_sessions WHERE runner_id = ?`, runner).Scan(&proto).Error
+ var rows []stepRecord
+ if err := tx.Where("runner_id = ? AND state IN ?", runner, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil {
+ return 0, err
+ }
+ for i := range rows {
+ st := rows[i]
+ k, err := t.loadTask(st.TaskID)
+ if err != nil {
+ return 0, err
+ }
+ started := st.Withdrawn || st.StartedAt != nil || proto < wire.Protocol2
+ switch {
+ case !started:
+ if err := t.replace(&k, &st); err != nil {
+ return 0, err
+ }
+ if err := t.saveStep(&st, &k); err != nil {
+ return 0, err
+ }
+ case now:
+ if err := t.voidAttempt(st); err != nil {
+ return 0, err
+ }
+ at := t.now()
+ st.State, st.Reason, st.Terminated, st.Withdrawn, st.FinishedAt = wire.StepFailed, "machine_removed", false, false, &at
+ if err := t.saveStep(&st, &k); err != nil {
+ return 0, err
+ }
+ default:
+ uncertain++
+ if st.Withdrawn {
+ continue
+ }
+ st.Withdrawn = true
+ if err := t.saveStep(&st, &k); err != nil {
+ return 0, err
+ }
+ if err := t.commandTo(runner, st.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: st.Person, TaskID: k.ID, StepID: st.ID, Attempt: st.Attempt}); err != nil {
+ return 0, err
+ }
+ }
+ }
+ return uncertain, nil
+}
+
+// RecoverTask settles a step stopped when its machine was removed: the
+// task's creator says the machine is off. Its end is recorded unverified
+// (audited), and Retry is possible.
+func (s *Store) RecoverTask(ctx context.Context, person, id string) (attempt int64, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ if err := t.isOwner(person); err != nil {
+ return err
+ }
+ k, err := t.loadTask(id)
+ if err != nil {
+ return err
+ }
+ if k.Creator != person {
+ return ErrForbidden
+ }
+ st, found, err := t.latestStep(k.ID)
+ if err != nil {
+ return err
+ }
+ if !found || st.State != wire.StepFailed || st.Reason != "machine_removed" || st.Terminated {
+ return ErrNotRetryable
+ }
+ st.Terminated, st.TerminationKind = true, wire.TerminationUnverified
+ if s.authority.Audit != nil {
+ if err := s.authority.Audit(t.db, person, "task.recover", st.ID); err != nil {
+ return err
+ }
+ }
+ attempt = st.Attempt
+ return t.saveStep(&st, &k)
+ })
+ return attempt, err
+}
+
// MaxRunnerLabel bounds the machine label a runner reports.
const MaxRunnerLabel = 80
@@ -90,11 +224,13 @@ type runnerInfo struct {
ID, Role, Label string
Seq int64
Online bool
- Protocol int
- Revision int64
- SeenAt time.Time
- Hello wire.Hello
- Running int64
+ // Removing: being removed; it gets no new work.
+ Removing bool
+ Protocol int
+ Revision int64
+ SeenAt time.Time
+ Hello wire.Hello
+ Running int64
}
func (r runnerInfo) tags() []string {
@@ -111,14 +247,15 @@ func (t *txn) runners(person string) ([]runnerInfo, error) {
var rows []struct {
ID, Role, Label string
Seq int64
+ Removing bool
}
- if err := t.db.Raw(`SELECT id, coalesce(role, '') AS role, coalesce(label, '') AS label, rowid AS seq FROM runners
+ if err := t.db.Raw(`SELECT id, coalesce(role, '') AS role, coalesce(label, '') AS label, rowid AS seq, removing_at IS NOT NULL AS removing FROM runners
WHERE person = ? AND revoked_at IS NULL ORDER BY rowid`, person).Scan(&rows).Error; err != nil {
return nil, err
}
out := make([]runnerInfo, 0, len(rows))
for _, r := range rows {
- info := runnerInfo{ID: r.ID, Role: wire.RolePrimary, Label: r.Label, Seq: r.Seq}
+ info := runnerInfo{ID: r.ID, Role: wire.RolePrimary, Label: r.Label, Seq: r.Seq, Removing: r.Removing}
if r.Role == wire.RoleWorker {
info.Role = wire.RoleWorker
}
@@ -163,7 +300,7 @@ func (t *txn) runnerOnline(person, id string) (bool, error) {
// runnerView is the Runner resource.
func runnerView(r runnerInfo) wire.Runner {
- v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities}
+ v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities, Removing: r.Removing}
if !r.SeenAt.IsZero() {
at := r.SeenAt
v.Since = &at
@@ -281,7 +418,7 @@ func (t *txn) place(k *taskRecord, s *stepRecord) (placed bool, err error) {
return false, err
}
for _, r := range rs {
- if r.ID == k.EngineeringRunner {
+ if r.ID == k.EngineeringRunner && !r.Removing {
s.RunnerID = r.ID
}
}
@@ -320,7 +457,7 @@ func (t *txn) place(k *taskRecord, s *stepRecord) (placed bool, err error) {
if r.ID == primary && r.Protocol >= wire.Protocol2 {
relay = true
}
- if wire.Covers(r.tags(), needs) && !slices.Contains(refused, r.ID) && r.Protocol >= wire.Protocol2 {
+ if wire.Covers(r.tags(), needs) && !slices.Contains(refused, r.ID) && r.Protocol >= wire.Protocol2 && !r.Removing {
fit = append(fit, r)
}
}
@@ -522,7 +659,7 @@ func (t *txn) offline(person string) error {
// the limit (the next attempt then waits, or resolves).
alt := false
for _, o := range rs {
- if o.ID != r.ID && o.Online && o.Protocol >= wire.Protocol2 && wire.Covers(o.tags(), decodeList(s.Needs)) && !slices.Contains(decodeList(s.RefusedBy), o.ID) {
+ if o.ID != r.ID && o.Online && !o.Removing && o.Protocol >= wire.Protocol2 && wire.Covers(o.tags(), decodeList(s.Needs)) && !slices.Contains(decodeList(s.RefusedBy), o.ID) {
alt = true
}
}
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 0eeebe35..eb9b2aed 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -56,6 +56,11 @@ type Authority struct {
// RunnerRole is the runner's enrolled role, wire.RolePrimary or
// wire.RoleWorker.
RunnerRole func(tx *gorm.DB, runnerID string) (string, error)
+ // FinishRemoval revokes a runner whose removal waited for its work's
+ // end, once that end is proven.
+ FinishRemoval func(tx *gorm.DB, runnerID string) error
+ // Audit records an action in the instance's audit log.
+ Audit func(tx *gorm.DB, actor, kind, record string) error
// ActivityLabel is the line a client shows for an activity, in a turn
// of turnKind (wire.TurnPerson, TurnMoveIn or TurnExplore).
ActivityLabel func(a wire.Activity, turnKind string) string
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index cf0268f3..c96d9cd7 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -133,7 +133,7 @@ func cardView(c wire.Card, choices []string, tasks map[string]wire.Task) chatCar
if t, ok := tasks[c.TaskID]; ok {
// A task card sits in its creator's own conversation.
line := taskLineOf(t, t.Creator)
- v.Task, v.Line, v.Open = &line, t.Title, line.Retry || line.Cancel || line.Merge
+ v.Task, v.Line, v.Open = &line, t.Title, line.Retry || line.Cancel || line.Merge || line.Recover
}
}
return v
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index 69abe05a..2212ad05 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -36,7 +36,13 @@ func (s *Store) Chat() *chat.Store {
_, err := runnerPrincipalAt(tx, RunnerPrincipal{RunnerID: p.RunnerID, Person: p.Person, CredentialID: p.CredentialID}, time.Now())
return err
},
- RunnerRole: runnerRole,
+ RunnerRole: runnerRole,
+ FinishRemoval: func(tx *gorm.DB, id string) error {
+ return revokeRunnerAt(tx, id, s.runnerClock.Now().UTC())
+ },
+ Audit: func(tx *gorm.DB, actor, kind, record string) error {
+ return appendAudit(tx, Actor{Address: actor}, kind, record)
+ },
ActivityLabel: activityLabel,
Copy: copyText,
TestPerson: func(address string) bool {
@@ -86,7 +92,7 @@ func primaryRunner(tx *gorm.DB, person string) (string, error) {
var ids []string
err := tx.Raw(`SELECT r.id FROM runners r JOIN members m ON m.address = r.person
WHERE r.person = ? AND r.revoked_at IS NULL AND m.active = 1 AND m.role = ?
- AND coalesce(r.role, '') IN ('primary', '')
+ AND coalesce(r.role, '') IN ('primary', '') AND r.removing_at IS NULL
ORDER BY r.rowid DESC LIMIT 1`, normalizeAddress(person), string(RoleOwner)).Scan(&ids).Error
if err != nil {
return "", storeError(err)
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index b628ae62..0faa2fa0 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -217,6 +217,10 @@ var pageCopy = map[string]string{
"onboarding.mac_later": "Mac runners are coming later. You can use a Linux runner from your Mac.",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): runner.requested
"runner.requested": "Requested at",
+ // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): runner.removing
+ "runner.removing": "Removing: waiting for it to stop its work",
+ // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): runner.remove_now
+ "runner.remove_now": "Remove now",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): runner.install.unavailable
"runner.install.unavailable": "Runner installation is unavailable.",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): runner.install.platform
@@ -534,6 +538,9 @@ var pageCopy = map[string]string{
"work.reason.other": "something went wrong", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"work.pushed": "Pushed %s at %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"work.open": "Open on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.recover": "Recover", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.needs.machine_removed": "Stopped: the machine was removed mid-step. Make sure it's switched off, then Recover", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.machine_removed": "the machine was removed mid-step", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"work.retry": "Retry", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"work.cancel": "Cancel", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"work.step": "%s, attempt %d: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/migrations/0054_thin_runners.sql b/internal/equipo/migrations/0054_thin_runners.sql
index a152e531..bfc19784 100644
--- a/internal/equipo/migrations/0054_thin_runners.sql
+++ b/internal/equipo/migrations/0054_thin_runners.sql
@@ -1,4 +1,5 @@
ALTER TABLE runners ADD COLUMN role text;
+ALTER TABLE runners ADD COLUMN removing_at datetime;
ALTER TABLE runner_commands ADD COLUMN runner_id text;
ALTER TABLE chat_steps ADD COLUMN runner_id text;
ALTER TABLE chat_steps ADD COLUMN needs text;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index eb0442a9..db75f231 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -220,7 +220,8 @@ CREATE TABLE runners (
revision integer,
revoked_at datetime,
instance_id text,
- role text
+ role text,
+ removing_at datetime
);
CREATE INDEX runner_person ON runners(person);
CREATE TABLE runner_enrolments (
diff --git a/internal/equipo/runner_handlers.go b/internal/equipo/runner_handlers.go
index bd39c977..d01d4e4f 100644
--- a/internal/equipo/runner_handlers.go
+++ b/internal/equipo/runner_handlers.go
@@ -228,6 +228,31 @@ func (a *application) revokeRunner(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, "/runners/enrol", http.StatusSeeOther)
}
+
+// removeRunnerNow removes a lost or compromised machine at once.
+func (a *application) removeRunnerNow(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 4096)
+ if r.ParseForm() != nil {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ revision, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
+ if err != nil || revision < 1 {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ id, ok := auth.From(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ if err := a.store.RemoveRunnerNow(r.Context(), Actor{Address: id.Address}, chi.URLParam(r, "id"), revision); err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/runners/enrol", http.StatusSeeOther)
+}
+
func (a *application) runnerFormFailure(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, ErrRunnerNeedsPrimary) {
renderStatus(w, http.StatusConflict, "form_error", pageData{Nav: Navigation(), Key: "connections", Title: "runner.title", ErrorKey: "runner.needs_primary", Back: "/runners/enrol"})
diff --git a/internal/equipo/runners.go b/internal/equipo/runners.go
index 5b0848f5..cdc043fe 100644
--- a/internal/equipo/runners.go
+++ b/internal/equipo/runners.go
@@ -9,9 +9,8 @@ import (
"time"
"amadan.net/oficina/equipo/internal/equipo/setup"
- "amadan.net/oficina/equipo/internal/wire"
-
"amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/wire"
"gorm.io/gorm"
)
@@ -35,7 +34,13 @@ func mintRunnerCredential(tx *gorm.DB, runner runnerRecord, now time.Time) (runn
if err := tx.Create(&record).Error; err != nil {
return runnerproto.RunnerCredential{}, storeError(err)
}
- return runnerproto.RunnerCredential{Version: 1, Token: token, TokenType: "Bearer", RunnerID: runner.ID, CredentialID: record.ID, Person: runner.Person, ExpiresAt: record.ExpiresAt}, nil
+ cred := runnerproto.RunnerCredential{Version: 1, Token: token, TokenType: "Bearer", RunnerID: runner.ID, CredentialID: record.ID, Person: runner.Person, ExpiresAt: record.ExpiresAt}
+ if runner.Role == wire.RoleWorker {
+ // Only a worker's credential names its role: a primary's stays
+ // what older runners decode.
+ cred.Role = wire.RoleWorker
+ }
+ return cred, nil
}
func authenticateRunnerAt(tx *gorm.DB, token string, now time.Time) (runnerRecord, runnerCredentialRecord, error) {
@@ -139,7 +144,14 @@ func revokeRunnerAt(tx *gorm.DB, id string, now time.Time) error {
return storeError(tx.Model(&runnerEnrolment{}).Where("runner_id = ? AND revoked_at IS NULL", id).Select("RevokedAt").Updates(&runnerEnrolment{RevokedAt: &now}).Error)
}
+// RevokeRunner removes a runner. Work it may have started keeps it
+// removing (it can still report that work's end, and gets no new work)
+// until the end is proven; only then is it revoked.
func (s *Store) RevokeRunner(ctx context.Context, actor Actor, runnerID string, revision int64) error {
+ return s.removeRunner(ctx, actor, runnerID, revision, false)
+}
+
+func (s *Store) removeRunner(ctx context.Context, actor Actor, runnerID string, revision int64, immediately bool) error {
return s.write(ctx, func(tx *gorm.DB) error {
member, err := currentRunnerMember(tx, actor.Address)
if err != nil {
@@ -167,10 +179,36 @@ func (s *Store) RevokeRunner(ctx context.Context, actor Actor, runnerID string,
if runner.RevokedAt != nil || runner.Revision != revision {
return ErrConflict
}
- if err := revokeRunnerAt(tx, runnerID, s.runnerClock.Now().UTC()); err != nil {
+ now := s.runnerClock.Now().UTC()
+ // Removing from here on: it gets no new work, so nothing withdrawn
+ // below is placed back on it.
+ if err := tx.Model(&runnerRecord{}).Where("id = ?", runnerID).Update("removing_at", now).Error; err != nil {
+ return storeError(err)
+ }
+ // Its work first: never-started attempts go elsewhere now; work it
+ // may have started is cancelled, and with now (a lost machine) it
+ // is quarantined instead of awaited.
+ uncertain, err := s.Chat().RemoveRunner(tx, runner.Person, runnerID, immediately)
+ if err != nil {
+ return err
+ }
+ kind := "runner.revoke"
+ switch {
+ case immediately:
+ kind = "runner.remove_now"
+ err = revokeRunnerAt(tx, runnerID, now)
+ case uncertain > 0:
+ // Removing: it reports the proofs, gets no new work, and is
+ // revoked when the last one arrives.
+ kind = "runner.removing"
+ err = storeError(tx.Model(&runnerRecord{}).Where("id = ?", runnerID).Update("revision", gorm.Expr("revision + 1")).Error)
+ default:
+ err = revokeRunnerAt(tx, runnerID, now)
+ }
+ if err != nil {
return err
}
- if err := appendAudit(tx, actor, "runner.revoke", runnerID); err != nil {
+ if err := appendAudit(tx, actor, kind, runnerID); err != nil {
return err
}
return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: revision + 1}, ErrConflict)
@@ -258,3 +296,10 @@ func runnerReport(tx *gorm.DB, id string) (*setup.RunnerReport, error) {
}
return r, nil
}
+
+// RemoveRunnerNow removes a runner at once, for a lost or compromised
+// machine: revoked now, and any step it may still be running is
+// quarantined until the task's creator recovers it.
+func (s *Store) RemoveRunnerNow(ctx context.Context, actor Actor, runnerID string, revision int64) error {
+ return s.removeRunner(ctx, actor, runnerID, revision, true)
+}
diff --git a/internal/equipo/setup/enrolment.go b/internal/equipo/setup/enrolment.go
index 72df1dc9..bc74aabc 100644
--- a/internal/equipo/setup/enrolment.go
+++ b/internal/equipo/setup/enrolment.go
@@ -140,7 +140,7 @@ func (s *Enrolments) ApproveOrInspect(ctx context.Context, actor Actor, userCode
// only be a worker is refused, shown or approved, until the person
// has a primary: it would become one.
var primaries int64
- if err := tx.Model(&RunnerRecord{}).Where("instance_id=? AND person=? AND revoked_at IS NULL AND coalesce(role,'') IN ('primary','')", instance, member.Address).Count(&primaries).Error; err != nil {
+ if err := tx.Model(&RunnerRecord{}).Where("instance_id=? AND person=? AND revoked_at IS NULL AND removing_at IS NULL AND coalesce(role,'') IN ('primary','')", instance, member.Address).Count(&primaries).Error; err != nil {
return s.Error(err)
}
if grant.WorkerOnly && primaries == 0 && s.NeedsPrimary != nil {
diff --git a/internal/equipo/setup/runner_models.go b/internal/equipo/setup/runner_models.go
index f26fdc15..79b6750e 100644
--- a/internal/equipo/setup/runner_models.go
+++ b/internal/equipo/setup/runner_models.go
@@ -18,6 +18,9 @@ type Runner struct {
// Report is what the runner last said of itself: its platform, how
// it confines checks and a Mac's self-probes (nil until it has).
Report *RunnerReport `gorm:"-"`
+ // RemovingAt: removal asked for while work it may have started was
+ // still running; it is revoked once that work's end is proven.
+ RemovingAt *time.Time
}
// RunnerReport is a runner's own report, for the Connections view.
diff --git a/internal/equipo/templates/runners.html b/internal/equipo/templates/runners.html
index dbb39fe3..f2062b07 100644
--- a/internal/equipo/templates/runners.html
+++ b/internal/equipo/templates/runners.html
@@ -37,9 +37,12 @@
{{with .Report}}{{if .Probes}}<h4>{{copy "runner.probes"}}</h4>
<ul equipo-probes>{{range .Probes}}<li data-probe="{{.ID}}" data-verdict="{{.Verdict}}"><span>{{copy (printf "runner.probe.%s" .ID)}}</span> <span>{{copy (printf "runner.verdict.%s" .Verdict)}}</span>{{with .Detail}} <span equipo-quiet>{{.}}</span>{{end}}</li>{{end}}</ul>{{end}}{{end}}
{{if .TrialOwner}}<p>{{copy "trial.history"}}: {{.TrialOwner}} / {{.TrialAt}}</p><pre>{{.TrialVersions}}</pre>{{end}}
-{{if not .RevokedAt}}<form method="post" action="/runners/{{.ID}}/revoke" equipo-form>
+{{if not .RevokedAt}}{{if .RemovingAt}}<p>{{copy "runner.removing"}}</p>{{else}}<form method="post" action="/runners/{{.ID}}/revoke" equipo-form>
<input type="hidden" name="revision" value="{{.Revision}}">
<button rst-btn type="submit">{{copy "runner.revoke"}}</button>
+</form>{{end}}<form method="post" action="/runners/{{.ID}}/remove-now" equipo-form>
+<input type="hidden" name="revision" value="{{.Revision}}">
+<button rst-btn type="submit">{{copy "runner.remove_now"}}</button>
</form>{{end}}
</section>
{{else}}<p>{{copy "runner.empty"}}</p>{{end}}
diff --git a/internal/equipo/templates/task_card.html b/internal/equipo/templates/task_card.html
index d24da56c..21d8cb5b 100644
--- a/internal/equipo/templates/task_card.html
+++ b/internal/equipo/templates/task_card.html
@@ -8,5 +8,5 @@
{{define "trial-label"}}{{if eq .Mode "owner mode"}}<span equipo-isolation>{{copy "isolation.owner_mode"}}</span>{{end}}{{if .ProfileApprovals}}<span equipo-isolation>{{copy "isolation.approved_beyond_profile"}}</span>{{end}}{{with .Trial}}<span equipo-isolation>{{copy "trial.label"}}: {{range .UnverifiedChecks}}<span>{{copy (printf "trial.check.%s" .)}}</span> {{end}}<span>{{copy "trial.observed_locally"}}</span></span>{{end}}{{end}}
-{{define "work-task-actions"}}{{if .Merge}}<form method="post" action="/conversation/tasks/{{.ID}}/merge" data-card-form><button equipo-link type="submit" data-task-merge>{{copy "work.merge_now"}}</button></form>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{.ID}}/retry" data-card-form><button equipo-link type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{.ID}}/cancel" data-card-form><button equipo-link type="submit" data-task-cancel>{{copy "work.cancel"}}</button></form>{{end}}{{end}}
+{{define "work-task-actions"}}{{if .Merge}}<form method="post" action="/conversation/tasks/{{.ID}}/merge" data-card-form><button equipo-link type="submit" data-task-merge>{{copy "work.merge_now"}}</button></form>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{.ID}}/retry" data-card-form><button equipo-link type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Recover}}<form method="post" action="/conversation/tasks/{{.ID}}/recover" data-card-form><button equipo-link type="submit" data-task-recover>{{copy "work.recover"}}</button></form>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{.ID}}/cancel" data-card-form><button equipo-link type="submit" data-task-cancel>{{copy "work.cancel"}}</button></form>{{end}}{{end}}
{{define "work-task-row"}}<li equipo-work-task data-task="{{.ID}}" data-stage="{{.Stage}}"><p><a href="/tasks/{{.ID}}">{{.Title}}</a></p><p equipo-card-note><span>{{.Project}}</span><span>{{.StageLine}}</span>{{with .Finding}}{{if .Path}}<span>{{.Path}}:{{.Line}}</span>{{end}}{{end}}<span>{{printf (copy "work.noted_by") .Creator}}</span></p>{{if and .Pushed (not .MergedLine)}}<p equipo-card-note data-pushed><span>{{.Pushed}}</span><a href="{{.URL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}{{if or .ChecksLine .ReviewLine}}<p equipo-card-note data-judged>{{with .ChecksLine}}<span data-checks>{{.}}</span>{{end}}{{with .ReviewLine}}<span data-verdict>{{.}}</span>{{end}}</p>{{end}}{{if .MergedLine}}<p equipo-card-note data-merged><span>{{.MergedLine}}</span><a href="{{.RepoURL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}</li>{{end}}
diff --git a/internal/equipo/templates/work_parts.html b/internal/equipo/templates/work_parts.html
index fcb6fc4f..6d172253 100644
--- a/internal/equipo/templates/work_parts.html
+++ b/internal/equipo/templates/work_parts.html
@@ -30,7 +30,7 @@
{{if $.Head}}{{template "mono" $t.Mono}}<div equipo-d-title><a href="/tasks/{{$t.ID}}">{{$t.Title}}</a><span equipo-quiet>{{$t.Project}} · {{template "source" $t}}</span></div>{{end}}
<p equipo-d-why>{{.Why}}</p>
<p equipo-d-ask>{{.Ask}}</p>
-<div equipo-d-actions>{{with .Card}}<form method="post" action="/conversation/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="task" value="{{$t.ID}}">{{range $.Task.Decision.Choices}}<button equipo-btn{{if .Primary}} data-primary{{end}} type="submit" name="choice" value="{{.Value}}" data-merge-choice="{{.Value}}">{{.Label}}</button>{{end}}</form>{{end}}{{if .Fold}}<form method="post" action="/tasks/{{$t.ID}}/duplicate"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="of" value="{{$t.Dup.ID}}"><button equipo-btn data-primary type="submit" data-task-duplicate>{{copy "work.decide.fold"}}</button></form>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{$t.ID}}/retry"><input type="hidden" name="from" value="{{$.From}}"><button {{if .Fold}}equipo-link{{else}}equipo-btn data-primary{{end}} type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Talk}}<a equipo-btn href="/conversation">{{copy "work.decide.talk"}}</a>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{$t.ID}}/cancel"><input type="hidden" name="from" value="{{$.From}}"><button equipo-link type="submit" data-task-cancel>{{copy "work.decide.cancel"}}</button></form>{{end}}{{with .Hint}}<span equipo-quiet>{{.}}</span>{{end}}</div>
+<div equipo-d-actions>{{with .Card}}<form method="post" action="/conversation/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="task" value="{{$t.ID}}">{{range $.Task.Decision.Choices}}<button equipo-btn{{if .Primary}} data-primary{{end}} type="submit" name="choice" value="{{.Value}}" data-merge-choice="{{.Value}}">{{.Label}}</button>{{end}}</form>{{end}}{{if .Fold}}<form method="post" action="/tasks/{{$t.ID}}/duplicate"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="of" value="{{$t.Dup.ID}}"><button equipo-btn data-primary type="submit" data-task-duplicate>{{copy "work.decide.fold"}}</button></form>{{end}}{{if .Recover}}<form method="post" action="/conversation/tasks/{{$t.ID}}/recover"><input type="hidden" name="from" value="{{$.From}}"><button equipo-btn data-primary type="submit" data-task-recover>{{copy "work.recover"}}</button></form>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{$t.ID}}/retry"><input type="hidden" name="from" value="{{$.From}}"><button {{if .Fold}}equipo-link{{else}}equipo-btn data-primary{{end}} type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Talk}}<a equipo-btn href="/conversation">{{copy "work.decide.talk"}}</a>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{$t.ID}}/cancel"><input type="hidden" name="from" value="{{$.From}}"><button equipo-link type="submit" data-task-cancel>{{copy "work.decide.cancel"}}</button></form>{{end}}{{with .Hint}}<span equipo-quiet>{{.}}</span>{{end}}</div>
</div>{{end}}{{end}}
{{define "project-facts"}}{{with .StackLine}}<span>{{if $.PhoneStack}}{{icon "phone"}}{{else}}{{icon "code"}}{{end}}{{.}}</span>{{end}}<span>{{icon "git"}}{{if eq (len .Repos) 1}}{{copy "work.project.one_repo"}}{{else}}{{printf (copy "work.project.repos") (len .Repos)}}{{end}}</span>{{with .ChecksLine}}<span data-tone="{{if $.Checks.Here}}positive{{else}}warning{{end}}" data-checks-fact>{{if $.Checks.Here}}{{icon "check-circle"}}{{else}}{{icon "help-circle"}}{{end}}{{.}}</span>{{end}}{{end}}
{{define "thinking-form"}}{{with .Thinking}}<div equipo-thinking-words data-thinking-words="{{.JSON}}"{{if not $.From}} data-settings-live{{end}}>{{if not $.From}}<template equipo-saved-template><span equipo-saved-tick role="status">{{icon "check"}}<span>{{copy "settings.saved"}}</span></span></template>{{end}}
diff --git a/internal/equipo/work_pages.go b/internal/equipo/work_pages.go
index d9bd1b5e..0f812abf 100644
--- a/internal/equipo/work_pages.go
+++ b/internal/equipo/work_pages.go
@@ -30,6 +30,8 @@ type taskLine struct {
Steps []stepLine
Finding *wire.Finding
Retry, Cancel bool
+ // Recover settles a step stopped when its machine was removed.
+ Recover bool
// Merge is the creator's quiet Merge on a task left at Ready to merge.
Merge bool
// The inner screens' pieces (work_views.go).
@@ -171,6 +173,9 @@ func taskLineOf(t wire.Task, viewer string) taskLine {
}
v.StageLine = fmt.Sprintf(copyText("work.stopped"), reason)
v.Retry = s.Terminated
+ if s.Reason == "machine_removed" && !s.Terminated {
+ v.StageLine, v.Recover = copyText("work.needs.machine_removed"), true
+ }
}
}
if t.Merged != nil {
@@ -188,7 +193,7 @@ func taskLineOf(t wire.Task, viewer string) taskLine {
v.Cancel = !wire.FinalStage(t.Stage) && t.Stage != wire.StageMerging
v.Merge = t.MergeOffered
if t.Creator != viewer {
- v.Retry, v.Cancel, v.Merge = false, false, false
+ v.Retry, v.Cancel, v.Merge, v.Recover = false, false, false, false
}
return v
}
@@ -575,6 +580,16 @@ func (a *application) workTaskMerge(w http.ResponseWriter, r *http.Request) {
// workTaskAction is Retry or Cancel from the task card or the task page:
// the same store calls a device makes, as the session's person.
+// workTaskRecover is Recover from the task card: the creator says the
+// removed machine is off.
+func (a *application) workTaskRecover(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ a.chatActionTo(w, r, workBack(r, id), func(ctx context.Context, address string) error {
+ _, err := a.store.Chat().RecoverTask(ctx, address, id)
+ return err
+ })
+}
+
func (a *application) workTaskAction(retry bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
diff --git a/internal/equipo/work_views.go b/internal/equipo/work_views.go
index bb3a6485..4ff47f9e 100644
--- a/internal/equipo/work_views.go
+++ b/internal/equipo/work_views.go
@@ -96,6 +96,8 @@ type decisionView struct {
Choices []decisionChoice
Retry, Cancel, Fold bool
Talk bool
+ // Recover settles a step stopped when its machine was removed.
+ Recover bool
}
type decisionChoice struct {
@@ -132,7 +134,7 @@ func needsViewer(t wire.Task, viewer string, card *wire.Card) bool {
return false
}
switch t.NeedsYou {
- case wire.NeedsRetry, wire.NeedsReviewBlocked, wire.NeedsFixRounds, wire.NeedsBranchMoved, wire.NeedsMergeConflict:
+ case wire.NeedsRetry, wire.NeedsReviewBlocked, wire.NeedsFixRounds, wire.NeedsBranchMoved, wire.NeedsMergeConflict, wire.NeedsMachineRemoved:
return true
case wire.NeedsMerge:
return card != nil
@@ -143,7 +145,7 @@ func needsViewer(t wire.Task, viewer string, card *wire.Card) bool {
// needsSomeone is the same for any creator, for "Waiting for Nora".
func needsSomeone(t wire.Task) bool {
switch t.NeedsYou {
- case wire.NeedsRetry, wire.NeedsReviewBlocked, wire.NeedsFixRounds, wire.NeedsBranchMoved, wire.NeedsMergeConflict:
+ case wire.NeedsRetry, wire.NeedsReviewBlocked, wire.NeedsFixRounds, wire.NeedsBranchMoved, wire.NeedsMergeConflict, wire.NeedsMachineRemoved:
return !wire.FinalStage(t.Stage)
}
return false
@@ -495,6 +497,8 @@ func decisionOf(t wire.Task, v taskLine) *decisionView {
d.Tone, d.Why, d.Ask, d.Talk, d.Cancel = "attention", copyText("work.decide.branch_moved_why"), copyText("work.decide.talk_ask"), true, v.Cancel
case wire.NeedsMergeConflict:
d.Tone, d.Why, d.Ask, d.Talk, d.Cancel = "attention", copyText("work.decide.conflict_why"), copyText("work.decide.talk_ask"), true, v.Cancel
+ case wire.NeedsMachineRemoved:
+ d.Tone, d.Why, d.Recover, d.Cancel = "attention", copyText("work.needs.machine_removed"), v.Recover, v.Cancel
}
return d
}
diff --git a/internal/plan3test/person_api_contract_test.go b/internal/plan3test/person_api_contract_test.go
index f41b5a86..cb5c5f61 100644
--- a/internal/plan3test/person_api_contract_test.go
+++ b/internal/plan3test/person_api_contract_test.go
@@ -56,7 +56,7 @@ func personAPIContractCoverage(t *testing.T) {
f := newFixture(t)
registered := map[string]bool{}
// Thin v1 conversation routes are contracted by internal/wire fixtures.
- thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/forget": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true}
+ thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/recover": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/forget": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true}
must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
if thin[method+" "+path] {
return nil
diff --git a/internal/runner/diagnostics.go b/internal/runner/diagnostics.go
index 528d033a..539a5ff0 100644
--- a/internal/runner/diagnostics.go
+++ b/internal/runner/diagnostics.go
@@ -67,6 +67,8 @@ func Diagnostic(err error) (string, string) {
code = "runner.reconcile"
case errors.Is(err, ErrInstanceOlder):
code = "runner.instance_older_than_worker"
+ case errors.Is(err, ErrEnrolledAsPrimary):
+ code = "runner.enrolled_as_primary"
}
return code, "-"
}
diff --git a/internal/runner/enrol.go b/internal/runner/enrol.go
index 360caffb..8e16b6f4 100644
--- a/internal/runner/enrol.go
+++ b/internal/runner/enrol.go
@@ -182,11 +182,50 @@ func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) {
if cred.Version != 1 || cred.Token == "" || cred.RunnerID == "" || !time.Now().Before(cred.ExpiresAt) {
return provider.ErrIdentity
}
- return runnerproto.JournalCredentials(credentialPath, runnerproto.CredentialRotation{Bearer: cred})
+ if c.WorkerOnly && cred.Role != wire.RoleWorker {
+ // The instance enrolled this machine as a primary: a Mac only
+ // ever runs as a worker, so it keeps nothing and says why.
+ return ErrEnrolledAsPrimary
+ }
+ if err := runnerproto.JournalCredentials(credentialPath, runnerproto.CredentialRotation{Bearer: cred}); err != nil {
+ return err
+ }
+ // The role is kept before the runner ever connects (a worker never
+ // serves as a primary), beside the credential so an older runner
+ // binary still reads that. No role is a primary's credential, or an
+ // older instance's, which has only primaries.
+ role := wire.RolePrimary
+ if cred.Role == wire.RoleWorker {
+ role = wire.RoleWorker
+ }
+ return WriteRole(c.StateDir, role)
}
return provider.ErrIdentity
}
+// RoleFile keeps the role a runner was enrolled with, in its state
+// directory.
+const RoleFile = "role"
+
+// WriteRole records the enrolled role.
+func WriteRole(stateDir, role string) error {
+ return runnerproto.JournalCredentials(filepath.Join(stateDir, RoleFile), role)
+}
+
+// ReadRole is the enrolled role, "" when the runner was enrolled before
+// roles.
+func ReadRole(stateDir string) string {
+ var role string
+ if privateJSON(filepath.Join(stateDir, RoleFile), &role) != nil || role != wire.RolePrimary && role != wire.RoleWorker {
+ return ""
+ }
+ return role
+}
+
+// ErrEnrolledAsPrimary: a runner that can only be a worker was given the
+// primary role (the person had no primary). Nothing is kept.
+var ErrEnrolledAsPrimary = errors.New("a worker-only runner was enrolled as a primary")
+
// ErrInstanceOlder refuses to enrol a runner that can only be a worker
// with an instance that does not speak protocol 2.
var ErrInstanceOlder = errors.New("the instance is older than this worker")
diff --git a/internal/runner/enrol_worker_test.go b/internal/runner/enrol_worker_test.go
index 1f7b3e8c..a9eada27 100644
--- a/internal/runner/enrol_worker_test.go
+++ b/internal/runner/enrol_worker_test.go
@@ -3,11 +3,17 @@ package runner
import (
"context"
"encoding/json"
+ "errors"
+ "fmt"
+ "io"
"net"
"net/http"
+ "os"
"path/filepath"
+ "strings"
"sync"
"testing"
+ "time"
"amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/wire"
@@ -72,3 +78,58 @@ func TestWorkerEnrolRefusesAnOlderInstance(t *testing.T) {
})
}
}
+
+// Enrolment keeps the role the instance gave the runner with its
+// credential, before the runner ever connects: worker when the instance
+// says so, primary when it says nothing (a primary, or an instance
+// without workers).
+func TestEnrolKeepsTheRole(t *testing.T) {
+ for _, tc := range []struct {
+ answer, want string
+ mac bool
+ }{{`,"role":"worker"`, "worker", false}, {"", "primary", false}, {`,"role":"worker"`, "worker", true}, {"", "", true}} {
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case wire.RunnerProtocolPath:
+ _, _ = w.Write([]byte(`{"protocol":2}`))
+ case "/api/enrolments":
+ _, _ = fmt.Fprintf(w, `{"version":1,"enrolment_id":"e1","instance_id":"inst","device_secret":"s","user_code":"ABCD-EFGH","challenge":"c","verification_uri":"http://%s/runners/enrol","expires_at":%q,"poll_interval_seconds":5}`, r.Host, time.Now().Add(time.Minute).UTC().Format(time.RFC3339))
+ case "/api/enrolments/token":
+ _, _ = fmt.Fprintf(w, `{"version":1,"token":"t","token_type":"Bearer","runner_id":"R2","credential_id":"C2","person":"p@x","expires_at":%q%s}`, time.Now().Add(time.Hour).UTC().Format(time.RFC3339), tc.answer)
+ default:
+ http.Error(w, "no", 404)
+ }
+ })}
+ go srv.Serve(l)
+ state := filepath.Join(t.TempDir(), "state")
+ c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: state, MachineLabel: "Tito Studio", WorkerOnly: tc.mac}
+ err = Enrol(context.Background(), c, io.Discard)
+ srv.Close()
+ if tc.mac && tc.want == "" {
+ // A Mac the instance made a primary keeps nothing and says why.
+ code, _ := Diagnostic(err)
+ if !errors.Is(err, ErrEnrolledAsPrimary) || code != "runner.enrolled_as_primary" {
+ t.Fatalf("a Mac enrolled as a primary: %v", err)
+ }
+ if _, serr := os.Stat(filepath.Join(state, "credentials.json")); !os.IsNotExist(serr) || ReadRole(state) != "" {
+ t.Fatal("a Mac kept a primary's credential")
+ }
+ continue
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if role := ReadRole(state); role != tc.want {
+ t.Fatalf("stored role %q, want %q", role, tc.want)
+ }
+ // The credential file stays what older runner binaries read.
+ raw, _ := os.ReadFile(filepath.Join(state, "credentials.json"))
+ if tc.want == "primary" && strings.Contains(string(raw), `"role"`) {
+ t.Fatalf("a primary's credential file names a role: %s", raw)
+ }
+ }
+}
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go
index 263f594c..514760c9 100644
--- a/internal/runner/thin/contract_test.go
+++ b/internal/runner/thin/contract_test.go
@@ -51,6 +51,9 @@ func (s *stubCoordinator) Close() {}
func i64(v int64) *int64 { return &v }
+// testEnrolledRole is the role startLink's runner was enrolled with.
+var testEnrolledRole = wire.RolePrimary
+
// fakeInstance is the instance end of the stream, driven from fixtures.
type fakeInstance struct {
t *testing.T
@@ -149,7 +152,7 @@ func startLink(t *testing.T, origin string, coord Coordinator, seed ...func(*Sta
if err := os.MkdirAll(sessions, 0700); err != nil {
t.Fatal(err)
}
- link := &Link{Origin: origin, Token: "token", State: state, Files: &Files{State: state, SessionRoot: sessions}, Hello: func() wire.Hello {
+ link := &Link{Origin: origin, Token: "token", State: state, Role: testEnrolledRole, Files: &Files{State: state, SessionRoot: sessions}, Hello: func() wire.Hello {
return wire.Hello{Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{{LocalID: "claude-a", Person: "owner@example.com", Provider: "claude", Kind: "subscription", Label: "owner@example.com", State: "healthy"}}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}}
}}
engine := &Engine{State: state, Emit: link.Delta, Notify: link.Notify, Authorize: link.Confirm, Open: func(string, runner.AccountBinding) (Coordinator, error) { return coord, nil }}
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index 3310b7b5..aa5be0af 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -35,10 +35,24 @@ var ErrRoleMismatch = errors.New("this runner is a worker and the instance welco
// metaRole keeps the role the instance gave this runner, in its state.
const metaRole = "role"
-// workerOnly: this runner can only be a worker, by its platform or
-// because the instance made it one.
+// workerOnly: this runner may be a worker, so it never runs at protocol
+// 1 nor under a primary's welcome: by its platform, its enrolled role, the
+// role the instance gave it, or because it knows no role yet (a
+// credential from before roles) until a protocol 2 welcome says.
func (l *Link) workerOnly(ctx context.Context) bool {
- if l.WorkerOnly {
+ if l.WorkerOnly || l.Role == wire.RoleWorker {
+ return true
+ }
+ role, err := l.State.meta(ctx, metaRole)
+ if err != nil || role == wire.RoleWorker {
+ return true
+ }
+ return l.Role == "" && role == ""
+}
+
+// knownWorker: a worker by platform, enrolment or the instance's word.
+func (l *Link) knownWorker(ctx context.Context) bool {
+ if l.WorkerOnly || l.Role == wire.RoleWorker {
return true
}
role, err := l.State.meta(ctx, metaRole)
@@ -84,6 +98,9 @@ type Link struct {
// WorkerOnly: this runner can only be a worker (a Mac), so it never
// runs at protocol 1.
WorkerOnly bool
+ // Role is the role this runner was enrolled with (its credential), ""
+ // when the credential predates roles.
+ Role string
// Protocol caps what this runner offers (default wire.ProtocolCurrent;
// tests set 1 to act as a slice 4 runner).
Protocol int
@@ -453,12 +470,14 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire
c.CloseNow()
return nil, nil, ErrInstanceTooOld
}
- if worker && role != wire.RoleWorker {
+ if role != wire.RoleWorker && l.knownWorker(ctx) {
c.CloseNow()
return nil, nil, ErrRoleMismatch
}
- if role == wire.RoleWorker {
- if err := l.State.setMeta(ctx, metaRole, wire.RoleWorker); err != nil {
+ if role != "" {
+ // The instance's word at protocol 2: kept, so a later rollback
+ // cannot make a worker a primary.
+ if err := l.State.setMeta(ctx, metaRole, role); err != nil {
c.CloseNow()
return nil, nil, err
}
diff --git a/internal/runner/thin/protocol_test.go b/internal/runner/thin/protocol_test.go
index 5c51c557..c233794c 100644
--- a/internal/runner/thin/protocol_test.go
+++ b/internal/runner/thin/protocol_test.go
@@ -188,3 +188,57 @@ func TestWorkerRefusesAPrimaryWelcome(t *testing.T) {
}
}
}
+
+// startLinkAs is startLink for a runner enrolled with role ("" when its
+// credential predates roles).
+func startLinkAs(t *testing.T, origin, role string) *Link {
+ t.Helper()
+ testEnrolledRole = role
+ defer func() { testEnrolledRole = wire.RolePrimary }()
+ link, _, _, _ := startLink(t, origin, &stubCoordinator{})
+ return link
+}
+
+// A worker enrolled with an instance that was then rolled back, before it
+// ever saw a welcome: its enrolled role keeps it from protocol 1.
+func TestEnrolledWorkerNeverFallsBack(t *testing.T) {
+ defer func(d time.Duration) { olderRetry = d }(olderRetry)
+ olderRetry = time.Hour
+ inst := newFakeInstance(t)
+ startLinkAs(t, inst.url, wire.RoleWorker)
+ olderInstance(t, <-inst.conns)
+ select {
+ case <-inst.conns:
+ t.Fatal("an enrolled worker said hello at protocol 1")
+ case <-time.After(1500 * time.Millisecond):
+ }
+}
+
+// A runner upgraded from before roles knows nothing of its own: it learns
+// its role from the instance at protocol 2 and, until then, never falls
+// back to protocol 1 (it might be a worker).
+func TestUnknownRoleWaitsForTheInstance(t *testing.T) {
+ defer func(d time.Duration) { olderRetry = d }(olderRetry)
+ olderRetry = time.Hour
+ inst := newFakeInstance(t)
+ link := startLinkAs(t, inst.url, "")
+ olderInstance(t, <-inst.conns)
+ select {
+ case <-inst.conns:
+ t.Fatal("a runner of unknown role fell back to protocol 1")
+ case <-time.After(1500 * time.Millisecond):
+ }
+ _ = link
+}
+
+func TestUnknownRoleLearnsFromProtocol2(t *testing.T) {
+ inst := newFakeInstance(t)
+ link := startLinkAs(t, inst.url, "")
+ c := <-inst.conns
+ read(t, c, wire.FrameHello)
+ write(t, c, wiretest.Fixture("frames/welcome-worker.json"))
+ read(t, c, wire.FrameSync)
+ if role, _ := link.State.meta(context.Background(), "role"); role != wire.RoleWorker {
+ t.Fatalf("role not learned: %q", role)
+ }
+}
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index b86b4b93..51992232 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -154,7 +154,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
defer cancel()
platform := hostPlatform()
caps := &Capabilities{Probe: linuxCapabilities(c)}
- link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: platform.OS == "darwin"}
+ link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: platform.OS == "darwin", Role: enrolledRole(c, creds.Bearer.Role)}
link.Files = &Files{State: state, SessionRoot: o.Claude.SessionRoot, Logger: o.Logger}
// Attachments stay bounded whether or not anything arrives.
go link.Files.Run(ctx, 10*time.Minute)
@@ -471,6 +471,18 @@ func verifiedExit(ctx context.Context, m *containment.Manager, id string) bool {
return true
}
+// enrolledRole is the role the runner was enrolled with: kept at
+// enrolment, or named by its credential; "" when it predates roles.
+func enrolledRole(c runner.Config, credential string) string {
+ if role := runner.ReadRole(c.StateDir); role != "" {
+ return role
+ }
+ if credential == wire.RoleWorker {
+ return wire.RoleWorker
+ }
+ return ""
+}
+
// ErrNotTestBuild refuses EQUIPO_FAKE_PLATFORM outside the test build:
// no release binary runs the unsandboxed fake worker.
var ErrNotTestBuild = errors.New("EQUIPO_FAKE_PLATFORM: this runner is not a test build")
@@ -529,7 +541,7 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
caps := &Capabilities{Probe: w.probe}
- link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true}
+ link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true, Role: enrolledRole(c, creds.Bearer.Role)}
link.Hello = func() wire.Hello {
report := caps.Get(ctx)
return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: w.gate.Sandbox(), Capabilities: &report}
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go
index 4a6b31f1..d79587af 100644
--- a/internal/runnerproto/types.go
+++ b/internal/runnerproto/types.go
@@ -58,6 +58,10 @@ type RunnerCredential struct {
CredentialID string `json:"credential_id"`
Person string `json:"person"`
ExpiresAt time.Time `json:"expires_at"`
+ // Role is "worker" for a worker (protocol 2 instances say so at
+ // enrolment); absent means primary, as an older instance's credential
+ // is. The runner keeps it with the credential.
+ Role string `json:"role,omitempty"`
}
type ErrorResponse struct {
diff --git a/internal/thintest/client.go b/internal/thintest/client.go
index 571d8c16..c1c029f6 100644
--- a/internal/thintest/client.go
+++ b/internal/thintest/client.go
@@ -199,6 +199,11 @@ func (c *Client) MarkDuplicate(ctx context.Context, id, of string) (out wire.Tas
}
// RetryTask starts a new attempt once the last one's termination is known.
+// RecoverTask settles a step stopped when its machine was removed.
+func (c *Client) RecoverTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
+ return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/recover", nil, &out)
+}
+
func (c *Client) RetryTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/retry", nil, &out)
}
diff --git a/internal/thintest/instance.go b/internal/thintest/instance.go
index c316428d..54b9db05 100644
--- a/internal/thintest/instance.go
+++ b/internal/thintest/instance.go
@@ -246,7 +246,16 @@ func WriteRunnerCredential(stateDir string, cred runnerproto.RunnerCredential) e
if err = os.MkdirAll(stateDir, 0700); err != nil {
return err
}
- return os.WriteFile(filepath.Join(stateDir, "credentials.json"), raw, 0600)
+ if err := os.WriteFile(filepath.Join(stateDir, "credentials.json"), raw, 0600); err != nil {
+ return err
+ }
+ // As enrolment keeps it, beside the credential: no role is a
+ // primary's credential.
+ role := `"primary"`
+ if cred.Role == "worker" {
+ role = `"worker"`
+ }
+ return os.WriteFile(filepath.Join(stateDir, "role"), []byte(role), 0600)
}
// ErrStatus is an unexpected HTTP status from the person API.
diff --git a/internal/thintest/migration_contract_test.go b/internal/thintest/migration_contract_test.go
index c834f2ca..a2420b9c 100644
--- a/internal/thintest/migration_contract_test.go
+++ b/internal/thintest/migration_contract_test.go
@@ -22,7 +22,7 @@ func slice4(t *testing.T, path string) {
defer d.Close()
for _, q := range []string{
"DROP INDEX runner_command_runner", "DROP INDEX chat_step_runner", "DROP TABLE runner_transfers",
- "ALTER TABLE runners DROP COLUMN role", "ALTER TABLE runner_commands DROP COLUMN runner_id", "ALTER TABLE runner_sessions DROP COLUMN protocol",
+ "ALTER TABLE runners DROP COLUMN role", "ALTER TABLE runners DROP COLUMN removing_at", "ALTER TABLE runner_commands DROP COLUMN runner_id", "ALTER TABLE runner_sessions DROP COLUMN protocol",
"ALTER TABLE chat_tasks DROP COLUMN engineering_runner",
"ALTER TABLE chat_steps DROP COLUMN runner_id", "ALTER TABLE chat_steps DROP COLUMN needs", "ALTER TABLE chat_steps DROP COLUMN placement",
"ALTER TABLE chat_steps DROP COLUMN waiting_since", "ALTER TABLE chat_steps DROP COLUMN refused_by", "ALTER TABLE chat_steps DROP COLUMN withdrawn",
diff --git a/internal/thintest/review1_contract_test.go b/internal/thintest/review1_contract_test.go
index a1823a5e..a91fd0cc 100644
--- a/internal/thintest/review1_contract_test.go
+++ b/internal/thintest/review1_contract_test.go
@@ -23,18 +23,23 @@ func (r *runnersRig) revoke(id string) {
}
}
-// A revoked primary keeps its attempts until their termination is
-// proven: its unacked dispatch is not sent to the replacement (a lost ack
-// may mean it runs), its running step stays its own, the replacement's
-// empty sync ends neither, and Retry stays refused.
+// Removing a primary keeps what it may have started its own until the
+// proof arrives: its running step is cancelled there, the replacement's
+// empty sync settles nothing, and Retry stays refused. A dispatch it never
+// started (protocol 2: no start authorization) moves to the replacement
+// as the next attempt, and the old attempt can never start.
func TestContractRevokedPrimaryKeepsItsAttempts(t *testing.T) {
r := newRunnersRig(t)
ctx := r.ctx
old := r.runner.Welcome.RunnerID
+ oldGen := r.runner.Welcome.Generation
running := taskID(t, r.call("v1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Running when revoked", "brief": "b"}))
r.call("v2", wire.ToolStartTask, map[string]string{"task": running, "brief": "go"})
_, body := r.expect(wire.FrameDispatch)
d := body.(*wire.DispatchCommand)
+ if !r.primary.lease(d.StepID, 1) {
+ t.Fatal("start refused")
+ }
r.step("v-run", wire.StepReport{TaskID: running, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40), Findings: []wire.Finding{}})
unacked := taskID(t, r.call("v3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Dispatched, never acked", "brief": "b"}))
r.call("v4", wire.ToolStartTask, map[string]string{"task": unacked, "brief": "go"})
@@ -52,20 +57,29 @@ func TestContractRevokedPrimaryKeepsItsAttempts(t *testing.T) {
}
np := &peer{t: t, r: r.toolRig, fr: p}
np.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}})
- np.send(wire.FrameStep, wire.StepReport{TaskID: running, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}})
- for _, id := range []string{running, unacked} {
- k, err := r.client.Task(ctx, id)
- if err != nil {
- t.Fatal(err)
- }
- if s := k.Steps[0]; wire.StepTerminal(s.State) || s.Terminated || s.RunnerID != old {
- t.Fatalf("the replacement took the revoked primary's attempt %s: %+v", id, s)
- }
- if _, err := r.client.RetryTask(ctx, id); Status(err) != 409 {
- t.Fatalf("retry of an unproven attempt: %v", err)
- }
+ k, _ := r.client.Task(ctx, running)
+ if s := k.Steps[0]; wire.StepTerminal(s.State) || s.Terminated || s.RunnerID != old {
+ t.Fatalf("the replacement settled the removed primary's running attempt: %+v", s)
+ }
+ if _, err := r.client.RetryTask(ctx, running); Status(err) != 409 {
+ t.Fatalf("retry of an unproven attempt: %v", err)
+ }
+ _, body = np.expect(wire.FrameDispatch)
+ if d2 := body.(*wire.DispatchCommand); d2.TaskID != unacked || d2.Attempt != 2 {
+ t.Fatalf("the never-started attempt %+v", d2)
+ }
+ // The removed primary may still report its proof; its old attempt of
+ // the moved step can never start.
+ back, err := DialRunnerHello(ctx, r.inst.URL, r.rig.runner, primaryHello(oldGen))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer back.Close()
+ bp := &peer{t: t, r: r.toolRig, fr: back}
+ k, _ = r.client.Task(ctx, unacked)
+ if bp.lease(k.Steps[0].ID, 1) {
+ t.Fatal("a withdrawn attempt may start on the removed primary")
}
- np.none(wire.FrameDispatch, 100*time.Millisecond)
}
// Never-dispatched waiting checks end on Cancel, locally: nothing is
diff --git a/internal/thintest/review2_contract_test.go b/internal/thintest/review2_contract_test.go
new file mode 100644
index 00000000..747a82ab
--- /dev/null
+++ b/internal/thintest/review2_contract_test.go
@@ -0,0 +1,207 @@
+package thintest
+
+import (
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Cancel after a withdrawal: the withdrawn attempt's proof finishes the
+// cancellation; no next attempt is placed or may start.
+func TestContractCancelAfterWithdrawal(t *testing.T) {
+ r := newRunnersRig(t)
+ task, step, w, _ := r.startedOnWorker("Withdrawn, then cancelled")
+ if _, err := r.client.CancelTask(r.ctx, task); err != nil {
+ t.Fatal(err)
+ }
+ w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: step, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}})
+ k, _ := r.client.Task(r.ctx, task)
+ s := r.checksStep(task)
+ if k.Stage != wire.StageCancelled || s.Attempt != 1 || s.State != wire.StepCancelled || !s.Terminated {
+ t.Fatalf("after the proof: task %s step %+v", k.Stage, s)
+ }
+ w.none(wire.FrameDispatch, 100*time.Millisecond)
+ if w.lease(step, 2) {
+ t.Fatal("a next attempt may start after the cancel")
+ }
+}
+
+// remove asks for a runner's removal as the owner: ordinary, or now.
+func (r *runnersRig) remove(id string, now bool) {
+ r.t.Helper()
+ var revision int64
+ if err := r.inst.DB.Writer().QueryRow("SELECT revision FROM runners WHERE id = ?", id).Scan(&revision); err != nil {
+ r.t.Fatal(err)
+ }
+ remove := r.inst.Store.RevokeRunner
+ if now {
+ remove = r.inst.Store.RemoveRunnerNow
+ }
+ if err := remove(r.ctx, equipo.Actor{Address: Owner}, id, revision); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func (r *runnersRig) revokedAt(id string) bool {
+ r.t.Helper()
+ var n int
+ if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runners WHERE id = ? AND revoked_at IS NOT NULL", id).Scan(&n); err != nil {
+ r.t.Fatal(err)
+ }
+ return n == 1
+}
+
+// Ordinary removal is two-phase. An attempt that never started is
+// withdrawn at once and placed elsewhere; one that may have started is
+// cancelled, and the runner reads Removing (still able to report, given
+// no new work) until its proof arrives; only then is it revoked.
+func TestContractRemovalWaitsForProof(t *testing.T) {
+ r := newRunnersRig(t)
+ a, _ := r.newWorker("Mac A")
+ b, _ := r.newWorker("Mac B")
+ started, _ := r.candidate("iOS started", true)
+ _, body := a.expect(wire.FrameDispatch)
+ d1 := body.(*wire.DispatchCommand)
+ if !a.lease(d1.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ waiting, _ := r.candidate("iOS not started", true)
+ _, body = b.expect(wire.FrameDispatch) // fewest running steps: B
+ d2 := body.(*wire.DispatchCommand)
+ if d2.TaskID != waiting {
+ t.Fatalf("second dispatch %+v", d2)
+ }
+ r.remove(b.fr.Welcome.RunnerID, false)
+ // Never started: withdrawn in the same transaction, and B (no
+ // uncertain attempt) is revoked at once.
+ if !r.revokedAt(b.fr.Welcome.RunnerID) {
+ t.Fatal("a runner with nothing uncertain was not revoked")
+ }
+ if s := r.checksStep(waiting); s.Attempt != 2 || s.RunnerID == b.fr.Welcome.RunnerID {
+ t.Fatalf("never-started attempt not withdrawn: %+v", s)
+ }
+ r.remove(a.fr.Welcome.RunnerID, false)
+ if r.revokedAt(a.fr.Welcome.RunnerID) {
+ t.Fatal("revoked before its attempt's termination proof")
+ }
+ runners, _ := r.client.Runners(r.ctx)
+ removing := false
+ for _, x := range runners.Items {
+ if x.ID == a.fr.Welcome.RunnerID && x.Removing {
+ removing = true
+ }
+ }
+ if !removing {
+ t.Fatalf("runner not shown as removing: %+v", runners.Items)
+ }
+ _, body = a.expect(wire.FrameCancelStep)
+ if c := body.(*wire.CancelStepCommand); c.StepID != d1.StepID {
+ t.Fatalf("cancel %+v", c)
+ }
+ // The primary's empty sync and time passing prove nothing.
+ r.primary.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}})
+ if r.revokedAt(a.fr.Welcome.RunnerID) || r.checksStep(started).Attempt != 1 {
+ t.Fatal("something other than the proof settled it")
+ }
+ a.send(wire.FrameStep, wire.StepReport{TaskID: started, StepID: d1.StepID, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}})
+ if !r.revokedAt(a.fr.Welcome.RunnerID) {
+ t.Fatal("not revoked after the proof")
+ }
+ if s := r.checksStep(started); s.Attempt != 2 || s.RunnerID == a.fr.Welcome.RunnerID {
+ t.Fatalf("next attempt %+v", s)
+ }
+}
+
+// Remove now revokes at once and quarantines what may still run: the
+// step stops (machine_removed, no termination proof) and Retry is
+// refused until the task's creator recovers it (audited); then Retry.
+func TestContractRemoveNowQuarantines(t *testing.T) {
+ r := newRunnersRig(t)
+ w, _ := r.newWorker("Mac A")
+ task, _ := r.candidate("iOS lost machine", true)
+ _, body := w.expect(wire.FrameDispatch)
+ d := body.(*wire.DispatchCommand)
+ if !w.lease(d.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ r.remove(w.fr.Welcome.RunnerID, true)
+ if !r.revokedAt(w.fr.Welcome.RunnerID) {
+ t.Fatal("remove now did not revoke at once")
+ }
+ k, _ := r.client.Task(r.ctx, task)
+ s := r.checksStep(task)
+ if s.State != wire.StepFailed || s.Reason != "machine_removed" || s.Terminated || k.NeedsYou != wire.NeedsMachineRemoved {
+ t.Fatalf("not quarantined: %+v needs %q", s, k.NeedsYou)
+ }
+ if _, err := r.client.RetryTask(r.ctx, task); Status(err) != 409 {
+ t.Fatalf("retry before recovery: %v", err)
+ }
+ mate := personToolRig(t, r.toolRig, "mate@example.com", equipo.RoleOwner)
+ if _, err := mate.client.RecoverTask(r.ctx, task); Status(err) != 403 {
+ t.Fatalf("a teammate recovered: %v", err)
+ }
+ if _, err := r.client.RecoverTask(r.ctx, task); err != nil {
+ t.Fatal(err)
+ }
+ s = r.checksStep(task)
+ if !s.Terminated || s.TerminationKind != wire.TerminationUnverified {
+ t.Fatalf("recovered %+v", s)
+ }
+ var audits int
+ if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM audit_events WHERE kind = 'task.recover'").Scan(&audits); err != nil || audits != 1 {
+ t.Fatalf("recovery not audited: %d %v", audits, err)
+ }
+ if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
+ t.Fatalf("retry after recovery %+v %v", acc, err)
+ }
+}
+
+// The instance tells a worker its role with its credential at enrolment
+// (a primary's credential says nothing, as an older instance's does).
+func TestContractEnrolmentNamesAWorker(t *testing.T) {
+ r := newRunnersRig(t)
+ if cred := r.inst.EnrolRunner(t); cred.Role != wire.RoleWorker {
+ t.Fatalf("second runner's credential role %q", cred.Role)
+ }
+}
+
+// The pages say what happened and offer the way out: a runner removing
+// shows so, with Remove now; a quarantined step's card says to make sure
+// the machine is off, then Recover, and Recover there settles it.
+func TestPagesRemovalAndRecover(t *testing.T) {
+ r := newRunnersRig(t)
+ owner := r.inst.Cookie()
+ w, _ := r.newWorker("Mac A")
+ task, _ := r.candidate("iOS removed", true)
+ _, body := w.expect(wire.FrameDispatch)
+ d := body.(*wire.DispatchCommand)
+ if !w.lease(d.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ r.remove(w.fr.Welcome.RunnerID, false)
+ page := r.get(owner, "/runners/enrol", 200)
+ if !strings.Contains(page, "Removing: waiting for it to stop its work") || !strings.Contains(page, `action="/runners/`+w.fr.Welcome.RunnerID+`/remove-now"`) {
+ t.Fatalf("runners page while removing: %s", page)
+ }
+ var revision string
+ if err := r.inst.DB.Writer().QueryRow("SELECT revision FROM runners WHERE id = ?", w.fr.Welcome.RunnerID).Scan(&revision); err != nil {
+ t.Fatal(err)
+ }
+ if status, _ := r.post(owner, "/runners/"+w.fr.Welcome.RunnerID+"/remove-now", url.Values{"revision": {revision}}); status != 303 || !r.revokedAt(w.fr.Welcome.RunnerID) {
+ t.Fatalf("remove now from the page: %d", status)
+ }
+ page = r.get(owner, "/tasks/"+task, 200)
+ if !strings.Contains(page, "Stopped: the machine was removed mid-step. Make sure it") || !strings.Contains(page, "s switched off, then Recover") || !strings.Contains(page, "data-task-recover") || strings.Contains(page, "data-task-retry") {
+ t.Fatalf("quarantined task page: %s", page)
+ }
+ if status, _ := r.post(owner, "/conversation/tasks/"+task+"/recover", url.Values{"from": {"task"}}); status != 303 {
+ t.Fatalf("recover from the page: %d", status)
+ }
+ if s := r.checksStep(task); !s.Terminated || s.TerminationKind != wire.TerminationUnverified {
+ t.Fatalf("not recovered: %+v", s)
+ }
+}
diff --git a/internal/wire/api.go b/internal/wire/api.go
index f59a5519..3f178a75 100644
--- a/internal/wire/api.go
+++ b/internal/wire/api.go
@@ -251,6 +251,9 @@ type Runner struct {
Since *time.Time `json:"since"`
Platform *Platform `json:"platform"`
Capabilities *Capabilities `json:"capabilities"`
+ // Removing: the person removed it and it is stopping the work it may
+ // have started; it is revoked once that work's end is proven.
+ Removing bool `json:"removing"`
}
// RunnerList is GET /api/v1/runners: the person's runners, primary first.
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index f517901e..b297079c 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -216,6 +216,9 @@ const (
const (
TerminationNamespace = "namespace"
TerminationProcessGroup = "process_group"
+ // TerminationUnverified: settled by the creator's Recover after the
+ // machine was removed; nothing proved the end.
+ TerminationUnverified = "unverified"
)
// Transfer directions: inbound (primary to worker) carries the candidate
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go
index 3c0f0b39..15a5bdd5 100644
--- a/internal/wire/tasks.go
+++ b/internal/wire/tasks.go
@@ -107,6 +107,9 @@ const (
// NeedsMergeConflict: the branch still conflicts with the default
// branch after Engineering's one rebase round.
NeedsMergeConflict = "merge_conflict"
+ // NeedsMachineRemoved: a step was running on a machine removed at
+ // once; the task's creator makes sure it is off, then recovers it.
+ NeedsMachineRemoved = "machine_removed"
// NeedsRunnerOffline: the only runner that can do the next step has
// been offline for 30 minutes.
NeedsRunnerOffline = "runner_offline"
@@ -762,6 +765,9 @@ var StepReasons = map[string]bool{
"withdrawn": true,
"transfer_refused": true,
"runner_offline": true,
+ // machine_removed: the runner was removed while the step may have been
+ // running; nothing proves its end (only Recover settles it).
+ "machine_removed": true,
// ReasonUnknown is what the instance records for a reason it does not
// know (a newer runner), rather than refusing the report.
ReasonUnknown: true,
diff --git a/internal/wire/wiretest/testdata/api/event-runner.json b/internal/wire/wiretest/testdata/api/event-runner.json
index c11a309e..052d33de 100644
--- a/internal/wire/wiretest/testdata/api/event-runner.json
+++ b/internal/wire/wiretest/testdata/api/event-runner.json
@@ -1 +1 @@
-{"cursor":43,"type":"runner","resource":"runner","id":"RUNNER1","revision":4,"data":{"id":"RUNNER1","revision":4,"online":false,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null}}
\ No newline at end of file
+{"cursor":43,"type":"runner","resource":"runner","id":"RUNNER1","revision":4,"data":{"id":"RUNNER1","revision":4,"online":false,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null,"removing":false}}
\ No newline at end of file
diff --git a/internal/wire/wiretest/testdata/api/runners.json b/internal/wire/wiretest/testdata/api/runners.json
index 943e8388..57903a0a 100644
--- a/internal/wire/wiretest/testdata/api/runners.json
+++ b/internal/wire/wiretest/testdata/api/runners.json
@@ -1 +1 @@
-{"items":[{"id":"RUNNER1","revision":4,"online":true,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":{"os":"linux","arch":"amd64"},"capabilities":{"xcode":{"version":"","build":""},"simulators":[],"toolchains":{"go":"go1.26.10","swift":"","node":""},"harness":{"claude":"2.1.312","codex":"","srt":""},"tags":["linux","claude","go"]}},{"id":"RUNNER2","revision":2,"online":false,"label":"Tito Studio","role":"worker","since":"2026-11-07T10:12:00Z","platform":{"os":"darwin","arch":"arm64"},"capabilities":{"xcode":{"version":"16.2","build":"16C5032a"},"simulators":[{"name":"iPhone 16 Pro","runtime":"iOS 18.2","udid":"5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3","state":"Shutdown"}],"toolchains":{"go":"","swift":"6.0.3","node":"v22.12.0"},"harness":{"claude":"2.1.312","codex":"","srt":"0.0.81"},"tags":["macos","xcode","ios_simulator","claude"]}}]}
\ No newline at end of file
+{"items":[{"id":"RUNNER1","revision":4,"online":true,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":{"os":"linux","arch":"amd64"},"capabilities":{"xcode":{"version":"","build":""},"simulators":[],"toolchains":{"go":"go1.26.10","swift":"","node":""},"harness":{"claude":"2.1.312","codex":"","srt":""},"tags":["linux","claude","go"]},"removing":false},{"id":"RUNNER2","revision":2,"online":false,"label":"Tito Studio","role":"worker","since":"2026-11-07T10:12:00Z","platform":{"os":"darwin","arch":"arm64"},"capabilities":{"xcode":{"version":"16.2","build":"16C5032a"},"simulators":[{"name":"iPhone 16 Pro","runtime":"iOS 18.2","udid":"5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3","state":"Shutdown"}],"toolchains":{"go":"","swift":"6.0.3","node":"v22.12.0"},"harness":{"claude":"2.1.312","codex":"","srt":"0.0.81"},"tags":["macos","xcode","ios_simulator","claude"]},"removing":false}]}
\ No newline at end of file
diff --git a/internal/wire/wiretest/testdata/api/snapshot.json b/internal/wire/wiretest/testdata/api/snapshot.json
index 4c4a0265..b918c4dd 100644
--- a/internal/wire/wiretest/testdata/api/snapshot.json
+++ b/internal/wire/wiretest/testdata/api/snapshot.json
@@ -1 +1 @@
-{"me":{"id":"owner@example.com","address":"owner@example.com","role":"owner","person":{"address":"owner@example.com","display_identity":"owner@example.com","active":true,"role":"owner"},"team_id":"TEAM1","team_name":"Example","revision":1},"messages":[{"id":"m_0001","revision":1,"role":"person","text":"hello","turn_id":"t_0001","created_at":"2026-11-06T10:00:00Z","switched":null}],"turns":[{"id":"t_0001","revision":2,"kind":"","state":"running","reason":"","attempt":1,"message_ids":["m_0001"],"reply_id":"","connection":"","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:01Z","timing":null}],"runner":{"id":"RUNNER1","revision":3,"online":true,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null},"projects":[{"id":"p_0001","revision":1,"repo":"amadan.net/oficina/sample","name":"oficina/sample","title":"Sample","attachments":[{"kind":"repo","ref":"amadan.net/oficina/sample","name":"oficina/sample","default_branch":"main","head_sha":"3333333333333333333333333333333333333333","head_subject":"Swipe from the edge goes back","head_at":"2026-11-07T09:30:00Z"}],"state":"active","added_by":"owner@example.com","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z","description":"A sample app for Equipo tests.","stack":["Go"],"checks":{"here":true,"gate":"make ci","reason":""},"people":[{"address":"owner@example.com","name":"Owner","initials":"O"}]}],"cards":[{"id":"c_0001","revision":1,"kind":"project","state":"added","turn_id":"t_0001","project_id":"p_0001","name":"oficina/sample","question":"","options":[],"choice":"","task_id":"","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z"}],"tasks":[],"coordinator":{"id":"owner@example.com","revision":2,"state":"ready","turn_id":"","moved_in_at":"2026-11-06T09:59:00Z"},"connections":null,"housekeeping_summary":{"open_suggestions":0,"paused":false,"disabled":[],"revision":0},"cursor":40,"runners":[{"id":"RUNNER1","revision":3,"online":true,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null}]}
\ No newline at end of file
+{"me":{"id":"owner@example.com","address":"owner@example.com","role":"owner","person":{"address":"owner@example.com","display_identity":"owner@example.com","active":true,"role":"owner"},"team_id":"TEAM1","team_name":"Example","revision":1},"messages":[{"id":"m_0001","revision":1,"role":"person","text":"hello","turn_id":"t_0001","created_at":"2026-11-06T10:00:00Z","switched":null}],"turns":[{"id":"t_0001","revision":2,"kind":"","state":"running","reason":"","attempt":1,"message_ids":["m_0001"],"reply_id":"","connection":"","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:01Z","timing":null}],"runner":{"id":"RUNNER1","revision":3,"online":true,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null,"removing":false},"projects":[{"id":"p_0001","revision":1,"repo":"amadan.net/oficina/sample","name":"oficina/sample","title":"Sample","attachments":[{"kind":"repo","ref":"amadan.net/oficina/sample","name":"oficina/sample","default_branch":"main","head_sha":"3333333333333333333333333333333333333333","head_subject":"Swipe from the edge goes back","head_at":"2026-11-07T09:30:00Z"}],"state":"active","added_by":"owner@example.com","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z","description":"A sample app for Equipo tests.","stack":["Go"],"checks":{"here":true,"gate":"make ci","reason":""},"people":[{"address":"owner@example.com","name":"Owner","initials":"O"}]}],"cards":[{"id":"c_0001","revision":1,"kind":"project","state":"added","turn_id":"t_0001","project_id":"p_0001","name":"oficina/sample","question":"","options":[],"choice":"","task_id":"","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z"}],"tasks":[],"coordinator":{"id":"owner@example.com","revision":2,"state":"ready","turn_id":"","moved_in_at":"2026-11-06T09:59:00Z"},"connections":null,"housekeeping_summary":{"open_suggestions":0,"paused":false,"disabled":[],"revision":0},"cursor":40,"runners":[{"id":"RUNNER1","revision":3,"online":true,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null,"removing":false}]}
\ No newline at end of file
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index c054d0c8..97cc352c 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -10907,7 +10907,7 @@
},
{
"path": "internal/wire/wiretest/testdata/api/runners.json",
- "line_sha256": "9464043f0114a6796fcfce08e97b15c7eb500e073a441252d8346e441135c503",
+ "line_sha256": "76ac979bf9acee38cd7c1d37e5fcd09c675a916d6ed6ac348bab6c4a6685d69d",
"match": "node",
"count": 2,
"reason": "Recorded runners fixture: the node toolchain version in a capability report."
@@ -12318,5 +12318,12 @@
"match": "NODE",
"count": 1,
"reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs."
+ },
+ {
+ "path": "cmd/equipo-runner/install_mac_test.go",
+ "line_sha256": "95d52f9f469ec8b20008417845b58eb0d08c992c0692843cf6523c2b0c622d2a",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs."
}
]