oficina / equipo Public
Equipo thin v1: magic by subtraction
Status: approved by Paul 2026-11-06 (decisions in §9), revised after Astra's review. Drafted by Claude (Fable 5.1) from the rev 3 design, the controller reports of 2026-11-03 to 11-06 and main (26ac471). Not implemented.
0. Verdict and two principles
The product idea is right: one coordinator per person, specialists running the official CLIs on his own machine in bubblewrap, branches on Amadan, a human merges. What is wrong is the trust model the code was built for. In six days we built a hosted multi-tenant control plane: fenced claims, admission tickets, period budgets with reservations, policy certificates with evidence bundles, two journals, 86 tables, 141,000 lines of Go. Every layer Paul hit today (unbound coordinator, unset budgets, capability_unverified from a certificate that hashed a binary path, expired logins, EQUIPO_ALWAYS_ON, --swap hold, fenced and "uncertain" turns, a repo the runner "doesn't report", a fresh CLI launch per turn) guards against a threat the only user does not have. The real threat is the model inside the sandbox.
- The runner is the brain; the instance is a thin API and ledger. Keep containment (§5) and the owner/teammate split; delete the control plane.
- Headless first. The core is fully drivable through one public person API; a headless conversation suite is green on staging before any UI test runs. The web UI and the native apps are clients of the same API and stream. If it needs the browser to work, it does not work yet.
1. One API, one stream
internal/equipo/personapi (bearer tokens from device sign-in, /me, /conversation, /projects, /needs-you) becomes person API v1, the only way anything talks to Equipo. Web pages call it server side with the session principal; native apps and the headless suite use a device bearer.
Resources (/api/v1/, JSON, every resource carries id and revision): me; projects (GET, POST {repo} restricted to the person's runner-advertised allowlist, DELETE = Remove); messages (GET ?before=&limit= for history, POST {text, idempotency_key}; same key with a different body → 409); turns/{id} (queued | running | replied | failed | cancelled, with reason); tasks and tasks/{id} (steps with candidate_sha, log tails, branch), PUT tasks/{id}/plan (edits unstarted steps, guarded by revision), tasks/{id}/cancel and POST turns/{id}/cancel (both return 202 {attempt} and end in a turn{state: cancelled} or step{state: cancelled, attempt} event once the runner reports termination for that attempt, or 409 if the turn or step is already terminal), tasks/{id}/retry (refused until the runner has confirmed termination of the current attempt; returns the new attempt id), steps/{id}/log; cards/{id}/answer ({choice, revision}; stale revision or already answered → 409 with the current card); needs-you; runners; accounts; snapshot (everything a client shows, plus cursor, in one transaction).
Event stream: GET /api/v1/events?after=<cursor>, Server-Sent Events, one person-scoped monotonic sequence; the event id is the cursor. Explicit ?after= wins over Last-Event-ID. Event types: message, turn, delta, card, task, step, project, needs_you, runner, ping (20 s). Each event carries {resource, id, revision} and its correlation ids (turn_id, task_id, message_id, attempt); clients apply an event only if its revision is newer, which is the dedup rule. delta{turn_id, offset, text} appends streamed text; the committed message for that turn_id replaces the draft. A terminal failure is turn{state: failed, reason} or step{state: failed}, never silence. State row and event are written in one SQLite transaction, so a client can never see one without the other. The instance keeps 24 hours of events; an older cursor gets 410 Gone, and the client recovers with snapshot then reopens at the returned cursor. Roster removal or device revocation closes open streams at the next flush (the handler re-checks the principal each time it writes). Browser EventSource cannot send a bearer, so this one GET also accepts the same-origin session cookie with a Sec-Fetch-Site: same-origin check; everything else is bearer only. SSE because every platform has it in one file, it survives the CARLOS edge and tunnel (#432), and it needs no upgrade handshake.
Contract tests record every request, response and event as fixtures and replay them against the handler; the native apps build against the same fixtures before they touch a server.
2. Coordinator: one long-lived session per person
One claude process per person, started on the first message and kept alive: claude -p --verbose --input-format stream-json --output-format stream-json --include-partial-messages --strict-mcp-config --mcp-config … --setting-sources '' --tools …, stdin held open; each message is one user frame. It runs in the same bubblewrap namespace as the specialists, with an empty workspace.
Sessions outlive processes. The runner keeps a persistent session home per person and provider (~/.local/share/equipo-runner/sessions/<person>/ <provider>), holding only transcripts (Claude projects/, Codex rollouts), never credentials, mounted read-write in the namespace. A durable sessions row (person, provider, account, session id, last turn) replaces the launcher's in-memory eligibility check, so a new process after an idle exit or a runner restart does --resume <id> (Codex thread/resume) from disk. Scenario 1 measures cold (resume) and warm (process already up) first token separately.
Credentials. Self-heal's rules stand: a runtime credential copy lives 25 minutes (accounts.go:192), never writes back, and cannot reach refresh hosts. So a process lives at most one copy, and a turn starts only if the copy's remaining validity covers the maximum turn duration plus a margin: with a 20 minute turn cap and a 2 minute margin, only in the copy's first 3 minutes; otherwise the runner ends the process cleanly between turns, refreshes in the source home under the lock, stages a new copy and resumes before sending the frame. Practically that means a rotation before most turns, which the session home makes cheap (the cold path in scenario 1). If the provider's copy lifetime turns out shorter than the cap plus margin, the cap drops to fit; a turn never runs on a copy that can expire under it. The source lock is held only for refresh and staging, not for the attempt: copies cannot refresh, so maintenance cannot race them. Specialists on the same account each get their own copy from the same source under the same short lock. If refresh reports a different identity, the account is marked sign_in_again, its sessions are not resumed on it, and the coordinator continues on another healthy account in a fresh session with one line saying so. Runtime homes are still deleted on process exit; the session home is what persists.
Tools go through the existing equipo-tool-proxy socket and the runner stream: status(), add_project(repo), start_task(project, kind, brief, steps[]), read_task, cancel_task, ask_person(question, options[]). The proxy mounts only the tool set for the running action, each call carries the authenticated runner and the session's person, and the instance authorises every call against the current roster inside the write transaction (as AGENTS.md already requires). Gone: post_message (the assistant text is the reply, which ends the duplicated question card), propose_project and its Set up tap (the coordinator adds the project; the card says "Added oficina/equipo · Remove"; adding never widens publishing authority, which stays with the forge checks in §5), propose_plan as a consent step.
Second message rule. If the person's turn is running, the new message is queued; when the turn ends, all queued messages go to the coordinator as one frame and produce one reply. A running turn is never interrupted by a new message; cancel is explicit (POST turns/{id}/cancel, §1): the runner interrupts the coordinator process for that attempt, the draft is discarded, and the turn ends cancelled; queued messages then start a fresh turn.
Setup by the agent: the heartbeat already carries every repository key in the runner's forge credential file; any of them is a valid add_project, and the runner clones on first use. The prompt is a five-line house rule plus a 50 message tail.
3. Specialists and tasks
A task is a row: id, project, kind, brief, branch (equipo/<task-id>-<slug>, so two tasks never share one), base SHA, state, creator, runner. A step is a row: task, index, specialist, state, account, session id, candidate SHA, started, finished, summary, attempt.
A step is one claude -p or Codex app-server thread in bubblewrap, in a git worktree of the project clone on the task branch, with the specialist's standing instructions and pinned tools. The runner captures stream-json to a per-step log and forwards a bounded tail. On exit it commits what changed, records the candidate SHA, pushes through internal/runner/forge (the only holder of the Amadan credential, with its record-then-reconcile publication kept), and starts the next step. Review runs in a fresh worktree of the exact candidate SHA with no write tools, on another family if one is healthy, else another Claude account with fresh context, labelled "same family" (Paul, §9). Checks are the repository's own gate (.amadan/ci or make ci) run in the sandbox on the candidate SHA, exit and 200 lines of tail recorded. CI result and review verdict are stored beside the SHA they judged; a new candidate invalidates both. The last step is the person: the card becomes "Ready to merge: branch, SHA, CI, verdict, open on Amadan".
Codex path, separately. Codex is JSON-RPC over the app-server's stdio: initialize then the initialized notification, account/read (refresh in the source home only), config/read, thread/start or thread/resume, turn/start. Streamed text is item/agentMessage/delta, command output is item/commandExecution/outputDelta, items are bracketed by item/started and item/completed (all names as in internal/runner/provider/codex). Server requests that need a response (item/commandExecution/requestApproval, item/fileChange/requestApproval, item/permissions/requestApproval, item/tool/requestUserInput) are answered deny by policy or relayed as ask_person; the turn ends on turn/completed; cancel is turn/interrupt and any item in flight is recorded interrupted, never completed. A thread stays with the account that started it; an account change starts a new thread with a summary. Codex native refresh is fake-tested only so far: staging must show one real refresh before slice 5 marks a Codex account healthy.
Dropped for owner mode: fences, leases, claims and admission tickets (team/scheduler.go, team/admission.go, runnerproto poll and claim); both journals; per-turn certification (runner/certified, release/manifest.json, release/evidence, policy inventories: CLI digests pinned at install, refuse to start on mismatch); budgets as gates (team/budget.go, periodbudget.go, reservations, coordinator_limits: one soft monthly ceiling per person on runs and wall minutes, a warning at 80%, a Pause toggle at 100%, never a precondition for a reply); evidence predicates (team/evidence.go, checks/executor.go definition pinning: v1 "done" is branch + CI exit + verdict on one SHA, labelled); the uncertain and quarantine states (a crash is a failed step with Retry, once termination is confirmed).
4. Runner protocol: one outbound stream with a durable mailbox
One outbound WebSocket per runner, wss://…/api/runner/stream, bearer runner credential, enrolment unchanged. JSON lines, every frame with an id:
- instance → runner:
message{person, session, turn_id, text},answer{person, turn_id, card_id, choice},dispatch{task, project, repo, branch, base_sha, steps, attempt},cancel{turn_id | task, step, attempt},tool_result{call_id, body},drain{retry_after}. - runner → instance:
hello{generation, repos, accounts[{id, provider, email, healthy, headroom}], versions}then every 30 s;sync{sessions, runs[{task, step, state, candidate_sha, attempt}]}on every connect;delta{turn_id, offset, text};reply{turn_id, text, usage};tool_call{call_id, turn_id, name, args};step{task, step, state, candidate_sha, attempt, termination};needs_you{kind, action};ack{id}.
Delivery. Both ends keep a small table: the instance's commands and the runner's outbox (id, kind, payload, sent, acked). Producing is atomic with the state it describes: start_task writes the task, its steps, the dispatch command and the task event in one transaction, and a message POST writes the row, the message command and the event together. Consuming is atomic too: the receiver records the frame id and applies its effect (the runner inserts the runs row, the instance updates the step) in one transaction, and acks only after that commit; unacked frames are resent on reconnect and a seen id is a no-op. Tool call ids are the provider's tool-use id plus turn, so a repeated tool_call returns the stored result. A push cut off mid-way is settled by forge's reconcile on the next sync, and the instance accepts only forward step transitions.
One owner. The instance keeps runner_sessions (runner, generation, connected). A new connection from the same credential bumps the generation, closes the old socket and rejects stale frames, but that alone does not stop an older runner process that is still executing. So the generation is an execution lease: the runner writes the generation it was granted in hello to its state file, checks it against the instance at every step start and immediately before every publish (a sync round trip; forge refuses without a fresh confirmation), and on seeing a newer generation kills its namespaces, marks its runs superseded and exits for systemd to restart it clean. A person's coordinator session and tasks live on one runner (the owner's primary), so two runners cannot touch one branch; the runner's runs table has a unique index on (task, state='running'). Every run has an attempt id; cancel frames and step reports carry it, so a delayed cancel for attempt 1 is ignored once attempt 2 exists. Retry is refused until the step's termination proof (namespace exit observed by pidfd, as containment does today) has arrived for the current attempt.
Instance restarts. Each instance process has a generation. On SIGTERM it sends drain to connected runners, finishes in-flight writes and exits; runners reconnect with backoff to whichever process now holds the socket. Messages POSTed during the overlap are rows and get forwarded by that process. --swap hold stays until staging proves overlap safety through the real edge: deploy during a running turn, cold wake of a sleeping instance, and a socket idle for an hour must all pass scenario 8 before the flag is dropped. EQUIPO_ALWAYS_ON goes in slice 1; an open socket keeps the instance awake, which for one team is the point.
First token path: POST → row and event → frame → one user frame on the coordinator's stdin → first delta in 1 to 3 s → delta → SSE. Under 5 s warm is the natural case; cold adds the resume.
5. What "keep containment" means
Kept verbatim and still tested, moved into the surviving packages before any old suite is deleted:
runner/containment: owned bubblewrap namespaces,--die-with-parent, pidfd exit proofs, protected-path and symlink-alias checks, no host/run,/sys,/tmp, bus or control sockets; credential homes mounted only to the harness, denied to model tools.provider/policy.goeffective-policy validation: exact argv, settings, MCP config, tool list and mounts constructed per launch and checked against the init frame; no inherited environment; managed config masked.runner/egress: the CONNECT relay with the provider hosts only, no loopback or LAN, refresh hosts excluded from runtime copies.workspace: git hooks and credential helpers disabled in every worktree; no push credential inside the namespace.forge: repository, ref (the task's own branch only), candidate SHA and person ownership validated before every push; never the default branch.- No credential, home path or raw stderr in any frame, event, log or report (today's sanitised failure payloads stay).
Authority that lived in claims and journals moves to: authenticated runner and person on every frame and API call; current-roster checks inside each write transaction; scoped tool permissions in the proxy per action; forge validation before publication. Teammate execution stays denied (a trusted flag on the runner row, set only by the owner's enrolment approval) until its own authority boundary is designed.
6. Setup and identity
equipo-runner enrol <origin>prints a URL; approve in the browser. The runner installs its own user unit.equipo-runner login claude|codexruns the official login into a dedicated home~/.local/share/equipo/accounts/<provider>-<n>and records the observed email. The try-equipo wizard and its certification run go.- On start and hourly the runner refreshes each home under its lock (the self-heal code) and reports
healthyandheadroom.
Selection is a 30-line function: healthiest Claude account with the most headroom for the coordinator and Engineering, else Codex; Review per §3. Every step records what ran. One card type, Needs you, with one action: sign in again, merge, or answer a question. It never blocks chat.
7. Testing as the backbone
In the order they must go green:
Contract tests, every push. Person API and events (fixtures replayed against the handler); runner ↔ instance frames (the transporttest pattern); runner ↔ CLI, where the fake claude and codex reproduce each pinned protocol from recordings of the real versions (stream-json with --verbose, app-server JSON-RPC including approval requests and turn/interrupt); containment and egress suites, unchanged, CI job 36.
Headless suite, every push, under two minutes. Fake CLIs, real instance, runner, bubblewrap and a local bare Amadan repo, blank database, a Go client on person API v1 and SSE only. Scenarios: (1) device sign-in → "hello" → first delta under 5 s, cold and warm measured separately; (2) "fix the README typo in oficina/sample" → project → task → Engineering step with a commit → Review verdict on that SHA → Ready to merge; (3) runner offline → queued → reconnect → reply, no duplicates; (4) runner killed mid-step → failed with termination → retry; (5) expired login → one needs_you; (6) two quick messages → one reply; (7) dropped stream → resume by cursor, then 410 → snapshot recovery; (8) instance restart during a turn → turn finishes or fails visibly, nothing lost.
Browser suite, after the headless suite. chromedp on the same scenarios, asserting the rendered page; it never sets up state the client could not.
Staging, pre-deploy and nightly. equipo-staging under oficina and equipo-runner-staging on docs-t1 (own state dir and account homes), running the headless then browser suites with the real CLIs and a scratch Amadan repo, about eight model turns. Staging runs the exact artifacts that deploy (instance binary, runner tarball, pinned CLI digests); make stage records their hashes and carlos deploy is refused unless the last green staging run matches them. The suite authenticates with a device bearer Paul approves once and stores as a staging secret; its revocation is scenario 1b. A verified export of the current production database is taken before the cutover (Paul, §9).
8. Migration and slices
Fresh database; owners from EQUIPO_OWNERS, re-enrol once, projects return by chatting. Delete (approximate lines): equipo/team and teamcontract (16,300), plan3test (13,000), equipotest (13,300), directlive (6,200), tryequipo and cmd/equipo-try (2,500), runner/certified, release manifest, evidence and policy inventory, runnerproto claims, fences and journal, runner/journal*.go, supervisor.go, witness.go, planflow, heartbeat, checks (3,400, replaced by about 200), equipo/planning and library UI (seeds kept), personapi extras and notifications (parked), ownermode, supervised_trial.go, old_runner.go, the runner_* files in internal/equipo, kernel budgets, the live-gate scripts and doc. Target about 35,000 lines. Security regression tests are ported first (§5) and old suites deleted last.
Their browser drives went first (ci-browser-lane, 2026-11-11): once CI ran them they failed every time against the thin pages, so they were deleted, and the pre-thin pages they covered go in this sweep with them:
TestFoundationBrowserWalk(equipotest): the old rail destinations (railPathsin equipotest:/journey,/needs-you,/specialists/*,/playbooks,/templates,/preferences,/settings/coordinator,/connections,/settings),/work,/projects/accountsand its/accountsform, the old project form (/projects/new,/projects/{id}/edit) and the empty pre-thin/conversation.TestChatBrowser(equipotest): the pre-thin conversation page (coordinator and specialist messages,#conversation-feed) and/tasks/{id}/thread.TestOptimisticChat(equipotest): the pre-thin chat's optimistic send into#conversation-feed.TestRunnerTaskBrowserWalk(equipotest): the pre-thin task page (taskDetail, page keyjourney),/tasks/newand its scriptless form,/settings/recoveryand/settings/recovery/release, the specialist instruction pages.TestConversationLayout(plan3test, and its!browserstub): plan 3's conversation layout, messages through the pre-thin conversation store, and the plan proposal page/tasks/{id}/plan.
Each slice lands headless first (contracts, runner, fake scenario green in CI and on staging with real CLIs), then UI, then deploy; Paul says hello.
| Slice | Headless half | UI half | Size | |---|---|---|---| | 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 | | 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 | | 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 | | 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 | | 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 | | 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 | | 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 |
About four weeks of agent time, one branch per slice, each shippable.
9. Decisions and risks
Paul, 2026-11-06: fresh database, with a verified export of the current one kept; same-family Review allowed on a second Claude account, fresh context, labelled, checking the exact candidate SHA; the coordinator adds projects itself with an "Added · Remove" card, limited to the person's runner-advertised allowlist, and adding never broadens publishing authority.
Risks: a long-lived session may bloat or wedge (copy rotation restarts it often; a new session each day, since Equipo tables hold the state); the edge may cut idle connections (pings, cursor resume, scenario 8 before --swap hold goes); v1 "done" is weaker than frozen evidence (labelled as branch, CI and verdict on one SHA; Paul merges); headroom is best effort; Codex refresh is unproven live until slice 5; deleted guards stay in history and §5 names what is kept.