Plan 3 (Astra): 3a conversation, 3b library, setup and API
Two questions ruled overnight by the controller: Linux-first own-machine onboarding; Claude browser sign-in on the enrolled machine as fallback.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+445
−0
docs/superpowers/plans/2026-11-04-equipo-plan-3-coordinator.md+445 −0
CI cancelled — superseded by a newer push — run details
Intent
diff --git a/docs/superpowers/plans/2026-11-04-equipo-plan-3-coordinator.md b/docs/superpowers/plans/2026-11-04-equipo-plan-3-coordinator.md| new file mode 100644 |
| index 00000000..43cbfd13 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-04-equipo-plan-3-coordinator.md |
| @@ -0,0 +1,445 @@ |
| +# Equipo coordinator and conversation Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. The dispatch brief takes precedence over generic execution workflows. This planning session authorizes no implementation, agents, provider runs, commits or pushes. |
| + |
| +**Goal:** Let a person talk to their own coordinator, run a bug fix or feature through an editable plan, receive a sourced recommendation, and set up their own accounts, specialists and playbooks. |
| + |
| +**Architecture:** The instance owns conversations, plans, authority and delivery. A person's enrolled runner resumes that person's direct provider session and exposes only a scoped Equipo tool server to the coordinator. Specialists, checks and publication continue through the fenced execution store, durable runner journal and Amadan publisher; HTML and the versioned person API call the same application operations. |
| + |
| +**Tech Stack:** Go 1.26.0 floor, gate toolchain go1.26.10, Rastrillo v0.30.1 from the pinned module cache, SQLite/GORM/chi, existing direct-launch provider adapters and bubblewrap 0.11.0. The current release targets Linux/amd64 runners and Linux/arm64 instances; provider pins are Claude Code 2.1.312 and Codex 0.165.0, subject to the completed Plan 2b review. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-01-equipo-design.md`, revision 3, especially §§3–7 and 13; `docs/superpowers/plans/CODEX-BRIEF-plan-3.md`; `docs/superpowers/plans/2026-11-01-equipo-roadmap.md`; `docs/mockups/README.md` and the seven mockups named in the brief. |
| + |
| +## Global Constraints |
| + |
| +- The brief and revision 3 supersede the roadmap's Paseo wording and old mockup project pickers. Use direct launch, dedicated Equipo credential homes, Teams above each team, one conversation per person and automatic task threads. |
| +- Execution is off unless `EQUIPO_EXECUTION_ENABLED=1`. `NewStore` grants no authority. Keep `EQUIPO_ORIGIN`, `EQUIPO_INSTANCE_KEY`, SMTP requirements and loopback-only logged mail. Open one activation database; preserve shutdown and failed-construction cleanup. |
| +- Derive `Actor` from the verified session, never a submitted form field. Check the current roster inside each write transaction. Removal and role changes must affect existing sessions immediately. Lookup errors deny access. |
| +- Never use `scope.Owned` or `scope.OwnedBy` for shared team records. Use the transaction handle throughout a transaction. Append the audit event there too, with no credentials in it. Never bind requests onto GORM models; decode explicit input types and use `.Select` for updates. |
| +- Keep migrations additive. App tables belong in `Models` and `Schema`; framework sessions, auth and proof tables belong only in `BootSchema`. Preserve old tasks, evidence, approvals, charges and historical execution records. |
| +- Connections belong to people. A coordinator and its tasks use only its person's connections. A step never changes account mid-step. Review uses a different family from every builder whose contribution remains in the candidate. Checks use no model. |
| +- Inferred preferences never decide anything. Confirmed preferences influence instructions, not authority, budgets, approvals, account consent or project ownership. Team rules take precedence. |
| +- Publication plans always retain independent review, checks and a person at the end. Recommendations publish nothing and have the explicit §6.3 exception. Never merge, push the default branch, or deploy autonomously. |
| +- App-owned runtime strings live only in `internal/equipo/copy.go`. Mark pending entries individually. Use plain words, no em dashes and no exclamation marks. Mockup copy is unapproved. This plan specifies keys and meaning, not approved wording. Leave README prose unchanged. Do not start a copy-review server. |
| +- Use the day theme and sidebar shell. Link tokens.css and theme.css. Keep vendored static files byte-identical and put app styling in equipo.css. Use attribute grammar, token colors, scriptless forms and phone index navigation. No split screen, initials, coloured left-border accents or authentication bypass. Values and badges never wrap; secondary text truncates. |
| +- An unknown count must remain unknown. Never turn a query error into zero. Unknown allowance, usage, delivery and containment remain unknown too. |
| +- Builds use `CGO_ENABLED=0`. Keep host Go caches at their defaults, scratch under on-disk `$TMPDIR`, servers on `127.0.0.1`, and stop processes/remove scratch created by the task. No sudo. Provider calls and external publication are absent from ordinary tests. |
| +- Every implementation task runs its named tests red before implementation, green afterwards, then breaks each new guard separately, observes failure and restores it. Record commands, exit status, failed assertions and restoration in `docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md`. Commit only when the later implementation dispatch authorizes it; use the task's subject, fewer than 80 characters. No such commits occur while writing this plan. |
| + |
| +## Review Focus |
| + |
| +1. Two tabs or a delayed phone answer race a plan edit, project correction or claim: only the current revision may change work, and started work keeps its identity (Tasks 2, 9, 10). |
| +2. A runner dies after a prompt/tool effect but before its acknowledgement: replay delivers recorded results once, never resends an uncertain prompt or grants new authority (Tasks 5–7). |
| +3. A teammate can see shared work but guesses another person's message, preference, login or notification ID: private data and credentials remain private, including live subscriptions (Tasks 1, 8–10, 17, 19). |
| +4. A template or model suggestion smuggles a shell tool, weaker review, new account or inferred preference into a plan: the same server-side constraints apply to all inputs (Tasks 3, 6, 12–14). |
| +5. Setup is interrupted, a provider has no supported device flow, or a remembered team is unreachable: show the actual pending/unavailable state without invented success, credentials on the instance or zero counts (Tasks 16–18). |
| + |
| +--- |
| + |
| +## Order, usable stops and dependencies |
| + |
| +There are **21 tasks**. Build **Plan 3a, Tasks 1–11**, then **Plan 3b, Tasks 12–21**, in this file. Each part has its own acceptance gate. |
| + |
| +- **3a:** Paul, with an already enrolled and certified runner, can use the live conversation for a bug, a feature or a sourced recommendation; edit and approve plans; answer questions; follow task threads; inspect preferences; and use the first person API endpoints. Existing default specialists and manual connection setup suffice. |
| +- **3b:** Paul can accept an invite, pair a supported own-machine runner, connect accounts, choose templates, edit specialists/playbooks, navigate remembered teams and use the complete API and notification feed. The web app remains the usable client; no native app code or delivery through Apple/Google push services is included. |
| + |
| +The roadmap's row 4 remains later: coordinator settlement/deadlock, routing to other people's coordinators, the product-view Now/Next/Later ranking surface and CARLOS signals (platform #514). This brief brings sourced recommendations, model picks with reasons, templates and onboarding into row 3. Recommendations use project material and people's requests, not invented CARLOS telemetry. Hosted runners and provider cloud agents remain unavailable options. |
| + |
| +### Baseline and Plan 2b review dependencies |
| + |
| +Inspected branch `plan-3` at `a446956`, containing direct-launch work through `9cd5910` and design revision 3. These are existing interfaces, not proposed replacements: |
| + |
| +| Existing seam | Reuse and change in Plan 3 | |
| +| --- | --- | |
| +| `provider.Launcher` in `internal/runner/provider/types.go` | Retain `Preflight`, `Open`, `Events`, `StartTurn`, `Respond`, `Interrupt`, `Close`; attach events before prompting. A session ID is distinct from attempt, turn and admission IDs. | |
| +| `Journal.BeginTurn`, `BindSession`, `RecoverDirect`, `ReconcileDirect`; `CaptureFactory` | Retain durable input barriers, captured frames, usage baselines and uncertainty. Extend purpose and conversation correlation without making provider history authoritative. | |
| +| `ToolBinding`, `OpenToolProxy`, `ServeTools`, `ToolSubmission` | Existing relay permits reproduction, candidate, review and question tools. Add separate coordinator tool schemas and capabilities, not a universal socket with every verb. | |
| +| `Execution.atomic`, `team.Store.Atomic`, `AdmitOnce` | Plan, core graph, audit, card and outbox changes share one SQLite commit. Extend graph mutation explicitly; do not update core tables from UI handlers. | |
| +| `CreateBug`, `PrepareBug`, `StartBug`, `BugJobSpec`, `BugPlan` | Current path hard-codes a bug and reproduce/implement/review/verify/publish. Keep compatibility wrappers while replacing scheduling and rendering with persisted plans. | |
| +| `PredicateSoftwareFix`, `FreezeBugEvidence`, trusted executor attestation | Add feature and rendered-change predicates. A recommendation needs delivery with sources, not a software-fix predicate or pretend branch. | |
| +| `forge.DescriptionTransport` and `NewDescriptionTransport` | Preserve production description write/readback and four-channel length-prefixed content hash; publication stays incomplete until exact head and description are confirmed. | |
| +| `live.New`, `live.Hub`, `JobNotifier`, `observeWrite` | Extend post-commit invalidation to private conversation/preferences and recipient notifications. Preserve job topics and current membership checks. | |
| + |
| +Before Task 1 implementation, compare the completed Plan 2b branch with these seams and record changed signatures in the controller report. In particular, its final review may change native permission handling, tool provenance, session resume, account refresh, evidence attestation and release policy identity. Adapt the consumers, never resurrect retired trial or unconfined paths. |
| + |
| +At this baseline `internal/release/manifest.json` has no certified tuples, and Plan 2b Task 11b's report says the live exercise driver is incomplete and describes an embedded-manifest/binary policy-digest cycle. These are **upstream live-use blockers**, not proof that the runner is certified. Offline Plan 3 implementation can proceed with fixtures. Both usable live stops require the completed Plan 2b release gate and certification of Plan 3's new coordinator/tool policies. Do not copy old certificates to changed policies. |
| + |
| +Two further boundaries are explicit. Bubblewrap does not provide a Mac runner; this plan's executable install lane targets the current Linux/amd64 release. A Mac containment implementation needs a separate design and certification, not a shell fallback. Installed `codex login --help` advertises `--device-auth`; installed `claude auth login --help` advertises browser/subscription/console/SSO options, without a device-code switch. That observation is not a supported Claude device protocol. Task 17 fails closed on missing provider capabilities; the two product choices are listed under Questions for Paul. |
| + |
| +## File structure and shared contracts |
| + |
| +Keep features beside existing `internal/equipo` operations. Put pure plan validation in new `internal/taskplan`, with no database or HTTP imports, to respect package size budgets. Put coordinator orchestration in new `internal/coordinator`, depending on neutral provider/runnerproto contracts rather than importing `equipo`. Every new Go package includes the existing budget `TestMain` pattern. Split files by responsibility rather than adding a second store or scheduler. |
| + |
| +| Responsibility | Files introduced or extended | |
| +| --- | --- | |
| +| Conversation, cards, threads | `internal/equipo/conversation_{models,store,views,handlers}.go`, `thread_store.go`, templates `conversation.html`, `thread.html`, `conversation_card.html` | |
| +| Plans and evidence | `internal/taskplan/{types,validate}.go`; `internal/equipo/{plans,plan_dispatch,plan_handlers,approval_settings}.go`; `internal/equipo/team/{plan_edit,feature_evidence,rendered_evidence,read_work}.go` | |
| +| Coordinator and tools | `internal/coordinator/{types,runtime,tools,recovery}.go`; `internal/equipo/{coordinator_store,coordinator_api,coordinator_tools}.go`; `internal/runnerproto/coordinator.go`; existing runner journal, proxy, service and provider policy files | |
| +| Preferences and live UI | `internal/equipo/preferences*.go`, `conversation_live.go`; existing live observer, navigation, task views and `static/equipo.css` | |
| +| Person API | `internal/equipo/person_api*.go`; `internal/personapi/{types,validate}.go`; `docs/api/equipo-v1.openapi.json` and later reviewed `docs/api/equipo-v1.md` | |
| +| Library and setup | `internal/equipo/{specialist_library,playbooks,templates_catalog,invites,onboarding,team_links}*.go`; `internal/runner/{install,account_login}.go`; `cmd/equipo-runner/main.go`; app-owned templates | |
| +| Push preparation | `internal/equipo/{notification_outbox,notification_api}.go`; recipient feed, subscription records and acknowledgements; no external push adapter | |
| + |
| +Migrations are assigned to the task that needs them: 0019 conversation (1), 0020 plans (2), 0021 coordinator (5), 0022 preferences (8), 0023 person API credentials (10), 0024 specialist library (12), 0025 playbooks (13), 0026 connection modes (14), 0027 invitations (15), 0028 onboarding (16), 0029 team links (18), 0030 notifications (19). Each also updates `models.go`, `migrations/schema.sql` and upgrade tests. Re-number only if the final 2b review adds migrations. Core execution schema changes also update `execution_models.go` and the core's ordered schema upgrade path; do not change a core schema version for a JSON-only field. |
| + |
| +The following contracts are shared, and each is implemented by its named task: |
| + |
| +- Task 1: `Mutation{RequestID string; Revision int64}`. Revisions start at 1. IDs are opaque strings; timestamps are UTC. A repeated request ID with identical canonical input returns its saved result; changed input conflicts. Key scope includes authenticated principal, operation and resource. Authorization is rechecked even on replay. |
| +- Task 1: `Message{ID, ConversationID, ThreadID, AuthorKind, AuthorID, Body string; Sequence, Revision int64; CreatedAt time.Time}`, `Card{ID, Kind, ResourceID string; Revision int64}`, and `ConversationPage{Messages []Message; Cards []Card; NextCursor string; Revision int64}`. Cards reference authoritative resources; they never contain permission authority. |
| +- Task 2: `taskplan.Kind` values `bug`, `feature`, `rendered_change`, `recommendation`, `investigation`; `Step{Key, Specialist, Action, Instructions string; ConnectionID, Model, SelectionReason string; Required bool}`; `Plan{TaskID string; Revision int64; Kind Kind; ProjectID int64; Steps []Step; PlaybookID string; PlaybookRevision int64}`. Server-owned state records actual starts, completions, selections and evidence separately. A client cannot submit `Required` to remove an invariant. |
| +- Task 10: `personapi.Page[T]{Items []T; NextCursor string; Revision int64}` and `Error{Code, CopyKey, RequestID string; CurrentRevision *int64}`. Person API types are explicit projections, never GORM rows or runner credentials. Missing/unknown quantities are nullable, not zero. |
| + |
| +## Plan 3a: Conversation that runs work |
| + |
| +### Task 1: Persist the private conversation and shared task threads |
| + |
| +**Files:** Create `internal/equipo/conversation_models.go`, `conversation_store.go`, `thread_store.go`, `internal/equipotest/conversation_test.go`, migration `0019_conversation.sql`; modify models, schema snapshot and migration tests. |
| + |
| +**Interfaces:** `Store.Conversation(ctx context.Context, actor Actor, cursor string, limit int) (ConversationPage,error)`; `Store.SendMessage(ctx context.Context, actor Actor, threadID, body string, m Mutation) (Message,error)`; `Store.TaskThread(ctx context.Context, actor Actor, taskID string, cursor string, limit int) (ConversationPage,error)`. Main conversation is unique by team/person; task thread is unique by task. Messages use monotonic per-conversation/thread sequences and explicit `person`, `coordinator`, `system` attribution. `RouteMessage(ctx context.Context, actor Actor, messageID, taskID string, m Mutation) (Message,error)` atomically places the reply in its task thread and leaves a reference notice in the main conversation. |
| + |
| +- [ ] **Tests first:** `TestConversationPrivateAndThreadShared` denies another member's main conversation, source messages and IDs, while allowing active members to read a team's task thread. `TestConversationMessageReplay` asserts one message/outbox entry for duplicate sends, conflict for changed body and rollback on audit failure. `TestConversationRouteOnce` asserts one automatic thread, one routed reply and one main notice after retry; an unrelated task/team or already-routed different target conflicts. `TestConversationPageBounds` checks 1–100 items, stable cursor order during concurrent inserts, escaped HTML, valid UTF-8 and 16 KiB body limit. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestConversation' -count=1`; expect missing operations or failed assertions. |
| +- [ ] **Implement:** Main conversation and preferences are person-private even from other team owners. Task threads are shared team records; routing deliberately copies only the selected message into shared work, never the person's history. Keep source provenance private. Create the thread with each task, including a lazy idempotent backfill for old tasks. Messages about existing tasks require current task visibility and the sender's own coordinator; another person's active task cannot receive new execution instructions in Plan 3. Distinguish ordinary thread discussion from commands that change a task. |
| +- [ ] **Green and guard mutations:** Repeat the command; require PASS. Bypass person scope, replay hash, audit transaction or route uniqueness independently; observe failures and restore. Run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: persist conversations and automatic task threads`. |
| + |
| +### Task 2: Add revisioned plans, approval settings and atomic graph edits |
| + |
| +**Files:** Create `internal/taskplan/{types,validate,validate_test,budget_test}.go`, `internal/equipo/{plans,plan_dispatch,approval_settings}.go`, `internal/equipo/team/plan_edit.go`, corresponding tests, `0020_plans.sql`; modify `tasks.go`, `task_prepare.go`, `team/{jobs,scheduler,model}.go`, schema/model mirrors. |
| + |
| +**Interfaces:** `taskplan.Validate(p Plan) error` and `taskplan.ValidateEdit(before, after Plan, started map[string]bool) error`; `Store.ProposePlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan,error)` for the verified person path; `Store.EditPlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan,error)`; `Store.ApprovePlan(ctx context.Context, actor Actor, taskID string, m Mutation) (Task,error)`; `Store.CorrectTaskProject(ctx context.Context, actor Actor, taskID string, projectID int64, m Mutation) (Task,error)`. Task 6's coordinator path calls an internal transaction operation with coordinator attribution and delegated authority, never constructs a person `Actor`. |
| + |
| +Core adds `PlanChange{Append, Replace []StepSpec; Cancel []string; Order []string}` and `team.Store.EditUnstarted(ctx context.Context, scope Scope, expectedRevision int64, change PlanChange) (Job,error)`. `ApprovalMode` is `immediate` or `required`; `Store.SetProjectApproval(ctx context.Context, actor Actor, projectID int64, mode ApprovalMode, m Mutation) error` is owner-only, and `Store.SetApprovalOverride(ctx context.Context, actor Actor, projectID int64, mode *ApprovalMode, m Mutation) error` changes only the person's override. Nil inherits. Default is immediate; precedence is person override, project, immediate. |
| + |
| +- [ ] **Tests first:** `TestPlanRequiredSteps` rejects deletion/renaming/substitution of review, checks or final person, duplicate keys, cycles and publication before evidence. `TestPlanEditClaimRace` makes an edit and claim race; exactly one revision wins, with no partial core/card/audit change. `TestPlanStartedImmutable` rejects reorder, instruction/model/account changes to started or finished steps and changes to their dependencies. `TestPlanApprovalPrecedence` covers defaults, inheritance, two tabs and switching to required before dispatch. `TestPlanProjectCorrection` rebinds an unstarted task and clears picks/preparation/approval; after any execution starts, keeps the old target, cancels safely and offers an explicitly linked replacement rather than retargeting a workspace. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/taskplan ./internal/equipo/team ./internal/equipotest -run '^TestPlan' -count=1`; expect failure. |
| +- [ ] **Implement:** For a new proposal, accept an empty task ID and revision 0, allocate the task/thread/card IDs on the server and return revision 1; every edit requires the current positive revision. Create the task, plan, thread, card and dispatch-outbox entry atomically. Store an append-only revision history with actor and changed step keys. Validate and mutate app/core rows through `Execution.atomic`; `EditUnstarted` uses the bound core transaction and current grant. Cancellation marks unstarted steps cancelled, never erases evidence. Recompute pending dependencies and guard review/checks after every candidate-producing step. Keep final person outside runner execution; publication produces a review branch and a human wait. Require current work authority, model constraints and budgets when approving and dispatching. An automatic start is the person's configured policy acting on a validated proposal, not a coordinator approval. Investigation starts with bounded read-only scope and a person checkpoint; any later publication is a new validated revision with all three mandatory steps. Plans retain the existing `team.MaxSteps = 16` limit, including hidden execution steps. Add/replace/reorder may affect only unstarted steps; instruction-only edits still increment the app and core revision in the same transaction. Persist task kind, current plan revision and approval revision, rather than deriving them from displayed text. |
| +- [ ] **Green and guard mutations:** Repeat; expect PASS. Remove each invariant, revision fence and approval recheck separately; require a failing named test. Test upgrade from existing bug tasks using `BugPlan` as the history-preserving seed; run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: add guarded plan revisions and approval settings`. |
| + |
| +### Task 3: Define feature, rendered-change and read-only completion contracts |
| + |
| +**Files:** Create `internal/equipo/team/{feature_evidence,rendered_evidence,read_work}.go` and tests; modify `team/{model,evidence,git_evidence,policy,publication}.go`, `internal/equipo/{authority,runner_provenance}.go`; create `internal/equipo/rendered_approval.go`, `internal/runnerproto/types.go`. |
| + |
| +**Interfaces:** Add `PredicateSoftwareFeature="software_feature"`, `PredicateRenderedChange="rendered_change"`; `FreezeFeatureEvidence(ctx context.Context, scope Scope, h Handle, acceptanceHash, definitionHash string) error`. Extend `EvidenceRequirement` with `FrozenAcceptanceHash` and `RenderedApprovalHash`; define `RenderedApproval{CandidateHash, RenderHash, Person string; DecisionRevision int64}` registered only through `Store.ApproveRenderedChange(ctx context.Context, actor Actor, taskID, candidateHash, renderHash string, m Mutation) error` in new `internal/equipo/rendered_approval.go`. The person field comes from that operation, never the submitted artifact. Add `CapScope`, `CapResearch`, `RoleAcceptance`, `RoleAnswer` and `AnswerResult{Body string; Sources []SourceRef}`, where `SourceRef{Kind, ID, Hash string; Revision int64}` references observed material, not an arbitrary model assertion. |
| + |
| +For read-only research add `TargetProjectRead` with project repository/base but no write ref; an empty evidence predicate is valid **only** for that target with research steps, and `CompleteReadWork(ctx context.Context, scope Scope, h Handle, answer ArtifactSpec) error` records the bounded sourced answer. There is no fabricated recommendation evidence predicate. Task 4 makes delivery to the conversation part of completion. |
| + |
| +- [ ] **Tests first:** `TestFeatureFreezeBeforeBuild` requires acceptance from the scope attempt frozen by hash before candidate work, rejects replacement and late freeze, and denies build admission before freezing/base failure. `TestFeatureExactCandidateEvidence` requires trusted base-fail/candidate-pass acceptance, nonzero test counts, repository checks and distinct-family review on the exact candidate. `TestRenderedChangeApproval` requires checks, review and owning person's approval of the exact rendered artifact; changed render/candidate invalidates approval. `TestReadWorkNoPublication` allows sourced answers with one provider, rejects missing/forged source refs and all publish/edit operations. `TestEvidenceKindsPreserveBug` retains frozen bug and historical reconciliation behavior. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipo/team ./internal/equipotest -run 'TestFeature|TestRenderedChange|TestReadWork|TestEvidenceKinds' -count=1`; expect failure. |
| +- [ ] **Implement:** Reuse trusted check attestations and immutable blob storage, never model-reported pass/fail. Keep acceptance tests outside workspaces and pass them by hash to the executor. All contributing builder families must differ from Review; if that is impossible, wait for a person to revise the plan. Read-only grants allow current members to inspect shared projects, but cannot authorize code changes through `bugAuthority` or forge publication. Recommendations and investigation checkpoints are delivery contracts; they do not require review/checks/merge or a second family. Copy/design publication does require its owning person's rendered approval; Plan 4 routing is not needed to display a shared pending approval. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Mutate freeze timing/hash, executor provenance, candidate subject, family comparison, render approval and read-only target restrictions independently. |
| +- [ ] **Implementation commit:** `feat: add feature evidence and sourced read-only results`. |
| + |
| +### Task 4: Execute the persisted plan through the current runner |
| + |
| +**Files:** Create `internal/equipo/plan_execution.go`, `internal/runner/plan_workflow.go`, `internal/equipotest/plan_workflow_test.go`; modify `task_prepare.go`, `runner_execution.go`, `runner_adapters.go`, `runnerproto/types.go`, runner `workflow.go`, `direct_workflow.go`, `turn_prompt.go`, `tools.go`, `witness.go`, checks and forge integration tests. |
| + |
| +**Interfaces:** `PlanJobSpec(task Task, project Project, p taskplan.Plan, policy team.Policy) (team.JobSpec,error)`; `runnerproto.StepBrief{PlanRevision int64; StepKey, SpecialistKey, Action string; SpecialistRevision int64; ArtifactHashes []string}` carried by `RunnerBrief`; `runner.NewPlanWorkflow(c BugWorkflowConfig) (*PlanWorkflow,error)` and `PlanWorkflow.Run(ctx context.Context, s *Supervisor, claim RunClaim) error`. Preserve `NewBugWorkflow` as a compatibility wrapper. Add scoped specialist tools `submit_acceptance`, `submit_answer`, `submit_render`, with strict payloads from Task 3 and no publication/check attestation verbs. |
| + |
| +- [ ] **Tests first:** `TestPlanWorkflowFeature` runs scope, frozen base failure, build, review, checks, publication/readback and human wait with fake providers and real local Git/checks. `TestPlanWorkflowRecommendation` delivers answer and sources once, creates no ref or mutable checkout and invokes neither publisher nor checks. `TestPlanWorkflowInvestigation` stops at its checkpoint and requires an explicit new plan revision to build. `TestPlanWorkflowSpecialistOrder` runs Copy/Design/Engineering/custom-compatible actions in persisted order with real step progress and actual selections. `TestPlanWorkflowNoMidStepSwitch` rejects account, policy or plan changes after dispatch; cancellation waits for namespace proofs. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run '^TestPlanWorkflow' -count=1`; expect failure. |
| +- [ ] **Implement:** Replace `specialistFor` and fixed key-based behavior with immutable step snapshots; capability, not a display name, selects runner actions. Compose additional candidate-producing stages with captured immutable candidate artifacts; Review sees candidate material, never builder dialogue. Preserve the same-runner evidence/workspace requirement until an explicit cross-runner artifact transport exists. Split builder and reviewer selection so one-family recommendations can start, while publication waits for an eligible independent reviewer. A queued feature can scope with one family; it cannot claim review or advertise publish readiness without the second. Capture source snapshots by hash from the read-only checkout at its exact revision and from authorized project/request records; register those snapshots before accepting `SourceRef` values. A URL supplied by the model is not an observed source. No CARLOS data fetch is added. Record answer delivery/card/thread changes atomically with read-work completion; a crash between artifact upload and delivery replays the delivery, not the provider turn. Preserve production Amadan readback after a lost write reply. |
| +- [ ] **Green and guard mutations:** Repeat; expect PASS. Break action mapping, frozen artifact handoff, answer-delivery uniqueness, immutable selection and no-publish research; observe failure. Run existing `TestDirectBugWorkflow` and `TestPublishDescriptionRecovery` with `-count=1` as regression guards. |
| +- [ ] **Implementation commit:** `feat: execute revisioned plans with the direct runner`. |
| + |
| +### Task 5: Give coordinator turns fenced authority and accounted admission |
| + |
| +**Files:** Create `internal/equipo/{coordinator_store,coordinator_api}.go`, `internal/runnerproto/coordinator.go`, `internal/equipo/team/coordinator_admission.go`, tests, `0021_coordinator.sql`; modify runner API routing, core budget/period queries, authority, policy and model/schema mirrors. |
| + |
| +**Interfaces:** `CoordinatorBinding{ID, Person, RunnerID, ConnectionID, SessionID string; Revision, Generation int64}`; `CoordinatorTurn{ID, MessageID, RequestID string; Generation, Revision int64; State string}`; `CoordinatorClaim{Binding CoordinatorBinding; Turn CoordinatorTurn; Scope team.Scope; Handle team.Handle; Brief runnerproto.RunnerBrief}`. Add `Execution.ClaimCoordinator(ctx context.Context, p RunnerPrincipal, turnID string, revision int64) (CoordinatorClaim,error)` and `Execution.CompleteCoordinator(ctx context.Context, p RunnerPrincipal, claim CoordinatorClaim, event runnerproto.Event) error`. Runner protocol exposes separate coordinator poll/claim/renew/event/containment operations under `/api/runner/v2/coordinator`, with capability negotiation; old v2 runners cannot receive them. |
| + |
| +Declare these three structures in `internal/runnerproto/coordinator.go`; Equipo aliases them rather than making the runner import the application. Add `Store.SaveCoordinatorBinding(ctx context.Context, actor Actor, runnerID, connectionID string, m Mutation) (CoordinatorBinding,error)`, `Store.ResetCoordinator(ctx context.Context, actor Actor, m Mutation) (CoordinatorBinding,error)` and `Store.RetryCoordinatorTurn(ctx context.Context, actor Actor, turnID string, m Mutation) (CoordinatorTurn,error)`. No submitted person or session ID is accepted. Reset/rebind first fences and contains active work, then increments generation; retry creates a new admitted turn only after uncertainty and containment are recorded. A process-completed event alone cannot prove all tool effects/delivery committed. |
| + |
| +Core adds `TargetConversation`, `CapCoordinate`, and `CoordinatorGrantRef(person string) string`. This target accepts an empty evidence predicate only with coordinate steps and no repository/ref; completion means the admitted turn and its recorded results were durably delivered, never completion of the lifelong conversation. These are team-only model-call authority, never repository authority. A coordinator turn uses an ordinary fenced job/attempt with `Project=0` only for this target. Extend core budget accounting so its reservation, call/time/token usage and unknown exposure count against the **same team ceiling** and a configured per-person coordinator limit. Normal project jobs still require `Project>0` and a configured project budget. Add versioned coordinator-limit rows and their model/schema mirror in 0021; include them in the same period reservation/exposure queries as team work, with no default grant of unlimited budget. `Store.SetCoordinatorLimits(ctx context.Context, actor Actor, person string, limits team.Limits, m Mutation) error` is owner-only; absent limits deny dispatch. |
| + |
| +- [ ] **Tests first:** `TestCoordinatorSingleWriter` races two runners/tabs and admits one turn per person/team, preserving message order. `TestCoordinatorAuthorityRevoked` covers roster removal, role/connection change, generation mismatch, failed lookup and revoked runner before claim/renew/tool use. `TestCoordinatorBudgetSharesTeam` races project and coordinator admission against the last reservation and permits only one; uncertain/cancelled turns remain charged. `TestCoordinatorNoProjectBudgetBypass` refuses `Project=0` for ordinary jobs and refuses forge operations under conversation authority. `TestCoordinatorTurnReplay` returns one admission for duplicate request and rejects changed message/binding. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipo/team ./internal/equipotest -run '^TestCoordinator(Single|Authority|Budget|NoProject|Turn)' -count=1`; expect failure. |
| +- [ ] **Implement:** Reuse the core ledger, admission and period-budget transaction; do not add a separate accounting counter that can overspend concurrently. Serialize queued messages, pause when no personal connection/runner is available and never borrow another person's subscription. A project-specific turn also checks that project's provider restrictions before any project material enters the prompt; general turns receive only permitted project labels, not restricted repository context. The coordinator's connection is explicitly selected by its person; project work can select a different eligible connection for a later specialist step. Audit coordinator effects as `coordinator:<binding ID>`, with a separate delegating person field, not as a person write. |
| +- [ ] **Green and guard mutations:** Repeat; expect PASS. Break uniqueness, generation/fence, current membership, shared budget reservation and target restriction independently; test period rollover, overflow and unknown usage. Run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: admit coordinator turns with person-bound authority`. |
| + |
| +### Task 6: Expose only structured coordinator tools |
| + |
| +**Files:** Create `internal/coordinator/{types,tools,tools_test,budget_test}.go`, `internal/equipo/coordinator_tools.go`; modify `internal/runner/{tool_proxy,tool_socket,tools,tool_journal}.go`, provider policy constructors and runnerproto coordinator types; test `internal/equipotest/coordinator_tools_test.go`. |
| + |
| +**Interfaces:** `CoordinatorToolCall{RequestID, Name string; Arguments json.RawMessage}`; `CoordinatorToolResult{ResourceID string; Revision int64; Value json.RawMessage}`; `Execution.CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, claim CoordinatorClaim, call CoordinatorToolCall) (CoordinatorToolResult,error)`. `coordinator.ToolClient.Call(ctx context.Context, call CoordinatorToolCall) (CoordinatorToolResult,error)` is the runner-facing interface. The instance binds principal/session/turn/fence, never trusts them in arguments. |
| + |
| +Add `runner.CoordinatorToolBinding{Claim runnerproto.CoordinatorClaim; Session provider.Session; Journal *Journal; Current func(context.Context) error; Call func(context.Context, runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult,error)}` and `OpenCoordinatorToolProxy(ctx context.Context, binding CoordinatorToolBinding) (*ToolProxy,error)`. Declare call/result wire types in runnerproto and alias them in coordinator/Equipo. Keep the existing task `ToolBinding` path intact. Journal coordinator submissions by instance/binding generation/turn/attempt/fence/request ID in an ordered additive journal migration; never invent a task ID to pass a task-only guard. Automatic MCP permission approval and later execution must validate the same bound request hash. |
| + |
| +Exact tools: `read_project(project_id)`, `read_task(task_id)`, `propose_plan(message_id, plan)`, `ask_person(message_id, question, options)`, `route_to_task(message_id, task_id)`, `post_message(body, source_refs)`, `suggest_preference(source_message_id, text)`, `suggest_specialist(source_message_ids, draft)`, `suggest_playbook(source_message_ids, draft)`. Each has a strict JSON schema with no unknown fields and the shared request ID. Suggestions are conversation records, not saves to the library. Only a later verified-person action can accept one. |
| + |
| +Define `ClarificationQuestion{ID, MessageID, TurnID, Prompt, State string; Options []QuestionOption; Revision, Generation int64; ExpiresAt time.Time}` and `QuestionOption{ID, Label string}` in the coordinator wire types; store them in 0021’s coordinator question table. `Store.AnswerClarification(ctx context.Context, actor Actor, id, optionID, text string, m Mutation) error` accepts one declared option or bounded free text, once. A clarification may outlive a cleanly completed coordinator turn: its answer queues a new admitted turn. It is invalid after reset, replacement or its 24-hour expiry. It does not reuse runner-native permission authority or keep an idle model process alive. |
| + |
| +- [ ] **Tests first:** `TestCoordinatorToolAllowlist` denies shell, arbitrary file/network, create-specialist/playbook, publication, approval, account selection changes and settlement tools; prose resembling a tool call has no effect. `TestCoordinatorToolScope` rejects other-person messages, unauthorized project content, wrong turn/fence and replay with changed arguments. `TestCoordinatorProjectInference` accepts a valid inferred project with visible attribution; ambiguity creates one question and no task, and correction uses Task 2's guarded path. `TestCoordinatorSuggestionOnly` proves suggestion tools create no specialist/playbook/preference confirmation. `TestCoordinatorToolCommitCrash` replays the original result after lost acknowledgement, including task, card, thread and audit IDs. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/coordinator ./internal/runner ./internal/equipotest -run '^TestCoordinator(Tool|Project|Suggestion)' -count=1`; expect failure. |
| +- [ ] **Implement:** Separate coordinator endpoint capabilities from task-attempt tools. Claude's coordinator has an empty built-in tool inventory and only Equipo MCP tools; Codex likewise has no shell/file/search/browser tools for this policy. Hash the exact inventory and certify it. No repository checkout is mounted into a coordinator. Validate a proposal's project/work authority and policy using the current delegated person inside the transaction, and retain the coordinator attribution. Never interpret natural-language output as a plan, answer, preference or action. Provider assistant text may be displayed as escaped commentary, but success/cards depend on tools and trusted events. Scope read results and redaction before they leave the instance. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Remove allowlist/schema/scope/replay guards and enable prose parsing separately; observe failure. Recheck both providers' broker-validation-before-approval tests. |
| +- [ ] **Implementation commit:** `feat: add the scoped coordinator tool server`. |
| + |
| +### Task 7: Resume the long-lived coordinator session safely |
| + |
| +**Files:** Create `internal/coordinator/{runtime,recovery,runtime_test,recovery_test}.go`, `internal/runner/coordinator_runtime.go`; modify runner `service.go`, `runtime_direct.go`, journal/capture/recovery files and provider adapter tests. |
| + |
| +**Interfaces:** `coordinator.Config{Launcher provider.Launcher; Tools ToolClient; OpenLaunch func(context.Context, runnerproto.CoordinatorClaim) (provider.Launch,error); Record func(context.Context, provider.Event) error}`; `coordinator.New(Config) (*Runtime,error)`; `Runtime.RunTurn(context.Context, runnerproto.CoordinatorClaim) error`; `Runtime.Stop(context.Context) error`. Use Task 5's wire aliases consistently in `runnerproto`; the local Equipo names alias those neutral wire structures. The existing runner supplies namespace ownership, admission, capture and account lease implementations. Preserve its per-home lease across a whole active turn: a coordinator and specialist using the same account queue rather than racing token refresh. Closing the coordinator process after a clean turn releases that lease for project work. |
| + |
| +- [ ] **Tests first:** `TestCoordinatorSessionContinuity` sends two separately admitted turns through fake Claude/Codex adapters, resumes the same provider session after a clean boundary and retains conversation identity. `TestCoordinatorCrashNeverRedispatches` crashes before/after durable intent, stdin, tool commit, frame commit and server ACK; only completed results replay, uncertain turns wait for the person. `TestCoordinatorResumeRevalidates` denies changed identity, policy, provider/model or revoked connection; same-identity credential refresh requires fresh preflight. `TestCoordinatorStopContains` waits for every namespace and endpoint, retains unknown usage and rejects late answers. `TestCoordinatorUsageOnce` covers cumulative/provider-local accounting, duplicate final events, missing usage and resume baselines. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/coordinator ./internal/runner ./internal/runner/provider/... -run '^TestCoordinator(Session|Crash|Resume|Stop|Usage)' -count=1`; expect failure. |
| +- [ ] **Implement:** A long-lived session is a durable provider session and person binding, not an immortal process or unbounded admission. Close and contain the process at a completed turn boundary; reopen/resume it for the next newly admitted turn on the same runner, account and policy. Preserve private session files outside disposable scratch. Each turn has a new bounded attempt and namespace, with events attached before `StartTurn`; provider session and local attempt IDs remain distinct. Runner death or incomplete output never resumes the uncertain turn automatically. Offer explicit retry as a new turn only after reconciliation, retaining the old unknown charge. Reset/switch connection increments generation and starts a new provider session from trusted stored context, not copied provider credentials or a cross-account resume. |
| +- [ ] **Green and guard mutations:** Repeat; expect PASS. Move durable barriers, resend uncertain prompts, ignore generation or reset usage baselines independently; require failures. Add journal upgrade/reopen tests without provider runs. |
| +- [ ] **Implementation commit:** `feat: run durable coordinator sessions through direct launch`. |
| + |
| +### Task 8: Make preferences inspectable and non-authoritative |
| + |
| +**Files:** Create `internal/equipo/{preferences,preference_handlers,preference_views}.go`, `templates/preferences.html`, `internal/equipotest/preferences_test.go`, `0022_preferences.sql`; modify coordinator prompt construction and `copy.go`. |
| + |
| +**Interfaces:** `Preference{ID, Text, Status, SourceMessageID string; Revision int64}` where status is `confirmed` or `inferred`; `Store.Preferences(ctx context.Context, actor Actor) ([]Preference,error)`; `Store.SetPreference(ctx context.Context, actor Actor, p Preference, m Mutation) (Preference,error)`; `Store.DeletePreference(ctx context.Context, actor Actor, id string, m Mutation) error`; `Store.ConfirmedPreferences(ctx context.Context, actor Actor, projectID int64) ([]Preference,error)`. |
| + |
| +Also add typed `PersonalSettings{Landing string; Revision int64}` and `Store.SavePersonalSettings(ctx context.Context, actor Actor, in PersonalSettings, m Mutation) (PersonalSettings,error)`. Landing allows `conversation` or `work`, defaults to `conversation`, and is stored separately from learned prose preferences in 0022. A model cannot change it by inferring a preference. |
| + |
| +- [ ] **Tests first:** `TestPreferencesConfirmedOnly` verifies prompts/plan decisions use confirmed entries only, and an inference cannot turn itself into confirmation. `TestPreferencesSourcePrivacy` denies cross-person source links, guesses and coordinator-supplied confirmation. `TestPreferencesCorrectionAndDelete` checks revisions, tombstone provenance, deletion from future prompts and invalidation of cached context. `TestPreferencesCannotGrantAuthority` tries to approve, spend, select another person's account or override team rules with preference text; each fails. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest ./internal/coordinator -run '^TestPreferences' -count=1`; expect failure. |
| +- [ ] **Implement:** Show status, source and correct/delete/confirm forms. A direct personal edit is confirmed; a coordinator suggestion remains inferred until a person confirms it. Rebuild instruction context on the next turn and include source IDs/revisions; do not allow a stale session memory to drive decisions after deletion. All effectful operations recheck current policy independent of prompt content. Do not rewrite historical task instructions that already ran. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break source scope, confirmation origin, deletion refresh and policy precedence separately; run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: add sourced and correctable personal preferences`. |
| + |
| +### Task 9: Build the live conversation, plan editor and question cards |
| + |
| +**Files:** Create conversation views/handlers/templates from the file map, `plan_handlers.go`, `templates/plan.html`, `conversation_live.go`, `internal/equipotest/conversation_browser_test.go`; modify `app.go`, live observer/changes, task/question views, navigation, `copy.go` and `static/equipo.css`. |
| + |
| +**Interfaces:** GET/POST `/conversation`, GET/POST `/tasks/{id}/thread`, GET/POST `/tasks/{id}/plan`, POST `/tasks/{id}/plan/approve`, POST `/tasks/{id}/project`; retain question-answer and cancellation routes. `Store.ConversationCards(ctx context.Context, actor Actor) ([]Card,error)` projects current plans/tasks/questions. New private live topic keys include team, person and resource; `application.allowConversation(r *http.Request, key string) bool` checks persisted membership/ownership on every authorization. |
| + |
| +Add GET/POST `/settings/coordinator` for Task 5’s own binding/reset and owner-only coordinator limits; expose missing budget configuration as a setup state. Add POST `/conversation/questions/{id}/answer` for Task 6 clarification cards. The plan page has project approval and personal override forms backed by Task 2; these settings are usable in 3a, before the complete 3b settings API. |
| + |
| +- [ ] **Tests first:** `TestConversationScriptless` posts a message, edits/reorders only unstarted steps, corrects a project and answers a card without JavaScript. `TestConversationNoProjectPicker` checks the composer lacks a project selector, chosen project is on the card, and ambiguity has one-tap options. `TestConversationLivePrivacy` denies another person's subscription, stops access after roster removal and emits nothing on rollback. `TestConversationQuestionRace` sends stale, expired, cancelled and duplicate answers and proves only one current answer can reach the original provider request. `TestConversationLayout` uses existing chromedp fixtures at phone/desktop widths and enlarged text: no split screen, initials, coloured left accents, wrapping values or lost keyboard focus. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestConversation(Scriptless|NoProject|Live|Question|Layout)' -count=1`; expect failure. |
| +- [ ] **Implement:** Use Rastrillo v0.30.1 `live.New` topics, `live.Hub` notifications and existing fragment rendering. Continue scriptless POST/redirect/get; live updates invalidate card regions after commit, never replace a composer draft or move focus. Preserve the hibernating/no-hub fallback and serve initial snapshots correctly before any event. Cards show plan revision, project correction action, playbook when present, picks/reasons, actual step progress and current approval state. Route task replies with a short reference line. Coordinator clarification questions have their own persisted card lifetime; runner permissions keep the existing attempt/fence/expiry rules and original request. Free text never substitutes for a native permission response. Add a thread link from task, Journey and specialist pages. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break private topic authorization, post-commit ordering, revision checks and layout constraints; restore. Run existing vendored-assets and live-gate tests. |
| +- [ ] **Implementation commit:** `feat: add live conversation cards and task discussions`. |
| + |
| +### Task 10: Establish the versioned person API and native sign-in contract |
| + |
| +**Files:** Create `internal/personapi/{types,validate,validate_test,budget_test}.go`, `internal/equipo/{person_api,person_api_auth,person_api_conversation}.go`, `internal/equipotest/person_api_test.go`, `docs/api/equipo-v1.openapi.json`, `0023_person_api.sql`; modify `app.go`, auth/session revocation integration and copy keys. |
| + |
| +**Interfaces:** `Store.PersonAPIHandler() http.Handler` mounted at `/api/v1`; `PersonPrincipal{Address, CredentialID string; SessionEpoch int64}` comes only from verified browser identity or a native person credential. `Store.BeginPersonDevice(ctx context.Context, publicKey, requestID string) (PersonDeviceChallenge,error)`; `ApprovePersonDevice(ctx context.Context, actor Actor, id string, m Mutation) error`; `ExchangePersonDevice(ctx context.Context, proof PersonDeviceProof) (PersonCredential,error)`; `RevokePersonDevice(ctx context.Context, actor Actor, id string, m Mutation) error`. Challenge/proof mirror existing runner enrollment's key-bound nonce/signature design but use distinct `equipo.person.v1` and `equipo.person.device.v1` audiences. Define a 10-minute single-use challenge, throttled polling, a 30-day revocable credential stored only as a keyed hash, and no provider credential fields. |
| + |
| +`PersonDeviceChallenge{ID, DeviceSecret, UserCode, Challenge, VerificationURI string; ExpiresAt time.Time; PollIntervalSeconds int}`; `PersonDeviceProof{ID, DeviceSecret, Challenge, Nonce, Signature string}`; `PersonCredential{ID, Token, Audience, InstanceID string; ExpiresAt time.Time}`. Return device secrets only to the initiating client, and the bearer only on successful proof exchange; never return either in a device list. Limit challenge creation and failed polling by source and challenge, preserve a five-second poll interval, and consume approval/exchange atomically. For an exchange whose response is lost, allow the same signed nonce to retrieve the same short-lived encrypted exchange result; never mint a second credential or reopen an already used challenge. Delete the encrypted result after its 10-minute exchange window. |
| + |
| +- [ ] **Tests first:** `TestPersonAPIAuthAudiences` rejects runner, cleanup, coordinator and other-instance tokens, mixed cookie/bearer auth and forged person fields. `TestPersonAPIBrowserCSRF` rejects cross-origin cookie writes and missing browser evidence; native writes without browser headers work only with a valid person bearer and no cookies. `TestPersonAPIRevisionReplay` asserts required `If-Match`, conflict on stale revision, duplicate result replay and changed-body conflict across browser/API. `TestPersonAPIDeviceApproval` requires verified keymail identity, matching key/nonce, current roster and single-use exchange; revocation/session epoch applies immediately. `TestPersonAPIConversationParity` checks private reads, task-thread visibility, cards and answers match HTML operations. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/personapi ./internal/equipotest -run '^TestPersonAPI' -count=1`; expect failure. |
| +- [ ] **Implement:** Document and implement the 3a rows of the API table below. Use `csrf.SameOrigin`/`csrf.Protect` for cookie writes. The existing outer middleware would reject a native client without browser headers: dispatch `/api/v1` through an audience-validating authentication middleware before choosing native-bearer or browser-CSRF handling. Do not add a prefix-wide CSRF exemption. Validate credential before bypassing browser evidence, reject cookies on the native lane, and never enable credentialed cross-origin access. Keep current framework sign-in/session handling. Device-token exchange is the only unauthenticated person-token endpoint and requires its own signed challenge proof, expiry, rate limit and prior browser approval. Return JSON errors, not sign-in HTML, for API failures. |
| +- [ ] **Green and guard mutations:** Repeat; expect PASS. Break audience separation, CSRF branch, key proof, current roster and revision guards individually. Validate OpenAPI operations against route tests and run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: expose person-authenticated conversation API v1`. |
| + |
| +### Task 11: Prove and package the 3a usable stop |
| + |
| +**Files:** Create `internal/equipotest/coordinator_acceptance_test.go`; modify relevant release tests/requirements, `Makefile` only for delegating targets, `copy.go`; create the 3a section in `docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md` and future reviewed `docs/plan-3-acceptance.md`. |
| + |
| +**Interfaces:** No new product interface. Exercise Tasks 1–10 through real HTTP, the runner service, fake provider streams, local Git and the existing fake forge. Report separate offline pass, pending copy and pending live certification states. |
| + |
| +- [ ] **Tests first:** `TestCoordinatorAcceptance3A` signs in two fixture people, starts a bug and feature from messages, gets one sourced recommendation with one family, edits a future step, answers a question, corrects an unstarted project, routes a reply, changes a preference, cancels active work and restarts mid-turn. Assert independent-family exact-candidate evidence, publication readback, human wait, isolated accounts and no duplicate task/turn/delivery. `TestCoordinatorReleaseNeedsPolicyCertification` rejects old/missing tuples and pending copy for new coordinator policies. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestCoordinator(Acceptance3A|Release)' -count=1`; expect missing behavior to fail. |
| +- [ ] **Implement integration fixes:** Finish wiring discovered by the acceptance test. List every new runtime key from the copy inventory; obtain review before release through the later controller's chosen review channel, without starting a copy-review server in this task. Do not mark pending entries reviewed on the strength of the mockups. Prepare bounded live acceptance inputs and certification assertions; no provider run is authorized by this plan-writing session. |
| +- [ ] **Green and gates:** Repeat targeted command; mutate duplicate-delivery, early-success and release-eligibility guards. Run `CGO_ENABLED=0 go build ./cmd/equipo ./cmd/equipo-runner`, `make migration-check`, then `make ci` once on a namespace-capable machine. Preserve `.amadan/ci` and `.amadan/ci.d/` delegation. Record the relevant Plan 2b gate result, changed policy identities and any remaining blocker. No fake provider fixture can certify a production tuple. |
| +- [ ] **Usable acceptance and implementation commit:** After 2b dependencies and reviewed copy, Paul authorizes a bounded certification/try-out with his dedicated homes and disposable repository. He performs the three request kinds, sees the branch/evidence, cancels and merges manually. Keep the release disabled until this gate passes. Subject: `test: verify the coordinator conversation acceptance flow`. |
| + |
| +## Plan 3b: Library, setup and the complete app API |
| + |
| +### Task 12: Add custom specialists and versioned specialist templates |
| + |
| +**Files:** Create `internal/equipo/{specialist_library,templates_catalog,specialist_handlers}.go`, templates `specialist_form.html`, `template_library.html`, `internal/equipotest/specialist_library_test.go`, `0024_specialist_library.sql`; modify specialists, connection selection, navigation, icons, provider policy and copy keys. |
| + |
| +**Interfaces:** `SpecialistInput{Key, Name, Icon, Instructions string; AllowedModels []ModelRef; Tools []string; ProjectIDs []int64; MaxConcurrent int}` with `ModelRef{Provider, Family, Model string}`; `Store.CreateSpecialist(ctx context.Context, actor Actor, in SpecialistInput, m Mutation) (Specialist,error)`; `UpdateSpecialist` with the same signature; `DeleteSpecialist(ctx context.Context, actor Actor, key string, m Mutation) error`. `TemplateRef{ID string; Version int64}`; `InstallSpecialistTemplate(ctx context.Context, actor Actor, ref TemplateRef, m Mutation) (Specialist,error)`; `SpecialistTemplateDiff(ctx context.Context, actor Actor, key string, target TemplateRef) (TemplateDiff,error)` where diff contains old/current/suggested field values. |
| + |
| +Define `TemplateDiff{From, To TemplateRef; CurrentRevision int64; Old, Current, Suggested map[string]json.RawMessage}`. Applying it requires the current specialist/playbook revision and explicit selected fields; later catalog changes cannot silently alter the accepted diff. |
| + |
| +- [ ] **Tests first:** `TestSpecialistLibraryCopies` installs two independent editable copies with template origin/version; changing a shipped template does not mutate either. `TestSpecialistRequiredDefaults` refuses Engineering/Review deletion or conversion away from their required roles. `TestSpecialistToolPolicy` refuses arbitrary commands, provider tools outside the certified catalog and a claimed tool set broader than project/team permission. `TestSpecialistScopeAndPermissions` allows active people to create team specialists, restricts edits/deletion to creator or owner, rejects other teams and preserves started snapshots. `TestSpecialistTemplateGroups` asserts all named templates and blank template exist with icon/name display. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest ./internal/runner/provider/... -run '^TestSpecialist(Library|Required|Tool|Scope|Template)' -count=1`; expect failure. |
| +- [ ] **Implement:** Preserve owner control of team rules and existing defaults. Add stable opaque keys, creator, archive state, icon catalog ID, allowed-model/tool/project sets and template provenance. Archiving a referenced specialist hides it from new plans but preserves historical cards; reject removal used by an unstarted plan until the person revises that plan. Offer template updates as field diffs accepted explicitly under revision checks. Ship Quality: QA and testing, Accessibility, Performance; Safety: Security, Privacy; Running things: Ops, Data, Support; Words and reach: Docs, Localisation, SEO; plus blank. Ops/Data templates grant no infrastructure or money authority. Ship catalog labels, descriptions and standing instruction text through individually pending `copy.go` entries, with catalog records referring to keys. On installation, copy approved values into the team-owned record; person-authored changes remain attributed content. All executable tool profiles must be certified; an unavailable combination remains unavailable. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break copy isolation, required-role protection, tool subset and edit authority independently; run `make migration-check` and size budgets. |
| +- [ ] **Implementation commit:** `feat: add custom specialists and template copies`. |
| + |
| +### Task 13: Add playbooks, defaults and explicit template updates |
| + |
| +**Files:** Create `internal/equipo/{playbooks,playbook_handlers,playbook_views}.go`, templates `playbooks.html`, `playbook_form.html`, `internal/equipotest/playbooks_test.go`, `0025_playbooks.sql`; extend template catalog, plan validation/coordinator tools and copy keys. |
| + |
| +**Interfaces:** `PlaybookInput{ID, Name string; Kind taskplan.Kind; Steps []taskplan.Step; ProjectIDs []int64; Template TemplateRef}`; `Store.SavePlaybook(ctx context.Context, actor Actor, in PlaybookInput, m Mutation) (Playbook,error)`; `Store.DeletePlaybook(ctx context.Context, actor Actor, id string, m Mutation) error`; `Store.SetPlaybookDefault(ctx context.Context, actor Actor, projectID int64, kind taskplan.Kind, playbookID string, m Mutation) error`; `Store.InstantiatePlaybook(ctx context.Context, actor Actor, id string, taskID string) (taskplan.Plan,error)`. Provide a blank playbook template with the required review/checks/person tail already present. Define `Playbook` as persisted input plus creator/revision/archive fields; use Task 12's `TemplateDiff` for offered updates. A template install/update is explicit and revisioned; define `Store.InstallPlaybookTemplate(ctx context.Context, actor Actor, ref TemplateRef, m Mutation) (Playbook,error)` and `Store.PlaybookTemplateDiff(ctx context.Context, actor Actor, id string, target TemplateRef) (TemplateDiff,error)` alongside the specialist equivalents. |
| + |
| +- [ ] **Tests first:** `TestPlaybookMandatorySteps` rejects removing review/checks/person from every saved playbook, including template copies. `TestPlaybookDefaultPrecedence` resolves project+kind, project-wide, kind-wide, then shipped kind template; only one default at each specificity. `TestPlaybookSnapshot` proves a later edit cannot change a task's instantiated revision. `TestPlaybookSuggestionNeedsPerson` creates only a suggestion until a verified-person save. `TestPlaybookTemplates` covers Bug, Website change, Infra change and Investigation, missing/archived specialists and deliberate update acceptance. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/taskplan ./internal/equipotest -run '^TestPlaybook' -count=1`; expect failure. |
| +- [ ] **Implement:** Reuse Task 2 validation. Active members create; creator/owner edits, owner controls project defaults; all changes are audited. Show the chosen playbook and any task-specific changes on the plan. Saved Investigation playbooks retain the mandatory tail but start at an explicit research/person checkpoint; later publishing requires new validation/admission, never an automatic leap past the checkpoint. Pure recommendations use Task 3's no-publication exception without instantiating a publishing playbook. Infra change is limited to repository changes, not production operations. Team continues to mean people. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break required tail, precedence, immutable snapshot and person-save checks; run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: add editable playbooks and project defaults`. |
| + |
| +### Task 14: Complete personal connection choices and model reasons |
| + |
| +**Files:** Modify `internal/equipo/{connections,connection_selection,connection_models,connection_handlers,connection_views,runner_execution}.go`, connection/project/plan templates and copy keys; create `internal/equipotest/plan_model_choice_test.go`. |
| + |
| +**Interfaces:** Extend existing `ConnectionChoice` input and `connectionChoiceRecord` with `Mode` values `best_fit`, `pinned`, `ask`; retain project/person ticked connection IDs and pin. `Store.SelectPlanStep(ctx context.Context, actor Actor, taskID, stepKey string, m Mutation) (Selection,error)`; `Store.ConfirmPlanSelection(ctx context.Context, actor Actor, taskID, stepKey, connectionID, model string, m Mutation) (Selection,error)`. Selection retains current connection, choice and specialist revisions, reason, family, runner and allowance-known fields. Create `0026_connection_modes.sql`, add `Mode` with default `best_fit` to `connection_choices`, update models/schema and preserve every existing personal tick/pin. Unchanged historical choices therefore retain their current behavior. |
| + |
| +- [ ] **Tests first:** `TestPlanModelChoiceOwnAccounts` covers two Claude and one Codex connections, person isolation, project ticks and provider/family rules. `TestPlanModelChoiceModes` verifies pinned behavior, explicit ask confirmation and deterministic best-fit within eligible choices, including unknown headroom. `TestPlanModelChoiceReviewFamily` blocks same-family Review regardless of pin/custom specialist. `TestPlanModelChoiceImmutableStep` preserves actual account/model/reason after a later settings change and never switches active work. `TestPlanModelChoiceUnavailable` keeps allowance/count unknown and reports the missing second family without borrowing accounts. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestPlanModelChoice' -count=1`; expect failure. |
| +- [ ] **Implement:** Treat model-proposed fit/reason as a proposal within server-validated choices. Use known headroom only when supplied by a supported observation; otherwise label counted usage and unknown allowance. Plan approval and ask-each-pick are separate gates. Recheck current choice/specialist/connection revisions at claim and every turn. Pinning never defeats independent review. A later step may use another personal account with its own recorded reason; no mid-step failover. Keep source credential paths out of every person API response. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Mutate person filter, allowed-family intersection, pin exception, unknown handling and actual-selection immutability separately; run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: show and guard per-step personal model choices`. |
| + |
| +### Task 15: Accept invitations through verified person identity |
| + |
| +**Files:** Create `internal/equipo/{invites,invite_handlers}.go`, `templates/invite.html`, `internal/equipotest/invites_test.go`, `0027_invitations.sql`; modify auth/roster routes and copy keys. |
| + |
| +**Interfaces:** `Invitation{ID, Address, Role string; ExpiresAt time.Time; Revision int64; State string}`; `Store.CreateInvitation(ctx context.Context, actor Actor, address string, role Role, m Mutation) (Invitation,error)`; `Store.AcceptInvitation(ctx context.Context, actor Actor, id, secret string, m Mutation) (Member,error)`; `Store.RevokeInvitation(ctx context.Context, actor Actor, id string, m Mutation) error`. Issue a random single-use secret, store its keyed hash and a seven-day expiry; expose the link only to the inviting owner for deliberate sharing. No automatic email send is required. |
| + |
| +- [ ] **Tests first:** `TestInviteVerifiedAddress` rejects a valid invite with the wrong/unverified keymail identity and does not create an active member on GET. `TestInviteReplayAndExpiry` covers identical retries, token reuse by another identity, expiry and revocation. `TestInviteCurrentAuthority` denies a removed inviter/owner's stale issuance action, protects the last owner and audits acceptance atomically. `TestInviteSignInPendingMember` allows verification of the invited identity before acceptance while denying every team resource until acceptance commits. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestInvite' -count=1`; expect failure. |
| +- [ ] **Implement:** Integrate with existing keymail verification rather than an invitation authentication bypass. Extend `NewAuth`’s current active-member-only `Authorize` callback to allow identity verification for an address with an unexpired, unrevoked invitation. The resulting session still fails `requireMember` until acceptance commits; a narrow verified-session invite handler does not use team-resource authorization. The acceptance page may read only safe invitation metadata after token validation; current membership is still mandatory elsewhere. Keep invitation secrets out of logs/audit/referrers. A verified sign-in can accept only the intended address and reviewed role. Record acceptance as the onboarding entry point. Task 16 initializes onboarding state from it without overwriting an existing person’s setup; this task does not depend on the later onboarding table. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break verified-address, single-use, expiry, roster and audit checks; run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: accept team invitations with verified identity`. |
| + |
| +### Task 16: Install and pair the supported own-machine runner |
| + |
| +**Files:** Create `internal/runner/install.go`, `install_test.go`, `internal/equipo/{onboarding,onboarding_handlers}.go`, `templates/onboarding.html`, `0028_onboarding.sql`; modify `cmd/equipo-runner/main.go`, existing enrolment/config/packaging/release tests; create a versioned installer asset and `internal/equipotest/onboarding_install_test.go`. |
| + |
| +**Interfaces:** `runner.InstallUser(ctx context.Context, opts InstallOptions) (InstallResult,error)` with `InstallOptions{Release, Root, InstanceOrigin string; EnableService bool}` and `InstallResult{Version, BinaryPath, ServicePath string}`; `Store.Onboarding(ctx context.Context, actor Actor) (OnboardingState,error)`; `Store.AdvanceOnboarding(ctx context.Context, actor Actor, step string, m Mutation) (OnboardingState,error)`. State records completed prerequisites independently, so resume does not rerun login or install. |
| + |
| +Define `OnboardingState{Revision int64; CurrentStep, ProviderChoice, RunnerID, AccountSetupID string; Completed map[string]bool}`. Allowed step keys are `welcome`, `account`, `runner`, `specialists`, `first_task`; advancement checks persisted prerequisites, not a submitted completed flag. The account-choice stage may be complete while actual login remains pending on the runner stage. Reuse `BeginEnrolmentRequest`, machine public key, challenge proof, browser approval and runner credential audiences; do not invent a second enrollment protocol. |
| + |
| +- [ ] **Tests first:** `TestOnboardingInstallVersioned` verifies version/checksum, user-writable destination, no sudo, no global config edits, no shell interpolation of origin/path and refusal of unsupported OS/arch or uncertified release. `TestOnboardingPairingBound` rejects replay/expiry/wrong machine and pairs only after the intended person's verified browser approval. `TestOnboardingInstallResume` retries partial install/pairing without duplicate service/runner and cleans only owned scratch. `TestOnboardingHostedUnavailable` shows Hosted by Equipo as later with no working launch route. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/runner ./cmd/equipo-runner ./internal/equipotest -run '^TestOnboarding(Install|Pairing|Hosted)' -count=1`; expect failure. |
| +- [ ] **Implement:** Generate a one-line install command from the configured HTTPS instance origin and immutable release version. Download to private on-disk scratch, verify against the authenticated versioned manifest, then install a user service and prompt for the short pairing code on the terminal, not in argv. Handle absent user-service support as an explicit setup failure; do not invoke sudo. Pairing code is expiring, throttled and machine-key bound. The runner dials outbound only. Testing never enables a persistent service. Production persistence is the explicit install action. Mac and unsupported Linux architectures get an accurate unavailable state pending certified containment/packaging; do not claim that compiling Go makes them supported. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break manifest verification, code binding, OS gate, user-only destination and retry uniqueness; run `make migration-check` and release packaging tests with fixtures. |
| +- [ ] **Implementation commit:** `feat: add versioned user runner installation and pairing`. |
| + |
| +### Task 17: Connect dedicated accounts and finish safe onboarding |
| + |
| +**Files:** Create `internal/runner/{account_login,account_login_test}.go`, `internal/runner/provider/login.go`, `internal/equipo/account_setup.go`, `internal/equipotest/onboarding_accounts_test.go`; modify runner command/config, onboarding views/routes, connection reports and copy keys. |
| + |
| +**Interfaces:** `provider.LoginDriver` exposes `Begin(ctx context.Context, providerName, credentialHome string) (LoginChallenge,error)`, `Poll(ctx context.Context, challengeID string) (LoginResult,error)`, `Cancel(ctx context.Context, challengeID string) error`; `LoginChallenge{ID, VerificationURI, UserCode, Mode string; ExpiresAt time.Time}` and `LoginResult{State string; Identity provider.Identity}`. This driver runs only on the person's runner and invokes supported, unmodified CLI login. `Store.RequestAccountSetup(ctx context.Context, actor Actor, runnerID, providerName, label string, m Mutation) (AccountSetup,error)` returns a setup ID/status and safe challenge metadata, never tokens. Home paths and provider device secrets stay runner-local. |
| + |
| +Define `AccountSetup{ID, RunnerID, Provider, Label, State string; Challenge *provider.LoginChallenge; ConnectionID string; Revision int64}` with states `waiting_runner`, `pending`, `connected`, `expired`, `denied`, `cancelled`, `unavailable`. Do not include a challenge ID that doubles as the provider’s secret polling credential. Correlate setup results with runner/person/generation and recheck the current roster before exposing or accepting them. |
| + |
| +- [ ] **Tests first:** `TestOnboardingAccountDedicatedHome` creates distinct private homes for two same-provider accounts, refuses interactive/shared homes, checks identity after login and proves no secret leaves the runner in HTTP, logs or journal events. `TestOnboardingDeviceFlow` uses fake supported CLI responses for approval, pending, expiry, denial, cancel and restart; no login success before identity readback. `TestOnboardingNoDeviceCapability` returns unavailable for a missing supported flow and never invents a verification URL or scrapes private OAuth endpoints. `TestOnboardingSafeFirstTask` starts a read-only sourced recommendation with one family and no branch/edit/publish; a change request asks for the second family before review. `TestOnboardingSpecialists` defaults the five specialists, keeps Engineering/Review required and installs selected library copies through Task 12. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run '^TestOnboarding(Account|Device|NoDevice|Safe|Specialists)' -count=1`; expect failure. |
| +- [ ] **Implement:** Present the five conceptual stages: welcome, account choice, own-machine setup, specialists, safe first task. On a new machine, account choice can be saved at stage 2, but login waits until stage 3 has paired the local runner; the instance never temporarily hosts a subscription credential. Reuse `provider.OpenAccount` and same-identity refresh rules after login. Use verified local CLI contracts, with `codex login --device-auth` only for a compatible pinned CLI. Claude device authentication remains unavailable until a supported flow is verified, or Paul accepts its supported browser-login alternative. Any browser callback listener binds loopback and is owned/closed by the setup process. Persist safe setup correlation, not provider secrets, across reconnects. Show multiple labeled connections and observed allowance/unknown state. A new account never replaces an existing credential home silently. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break dedicated-home enforcement, identity readback, secret filtering, safe-first-task permissions and family gate; require failures. Live sign-in and any provider execution require Paul's later explicit action with dedicated accounts. |
| +- [ ] **Implementation commit:** `feat: onboard personal accounts and a safe first task`. |
| + |
| +### Task 18: Put Teams above the team on web and phone |
| + |
| +**Files:** Create `internal/equipo/{team_links,team_link_handlers}.go`, `templates/teams.html`, `internal/equipotest/teams_navigation_test.go`, `0029_team_links.sql`; modify navigation/chrome/index/layout, sign-in success handling, preference landing setting and copy keys. |
| + |
| +**Interfaces:** `TeamLink{ID, Origin, Name string; LastSignedInAt *time.Time; Revision int64}`; `Store.TeamLinks(ctx context.Context, actor Actor) ([]TeamLink,error)`; `Store.RememberTeam(ctx context.Context, actor Actor, in TeamLink, m Mutation) (TeamLink,error)`; `ForgetTeam(ctx context.Context, actor Actor, id string, m Mutation) error`. GET `/teams` is a link directory, GET `/work` is the current team index. `Landing` preference is `conversation` (default) or `work` and is changed only by the person. |
| + |
| +- [ ] **Tests first:** `TestTeamsHierarchy` checks desktop Teams link and phone Teams → team → page → task/thread back links with scripts disabled. `TestTeamsDirectoryPrivacy` scopes links to the person and rejects credentials, script URLs, fragments, userinfo and non-HTTPS remote origins. `TestTeamsNoFederatedAuthority` proves remembering a link creates no remote membership, credential sharing or server fetch. `TestTeamsUnavailableCounts` keeps remote counts absent/unknown and renders current-team errors as unknown. `TestTeamsLandingPreference` covers default, override and stable task deep links after sign-in. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestTeams' -count=1`; expect failure. |
| +- [ ] **Implement:** Remember the current instance after successful sign-in. Provide an explicit person-managed add/forget link form for other instances they have signed in to; make clear that this is their remembered directory, not a federation roster. Independent origins cannot automatically discover each other's browser sessions. Allow import/export of nonsecret link metadata so the same list can be copied between instances; imported entries have unknown last-sign-in time. Never trust a submitted `LastSignedInAt` as verified. This meets the brief's links-only web boundary; automatic cross-origin discovery and aggregated remote Needs you need a separate authenticated directory/client design. Native clients can later remember their own signed-in instances. Include Preferences, Playbooks and dynamic specialists in the current team's navigation; preserve phone landing preference and icon-plus-name display. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break URL validation, private scope, back-link hierarchy and unknown count handling; run `make migration-check` and layout/vendored tests. |
| +- [ ] **Implementation commit:** `feat: add the Teams directory and web navigation hierarchy`. |
| + |
| +### Task 19: Add the durable notification outbox and subscription feed |
| + |
| +**Files:** Create `internal/equipo/{notification_outbox,notification_api}.go`, `internal/equipotest/notifications_test.go`, `0030_notifications.sql`; modify question/conversation/plan commit hooks, API schema, current-member revocation and copy keys. |
| + |
| +**Interfaces:** `Notification{ID, Kind, ResourceID, DeepLink string; ResourceRevision int64; CreatedAt time.Time; State string}`; `Store.Notifications(ctx context.Context, actor Actor, cursor string, limit int) (personapi.Page[Notification],error)`; `Store.SubscribeNotifications(ctx context.Context, actor Actor, deviceID string, m Mutation) (NotificationSubscription,error)`; `Store.AcknowledgeNotification(ctx context.Context, actor Actor, subscriptionID, notificationID string, m Mutation) error`; `UnsubscribeNotifications` with the same actor/subscription/mutation pattern. Subscriptions belong to a person device credential and have independent delivery cursors. Wire responses contain no bearer or permission answer capability. |
| + |
| +Define `NotificationSubscription{ID, DeviceID, Cursor string; Revision int64; Active bool}`; the recipient comes from the verified actor and is never a submitted field. ACK requires a notification actually delivered on that subscription, and advances only a contiguous cursor; an out-of-order ACK cannot skip an earlier event. |
| + |
| +- [ ] **Tests first:** `TestNotificationOutboxAtomic` commits question/task-ready/card changes and one recipient event together, emits nothing on rollback and deduplicates replay. `TestNotificationRecipientIsolation` denies other people and removed members, including stale live subscriptions. `TestNotificationReconnect` retries after lost acknowledgement, advances only the specified device cursor and preserves unread state across another device's ACK. `TestNotificationStaleAnswer` invalidates superseded question notifications and requires a fresh GET plus Task 10's revisioned person answer; no push payload grants authority. `TestNotificationNoExternalDelivery` registers no APNs/FCM/network sender and stores no provider secrets or arbitrary callback URL. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestNotification' -count=1`; expect failure. |
| +- [ ] **Implement:** Insert outbox rows in the effect's existing transaction, unique by recipient/event/resource revision. Feed delivery is at least once; clients deduplicate by notification ID. Keep task/question content private by default: the notification contains type, ID, revision and an instance-relative deep link; the authenticated client fetches current card/options. Support resumable GET polling and private Rastrillo invalidation for web; external mobile push is a later adapter over these records. Mark obsolete events superseded. Keep 30 days of acknowledged entries; a cursor older than retained history returns `410 cursor_expired` and a fresh-snapshot instruction, never silently skips pending questions. Unacknowledged current questions remain discoverable in Needs you. Plan 3 recipients are the requesting person and existing explicit human decision owners, not coordinator-to-coordinator routing. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Break commit atomicity, recipient scope, deduplication, independent cursor and stale-resource checks; run `make migration-check`. |
| +- [ ] **Implementation commit:** `feat: add a person-scoped notification outbox`. |
| + |
| +### Task 20: Complete and document the native-facing JSON API |
| + |
| +**Files:** Extend `internal/personapi` projections and `internal/equipo/person_api_*.go`; create `internal/equipotest/person_api_contract_test.go`; complete `docs/api/equipo-v1.openapi.json` and reviewed `docs/api/equipo-v1.md`; modify copy keys for exposed validation states. |
| + |
| +**Interfaces:** Implement every 3b row below using the same store operations as HTML, including CRUD, template install/diff/apply, account choices, setup status and invitation acceptance. OpenAPI is the versioned contract, not autogenerated exposure of database models. Handler registration supplies operation IDs consumed by `TestPersonAPIContractCoverage`. |
| + |
| +- [ ] **Tests first:** `TestPersonAPIContractCoverage` compares implemented methods/routes/schemas with OpenAPI and fails for missing/undocumented operations. `TestPersonAPISharedOperations` runs specialist/playbook/project/connection/onboarding actions by HTML and JSON and compares authority, revisions, audits and results. `TestPersonAPINativeAnswers` answers a question through a device credential, rejects stale/cancelled/other-recipient answers and never accepts an OS notification action as authentication. `TestPersonAPIPaginationUnknown` covers interleaved inserts, invalid cursors, bounded limits, null counts and private-field omission. `TestPersonAPISchemaCompatibility` reads fixed v1 fixtures and rejects unknown mutation fields/duplicate keys without silently binding models. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/personapi ./internal/equipotest -run '^TestPersonAPI(Contract|Shared|Native|Pagination|Schema)' -count=1`; expect failure. |
| +- [ ] **Implement:** Finish the endpoint/DTO/error inventory below and add request/response examples as contract fixtures. Document sign-in, credential revocation, browser CSRF, idempotency, revisions, cursor pagination, live reconnection and notification answer flow. Use the repository’s humane-docs guidance for that implementation documentation; API prose is future reviewed copy; list its sections for review with runtime keys before release. No native client, SDK or cross-team aggregation service. Do not expose provider session files, runner credentials, raw permission secrets or other people's private conversations through convenience expansions. |
| +- [ ] **Green and guard mutations:** Repeat; require PASS. Remove one route/schema, bypass a shared operation, leak a private field and accept an answer without person auth; require failures. Ensure every UI action needed by native clients has an API equivalent. |
| +- [ ] **Implementation commit:** `feat: complete the versioned person API contract`. |
| + |
| +### Task 21: Verify the 3b onboarding-to-work path and release boundary |
| + |
| +**Files:** Create `internal/equipotest/onboarding_acceptance_test.go`; extend API contract/release tests, `copy.go`, controller report and future reviewed acceptance documentation. Preserve Make/CI delegation. |
| + |
| +**Interfaces:** No new product interface. Acceptance uses HTTP/person API, fake login/provider streams, a temporary home, the runner, local Git/checks and fake Amadan. |
| + |
| +Do not mark this stop fully complete if Paul requires either unsupported onboarding path in the questions below. The Linux/Codex path is independently usable; the controller must report the exact platform/provider coverage. It exercises the complete supported own-machine path without touching real accounts, services or remote repositories. |
| + |
| +- [ ] **Tests first:** `TestCoordinatorAcceptance3B` accepts an invite, resumes interrupted setup, pairs Linux runner, creates two same-provider account homes plus a review family, installs and edits a specialist/template/playbook, chooses a default, receives a safe recommendation, starts a feature and answers through a device token. Assert all three mandatory publishing steps, correct personal accounts, no silent template updates, Teams links and one durable notification per effect. `TestPlan3ReleaseBoundaries` refuses pending copy, uncertified policy/login/OS support, missing API operation, hosted runner claims and automatic merge/deploy. |
| +- [ ] **Red:** `CGO_ENABLED=0 go test ./internal/equipotest -run 'TestCoordinatorAcceptance3B|TestPlan3ReleaseBoundaries' -count=1`; expect failure. |
| +- [ ] **Implement integration fixes:** Resolve only defects exposed by this path; update the controller report's dependency table against completed 2b review. Apply reviewed copy verbatim through the later controller's review channel. Keep unresolved Mac/Claude support accurately gated. Prepare versioned release artifacts only after branch review, copy and real policy certification; Paul installs and enables them. |
| +- [ ] **Green and gates:** Repeat targeted tests and guard mutations; run `make migration-check`, `make ci` once after final changes and the contract/namespace release checks required by the settled 2b manifest. Test upgrade of an 0018 fixture with existing active/history data, plus 3a → 3b and idempotent reopen. No live login/provider action occurs without Paul's later explicit authorization. Record remaining unsupported setup paths as such, not passed acceptance. Clean all owned scratch/processes. |
| +- [ ] **Usable acceptance and implementation commit:** Paul follows the supported install/login path, runs the safe recommendation, then a bounded feature through review/checks to a human merge. A teammate repeats with their own accounts. No Plan 4 settlement or CARLOS signal is claimed. Subject: `test: verify onboarding and the complete person API`. |
| + |
| +## Person API v1 contract |
| + |
| +Publish the contract using OpenAPI 3.1.0 with `info.version` set to `1.0.0`; additive response fields are allowed within v1, while changed meanings or required inputs need a new major API version. All resource endpoints below are under `/api/v1`, authenticated as a person, and available on the current instance only. IDs in paths never expand authority. The person-authenticated browser uses the existing secure session and same-origin protection; a native client uses its distinct revocable device bearer. No runner/coordinator credential is accepted. Public challenge creation/exchange is the narrow Task 10 exception with its own proof and throttling. |
| + |
| +GET returns explicit JSON projections and `ETag: "<revision>"`. Resource updates require `If-Match`; create/action requests require `Idempotency-Key` of 1–256 bytes. A duplicate key is checked before stale-revision rejection only after current authorization and exact canonical body comparison, so retry after a lost successful response returns the saved result. New input with a stale revision gets `409 revision_conflict`; missing precondition gets `428`; invalid input `422`; no valid identity `401`; denied current authority `403`; absent/non-visible private resources `404`; expired challenge/cursor `410`; unavailable runner/query `503`. Bodies are capped at 64 KiB, message text at 16 KiB; reject duplicate JSON keys/unknown mutation fields. Lists use opaque scope-bound cursors, limit default 50 and maximum 100. API errors contain stable codes/copy keys; prose is supplied by reviewed copy. Responses with personal data use `Cache-Control: no-store`. |
| + |
| +| Part | Resource and operations | Result / shared operation | |
| +| --- | --- | --- | |
| +| 3a | `GET /me`; `GET /capabilities`; `GET /me/settings`; `PATCH /me/settings` | Person, current team, version/capabilities, typed personal settings and landing preference | |
| +| 3a | `POST /auth/devices`; `POST /auth/devices/exchange`; browser `POST /auth/devices/{id}/approve`; `GET /auth/devices`; `DELETE /auth/devices/{id}` | Person device challenge, proof exchange, explicit approval, own devices/revocation | |
| +| 3a | `GET /conversation`; `POST /conversation/messages` | ConversationPage / SendMessage | |
| +| 3a | `GET /conversation/cards`; `GET /cards/{id}` | Current task, question, proposal or suggestion projection with resource revision | |
| +| 3a | `GET /tasks`; `GET /tasks/{id}`; `POST /tasks`; `POST /tasks/{id}/cancel` | Shared task list/detail; validated explicit task proposal; existing cancellation | |
| +| 3a | `GET /tasks/{id}/thread`; `POST /tasks/{id}/thread/messages`; `POST /conversation/messages/{id}/route` | TaskThread, SendMessage and explicit RouteMessage | |
| +| 3a | `GET /tasks/{id}/plan`; `PATCH /tasks/{id}/plan`; `POST /tasks/{id}/plan/approve`; `POST /tasks/{id}/project` | Current plan, EditPlan, ApprovePlan, CorrectTaskProject | |
| +| 3a | `GET /questions/{id}`; `POST /questions/{id}/answer`; `POST /tasks/{id}/rendered-approval`; `POST /tasks/{id}/acknowledge-merge` | Clarification/native question union, typed answer, person rendered approval and existing human merge acknowledgement; never merge itself | |
| +| 3a | `GET /journey`; `GET /needs-you` | Real planned-step projections and current person's actionable work; nullable counts | |
| +| 3a | `GET /preferences`; `POST /preferences`; `PATCH /preferences/{id}`; `DELETE /preferences/{id}` | Own inferred/confirmed preferences and guarded confirmation/correction/deletion | |
| +| 3b | `GET /teams`; `POST /teams/links`; `PATCH /teams/links/{id}`; `DELETE /teams/links/{id}` | Remembered instance links; no federation access | |
| +| 3b | `GET /accounts`; `POST /accounts`; `GET /projects`; `POST /projects`; `GET /projects/{id}`; `PATCH /projects/{id}` | Existing CARLOS-account labels and project bindings/owners; no CARLOS credential shortcut | |
| +| 3b | `GET /projects/{id}/settings`; `PATCH /projects/{id}/settings`; `PATCH /projects/{id}/my-settings` | Team-owned rules/approval/default playbook versus own approval/connection overrides | |
| +| 3b | `GET /specialists`; `POST /specialists`; `GET /specialists/{id}`; `PATCH /specialists/{id}`; `DELETE /specialists/{id}` | Specialist details/work counts/settings and creator/owner mutations | |
| +| 3b | `GET /playbooks`; `POST /playbooks`; `GET /playbooks/{id}`; `PATCH /playbooks/{id}`; `DELETE /playbooks/{id}` | Playbook definitions and versioned copies | |
| +| 3b | `GET /templates`; `GET /templates/{id}`; `POST /templates/{id}/install`; `GET /specialists/{id}/template-diff`; `GET /playbooks/{id}/template-diff`; `POST /specialists/{id}/template-update`; `POST /playbooks/{id}/template-update` | Version-pinned catalog, install, offered diff and explicit update acceptance | |
| +| 3b | `GET /connections`; `GET /connections/{id}`; `PATCH /connections/{id}`; `DELETE /connections/{id}`; `PUT /projects/{id}/connections` | Own safe metadata/label/revoke/project choices; local credentials never returned or deleted by remote file path | |
| +| 3b | `POST /tasks/{id}/steps/{key}/selection` | ConfirmPlanSelection, reason and immutable actual selection | |
| +| 3a | `GET /coordinator`; `PATCH /coordinator`; `POST /coordinator/reset`; `POST /coordinator/retry`; `PATCH /coordinator/limits` | Own binding/status, explicit connection change at safe boundary, generation reset, retry after containment and owner-only limits | |
| +| 3b | `GET /runners`; `GET /runners/{id}`; `POST /runners/enrol/approve`; `DELETE /runners/{id}` | Own runners, existing pairing approval/revocation; never runner bearer material | |
| +| 3b | `GET /onboarding`; `POST /onboarding/advance`; `POST /account-setups`; `GET /account-setups/{id}`; `DELETE /account-setups/{id}` | Prerequisite state, runner-local login requests and safe challenge status/cancellation | |
| +| 3b | `POST /invites`; `GET /invites/{id}`; `POST /invites/{id}/accept`; `DELETE /invites/{id}` | Owner invite creation/revoke, intended verified recipient's acceptance | |
| +| 3b | `GET /notifications`; `POST /notification-subscriptions`; `DELETE /notification-subscriptions/{id}`; `POST /notification-subscriptions/{id}/ack` | Recipient outbox, per-device subscription and idempotent acknowledgement | |
| + |
| +Task 20 must implement missing thin application operations for API-only lifecycle actions: own connection label/revoke; coordinator reset/retry already belongs to Task 5 and subscription management to Task 19. Add `Store.RenameConnection(ctx context.Context, actor Actor, id, label string, m Mutation) error` and `Store.RevokeConnection(ctx context.Context, actor Actor, id string, m Mutation) error` in `connection_handlers.go`’s application-operation companion `connections.go`. Revocation fences dependent work and requests containment; it does not remotely erase a credential home. They use the same current-member, containment, generation and revision rules already specified; they cannot call a GORM model update directly from a handler. OpenAPI describes the question union (clarification choices/free text versus native permission), exact allowed answer shape and the original request revision. The notification feed is a wake-up hint: answering always uses `/questions/{id}/answer` with person auth and a current revision. Journey cards include specialist category/action/model/account/reason, actual status and nullable usage; no percentage estimate. |
| + |
| +## Copy inventory for the later review pass |
| + |
| +These are keys/meanings to add in `internal/equipo/copy.go`, individually pending. They are not approved strings, and this planning change adds no runtime copy. Existing reviewed labels should be reused where their meaning is unchanged. Template descriptions, installer/runner diagnostics shown to a person and API-guide prose join this review inventory; model-produced messages are attributed task content, never stored as application copy. |
| + |
| +| Owner task | Key groups and meanings | |
| +| --- | --- | |
| +| 1, 9 | `conversation.title`, `.empty`, `.composer`, `.send`, `.queued`, `.offline`, `.routed`, `.thread_link`, `.thread_reply`, `.route_confirmation`, `.private`, `.shared_thread` | |
| +| 2, 9 | `plan.proposed`, `.edit`, `.approve`, `.immediate`, `.required`, `.inherit`, `.locked_step`, `.revision_conflict`, `.project`, `.correct_project`, `.replacement`, `.investigation_checkpoint`, `.playbook`, `.changes` | |
| +| 3, 4 | `evidence.acceptance`, `.frozen`, `.render_approval`, `.sources`, `.answer_delivered`, `.missing_sources`, `.awaiting_person`, `.candidate_changed` | |
| +| 5–7 | `coordinator.connection`, `.unavailable`, `.budget_needed`, `.queued`, `.interrupted`, `.uncertain`, `.retry`, `.reset`, `.identity_changed`, `.policy_changed`; all coordinator MCP tool descriptions/errors | |
| +| 8 | `preferences.title`, `.confirmed`, `.inferred`, `.source`, `.confirm`, `.correct`, `.delete`, `.team_rule`, `.source_unavailable` | |
| +| 9, 10 | `question.choose`, `.reply`, `.expired`, `.answered`, `.superseded`; API validation/auth/revision/cursor errors; device approval/expiry/revoke labels | |
| +| 12 | `specialists.new`, `.name`, `.icon`, `.instructions`, `.models`, `.tools`, `.projects`, `.required`, `.archive`; library group/template names, descriptions, blank template and update-diff actions | |
| +| 13 | `playbooks.title`, `.new`, `.default`, `.kind`, `.steps`, `.used`, `.suggested`, `.save_suggestion`, `.update_available`; four playbook template labels/descriptions | |
| +| 14 | `connections.add`, `.label`, `.remaining_unknown`, `.counted_usage`, `.best_fit`, `.pinned`, `.ask`, `.reason`, `.second_family`, `.selection_changed` | |
| +| 15–17 | `invite.welcome`, `.accept`, `.expired`, `.wrong_person`; all five onboarding stage labels/actions; runner install/pairing/status errors, dedicated-home/device-login/pending/unsupported/cancel messages, hosted-later label, safe-first-task choice | |
| +| 18 | `teams.title`, `.add`, `.forget`, `.remembered`, `.last_signin_unknown`, `.remote_unavailable`; phone parent labels and landing-screen settings | |
| +| 19 | `notifications.question`, `.task_ready`, `.interrupted`, `.superseded`, `.subscribe`, `.unsubscribe`, `.cursor_expired`; no promise of live mobile push delivery | |
| +| 11, 20, 21 | API guide sections and acceptance/setup instructions, reviewed separately from implementation identifiers; README remains untouched | |
| + |
| +## Self-review |
| + |
| +- **Spec coverage:** §§3.1/5.1/6.6 → Tasks 1, 5–8, 10; §§3.4/6.7 → 2, 4; §§4.2–4.4 and 13.4–13.5 → 1, 6, 9; §6.3's complete task-kind table → 3–4; §§6.4–6.5/13.1–13.2 → preserved 2b contracts and 4–7, 17; §7/13.12 → 5, 14, 17; §13.3 → 18; §§13.6–13.7/13.9 → 12–13; §13.8 API/push preparation → 10, 19–20; §§13.10–13.11 supported own-machine onboarding → 15–17, 21. Human project ownership and required approvals remain enforced without implementing Plan 4 coordinator routing. |
| +- **Explicit limits:** Mac containment and a supported Claude device-code flow are not established by the checkout. They are not claimed as working paths. Two questions below decide the acceptable first onboarding surface. Web Teams is a person-maintained links directory, as scoped by the brief, with automatic recording of the current instance only; cross-origin session discovery/count aggregation is not fabricated. CARLOS signals, settlement, other-person task routing, hosted execution, provider cloud agents and native app code stay later. |
| +- **Step scan:** Each task has exact files, produced/consumed contracts, named assertions, red/green commands, independent guard mutations and an implementation-only commit subject. No product function bodies or test bodies are supplied. Thin API lifecycle operations have named owners rather than being assumed to exist. |
| +- **Type consistency:** `Mutation`, `taskplan.Plan/Step/Kind`, coordinator wire structures, explicit person projections and source references have one declared meaning each. Existing `team.Scope`, `Handle`, provider session/turn/admission and runner selection types remain separate. Coordinator attribution does not become `Actor`. Empty evidence predicates are restricted to the read-only/conversation targets, never accepted for publication. The coordinator conversation target uses completion of an admitted turn and durable result delivery, the same no-publication rule as read-work; it does not mark the lifelong conversation finished. |
| +- **Review focus:** Race/revision tests → 2/9/10; uncertain dispatch/tool replay → 5–7; private conversations/preferences/tokens/notifications → 1/8/10/17/19; suggested privilege/predicate changes → 3/6/12–14; setup gaps/unknown data → 16–18. All five review-focus entries have explicit tests in owning tasks. |
| +- **Proportion:** 11 tasks in 3a and 10 in 3b. Each part ends with a usable path, subject to stated upstream live gates. Existing containment, journal, evidence, question and publication machinery is extended rather than replaced. Repeated constraints live in the global section; API endpoints and copy meanings have one inventory each. |
| +- **Planning verification:** Read the complete design, roadmap, named mockups, writing-plans skill and relevant Plan 2b plan/code/report sections. Checked current provider contracts, fixed bug graph, atomic store bridge, live/CSRF v0.30.1 APIs, Amadan readback and empty certification manifest. Ran only local inspection/help and document checks in this planning session. Product tests, provider logins/runs, servers, helper agents, commits and pushes were not performed. Future red/green and certification results are requirements, not results claimed here. |
| + |
| +## Questions for Paul |
| + |
| +1. **May 3b's first own-machine onboarding release support Linux/amd64, with Mac clearly unavailable until a separately designed and certified containment backend exists?** This matches the runner that 2b built. Requiring Mac in 3b adds a platform implementation and its own release gate; an unconfined Mac fallback would violate the chosen design. |
| +2. **If Claude still has no verified supported device-code flow at implementation time, is its supported browser sign-in on the enrolled machine acceptable, while Codex uses device code?** Otherwise keep Claude onboarding unavailable until that provider capability exists. In both cases credentials stay in a dedicated Equipo home on the person's machine. |