oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1# Equipo thin v1: magic by subtraction
2
3Status: approved by Paul 2026-11-06 (decisions in §9), revised after Astra's
4review. Drafted by Claude (Fable 5.1) from the rev 3 design, the controller
5reports of 2026-11-03 to 11-06 and `main` (26ac471). Not implemented.
6
7## 0. Verdict and two principles
8
9The product idea is right: one coordinator per person, specialists running
10the official CLIs on his own machine in bubblewrap, branches on Amadan, a
11human merges. What is wrong is the trust model the code was built for. In six
12days we built a hosted multi-tenant control plane: fenced claims, admission
13tickets, period budgets with reservations, policy certificates with evidence
14bundles, two journals, 86 tables, 141,000 lines of Go. Every layer Paul hit
15today (unbound coordinator, unset budgets, `capability_unverified` from a
16certificate that hashed a binary path, expired logins, `EQUIPO_ALWAYS_ON`,
17`--swap hold`, fenced and "uncertain" turns, a repo the runner "doesn't
18report", a fresh CLI launch per turn) guards against a threat the only user
19does not have. The real threat is the model inside the sandbox.
20
211. **The runner is the brain; the instance is a thin API and ledger.** Keep
22 containment (§5) and the owner/teammate split; delete the control plane.
232. **Headless first.** The core is fully drivable through one public person
24 API; a headless conversation suite is green on staging before any UI test
25 runs. The web UI and the native apps are clients of the same API and
26 stream. If it needs the browser to work, it does not work yet.
27
28## 1. One API, one stream
29
30`internal/equipo/personapi` (bearer tokens from device sign-in, `/me`,
31`/conversation`, `/projects`, `/needs-you`) becomes **person API v1**, the only
32way anything talks to Equipo. Web pages call it server side with the session
33principal; native apps and the headless suite use a device bearer.
34
35**Resources** (`/api/v1/`, JSON, every resource carries `id` and `revision`):
36`me`; `projects` (GET, POST `{repo}` restricted to the person's
37runner-advertised allowlist, DELETE = Remove); `messages` (GET
38`?before=&limit=` for history, POST `{text, idempotency_key}`; same key with a
39different body → 409); `turns/{id}` (`queued | running | replied | failed |
40cancelled`, with `reason`); `tasks` and `tasks/{id}` (steps with `candidate_sha`,
41log tails, branch), `PUT tasks/{id}/plan` (edits unstarted steps, guarded by
42`revision`), `tasks/{id}/cancel` and `POST turns/{id}/cancel` (both return `202 {attempt}`
43and end in a `turn{state: cancelled}` or `step{state: cancelled, attempt}`
44event once the runner reports termination for that attempt, or `409` if the
45turn or step is already terminal), `tasks/{id}/retry` (refused until the
46runner has confirmed termination of the current attempt; returns the new
47attempt id), `steps/{id}/log`; `cards/{id}/answer`
48(`{choice, revision}`; stale revision or already answered → 409 with the
49current card); `needs-you`; `runners`; `accounts`; `snapshot` (everything a
50client shows, plus `cursor`, in one transaction).
51
52**Event stream**: `GET /api/v1/events?after=<cursor>`, Server-Sent Events,
53one person-scoped monotonic sequence; the event id is the cursor. Explicit
54`?after=` wins over `Last-Event-ID`. Event types: `message`, `turn`, `delta`,
55`card`, `task`, `step`, `project`, `needs_you`, `runner`, `ping` (20 s). Each
56event carries `{resource, id, revision}` and its correlation ids (`turn_id`,
57`task_id`, `message_id`, `attempt`); clients apply an event only if its
58revision is newer, which is the dedup rule. `delta{turn_id, offset, text}`
59appends streamed text; the committed `message` for that `turn_id` replaces
60the draft. A terminal failure is `turn{state: failed, reason}` or `step{state:
61failed}`, never silence. State row and event are written in one SQLite
62transaction, so a client can never see one without the other. The instance
63keeps 24 hours of events; an older cursor gets `410 Gone`, and the client
64recovers with `snapshot` then reopens at the returned cursor. Roster removal
65or device revocation closes open streams at the next flush (the handler
66re-checks the principal each time it writes). Browser `EventSource` cannot
67send a bearer, so this one GET also accepts the same-origin session cookie
68with a `Sec-Fetch-Site: same-origin` check; everything else is bearer only.
69SSE because every platform has it in one file, it survives the CARLOS edge
70and tunnel (#432), and it needs no upgrade handshake.
71
72Contract tests record every request, response and event as fixtures and
73replay them against the handler; the native apps build against the same
74fixtures before they touch a server.
75
76## 2. Coordinator: one long-lived session per person
77
78One `claude` process per person, started on the first message and kept alive:
79`claude -p --verbose --input-format stream-json --output-format stream-json
80--include-partial-messages --strict-mcp-config --mcp-config … --setting-sources
81'' --tools …`, stdin held open; each message is one user frame. It runs in the
82same bubblewrap namespace as the specialists, with an empty workspace.
83
84**Sessions outlive processes.** The runner keeps a persistent *session home*
85per person and provider (`~/.local/share/equipo-runner/sessions/<person>/
86<provider>`), holding only transcripts (Claude `projects/`, Codex rollouts),
87never credentials, mounted read-write in the namespace. A durable `sessions`
88row (person, provider, account, session id, last turn) replaces the
89launcher's in-memory eligibility check, so a new process after an idle exit
90or a runner restart does `--resume <id>` (Codex `thread/resume`) from disk.
91Scenario 1 measures **cold** (resume) and **warm** (process already up) first
92token separately.
93
94**Credentials.** Self-heal's rules stand: a runtime credential copy lives 25
95minutes (`accounts.go:192`), never writes back, and cannot reach refresh
96hosts. So a process lives at most one copy, and **a turn starts only if the
97copy's remaining validity covers the maximum turn duration plus a margin**:
98with a 20 minute turn cap and a 2 minute margin, only in the copy's first 3
99minutes; otherwise the runner ends the process cleanly between turns,
100refreshes in the source home under the lock, stages a new copy and resumes
101before sending the frame. Practically that means a rotation before most
102turns, which the session home makes cheap (the cold path in scenario 1). If
103the provider's copy lifetime turns out shorter than the cap plus margin, the
104cap drops to fit; a turn never runs on a copy that can expire under it. The
105source lock is held only for refresh and staging, not for the attempt:
106copies cannot refresh, so maintenance cannot race them. Specialists on the same account each get their own copy from the
107same source under the same short lock. If refresh reports a different
108identity, the account is marked `sign_in_again`, its sessions are not
109resumed on it, and the coordinator continues on another healthy account in
110a fresh session with one line saying so. Runtime homes are still deleted on
111process exit; the session home is what persists.
112
113**Tools** go through the existing `equipo-tool-proxy` socket and the runner
114stream: `status()`, `add_project(repo)`, `start_task(project, kind, brief,
115steps[])`, `read_task`, `cancel_task`, `ask_person(question, options[])`. The
116proxy mounts only the tool set for the running action, each call carries the
117authenticated runner and the session's person, and the instance authorises
118every call against the current roster inside the write transaction (as
119`AGENTS.md` already requires). Gone: `post_message` (the assistant text *is*
120the reply, which ends the duplicated question card), `propose_project` and
121its Set up tap (the coordinator adds the project; the card says "Added
122oficina/equipo · Remove"; adding never widens publishing authority, which
123stays with the forge checks in §5), `propose_plan` as a consent step.
124
125**Second message rule.** If the person's turn is `running`, the new message is
126`queued`; when the turn ends, all queued messages go to the coordinator as
127one frame and produce one reply. A running turn is never interrupted by a
128new message; cancel is explicit (`POST turns/{id}/cancel`, §1): the runner
129interrupts the coordinator process for that attempt, the draft is discarded,
130and the turn ends `cancelled`; queued messages then start a fresh turn.
131
132Setup by the agent: the heartbeat already carries every repository key in
133the runner's forge credential file; any of them is a valid `add_project`, and
134the runner clones on first use. The prompt is a five-line house rule plus a
13550 message tail.
136
137## 3. Specialists and tasks
138
139A **task** is a row: id, project, kind, brief, branch
140(`equipo/<task-id>-<slug>`, so two tasks never share one), base SHA, state,
141creator, runner. A **step** is a row: task, index, specialist, state, account,
142session id, **candidate SHA**, started, finished, summary, attempt.
143
144A step is one `claude -p` or Codex app-server thread in bubblewrap, in a git
145worktree of the project clone on the task branch, with the specialist's
146standing instructions and pinned tools. The runner captures stream-json to a
147per-step log and forwards a bounded tail. On exit it commits what changed,
148records the candidate SHA, pushes through `internal/runner/forge` (the only
149holder of the Amadan credential, with its record-then-reconcile publication
150kept), and starts the next step. **Review** runs in a fresh worktree of the
151exact candidate SHA with no write tools, on another family if one is
152healthy, else another Claude account with fresh context, labelled "same
153family" (Paul, §9). **Checks** are the repository's own gate (`.amadan/ci` or
154`make ci`) run in the sandbox on the candidate SHA, exit and 200 lines of
155tail recorded. CI result and review verdict are stored beside the SHA they
156judged; a new candidate invalidates both. The last step is the person: the
157card becomes "Ready to merge: branch, SHA, CI, verdict, open on Amadan".
158
159**Codex path, separately.** Codex is JSON-RPC over the app-server's stdio:
160`initialize` then the `initialized` notification, `account/read` (refresh in
161the source home only), `config/read`, `thread/start` or `thread/resume`,
162`turn/start`. Streamed text is `item/agentMessage/delta`, command output is
163`item/commandExecution/outputDelta`, items are bracketed by `item/started`
164and `item/completed` (all names as in `internal/runner/provider/codex`).
165Server requests that need a response (`item/commandExecution/requestApproval`,
166`item/fileChange/requestApproval`, `item/permissions/requestApproval`,
167`item/tool/requestUserInput`) are answered deny by policy or relayed as
168`ask_person`; the turn ends on `turn/completed`; cancel is `turn/interrupt`
169and any item in flight is recorded `interrupted`, never completed. A thread stays
170with the account that started it; an account change starts a new thread with
171a summary. Codex native refresh is fake-tested only so far: staging must
172show one real refresh before slice 5 marks a Codex account healthy.
173
174Dropped for owner mode: fences, leases, claims and admission tickets
175(`team/scheduler.go`, `team/admission.go`, `runnerproto` poll and claim);
176both journals; per-turn certification (`runner/certified`,
177`release/manifest.json`, `release/evidence`, policy inventories: CLI digests
178pinned at install, refuse to start on mismatch); budgets as gates
179(`team/budget.go`, `periodbudget.go`, reservations, `coordinator_limits`:
180one soft monthly ceiling per person on runs and wall minutes, a warning at
18180%, a Pause toggle at 100%, never a precondition for a reply); evidence
182predicates (`team/evidence.go`, `checks/executor.go` definition pinning: v1
183"done" is branch + CI exit + verdict on one SHA, labelled); the uncertain and
184quarantine states (a crash is a failed step with Retry, once termination is
185confirmed).
186
187## 4. Runner protocol: one outbound stream with a durable mailbox
188
189One outbound WebSocket per runner, `wss://…/api/runner/stream`, bearer runner
190credential, enrolment unchanged. JSON lines, every frame with an `id`:
191
192- instance → runner: `message{person, session, turn_id, text}`,
193 `answer{person, turn_id, card_id, choice}`, `dispatch{task, project, repo,
194 branch, base_sha, steps, attempt}`, `cancel{turn_id | task, step,
195 attempt}`, `tool_result{call_id, body}`, `drain{retry_after}`.
196- runner → instance: `hello{generation, repos, accounts[{id, provider,
197 email, healthy, headroom}], versions}` then every 30 s; `sync{sessions,
198 runs[{task, step, state, candidate_sha, attempt}]}` on every connect;
199 `delta{turn_id, offset, text}`; `reply{turn_id, text, usage}`;
200 `tool_call{call_id, turn_id, name, args}`; `step{task, step, state,
201 candidate_sha, attempt, termination}`; `needs_you{kind, action}`; `ack{id}`.
202
203**Delivery.** Both ends keep a small table: the instance's `commands` and the
204runner's `outbox` (id, kind, payload, sent, acked). Producing is atomic with
205the state it describes: `start_task` writes the task, its steps, the
206`dispatch` command and the `task` event in one transaction, and a message
207POST writes the row, the `message` command and the event together. Consuming
208is atomic too: the receiver records the frame id and applies its effect (the
209runner inserts the `runs` row, the instance updates the step) in one
210transaction, and acks only after that commit; unacked frames are resent on
211reconnect and a seen id is a no-op. Tool call ids are the provider's
212tool-use id plus turn, so a repeated `tool_call` returns the stored result.
213A push cut off mid-way is settled by forge's reconcile on the next `sync`,
214and the instance accepts only forward step transitions.
215
216**One owner.** The instance keeps `runner_sessions` (runner, generation,
217connected). A new connection from the same credential bumps the generation,
218closes the old socket and rejects stale frames, but that alone does not stop
219an older runner process that is still executing. So the generation is an
220**execution lease**: the runner writes the generation it was granted in
221`hello` to its state file, checks it against the instance at every step
222start and immediately before every publish (a `sync` round trip; forge
223refuses without a fresh confirmation), and on seeing a newer generation
224kills its namespaces, marks its runs `superseded` and exits for systemd to
225restart it clean. A person's coordinator session and tasks live on one
226runner (the owner's `primary`), so two runners cannot touch one branch; the
227runner's `runs` table has a unique index on `(task, state='running')`. Every
228run has an `attempt` id; `cancel` frames and `step` reports carry it, so a
229delayed cancel for attempt 1 is ignored once attempt 2 exists. Retry is
230refused until the step's `termination` proof (namespace exit observed by
231pidfd, as `containment` does today) has arrived for the current attempt.
232
233**Instance restarts.** Each instance process has a generation. On SIGTERM it
234sends `drain` to connected runners, finishes in-flight writes and exits;
235runners reconnect with backoff to whichever process now holds the socket.
236Messages POSTed during the overlap are rows and get forwarded by that
237process. **`--swap hold` stays** until staging proves overlap safety through
238the real edge: deploy during a running turn, cold wake of a sleeping
239instance, and a socket idle for an hour must all pass scenario 8 before the
240flag is dropped. `EQUIPO_ALWAYS_ON` goes in slice 1; an open socket keeps
241the instance awake, which for one team is the point.
242
243First token path: POST → row and event → frame → one user frame on the
244coordinator's stdin → first delta in 1 to 3 s → `delta` → SSE. Under 5 s
245warm is the natural case; cold adds the resume.
246
247## 5. What "keep containment" means
248
249Kept verbatim and still tested, moved into the surviving packages before any
250old suite is deleted:
251
252- `runner/containment`: owned bubblewrap namespaces, `--die-with-parent`,
253 pidfd exit proofs, protected-path and symlink-alias checks, no host
254 `/run`, `/sys`, `/tmp`, bus or control sockets; credential homes mounted
255 only to the harness, denied to model tools.
256- `provider/policy.go` effective-policy validation: exact argv, settings,
257 MCP config, tool list and mounts constructed per launch and checked
258 against the init frame; no inherited environment; managed config masked.
259- `runner/egress`: the CONNECT relay with the provider hosts only, no
260 loopback or LAN, refresh hosts excluded from runtime copies.
261- `workspace`: git hooks and credential helpers disabled in every worktree;
262 no push credential inside the namespace.
263- `forge`: repository, ref (the task's own branch only), candidate SHA and
264 person ownership validated before every push; never the default branch.
265- No credential, home path or raw stderr in any frame, event, log or
266 report (today's sanitised failure payloads stay).
267
268Authority that lived in claims and journals moves to: authenticated runner
269and person on every frame and API call; current-roster checks inside each
270write transaction; scoped tool permissions in the proxy per action;
271forge validation before publication. Teammate execution stays **denied** (a
272`trusted` flag on the runner row, set only by the owner's enrolment
273approval) until its own authority boundary is designed.
274
275## 6. Setup and identity
276
2771. `equipo-runner enrol <origin>` prints a URL; approve in the browser. The
278 runner installs its own user unit.
2792. `equipo-runner login claude|codex` runs the official login into a
280 dedicated home `~/.local/share/equipo/accounts/<provider>-<n>` and records
281 the observed email. The try-equipo wizard and its certification run go.
2823. On start and hourly the runner refreshes each home under its lock (the
283 self-heal code) and reports `healthy` and `headroom`.
284
285Selection is a 30-line function: healthiest Claude account with the most
286headroom for the coordinator and Engineering, else Codex; Review per §3.
287Every step records what ran. One card type, **Needs you**, with one action:
288sign in again, merge, or answer a question. It never blocks chat.
289
290## 7. Testing as the backbone
291
292In the order they must go green:
293
294**Contract tests, every push.** Person API and events (fixtures replayed
295against the handler); runner ↔ instance frames (the `transporttest` pattern);
296runner ↔ CLI, where the fake `claude` and `codex` reproduce each pinned
297protocol from recordings of the real versions (stream-json with
298`--verbose`, app-server JSON-RPC including approval requests and
299`turn/interrupt`); containment and egress suites, unchanged, CI job 36.
300
301**Headless suite, every push, under two minutes.** Fake CLIs, real instance,
302runner, bubblewrap and a local bare Amadan repo, blank database, a Go client
303on person API v1 and SSE only. Scenarios: (1) device sign-in → "hello" →
304first `delta` under 5 s, cold and warm measured separately; (2) "fix the
305README typo in oficina/sample" → `project` → `task` → Engineering `step` with
306a commit → Review verdict on that SHA → Ready to merge; (3) runner offline →
307queued → reconnect → reply, no duplicates; (4) runner killed mid-step →
308failed with termination → retry; (5) expired login → one `needs_you`; (6)
309two quick messages → one reply; (7) dropped stream → resume by cursor, then
310410 → snapshot recovery; (8) instance restart during a turn → turn finishes
311or fails visibly, nothing lost.
312
313**Browser suite, after the headless suite.** chromedp on the same scenarios,
314asserting the rendered page; it never sets up state the client could not.
315
316**Staging, pre-deploy and nightly.** `equipo-staging` under oficina and
317`equipo-runner-staging` on docs-t1 (own state dir and account homes), running
318the headless then browser suites with the real CLIs and a scratch Amadan
319repo, about eight model turns. Staging runs the **exact artifacts** that
320deploy (instance binary, runner tarball, pinned CLI digests); `make stage`
321records their hashes and `carlos deploy` is refused unless the last green
322staging run matches them. The suite authenticates with a device bearer Paul
323approves once and stores as a staging secret; its revocation is scenario 1b.
324A verified export of the current production database is taken before the
325cutover (Paul, §9).
326
327## 8. Migration and slices
328
329Fresh database; owners from `EQUIPO_OWNERS`, re-enrol once, projects return
330by chatting. Delete (approximate lines): `equipo/team` and `teamcontract`
331(16,300), `plan3test` (13,000), `equipotest` (13,300), `directlive` (6,200),
332`tryequipo` and `cmd/equipo-try` (2,500), `runner/certified`, release
333manifest, evidence and policy inventory, `runnerproto` claims, fences and
334journal, `runner/journal*.go`, `supervisor.go`, `witness.go`, `planflow`,
335`heartbeat`, `checks` (3,400, replaced by about 200), `equipo/planning` and
336`library` UI (seeds kept), `personapi` extras and `notifications` (parked),
337`ownermode`, `supervised_trial.go`, `old_runner.go`, the `runner_*` files in
338`internal/equipo`, `kernel` budgets, the live-gate scripts and doc. Target
339about 35,000 lines. Security regression tests are ported first (§5) and old
340suites deleted last.
341
342Their browser drives went first (ci-browser-lane, 2026-11-11): once CI
343ran them they failed every time against the thin pages, so they were
344deleted, and the pre-thin pages they covered go in this sweep with them:
345
346- `TestFoundationBrowserWalk` (equipotest): the old rail destinations
347 (`railPaths` in equipotest: `/journey`, `/needs-you`, `/specialists/*`,
348 `/playbooks`, `/templates`, `/preferences`, `/settings/coordinator`,
349 `/connections`, `/settings`), `/work`, `/projects/accounts` and its
350 `/accounts` form, the old project form (`/projects/new`,
351 `/projects/{id}/edit`) and the empty pre-thin `/conversation`.
352- `TestChatBrowser` (equipotest): the pre-thin conversation page
353 (coordinator and specialist messages, `#conversation-feed`) and
354 `/tasks/{id}/thread`.
355- `TestOptimisticChat` (equipotest): the pre-thin chat's optimistic send
356 into `#conversation-feed`.
357- `TestRunnerTaskBrowserWalk` (equipotest): the pre-thin task page
358 (`taskDetail`, page key `journey`), `/tasks/new` and its scriptless form,
359 `/settings/recovery` and `/settings/recovery/release`, the specialist
360 instruction pages.
361- `TestConversationLayout` (plan3test, and its `!browser` stub): plan 3's
362 conversation layout, messages through the pre-thin conversation store,
363 and the plan proposal page `/tasks/{id}/plan`.
364
365Each slice lands headless first (contracts, runner, fake scenario green in CI
366and on staging with real CLIs), then UI, then deploy; Paul says hello.
367
368| Slice | Headless half | UI half | Size |
369|---|---|---|---|
370| 1 Real conversation | API v1 `me`, `messages`, `turns`, `events` with cursor, 410 and `snapshot`; WebSocket with mailbox, acks, generations, drain; `login` into dedicated homes, refresh and copy cycling, persistent session home and resume; cancel and crash recovery for the coordinator; staging app, unit and secret; delete poll, claim, journals, `EQUIPO_ALWAYS_ON`; scenarios 1, 3, 6, 7, 8 | chat page on the stream, offline line | 5 days |
371| 2 Tools and projects | proxy with scoped `status`, `add_project` (allowlist), `ask_person`; `projects` and `cards`; clone on demand; scenario 2 to the project | Added · Remove and question cards | 2 days |
372| 3 Engineering | task and step tables, `dispatch`, `sync`, worktree run, SHA record, forge push with reconcile, `runs` index, termination before retry; scenario 2 to the branch, 4 | task card, Retry, Cancel | 3 days |
373| 4 Review and checks | Review per §3, repo CI on the SHA, invalidation, Ready to merge; scenario 2 complete | Ready to merge, Needs you | 2 days |
374| 5 Accounts | headroom selection, Codex app-server path and one real staged refresh, `accounts`, `needs_you`; scenario 5 | accounts list, sign-in card | 2 days |
375| 6 Plans and limits | `PUT plan`, soft ceiling, Pause; `--swap hold` dropped only if scenario 8 passed through the real edge | plan editing, 80% line | 2 days |
376| 7 Sweep | delete the packages above, squash migrations, README deploy, mark rev 3 §§6, 9, 13.1, 13.2 superseded, publish API fixtures for the native apps | none | 2 days |
377
378About four weeks of agent time, one branch per slice, each shippable.
379
380## 9. Decisions and risks
381
382Paul, 2026-11-06: **fresh database**, with a verified export of the current
383one kept; **same-family Review** allowed on a second Claude account, fresh
384context, labelled, checking the exact candidate SHA; **the coordinator adds
385projects itself** with an "Added · Remove" card, limited to the person's
386runner-advertised allowlist, and adding never broadens publishing authority.
387
388Risks: a long-lived session may bloat or wedge (copy rotation restarts it
389often; a new session each day, since Equipo tables hold the state); the edge
390may cut idle connections (pings, cursor resume, scenario 8 before `--swap
391hold` goes); v1 "done" is weaker than frozen evidence (labelled as branch, CI
392and verdict on one SHA; Paul merges); headroom is best effort; Codex refresh
393is unproven live until slice 5; deleted guards stay in history and §5 names
394what is kept.
395