oficina / equipo Public

Plan 2 round 1b: unconfined Codex by owner acknowledgement, Rastrillo live, trimmed (Astra)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 5be6d266411e42fcdbf5cddbf98b5059796bda24 parent 2911a91
1 file changed, +254 −345
  • docs/superpowers/plans/2026-11-02-equipo-plan-2-runner.md +254 −345

CI passed — run details

diff --git a/docs/superpowers/plans/2026-11-02-equipo-plan-2-runner.md b/docs/superpowers/plans/2026-11-02-equipo-plan-2-runner.md
index 56726722..1c682d9b 100644
--- a/docs/superpowers/plans/2026-11-02-equipo-plan-2-runner.md
+++ b/docs/superpowers/plans/2026-11-02-equipo-plan-2-runner.md
@@ -1,492 +1,401 @@
-# Equipo Runner Implementation Plan
+# Equipo runner implementation plan
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. This is the future execution method. This planning session authorizes no implementation or agent dispatch.
+> **Future implementation:** use `superpowers:subagent-driven-development` task by task. The R1b planning session does not invoke that workflow or dispatch agents.
-**Goal:** Paul submits a bug through a task form, watches Engineering and Review work, and receives an Amadan review branch with evidence, with cancellation that confirms the work has stopped.
+**Goal:** Paul submits a bug, watches Engineering and Review, receives an Amadan review branch with evidence, and can cancel with verified containment.
-**Architecture:** Keep the instance authoritative for tasks, connections, leases, budgets and evidence. Attach the execution core to the instance's existing activation database, and run a separate Go service on docs-t1 that makes outbound requests and controls local Paseo through a version-pinned Node client adapter. The runner owns repository credentials and the check executor; agents receive neither runner credentials nor permission to publish.
+**Architecture:** The instance owns tasks, connections, leases, budgets and evidence in its activation database. A Go user service on docs-t1 dials out, controls local Paseo through a pinned Node adapter, and owns the check executor and repository credentials.
-**Tech Stack:** Go module `amadan.net/oficina/equipo`, Go floor `1.25.0`, gate toolchain `go1.26.10`, Rastrillo `v0.28.0`, chi, GORM and `modernc.org/sqlite`; Go runner plus `@getpaseo/client`, `@getpaseo/protocol` and `@getpaseo/server` exactly `0.14.0`; Linux user systemd service on docs-t1.
+**Baseline:** Repository HEAD `2911a91`. Implement this plan in order, Task 0 then Tasks 1–18: 19 tasks. Task 0 is the new prerequisite; existing task numbers stay stable. This revision changes only this plan and authorizes no implementation, agents, commits, pushes or deployment.
-**Spec:** `docs/superpowers/specs/2026-11-01-equipo-design.md`, especially §§3.2, 3.4, 6–7 and 9–10; Runner row of `docs/superpowers/plans/2026-11-01-equipo-roadmap.md`; binding corrections in `docs/superpowers/specs/2026-11-01-paseo-probe.md`; `CODEX-BRIEF-plan-2-runner.md`; carries read with `amadan discuss show oficina/equipo 2`.
+**Sources:** `docs/superpowers/specs/2026-11-01-equipo-design.md` §§3.2–3.4, 4, 6–7, 9–10; roadmap Runner row; `2026-11-01-paseo-probe.md`; runner briefs and Round 1 findings in this directory. R1b supersedes R1's Codex prohibition and periodic refresh. Subscription calls mean dispatched Paseo turns, as ruled on 2026-11-02.
-## Global Constraints
+**Stack after Task 0:** Go floor 1.26.0, gate toolchain go1.26.10, Rastrillo v0.30.0, chi, GORM, modernc SQLite. Paseo client/protocol/server 0.14.0; Node v24.19.0; Claude Code 2.1.312; Codex CLI 0.165.0. Changed runtime versions require renewed capability verification.
-- “Paseo runs the agents.” `equipo-runner` is a “small Go binary, a user service under systemd or launchd, no root, no inbound ports”. This means no TCP or inet listener; Task 13 uses a private per-attempt Unix socket. This plan implements Linux/systemd on docs-t1; tito-studio and launchd are outside the acceptance gate.
-- “Connections belong to people, not the team.” Every task uses its requester's explicitly enabled connections on their enrolled machines. No subscription credentials reach the instance.
-- “Review always a different family from the builder.” Distinct sessions and producer identities are also required. Unknown family cannot establish independence.
-- “Equipo never merges and never pushes the default branch.” Push only the bound review branch, using a disclosed Amadan agent account held by the runner.
-- “A changed candidate invalidates checks and review.” Bugs require frozen reproduction failing on base, passing on candidate, repository checks, independent review and publication of that candidate.
-- “Uncertain external actions stay unknown and charged.” Cancel, restart, a missing event and quarantine release cannot manufacture receipts or refunds.
-- “Three steps cannot be removed”: independent review, checks and the person at the end. This plan has a fixed bug plan and no plan editor.
-- “Subscriptions are first-class connections.” Record measured usage and enforce admission, turn, attempt and time limits; do not present subscription tokens or currency as a provider-enforced cap. The controller has approved counting subscription calls as dispatched Paseo turns; the technical live gates still apply.
-- “No split screen”; phone navigation uses index screens and parent links. Keep the existing day/sidebar shell, token colors, byte-identical vendored assets and scriptless forms. No coloured left-border accents.
-- “Copy for every user-facing string goes through copy review before it ships.” App-owned runtime strings, including runner diagnostics, live only in `internal/equipo/copy.go`. Mark each pending entry `COPY REVIEW REQUIRED`; review before release. This plan specifies copy keys and meaning, not final wording. Leave README prose unchanged.
-- Current roster checks and audit writes belong inside each app write transaction. Derive browser `Actor` from the verified session; runner actor identity comes from its credential. Never bind requests onto GORM models or use `scope.Owned` for team records.
-- Preserve `EQUIPO_ORIGIN`, `EQUIPO_INSTANCE_KEY`, SMTP requirements and first-boot-only owners. App tables belong in `Models`/`Schema`; framework tables remain in `BootSchema` only. Migrations are additive.
-- Builds use `CGO_ENABLED=0`; leave Go caches at their defaults. Use on-disk `$TMPDIR`, bind test servers to `127.0.0.1`, stop processes and remove owned scratch. No sudo.
-- `make ci` remains the shared gate and `.amadan/ci*` delegates to Make. No automatic merge, default-branch push or deployment. Commits below are future implementation steps, with subjects under 80 characters.
+## Constraints and task conventions
-## Review Focus
+- Paseo runs agents. The runner has no TCP/inet listener; tools use private per-attempt Unix sockets. Linux/systemd on docs-t1 only; no launchd or tito-studio gate.
+- Connections belong to people. Use the requester's explicitly enabled connections and enrolled machine. Both families must be available on that same runner before spending. Review needs a different known family, producer and session.
+- Publish only the saved review branch through a disclosed Amadan agent account. Never merge, deploy or push the default branch. A changed candidate invalidates checks and review. Success delivers a verified branch; the app then waits for the named person's merge acknowledgement, attributed to that person rather than forge verification.
+- Unknown outcomes stay unknown and charged. Cancellation, restart, missing events and quarantine release cannot create receipts or refunds. Subscription reservations are accounting limits, not provider-enforced token/currency ceilings.
+- Preserve the day/sidebar shell, token colors, phone indexes/back links, scriptless forms, and byte-identical framework assets. No split screen, initials, progress percentages or coloured left-border accents.
+- Runtime strings, including runner diagnostics, belong only in `internal/equipo/copy.go`. Mark each draft `COPY REVIEW REQUIRED`; review and apply edits verbatim before release. This plan specifies keys/meaning, not final copy. Leave README unchanged. Use plain words without em dashes or exclamation marks.
+- Browser Actor comes from verified sessions; runner identity comes from its credential. Check the current roster and append audit inside each write transaction. Use its transaction handle throughout. No request-to-GORM binding or `scope.Owned` for shared records.
+- Keep origin/key/SMTP requirements and first-boot-only owners. App tables belong in `Models`/`Schema`, framework tables only in `BootSchema`. Migrations are additive. Preserve one activation database and Foundation's closed execution default until Task 17.
+- Builds use `CGO_ENABLED=0`. Keep default Go caches; scratch under on-disk `$TMPDIR`; servers bind `127.0.0.1`. No sudo. Remove owned scratch and stop test processes.
+- `make ci` is the common local/CI gate; `.amadan/ci*` delegates to Make. No ordinary test starts providers/Paseo agents or pushes to Amadan. Live gates require explicit opt-in.
+- Each task follows **red → implement → green → guard mutations → commit**. Add every named new test before implementation, including names introduced in implementation/gate paragraphs. Record commands/results in the controller report. Missing symbols can establish red; after green, bypass each guard independently, observe its assertion fail, then restore. Stage only task files; future commit subjects below are under 80 characters. This planning session makes no commits.
+- Interfaces below omit repeated `ctx context.Context` from method listings; every operation accepts it first. IDs are opaque except existing core types. Wire version 1 uses strict snake_case JSON, UTC timestamps and integer-second durations. UI errors are copy-key enums. Test fakes require explicit injection; production constructors reject missing real dependencies.
-1. A reply lost after agent creation, push or task submission must not duplicate effects. Tasks 7, 12 and 14 test crash boundaries and replay conflicts.
-2. A runner token, old cookie or delayed answer from the wrong person/machine must not authorize work after removal or reassignment. Tasks 5, 8 and 13 test these with successful controls.
-3. Clock rollback, machine sleep and process-ID reuse must not keep a lease alive or produce a false stop acknowledgement. Tasks 2 and 15 test each condition.
-4. A reconnect that replaces history, repeats cumulative usage or omits completion must not undercharge or declare success. Task 12 tests all three, including unknown usage.
-5. A candidate that edits check scripts, deletes tests, or changes after review must not pass the trusted evidence gate. Tasks 4, 10 and 11 test these independently.
+Plan 2 excludes cross-machine bundles/chunking, enrolment-response recovery, Journey pagination, owner provider/family allowlists (plan 4), best-fit reasoning, ask-each-time selection, coordinators, preferences, settlement, plan editing, product ranking, CARLOS signals, features and copy/design tasks. Project/account deletion stays absent; ASCII uniqueness and existing non-ASCII lower-case behavior stay unchanged. Labels never confer identity or authority.
----
+## Read isolation and Paul's ruling
-## Grounding, decisions and boundaries
+`ReadIsolation` remains a measured preflight capability per provider/version, permission mode, credential home and effective configuration hash. Canonical denied paths cover runner state/config/journal/bearer/cleanup files, the configured Amadan credential, actual Paseo and routed provider credential homes, `~/.ssh`, and resolved symlink targets. Reject workspaces inside those subtrees. Revalidate before creation and every turn; changed mode/home/routing/policy invalidates preflight. Permission answers cannot relax the trusted policy.
-Round 1 revision grounded at repository HEAD `a66c96e`, branch `plan-2`, with a clean worktree before this revision. The earlier plan was grounded at `5954de4`; the findings reviewed `6d88d2b`. The brief's `e5c58ab` is ancestry, not a reason to reset HEAD. Plan 1, its controller brief and discussion 2 are historical inputs; their push/reviewer instructions do not override this planning brief.
+Installed-source findings from Round 1: `@getpaseo/{client,protocol,server}` 0.14.0; provider options/agents under the installed CLI's `node_modules/@getpaseo/server/dist/server/server/agent/providers/`. These are inspection references, never runtime imports.
-| Existing code | Plan decision |
+| Provider | Capability and dispatch decision |
|---|---|
-| `cmd/equipo/main.go`, `app.go`, `db.DB.Writer()` in pinned Rastrillo | Preserve one activation database. Add a borrowed-pool core constructor, not an unreplicated second SQLite file. |
-| `team.Open`, `Status`, `Resume`, `.incarnation` and `.lock` | Preserve witness/lock behavior. Implement audited quarantine release before production attaches the core. A missing witness pauses admission, including after hibernation that loses local files. |
-| `JobSpec.Project`, `GrantRef`, `RosterAuthority.Introspect` | Derive project, requester and grant together. Extend `AdmissionRequest` with `Project` so the core can verify the binding at every admission. |
-| `Claim`, `Renew`, `Complete`, `Release`, `Contain` | Keep these APIs. Add an explicit supervisor stop transition for clock rollback; do not weaken `Contain` to accept an active lease. |
-| `Intend`, `Admit`, `Record`, `Lost`, `Reconcile` | Instance records/admit actions; runner executes them. Instance adapters reconcile from durable runner observations and never connect inbound to a machine. |
-| `Artifact.Hash`, `CheckResult.SubjectHash`, publication `head` | Artifact hash is SHA-256 of bytes, not a Git object ID. Add a typed Git candidate payload and retain both identities through evidence and publication. |
-| `evaluateSoftwareFix`, `RequireDistinctReviewProvider` | Add separate repository-check evidence and explicit model-family independence without weakening legacy fixture policies. |
-| `periodSum`, `Admit` | Index open/current-month rows; preserve checked arithmetic. Lower limits block even previously reserved, undispatched actions. Already dispatched actions remain charged and are contained when limits are exceeded. |
-| Probe and installed client package metadata | Pin the public client packages to `0.14.0`; do not import the probe's absolute CLI-internal path. SDK behavior still needs contract tests, especially Codex, recovery, account routing and cleanup. |
-| `handlers.go`, templates and mockups | Replace empty Journey/Connections and specialist activity with real reads. Borrow task cards from Conversation without building a coordinator or chat. |
+| Claude Code 2.1.312 | `ClaudeProviderOptionsSchema` and `buildOptions` support sandbox `filesystem.denyRead`, `failIfUnavailable` and permission deny rules. Use `modeId: "default"`, enabled filesystem sandbox, no excluded commands, `allowUnsandboxedCommands: false`, absolute built-in `Read(...)` denies. Keep `ReadIsolation=false` until Task 18 proves every sentinel and policy-tampering assertion. Claude must remain confined; no acknowledgement bypass. |
+| Codex CLI 0.165.0 / Paseo 0.14.0 | Legacy read-only/workspace-write modes do not deny protected reads. Command-only probes read an outside sentinel even with `sandbox_permissions=[]`; an explicit named filesystem deny profile blocked it while permitting the workspace control. Paseo's strict schema rejects the needed profile fields and maps legacy turn policies. Report `ReadIsolation=false`, reason `unsupported_per_agent_profile`. Paul permits this connection to run unconfined under the acknowledgement below. Do not report confinement, modify shared provider homes, invent passthrough fields or bypass Paseo. |
-Plan 2 includes personal connection selection. The controller moves the owner provider/family allowlist to plan 4; the different-family review rule stays mandatory. Selection is pinned, otherwise first eligible connection ordered by connection ID; fixed specialist model settings further filter eligibility. Both model families must be eligible on the same docs-t1 runner; otherwise the task waits before any provider turn. Cross-machine Git bundles, chunked blobs, lost-enrolment-response recovery, EventSource refresh and Journey pagination are cut from this plan. It does not build best-fit reasoning, ask-each-time policy, coordinators, preferences, plan editing, owner-routing conversations, product ranking, CARLOS signals, features or copy/design tasks.
+**Paul's ruling, 2026-11-02:** for his own repositories, Codex may run without read isolation for now, clearly labelled. A **current team owner** must explicitly acknowledge each unconfined connection. Personal connection opt-in remains separate. No acknowledgement means no creation or dispatch. This exception changes only read-isolation eligibility; account pinning, identity, timeline, process ownership and every other gate still apply.
-Keep project/account deletion absent. Task 6 pins this carry with `TestProjectAccountNoDeleteAndASCIILabels`: DELETE routes do not succeed, records/audit remain unchanged, ASCII case duplicates conflict, and existing non-ASCII lower-case behavior stays unchanged. Revoking a machine or disabling a connection is necessary and included; deleting projects/accounts is not. Preserve existing ASCII label uniqueness and IDs; labels are never identity or authority.
+Task 6 persists `IsolationAcknowledgement{ID, ConnectionID, Owner, Provider, ProviderVersion, PaseoVersion, IsolationConfigHash string; AcknowledgedAt time.Time; ConnectionRevision int64}` and its audit in the owner transaction. No bulk or label-based acknowledgement; submitted owner/time/version fields cannot establish authority. Bind to trusted observed versions and connection identity. Revoke by owner action; provider identity/version or Paseo version changes automatically lapse it. A changed effective configuration/security revision also requires fresh preflight and acknowledgement; heartbeat/LastSeen updates do not change that revision. Recheck at assignment, claim, create and each turn/admission; version change fences pending work and contains affected running attempts before reuse. Never grandfather stale approvals.
-Execution success means verified branch delivered. The app task then waits for the named merge owner with an Amadan link. It never claims the branch was merged or the app deployed. The human step stays visible and incomplete until a person records completion; that record is attributed as a person's acknowledgement, not forge verification.
+Snapshot `IsolationStatus` (`confined` or `unconfined`), acknowledgement ID and observed versions/config into each selection, attempt, step and evidence provenance. The runner derives these from the authorized assignment and observed session, never tool-submitted JSON. Persist the historical label even after acknowledgement expiry or later confinement. Executor evidence retains its own confined executor identity and the unconfined source-candidate/step lineage. Missing or stripped provenance fails registration/publication. Display literal `unconfined` on every affected task card, Journey chip, task detail/evidence entry and published review branch description. Mixed runs retain per-step labels and a task/publication summary if any contributing step was unconfined.
-## Read isolation and installed-provider findings
+Unconfined workspaces/environments still contain no injected credentials; hooks/helpers stay disabled, checks use the trusted confined executor, publication uses the runner-held credential, and Review uses another family. Unconfined means host read denial is unproven: do not claim that filesystem secrets or the tool capability file are unreadable by that agent. The fixed Equipo MCP helper is the sole approved helper; typed tool, lease and fence restrictions remain enforced. Claude's shell sandbox plus built-in denies must protect every path; arbitrary hooks/plugins/MCP helpers and unsandboxed retries remain forbidden.
-Inspected on docs-t1 at `a66c96e`: Paseo client/protocol/server 0.14.0, Claude Code 2.1.312, Codex CLI 0.165.0 and Node v24.19.0. Package evidence is under `/home/paulca/.local/lib/node_modules/@getpaseo/cli/node_modules/`: `@getpaseo/client/dist/{daemon-client,index}.d.ts`, `@getpaseo/server/dist/server/server/agent/providers/claude/{options,agent}.js`, and `providers/{codex/options,codex-app-server-agent}.js`. These paths are inspection references, never runtime imports.
+**Restore confinement:** Task 9 owns the future supported per-agent Codex profile adapter. When Paseo ships it, remove that version's exception eligibility, construct the deny profile through its supported API, observe effective policy, and run Tasks 10/18 sentinel tests. The Paseo version change already lapses old acknowledgements. Require `ReadIsolation=true` before re-enabling Codex once the supported profile contract exists; retain historical unconfined labels. No global skip or permanent bypass flag.
-`ReadIsolation` is mandatory for each provider, permission mode, credential home and effective configuration hash. Tasks 9/10 build the denied-path set from canonical runner state, the configured Amadan credential, the actual Paseo daemon/account credential locations (including managed provider homes), and `~/.ssh`. Protect configuration, journals, bearer/cleanup files and resolved symlink targets too. A worktree located under the Paseo home does not justify reopening credential directories. Reject a workspace inside any denied subtree. Revalidate before creation and every turn; changing mode, home, plugin routing or policy invalidates the preflight result. Permission answers cannot override these denials.
+## Storage and dependencies
-| Provider | Finding and eligibility |
-|---|---|
-| Claude Code 2.1.312 through Paseo 0.14.0 | Supported configuration surface, not yet live-proven. `ClaudeProviderOptionsSchema` accepts `settings.sandbox.filesystem.denyRead`, `failIfUnavailable` and strict sandbox settings, and `settings.permissions.deny`. `buildOptions` forwards those settings. Choose `modeId: "default"`; set `settings.sandbox` to enabled, fail-if-unavailable, filesystem enabled, no excluded commands and `allowUnsandboxedCommands: false`. Set `denyRead` to all protected paths and matching absolute `Read(...)` deny rules for built-in file access. No bypass mode, unsandboxed retry, unreviewed hooks/plugins/MCP servers or policy-changing permission responses. Keep `ReadIsolation=false` until Task 18 passes every sentinel and policy-tampering test for this exact configuration. |
-| Codex CLI 0.165.0 through Paseo 0.14.0 | **Ineligible on the installed adapter.** `-s` offers `read-only`, `workspace-write`, `danger-full-access`; none is a deny-read path declaration. The installed `codex sandbox -P :read-only` and `-P :workspace` both read a task-owned sentinel outside the workspace, both with `sandbox_permissions` omitted and with `-c 'sandbox_permissions=[]'`. Omitting `disk-full-read-access` therefore does not establish read confinement. A named profile with an explicit filesystem `deny` did block that sentinel while a workspace control remained readable. However, Paseo's strict `CodexProviderOptionsSchema` rejects both `sandbox_permissions` and `default_permissions`/`permissions`; its turn policy maps the legacy modes. Plan 2 does not invent a passthrough, edit shared provider homes, or bypass Paseo. Require a supported per-agent profile interface, effective-policy observation and the sentinel gate before making Codex eligible. |
-
-Claude's sandbox covers shell commands; built-in file tools use permission rules, and hooks/MCP/helper processes can run outside it. The trusted Equipo MCP executable is deliberately outside the agent command sandbox so it can read its scoped capability file. Only that fixed executable/configuration is accepted. See [https://code.claude.com/docs/en/sandboxing](https://code.claude.com/docs/en/sandboxing) and [https://code.claude.com/docs/en/settings-reference](https://code.claude.com/docs/en/settings-reference). Codex documents explicit filesystem `deny` entries in named profiles at [https://learn.chatgpt.com/docs/permissions](https://learn.chatgpt.com/docs/permissions); that CLI capability alone does not supply Paseo's missing per-agent contract.
-
-Local verification ran no agents or provider calls. `codex --version`, `codex --help`, `codex sandbox --help`, `claude --version` and `claude --help` established versions/options. Node `safeParse` accepted the Claude settings and legacy Codex mode, but rejected the Codex read-profile fields. For the command-only Codex probes, `codex sandbox -P <profile> -C <scratch/workspace> [-c 'sandbox_permissions=[]'] -- /bin/cat <scratch/outside/sentinel>` exited 0 under both built-ins. A custom profile extending `:workspace` with `<scratch/outside> = "deny"` exited 1 with permission denied; reading `<scratch/workspace/control>` exited 0. The profile was passed as one TOML `permissions={...}` override to avoid dotted path parsing. Preliminary probes without `-P`, or with `--strict-config` (unsupported by `sandbox`), failed at argument validation and are not isolation evidence. All probe files were under `$TMPDIR` and removed.
+App paths below are relative to `internal/equipo`; core paths to `internal/equipo/team`. Shared DTOs live in `internal/runnerproto/{types,validate}.go`; SDK types stay in `internal/runner/paseo`. Core scope uses persisted Team.ID, not CARLOS account labels.
-This means the current Claude/Codex pair cannot pass live acceptance now. Keep the different-family requirement and zero-dispatch wait. The subscription-turn ruling is settled; upstream Codex support and live proof are technical blockers, not new questions for Paul.
+Keep standalone core migrations for fixtures; mirror their exact tables/indexes/defaults/foreign keys in app SQL and private GORM models. At every bump update `team.SchemaVersion`, standalone ordered migrations, app migration and `migrations/schema.sql` together. `TestExecutionSchemaParity` covers fresh databases, every supported upgrade, preserved data, newer-version refusal and two no-op reopens. Never stamp legacy state directly to the newest version.
-## File map and shared conventions
+| Task | App migration | Core version/change |
+|---|---|---|
+| 1 | `0007_execution.sql` | Mirror version 3 |
+| 2 | `0008_recovery.sql` | 3 → 4: recovery generation, clock high-water, stale grants, recovery charges |
+| 3 | `0009_runner_policy.sql` | 4 → 5: reservation period/project indexes |
+| 5 | `0010_runners.sql` | Enrolment/credentials |
+| 6 | `0011_connections.sql` | Personal choices and isolation acknowledgements |
+| 7 | `0012_tasks.sql` | 5 → 6: job request key/hash |
+| 8 | `0013_runner_assignments.sql` | 6 → 7: atomic admission request/ticket |
+| 11–13 | `0014_artifact_blobs.sql`, `0015_runner_events.sql`, `0016_questions.sql` | Blob/event/question projections |
-| Area | Files and responsibility |
-|---|---|
-| Shared database and recovery | `internal/equipo/team/shared.go`, `recovery_release.go`, `stop.go`; app `execution.go`, `execution_models.go`, `recovery.go`; existing core store/recovery/scheduler files. |
-| Policy/evidence | Core `policy.go`, `budget.go`, `periodbudget.go`, `model.go`, `evidence.go`, `actions.go`, new `git_evidence.go`; ordered core migrations advance to version 7. |
-| Instance records and endpoints | App `runners.go`, `enrolment.go`, `connections.go`, `tasks.go`, `task_prepare.go`, `runner_api.go`, `runner_events.go`, `questions.go`, `task_views.go`, `task_handlers.go`. |
-| Wire contract | `internal/runnerproto/{types,validate}.go`: versioned request/response types shared by instance and runner, no database or provider access. |
-| Runner | `cmd/equipo-runner/main.go`; `internal/runner/{config,client,journal,service,supervisor,process_linux,events,usage,questions,connections,tools,tool_socket}.go`. |
-| Local boundaries | `internal/runner/paseo/{client,types}.go`; `runner/paseo/{package.json,package-lock.json,bridge.mjs,bridge.test.mjs}`; `internal/runner/workspace/workspace.go`, `internal/runner/checks/{executor,definition,goresults}.go`, `internal/runner/forge/forge.go`. |
-| UI/package | App templates `tasks.html`, `task.html`, `task_form.html`, `connections.html`, `enrol.html`, `recovery.html`, shared `task_card.html`; existing specialist/chrome/index/project templates, `copy.go`, `equipo.css`; `packaging/equipo-runner.service`, Makefile and matching CI wrappers. |
-
-Each task lists its tests and migrations. Every new test named in an implementation step must be added to that task's red/green selection before implementation, not merely left for the full CI run. App migration numbers start after `0006_account_label.sql`; update `migrations/schema.sql` with every addition. New app tables use the existing model inventory. Shared core tables also get exact GORM schema mirrors, not business logic in GORM. Keep the standalone core migrator for its existing fixture/tests and compare its result to the app migration in Task 1 and at every later core version bump.
+JSON-only policy/evidence extensions need no columns. Task 6 builds instance selection; runner discovery waits for 17. Task 7 tests preparation DTOs/outbox/graph with a fake, without HTTP or workspace calls. Task 8 uses seeded assignments, real admissions and fake validators. Task 15 connects preparation to Tasks 8/10/11 and installs real artifact/question validators. Task 17 attaches production execution after recovery/supervision exist. Task 16 supplies a post-commit notifier to earlier write paths; nil notifier during earlier tasks preserves that dependency order.
-Core migration ownership is explicit: Task 1 mirrors version 3; Task 2 adds recovery generation, clock high-water state, per-job authority staleness and recovery charges, advancing 3 → 4 in `0008_recovery.sql`; Task 3 adds indexed reservation period/project fields, advancing 4 → 5 in `0009_runner_policy.sql`; Task 7 adds job request-key/hash fields, advancing 5 → 6 in `0012_tasks.sql`; Task 8 adds durable admission request identity/tickets, advancing 6 → 7 in `0013_runner_assignments.sql`. Each owner updates `team.SchemaVersion`, the ordered standalone migrator, app SQL and schema mirrors together. JSON-only evidence/policy additions in Tasks 4/7 need no separate columns. Never stamp a legacy database straight to the newest version: apply each missing step in order. At each bump run `TestExecutionSchemaParity` against the current constant, fresh creation and every supported upgrade path, then reopen twice and assert no repeated changes; preserve data and refuse newer versions.
+### Task 0: Upgrade Foundation to Rastrillo v0.30.0
-Dependency split: execute Tasks 1–18 in numbered order. Task 6 implements instance selection/report validation only; its runner discovery and account-home wiring move to Task 17 after Tasks 9/15 exist. Task 7 owns durable tasks, preparation DTOs and a pure fixed-graph builder tested with a fake preparation source; it does not call HTTP or Task 10. Task 8 tests route authority with seeded assignments, real core admissions and fake result validators; it does not import Tasks 11–13. Task 15 wires the preparation outbox to Tasks 8/10 and replaces those validators with Tasks 11–13, including the deferred crash and integration tests. Task 17 wires discovery and startup. Test fakes must be explicitly injected; production constructors reject missing real dependencies.
+**Files:** `go.mod`, `go.sum`, app locale-pack import, `static/`, `templates/layout.html`, `internal/equipotest/browser_test.go`, compatibility tests; Makefile/CI only if needed to retain the existing gates. No Foundation behavior expansion.
-New JSON uses protocol version `1`, snake_case fields and strict decoding. IDs are opaque strings except existing typed core IDs. Times are UTC; durations cross the wire as integer seconds. New UI codes are enums mapped through `copy.go`, never raw internal errors. Every test step below gives names and assertions; snippets are assertions inside those named tests, not implementation bodies.
+Checked against local tag `v0.30.0` in `/home/paulca/amadan.net/rastrillo/rastrillo`, including `go.mod`, `serve.go`, `auth/{auth,handlers,signin}.go`, `pow`, `sessions`, `migrate`, `ui/{funcs,ui,vendored}.go`, `harness`, `budget`, `db`, `dbtest`, `csrf`, `mail`, `background`, `perf`, and `docs/site/{live,reference/live}.md`:
-For every task: record red command/result, green command/result and guard-mutation result in the controller's report. A missing-symbol failure starts the test cycle but does not prove a guard: after green, temporarily bypass each security/evidence guard, observe its named assertion fail, and restore it. Stage only the task's named files before its commit. No tests in ordinary CI invoke live providers, push to Amadan or start Paseo agents.
+| Foundation use | Required upgrade work |
+|---|---|
+| Module/toolchain | Raise `go 1.25.0` to `1.26.0`; require Rastrillo v0.30.0 and tidy its dependency graph. Existing Make `GOTOOLCHAIN=go1.26.10` already meets the floor; retain it. Keep the Rastrillo CLI tool directive. |
+| `Resolve`, `Options`, `Serve`, `Handler`, assets | Existing activation/Mux/Wrap/ErrorPage/Background APIs remain. `Handler` now checks locale packs even for default English: blank-import `amadan.net/rastrillo/rastrillo/locales/en` in the app package so production and test binaries link it. Preserve one DB, clear `opts.DBPath`, close on failure/shutdown. Later set `Options.Live`. |
+| `auth.New/Config`, handlers, `From`, `RequireSession`, `SigninState`, `PrepareSigninResponse`, `Sweep` | Existing database mode and fields remain supported. Keep DB/Origin/InstanceKey/Proof, roster `Authorize`, `SubjectFor`, confirmation renderer and paths. Do not switch to new records/signed-session mode. Recheck email/keymail, replay, signout and removed-member tests; v0.30.0 also preserves safe posted return_to through sign-in, with SignedInPath as fallback. |
+| `pow.New/Config`, `SQLNonces`, `NonceStore`, `NoProof`, `DefaultMinAge`, `Schema` | No caller changes. New record nonces and `Form.At` are additive; keep SQL nonces, scriptless NoProof and minimum-age checks. |
+| `sessions.Schema`, `HashToken`, auth-managed SQL sessions | No signature/schema changes needed. New signed mode is optional. Row sessions now refuse path-routed tenants: keep this lone-instance origin, no BasePath adoption or auth bypass. |
+| `migrate.MustFromFS`, `Merge`, `Apply`, `Set`; `dbtest.FromSet` | Existing calls/sets remain. New schema introspection excludes `_litestream_*`; retain app/framework inventory separation and migration idempotence. No rewritten historical migration. |
+| `db.Open`, `.G`, `.Writer()`, `.Close()` | Compatible; writer still has `SetMaxOpenConns(1)` and no `_txlock=immediate`. Keep Task 1's pool guard. |
+| `ui.Funcs(WithIcons)`, `Templates`, `Layout("stage")`, `VendoredAssets("day")` | Compatible, including legacy `T "key"` and nil localizer. Keep current template map; no required `ui.Pages` migration. Replace all vendored assets from this tag byte-for-byte, including new `live.js`, `light.js`, `anchor.js`. Link `live.js` after `busy.js` in the app layout; stage now references the new assets. Preserve app CSS in `equipo.css`. |
+| Browser harness/chromedp | `harness.New`, `WithScrollbars`, `Screen` remain. `Rig.Run` now takes `chromedp.Action[chromedp.Void]`; dependency graph uses chromedp v0.21.0/cdproto v0.158.6. Port `Evaluate`/Location/screenshots to typed `harness.Evaluate[T]`, `Read` or `Into`; selectors to `chromedp.CSS`; custom `ActionFunc`/`.Do(ctx)` helpers to `chromedp.Func(func(ctx, target) error)` and typed actions/`cdp.Call`. Port CDP cookie, media and script-disable calls to command constants with params. Preserve navigation waits, assertions and scripts-off coverage. |
+| `budget.Main`, CLI budget size/test; `perf.Middleware`, `perftest`; mail/background/CSRF | Budget, performance, mail and background APIs used here are unchanged. `csrf.Protect(origin, ...Option)` remains compatible with existing calls; no new exemptions for browser forms. Keep all Make gates and TestMain budgets. |
+
+- [ ] **Red:** Add `TestRastrilloUpgradeContract` checking linked version/floor, default-English Handler boot and static assets including live.js. Run `go test ./internal/equipotest -run 'TestRastrilloUpgradeContract|TestVendoredAssetsMatchTheLibrary' -count=1`; the upgrade assertion fails on v0.28.0. Retain the existing Foundation suite as regression coverage.
+- [ ] **Implement:** `go mod edit -go=1.26.0`; `GOTOOLCHAIN=go1.26.10 go get amadan.net/rastrillo/rastrillo@v0.30.0`; `GOTOOLCHAIN=go1.26.10 go mod tidy`. Apply the table's locale/assets/browser changes, inspecting dependency diff. Use `ui.VendoredAssets("day")` as the authoritative copy set; do not broadly rewrite app files with doctor.
+- [ ] **Green:** Repeat red; run Foundation's full `make ci`, plus `go test -tags browser ./internal/equipotest -run TestFoundationBrowserWalk -count=1` and the same with `EQUIPO_BROWSER_NO_JS=1`. Both widths 1280/390 remain covered. Check normal motion separately; record any reproducible framework transition issue rather than hiding it. Removing the locale import, changing a vendored byte or dropping the live asset must fail the relevant assertion. Do not weaken tests/budgets to accommodate the upgrade.
+- [ ] **Commit:** `build: upgrade Foundation to Rastrillo v0.30.0`.
### Task 1: Put execution state in the activation database
-**Files:** Create `internal/equipo/team/shared.go`, `internal/equipo/execution_models.go`, `internal/equipo/migrations/0007_execution.sql`, `internal/equipotest/execution_schema_test.go`, `internal/equipo/team/shared_test.go`; modify `team/store.go`, app `store.go`, `models.go`, `migrations/schema.sql`; create the transaction wrapper in `internal/equipo/execution.go` (expanded in Task 8).
+**Files:** Core `shared.go`, `shared_test.go`, `store.go`; app `execution.go`, `execution_models.go`, `store.go`, `models.go`; migration 0007; `internal/equipotest/execution_schema_test.go`.
-**Interfaces:** Add `team.OpenShared(ctx context.Context, writer *sql.DB, path string, o team.Options) (*team.Store, error)`. It borrows `db.DB.Writer()`, owns neither pool nor app migrations, and verifies core schema version before `start`. `Close` records the witness but closes SQL only for stores opened by existing `team.Open`. Produce app-private schema mirrors for the existing `service`, `jobs`, `steps`, `attempts`, `reservations`, `actions`, `events`, `artifacts`, `period_budgets`, `time_reservations` tables and indexes. Keep existing names: none collide with Foundation tables. Add `(*team.Store).WithTransaction(ctx context.Context, fn func(*sql.Tx) error) error` using the existing witnessed transaction path. App `(*Execution).Write(ctx context.Context, fn func(*gorm.DB) error) error` binds a fresh GORM session to that SQL transaction, preserving the writer resolver and disabling nested transaction creation. When execution is attached, `Store.write` delegates to this wrapper. Never modify core rows in an ordinary app transaction outside its lock/witness protocol.
+**Interfaces:** `team.OpenShared(ctx, writer *sql.DB, path string, o Options) (*Store, error)` borrows the writer without owning migrations/pool; checks schema before start. `Close` writes the witness but closes SQL only for standalone `Open`. Mirror existing `service`, `jobs`, `steps`, `attempts`, `reservations`, `actions`, `events`, `artifacts`, `period_budgets`, `time_reservations` names. `Store.WithTransaction(ctx, fn func(*sql.Tx) error) error` uses the witnessed transaction path. `Execution.Write(ctx, fn func(*gorm.DB) error) error` binds a fresh GORM session to that SQL transaction, preserves writer resolution and disables nested transaction creation. Attached `Store.write` delegates there.
-- [ ] **Step 1: Add `TestExecutionSharedPool`, `TestExecutionSchemaParity` and `TestExecutionBackupIncludesArtifacts`.** Apply `BootSchema` twice, attach the core, write through both stores, close core and prove the app pool remains usable. Compare columns, defaults, indexes and foreign keys with standalone `team.SchemaVersion` (3 in this task, advanced by the owning tasks below). A combined app/core write and its audit roll back together; a crash after SQL commit but before witness publication has the existing recoverable-gap behavior. Assert no nested pool acquisition while the shared writer is held. A SQLite backup of the activation database includes jobs, reproduction bytes and app records. Assert `len(second.Applied) == 0` and `writer.Ping() == nil` after core close.
- ```go
- if err := writer.Ping(); err != nil { t.Fatal("core closed the borrowed pool") }
- if len(second.Applied) != 0 { t.Fatal("execution migration repeated") }
- ```
-
-- [ ] **Step 2: Run red.** `go test ./internal/equipo/team ./internal/equipotest -run 'TestExecution' -count=1`; expect missing `OpenShared`/execution tables.
-- [ ] **Step 3: Implement borrowed ownership and additive schema mirrors.** Do not call the core's standalone migrations on the production pool. Preserve lock ordering, external witness writes and commit-failure poisoning. The Rastrillo writer DSN lacks `_txlock=immediate`; this design is safe only with its existing `SetMaxOpenConns(1)` and serialized witnessed writes. Assert `writer.Stats().MaxOpenConnections == 1` and refuse attachment otherwise; never expand the pool without revisiting locking. All core transactions close rows before nested queries. No production startup wiring yet.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`; expect PASS and no drift. Re-run `TestCommit`/`TestRecovery` tests selected from the existing core suite after changing pool ownership.
-- [ ] **Step 5: Commit.** `git commit -m "feat: attach execution storage to the activation database"`.
+- [ ] **Tests:** `TestExecutionSharedPool`, `TestExecutionSchemaParity`, `TestExecutionBackupIncludesArtifacts`: apply BootSchema twice, use both stores, close core and still ping app writer. App/core/audit roll back together; crash between SQL commit and witness publication retains recoverable-gap behavior. No nested pool acquisition; backup includes jobs, reproduction bytes and app records. Second migration applies nothing.
+- [ ] **Red/green:** `go test ./internal/equipo/team ./internal/equipotest -run 'TestExecution' -count=1`; green also `make migration-check` and existing `TestCommit|TestRecovery` core tests.
+- [ ] **Implement:** Preserve lock ordering, witness writes and commit-failure poisoning; never run standalone migrations on production. Refuse writer pools whose `Stats().MaxOpenConnections != 1`; close rows before nested queries. No ordinary GORM transaction may bypass core locking/witnesses. Production attachment waits for Task 17.
+- [ ] **Commit:** `feat: attach execution storage to the activation database`.
### Task 2: Release quarantine and handle stale authority safely
-**Files:** Create core `recovery_release.go`, `stop.go`, their `_test.go` files; app `recovery.go`, `internal/equipotest/recovery_test.go`; modify core `authority.go`, `jobs.go`, `scheduler.go`, `actions.go`, `recovery.go`, `periodbudget.go`, `store.go`, app `authority.go`, `projects.go`, `roster.go`, `budgets.go`; add `0008_recovery.sql` and model/schema mirrors.
-
-**Interfaces:** Extend `team.AdmissionRequest` with `Project team.ProjectID` (inside package: `Project ProjectID`). Add global `(*team.Store).Pause(ctx context.Context, reason string) error` for startup/quarantine only, plus `FenceGrantsTx(ctx context.Context, tx *sql.Tx, changes []GrantChange) error`, where `GrantChange{Ref GrantRef; Version, Epoch int64}` names the current authority observation; `(*team.Store).StopAttempt(ctx context.Context, scope team.Scope, h team.Handle, reason string) error`, `RecoverySnapshot(ctx context.Context) (RecoverySnapshot, error)` and `ReleaseQuarantine(ctx context.Context, expectedRevision int64, actor, reason, reconciliationHash string) error`. `RecoverySnapshot` contains `Revision int64`, `Incarnation int64`, `Hash string`, `Unresolved []ActionID`, `Uncontained []AttemptID`. Also expose `ReleaseQuarantineTx(ctx context.Context, tx *sql.Tx, expectedRevision int64, actor, reason, reconciliationHash string) error` for the witnessed app transaction. `RecoverySnapshot.Revision` is a dedicated recovery generation changed by reconciliation, stop, receipt and release mutations, not `service.revision` (even reads advance that witness counter). App `(*Store).ReleaseExecution(ctx context.Context, actor Actor, expectedRevision int64, reason, snapshotHash string) error` is the owner-only entry point.
+**Files:** Core `recovery_release.go`, `stop.go`, tests; authority/jobs/scheduler/actions/recovery/periodbudget/store; app `recovery.go`, authority/projects/roster/budgets; migration 0008; `internal/equipotest/recovery_test.go`.
-- [ ] **Step 1: Add `TestRecoveryReleaseOwnerAndRevision`, `TestRecoveryReleaseKeepsUnknownCharged`, `TestProjectGrantChargeAgreement`, `TestRuntimeAuthorityEditFencesOnlyChangedGrants`, `TestContainAfterClockRollback`.** A member, stale snapshot or missing reconciliation evidence cannot release. A known unresolved action remains uncertain/charged after release and cannot be replayed. All known attempts must be contained first. Wrong `Project` with a valid grant fails at create, renew and admit. Project edits atomically mark and fence only jobs whose saved grant version/epoch differs. Run two projects: editing A stops A until Resume while B can renew and admit. A roster edit advances the current global `RosterEpoch`, so all grants using that epoch become stale; this is an actual epoch change, not an unconditional pause for any app edit. An account label or unrelated settings edit must not stop either job. Removed authority cancels its jobs; lookup errors deny the affected operation. Move fake time backwards during an active lease: `StopAttempt`, physical cleanup, then `Contain` succeeds without waiting for the old deadline; old handle fails. Unknown elapsed time retains the full reserved seconds rather than settling to zero. Persist a clock high-water mark for mutating operations; a backward observation marks affected attempt time uncertain even when the new time remains after CreatedAt. No read or clock step can refund that uncertainty.
+**Interfaces:** `AdmissionRequest.Project ProjectID`; `Store.Pause(ctx, reason string) error` for startup/quarantine; `FenceGrantsTx(ctx, tx *sql.Tx, changes []GrantChange) error`, `GrantChange{Ref GrantRef; Version, Epoch int64}`; `StopAttempt(ctx, scope Scope, h Handle, reason string) error`. `RecoverySnapshot(ctx) (RecoverySnapshot, error)` returns `Revision, Incarnation int64; Hash string; Unresolved []ActionID; Uncontained []AttemptID`. `ReleaseQuarantine(ctx, expectedRevision int64, actor, reason, reconciliationHash string) error` and its `ReleaseQuarantineTx` variant take the current SQL transaction. App owner entry: `ReleaseExecution(ctx, actor Actor, expectedRevision int64, reason, snapshotHash string) error`.
- ```go
- if !errors.Is(err, team.ErrGrantRevoked) { t.Fatal("project and grant diverged") }
- if after.Reserved != before.Reserved { t.Fatal("release refunded uncertainty") }
- if oldHandleAccepted { t.Fatal("stopped attempt retained authority") }
- ```
+- [ ] **Tests:** `TestRecoveryReleaseOwnerAndRevision`: deny member, stale snapshot, missing reconciliation, or uncontained attempts. `TestRecoveryReleaseKeepsUnknownCharged`: release cannot replay/refund unknown work. `TestProjectGrantChargeAgreement`: wrong project with valid grant fails create/renew/admit. `TestRuntimeAuthorityEditFencesOnlyChangedGrants`: edit A stops A until Resume while B renews/admits; global RosterEpoch changes stale all its grants; label/unrelated edits stop neither; removal cancels, lookup errors deny. `TestContainAfterClockRollback`: StopAttempt → physical cleanup → Contain works before the old deadline and rejects old handle. Clock rollback, including to a time after CreatedAt, preserves full reserved seconds when elapsed time is unknown; no read refunds it.
+- [ ] **Red/green:** `go test ./internal/equipo/team ./internal/equipotest -run 'TestRecoveryRelease|TestProjectGrantCharge|TestRuntimeAuthority|TestContainAfter' -count=1`; green also `make migration-check` and existing restore/witness/crash tests.
+- [ ] **Implement:** Resolve Project against grant in every Authority call; production admissions last 5 seconds. Use Task 1's current transaction for grant fencing. Changed grants stale only their jobs, fence attempts, request stops and revoke undispatched intents. Resume reconciles contained, still-authorized jobs; revoked/target-changed jobs cancel. Budget edits synchronize only affected scope without staling unrelated grants. Persist reconciliation work and audit atomically; serialize budget sync/contain/Resume.
-- [ ] **Step 2: Run red.** `go test ./internal/equipo/team ./internal/equipotest -run 'TestRecoveryRelease|TestProjectGrantCharge|TestRuntimeAuthority|TestContainAfter' -count=1`.
-- [ ] **Step 3: Implement the recovery contract.** Resolve `Project` against the grant in every Authority call; set production `AdmissionSeconds = 5`. Use the witnessed transaction wrapper from Task 1 and its current `*sql.Tx` for `FenceGrantsTx`, never a root-pool call inside GORM's transaction. Mark only changed grants stale, fence their active attempts, request stop and revoke their undispatched intents. Extend `Resume` to reconcile those stale jobs while admission for unrelated jobs remains open; revalidate and clear only contained, still-authorized jobs. Revoked or target-changed jobs cancel. Startup/quarantine retains the existing global pause. Roster/project edits persist scoped reconciliation work with their audit; budget edits synchronize only their team/project scope and block admissions under the new limit without staling unrelated grants. A serialized execution service synchronizes budgets, contains affected attempts and calls Resume. Owner release records both core and app audit in the shared transaction, clears restore quarantine only for the exact reconciled revision, then leaves Resume to reopen admission. Missing post-restore history requires an owner attestation plus conservative recovery charges for identified lost work; add `RecoveryCharge{Key string; Account AccountID; Project ProjectID; Reserved PeriodLimits}` and `(*team.Store).RecordRecoveryCharge(ctx context.Context, charge RecoveryCharge, actor, reason string) error`, idempotent by key/content and owner-gated by the app, included in period totals without inventing receipts; do not infer that missing work was free. No public runner release endpoint.
-- [ ] **Step 4: Run green and mutate guards.** Repeat Step 2 and `make migration-check`. Remove owner/revision checks, project matching and the stop fence one at a time; their tests must fail. Restore each. Preserve existing restore/witness/crash tests.
-- [ ] **Step 5: Commit.** `git commit -m "feat: reconcile and release execution quarantine"`.
+ Recovery revision is a dedicated generation advanced by reconciliation/stop/receipt/release, not read-advancing `service.revision`. Persist a clock high-water mark for mutations. Owner release writes core/app audit atomically, clears only the reconciled quarantine revision, then Resume reopens admission. Missing history requires owner attestation and conservative `RecoveryCharge{Key string; Account AccountID; Project ProjectID; Reserved PeriodLimits}` via `RecordRecoveryCharge(ctx, charge, actor, reason) error`: owner-gated, idempotent key/content, included in totals without fabricated receipts. No runner release endpoint for quarantine.
+- [ ] **Commit:** `feat: reconcile and release execution quarantine`.
### Task 3: Define subscription accounting and bound period queries
-**Files:** Modify core `policy.go`, `model.go`, `budget.go`, `periodbudget.go`, `store.go`; create `subscription_test.go`, `periodquery_test.go`; add `0009_runner_policy.sql` and update schema mirrors; modify app `budgets.go`, create `internal/equipotest/budget_sync_test.go`.
+**Files:** Core policy/model/budget/periodbudget/store, `subscription_test.go`, `periodquery_test.go`; app budgets, migration 0009, `internal/equipotest/budget_sync_test.go`.
-**Interfaces:** Policy version 2 adds `UsageMode string` with `metered` and `subscription` plus `RequireDistinctReviewFamily bool`. Preserve version-1 decoding and behavior. Add `team.RunnerPolicy(mode string, limits, perTurn team.Limits, rates team.Rates) (team.Policy, error)` and `(*team.Store).ConfiguredBudgets(ctx context.Context, account team.AccountID) (team.BudgetSet, error)`. Subscription currency is unavailable, not a fictitious positive price; its ledger currency component is zero and displayed through a separate availability flag. Policy still requires positive calls/tokens/time bounds. Metered mode retains positive cost caps and explicit rates. Under configured team/project budgets, select pricing and per-call limits from the job policy, not the first account job; subscription and metered jobs must coexist regardless of creation order. Keep legacy unconfigured account policy behavior.
+**Interfaces:** Policy v2 adds `UsageMode` (`metered`, `subscription`) and `RequireDistinctReviewFamily`; retain v1 behavior. `RunnerPolicy(mode string, limits, perTurn Limits, rates Rates) (Policy, error)` is a pure constructor. `ConfiguredBudgets(ctx, account AccountID) (BudgetSet, error)`. Subscription ledger currency is zero with an unavailable flag, not a fabricated price; calls/tokens/time remain positive bounds. Metered jobs retain positive cost caps/rates. Configured team/project budgets use each job's pricing/per-call policy, independent of job creation order; retain legacy unconfigured-account behavior.
-- [ ] **Step 1: Add `TestSubscriptionPolicy`, `TestMixedConnectionPolicies`, `TestLoweredBudgetBlocksReservedAdmission`, `TestBudgetSyncCrash`, `TestPeriodQueriesBoundedHistory`, `TestUnknownUsageStillCharged`.** Pin 5-second admissions, 60-second leases, 1,200-second attempts, 2,700-second jobs, two attempts per step, concurrency two, depth zero for runner jobs, 24 external actions/job (at most 23 provider turns, with one slot held for publication). Token limits and per-turn token reservations are explicit configuration, not Foundation fixture defaults. Task 18 measures real turns before setting project/team token limits. Each turn reserves one call and the configured bounded `PerCall` input/output allowance, clipped to positive remaining job and period headroom; never reserve the whole remaining job allowance by default. These are accounting reservations, not provider output caps. Seed an offline example with headroom for two such reservations: after one turn has unknown usage, its reservation stays open and a second may proceed if the turn is otherwise known complete and the remaining ledger permits it. An unknown external outcome still stops replay/progression. Exhausted headroom blocks. Lower a limit after Intend: Admit returns `ErrBudget`. Duplicate budget sync does not advance twice. Seed 100,000 settled old rows plus open rows from earlier months; query plans use indexes and return the same checked totals. Zero remaining headroom prevents new work; unknown receipts keep reservations open.
- ```go
- if policy.AdmissionSeconds != 5 || policy.LeaseSeconds != 60 { t.Fatal("wrong admission or lease") }
- if !errors.Is(err, team.ErrBudget) { t.Fatal("lowered limit admitted reserved action") }
- ```
+- [ ] **Tests:** `TestSubscriptionPolicy`, `TestMixedConnectionPolicies`, `TestLoweredBudgetBlocksReservedAdmission`, `TestBudgetSyncCrash`, `TestPeriodQueriesBoundedHistory`, `TestUnknownUsageStillCharged`, `TestBoundedTurnReservation`, `TestCachedUsageSeparate`. Assert 5-second admissions, 60-second leases, 1,200-second attempts, 2,700-second jobs, two attempts/step, concurrency two, depth zero, 24 external actions/job with one publication slot and at most 23 provider turns. Limit reduction after Intend makes Admit return `ErrBudget`; repeated sync does not advance twice. Compare checked totals/query plans across 100,000 settled old rows and older open rows.
+- [ ] **Red/green:** `go test ./internal/equipo/team ./internal/equipotest -run 'TestSubscription|TestMixedConnection|TestLoweredBudget|TestBudgetSync|TestPeriodQueries|TestUnknownUsage|TestBoundedTurnReservation|TestCachedUsageSeparate' -count=1`. Green: migration check and existing `TestReservationLimitsAndOverflow|TestSettlementRules|TestLateUsageAfterCancelAndAuditedSettlement|TestTimeReservationsDoNotChangeCallLedger`.
+- [ ] **Implement:** Reserve one call plus configured bounded PerCall input/output, clipped to positive remaining job/period headroom; never default to all remaining tokens. A completed turn with unknown usage keeps its reservation; another turn may proceed with remaining headroom. Unknown outcome blocks progression/replay. Zero headroom blocks. Persist overrun before stopping further turns. Count reviewer/follow-up turns; underlying requests remain unavailable unless proven.
-- [ ] **Step 2: Run red.** `go test ./internal/equipo/team ./internal/equipotest -run 'TestSubscription|TestMixedConnection|TestLoweredBudget|TestBudgetSync|TestPeriodQueries|TestUnknownUsage|TestBoundedTurnReservation|TestCachedUsageSeparate' -count=1`.
-- [ ] **Step 3: Implement policy and indexed accounting.** Make currency validation mode-aware rather than fabricating a positive subscription cap; retain checked token/call arithmetic and actual overrun settlement. Add validated reservation period/project columns, backfilled from parsed timestamps and job rows, with indexes for open rows and settled rows by account/project/month. Use separate indexed queries instead of `(?=0 OR ...)`; checked Go accumulation preserves overflow errors. Include every open row regardless of month. Synchronize app budget revisions in order within their affected scope; a crash after core configuration is recognized by revision and content hash on retry. Calls count dispatched Paseo turns, including reviewer turns and follow-ups; underlying provider requests are unavailable unless the adapter proves them. Display that distinction. Persist overruns and stop before the next turn. The controller approved this call meaning; no fabricated hard subscription cap. Add `TestBoundedTurnReservation` and `TestCachedUsageSeparate` to the red/green command. Task 18 records measured uncached input, cached input and output separately, then sets explicit per-turn/job/project/team limits; missing calibration keeps production dispatch unavailable, not on fixture defaults.
-- [ ] **Step 4: Run green.** Repeat Step 2, `make migration-check`, and existing `TestReservationLimitsAndOverflow`, `TestSettlementRules`, `TestLateUsageAfterCancelAndAuditedSettlement`, `TestTimeReservationsDoNotChangeCallLedger`. Verify the history query test fails when the month/state predicates are removed.
-- [ ] **Step 5: Commit.** `git commit -m "feat: account for subscription turns and index period usage"`.
+ Backfill validated period/project columns from timestamps/job rows. Separate indexed queries for open rows and settled account/project/month rows, avoiding `(?=0 OR ...)`; include every open month and checked overflow arithmetic. Sync budget revisions/content hashes idempotently across crashes. Removing month/state predicates must fail the bounded-history assertion. Production token limits require Task 18 calibration, not fixture defaults; cached input remains separate in display.
+- [ ] **Commit:** `feat: account for subscription turns and index period usage`.
### Task 4: Make Git identity and repository checks part of evidence
-**Files:** Create core `git_evidence.go`, `git_evidence_test.go`; modify core `model.go`, `evidence.go`, `actions.go`, `policy.go`; update schema mirrors only if persistence fields change.
-
-**Interfaces:** Add `team.GitCandidate{Repository, BaseCommit, Commit, Tree string}` with media type `application/vnd.equipo.git-candidate+json`; `team.RepositoryCheckResult{CandidateHash, Commit, CheckDefinitionHash, BaselineTestSetHash, ObservedTestSetHash string; Outcome CheckOutcome; ExitCode, TestsRun, TestsFailed int; LogHash string}`; `RoleRepositoryChecks` allowed only for `CapVerify`. Add `ModelFamily string` to `Provenance`; require it under version-2 family policy. Extend publication JSON with `candidate_hash`; `head` is the Git commit. Add read-only `(*Store).Evidence(ctx context.Context, scope Scope) (EvidenceReport, error)` and `(*Store).ReadyToPublish(ctx context.Context, scope Scope) (EvidenceReport, error)`; the latter checks all evidence except the publication receipt.
+**Files:** Core `git_evidence.go`, tests, model/evidence/actions/policy; schema mirrors if fields require columns.
-- [ ] **Step 1: Add `TestGitCandidateIdentity`, `TestBugNeedsRepositoryChecks`, `TestReviewDifferentFamily`, `TestChangedCandidateInvalidatesEvidence`.** Compute candidate artifact hash from canonical payload bytes; prove it differs from the commit ID. Candidate reproduction/review references that artifact hash; base reproduction references base commit as today. Publish must match both identities. Passing reproduction plus review without repository checks fails. Same family across different profiles/providers fails; different family with separate producer/session passes. Missing family fails. A second candidate invalidates both check results and review. Compilation failure, skipped/no tests, zero-exit without measured tests, wrong definition and malformed SHA values fail.
+**Interfaces:** `GitCandidate{Repository, BaseCommit, Commit, Tree string}`, media type `application/vnd.equipo.git-candidate+json`. `RepositoryCheckResult{CandidateHash, Commit, CheckDefinitionHash, BaselineTestSetHash, ObservedTestSetHash string; Outcome CheckOutcome; ExitCode, TestsRun, TestsFailed int; LogHash string}`. `RoleRepositoryChecks` requires CapVerify. Provenance adds observed `ModelFamily` and the isolation snapshot defined above. Publication JSON includes `candidate_hash`; `head` remains Git commit. Read-only `Evidence(ctx, scope) (EvidenceReport, error)` and `ReadyToPublish(ctx, scope)`; the latter excludes only publication receipt.
- ```go
- if report.Satisfied { t.Fatal("missing repository checks accepted") }
- if publish.Head != candidate.Commit { t.Fatal("artifact digest used as Git object") }
- if !errors.Is(err, team.ErrEvidence) { t.Fatal("same-family review accepted") }
- ```
-
-- [ ] **Step 2: Run red.** `go test ./internal/equipo/team -run 'TestGitCandidate|TestBugNeeds|TestReviewDifferent|TestChangedCandidate' -count=1`.
-- [ ] **Step 3: Implement typed candidate validation and predicate extensions.** Preserve legacy fixture byte-subject semantics for version-1 jobs. Version-2 bug jobs require Git candidate media type and both checks. `checkPublication` validates repository, ref, commit and candidate hash at Intend and again at Admit, closing a candidate-change race. `ReadyToPublish` never terminates a job; reserve `Conclude` for the final contained workflow because it fails the job when evidence is incomplete. Family comes from the observed session, not model-authored review JSON. Reject unsupported Git object formats explicitly; support SHA-1 and SHA-256 with exact lengths and lowercase hex.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `go test ./internal/equipo/team -run 'TestFixture|TestReview|TestEvidence|TestConclude' -count=1`. Mutate commit/hash matching, the repository-check requirement and family comparison independently.
-- [ ] **Step 5: Commit.** `git commit -m "feat: require Git-bound checks and independent model families"`.
+- [ ] **Tests:** `TestGitCandidateIdentity`, `TestBugNeedsRepositoryChecks`, `TestReviewDifferentFamily`, `TestChangedCandidateInvalidatesEvidence`: SHA-256 artifact digest hashes canonical payload bytes, differs from commit; base reproduction references base commit, candidate reproduction/review reference artifact hash; publication matches both. Reproduction/review without repository checks fails. Same family across profiles/providers or unknown family fails; different family plus distinct producer/session passes. New candidate invalidates review/checks. Compile failure, skip/no tests, zero exit without measured tests, wrong definition or malformed hash fails. Isolation provenance must survive new evidence and candidate lineage.
+- [ ] **Red/green:** `go test ./internal/equipo/team -run 'TestGitCandidate|TestBugNeeds|TestReviewDifferent|TestChangedCandidate' -count=1`; green also `go test ./internal/equipo/team -run 'TestFixture|TestReview|TestEvidence|TestConclude' -count=1`.
+- [ ] **Implement:** Preserve v1 byte-subject semantics; v2 bugs require typed candidate and both checks. Validate publication repository/ref/commit/hash at Intend and Admit. ReadyToPublish never terminates; Conclude waits for contained final workflow. Family/isolation come from runner-observed session, not review JSON. Support exact lowercase SHA-1/SHA-256 object lengths; reject other formats. Mutate identity, repository-check and family guards independently.
+- [ ] **Commit:** `feat: require Git-bound checks and independent model families`.
### Task 5: Enrol and revoke machines with scoped credentials
-**Files:** Create app `enrolment.go`, `runners.go`, `internal/runnerproto/types.go`, `validate.go`, `internal/equipotest/enrolment_test.go`; add `0010_runners.sql`, models/schema entries; modify app routing and copy keys.
-
-**Interfaces:** Define `Runner{ID, Person, MachineKeyHash, Label string; Revision int64; RevokedAt *time.Time}` and `RunnerPrincipal{RunnerID, Person string; CredentialID string}`. `(*Store).BeginEnrolment(ctx context.Context, machinePublicKey, label string) (runnerproto.DeviceCode, error)`, `ApproveEnrolment(ctx context.Context, actor Actor, userCode string) error`, `ExchangeEnrolment(ctx context.Context, deviceSecret, proof string) (runnerproto.RunnerCredential, error)`, `AuthenticateRunner(ctx context.Context, token string) (RunnerPrincipal, error)`, `RevokeRunner(ctx context.Context, actor Actor, runnerID string, revision int64) error`. Wire DTOs include expiry and polling interval, never provider secrets.
+**Files:** App enrolment/runners, protocol types/validation, routing/copy keys; migration 0010; `internal/equipotest/enrolment_test.go`.
-- [ ] **Step 1: Add `TestEnrolmentAudience`, `TestEnrolmentSingleUse`, `TestRunnerRemovalRevokes`, `TestEnrolmentCSRFAndRate`.** A device grant can only poll/exchange, never claim; runner bearer cannot approve in the browser or access private UI; session cookie cannot authenticate runner endpoints. Approver identity is stored, submitted person ignored/rejected. Device code expires after 10 minutes, polls no faster than 5 seconds, approval is one use, machine proof is required. Ed25519 proof signs the enrolment ID, server challenge and exchange nonce; never trust a submitted person field. A lost successful exchange response requires fresh enrolment and browser approval. The consumed code cannot recover or mint a second bearer; the owner can revoke the unused runner record. Removal and revoke deny the next request, including an existing long-poll delivery. DB errors return unavailable, never authorize. No credential appears in audit/log/HTML.
- ```go
- if response.Code != http.StatusUnauthorized { t.Fatal("wrong credential audience accepted") }
- if grantedPerson != approver.Address { t.Fatal("enrolment trusted submitted person") }
- ```
+**Interfaces:** `Runner{ID, Person, MachineKeyHash, Label string; Revision int64; RevokedAt *time.Time}`; `RunnerPrincipal{RunnerID, Person, CredentialID string}`. Store methods `BeginEnrolment(ctx, machinePublicKey, label) (DeviceCode, error)`, `ApproveEnrolment(ctx, actor, userCode) error`, `ExchangeEnrolment(ctx, deviceSecret, proof) (RunnerCredential, error)`, `AuthenticateRunner(ctx, token) (RunnerPrincipal, error)`, `RevokeRunner(ctx, actor, runnerID, revision) error`. DTOs carry expiry/poll interval, no provider secrets.
-- [ ] **Step 2: Run red.** `go test ./internal/equipotest -run 'TestEnrolment|TestRunnerRemoval' -count=1`.
-- [ ] **Step 3: Implement routes and credential storage.** POST `/api/enrolments`, POST `/api/enrolments/token`; GET/POST `/runners/enrol` under session and CSRF; POST `/runners/{id}/revoke`. Generate 256-bit device/bearer secrets, store hashes and explicit audience/instance/person/machine bindings. User code has 10 unambiguous base32 characters; rate-limit creation and approval attempts. Runner credentials expire after 30 days; rotation overlaps for at most 5 minutes and cannot revive revocation. Persist credential hashes only; do not retain an encrypted exchange response or add an enrolment replay endpoint. Keep browser CSRF on browser routes and reject cookie-only runner requests. Approval must disclose the machine label/key fingerprint and real instance origin. Export runner display strings from `copy.go` through a small copy accessor; do not duplicate literals in the runner package.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`. Mutate audience and live membership checks separately; successful approval/claim controls must still work.
-- [ ] **Step 5: Commit.** `git commit -m "feat: enrol person-bound runners with separate credentials"`.
+- [ ] **Tests:** `TestEnrolmentAudience`, `TestEnrolmentSingleUse`, `TestRunnerRemovalRevokes`, `TestEnrolmentCSRFAndRate`: device grant only polls/exchanges; bearer cannot approve/access browser UI; cookie cannot authenticate runner API. Approver determines person. Ten-minute expiry, minimum five-second poll, one-use approval, required Ed25519 proof over enrolment ID/challenge/exchange nonce. Lost successful exchange needs new browser-approved enrolment; consumed code cannot mint/recover bearer. Owner can revoke unused runner. Removal/revoke denies next request and pending poll delivery; DB error denies; secrets absent from logs/audit/HTML.
+- [ ] **Red/green:** `go test ./internal/equipotest -run 'TestEnrolment|TestRunnerRemoval' -count=1`; green also migration check. Mutate audience/current-membership gates with successful approval/claim controls.
+- [ ] **Implement:** POST `/api/enrolments`, `/api/enrolments/token`; session/CSRF GET/POST `/runners/enrol`; POST `/runners/{id}/revoke`. 256-bit device/bearer secrets, hashes only, explicit audience/instance/person/machine binding. Ten unambiguous base32 user-code characters; creation/approval rate limits. Thirty-day bearer expiry, rotation overlap at most five minutes, no revival after revoke. No encrypted exchange response/replay endpoint. Approval displays machine label/key fingerprint and real origin. Runner copy comes through an accessor to copy.go.
+- [ ] **Commit:** `feat: enrol person-bound runners with separate credentials`.
### Task 6: Discover and select personal connections
-**Files:** Create app `connections.go`, `internal/equipotest/connections_test.go`; runner `connections.go` and its tests belong to Task 17; add `0011_connections.sql`, models/schema entries; modify specialist/project handlers later consumed by Task 16.
+**Files:** App connections, migration 0011, `internal/equipotest/connections_test.go`; selection handlers later rendered in Task 16. Runner discovery belongs to Task 17.
-**Interfaces:** `runnerproto.ConnectionReport{LocalID, Provider, Family, Model, AccountLabel, Kind, UnavailableReason, IsolationConfigHash string; Available, ReadIsolation bool; AllowanceKnown bool; AllowanceRemaining int64}`; one stable connection/profile identity may expose multiple model rows. App `Connection{ID, RunnerID, Person, LocalID string; Revision int64; LastSeen time.Time}` plus reports and personal `ConnectionChoice{ProjectID, Revision int64; ConnectionIDs []string; PinnedID string}`. Store methods `ReportConnections(ctx context.Context, principal RunnerPrincipal, reports []runnerproto.ConnectionReport) error`, `SaveConnectionChoice(ctx context.Context, actor Actor, choice ConnectionChoice) error`, `SelectConnection(ctx context.Context, person string, projectID int64, specialist, excludedFamily string) (runnerproto.Selection, error)`. This internal selector receives person/project from the authenticated task service in Task 7, never submitted form fields; Task 6 tests it with current roster/project fixtures without a task table. `Selection` includes connection, runner, provider, family, model, account label, revision and reason code (`pinned` or `first_allowed`). All signatures use `context.Context` for `ctx`.
+**Interfaces:** `ConnectionReport{LocalID, Provider, ProviderVersion, PaseoVersion, Family, Model, AccountLabel, Kind, UnavailableReason, IsolationConfigHash string; Available, ReadIsolation, AllowanceKnown bool; AllowanceRemaining int64}`. Stable connection/profile identity may expose multiple models. `Connection{ID, RunnerID, Person, LocalID string; Revision int64; LastSeen time.Time}`; `ConnectionChoice{ProjectID, Revision int64; ConnectionIDs []string; PinnedID string}`. Store `ReportConnections(ctx, principal, reports) error`, `SaveConnectionChoice(ctx, actor, choice) error`, `SelectConnection(ctx, person, projectID, specialist, excludedFamily) (Selection, error)`. Task service supplies person/project, never forms. Selection carries connection/runner/provider/family/model/account/revision, reason `pinned` or `first_allowed`, and isolation snapshot. Add owner-only `AcknowledgeUnconfined(ctx, actor, connectionID, expectedRevision) error` and `RevokeIsolationAcknowledgement` with the same binding.
-- [ ] **Step 1: Add `TestConnectionsBelongToPersonAndMachine`, `TestConnectionSelection`, `TestReviewWaitsForOtherFamily`, `TestAccountFailoverStops`, `TestProjectAccountNoDeleteAndASCIILabels`.** Two people with the same account label never share credentials/selection. Explicit personal opt-in is required; there is no owner provider/family allowlist in plan 2. Builder and reviewer must be available to that person on the same docs-t1 runner, both passing preflight including read isolation. A missing pin waits, never silently falls back. First allowed is stable by connection ID then model ID. A selected model must satisfy fixed specialist settings. One-family tasks wait before spending on the build. Unexpected actual account/family at session-open stops before the first prompt; mid-step failover contains and requires a disclosed new assignment.
- ```go
- if selection.RunnerID != connection.RunnerID { t.Fatal("wrong machine selected") }
- if selection.Family == builderFamily { t.Fatal("review used the builder family") }
- ```
+- [ ] **Tests:** `TestConnectionsBelongToPersonAndMachine`, `TestConnectionSelection`, `TestReviewWaitsForOtherFamily`, `TestAccountFailoverStops`, `TestProjectAccountNoDeleteAndASCIILabels`. Same account label across people never shares selection/credentials. Require personal opt-in; same-runner two-family preflight before build. Missing pin waits; stable fallback orders connection ID then model ID and respects fixed specialist model/concurrency. Actual account/family mismatch stops before first prompt; mid-step failover contains before reassignment. DELETE routes fail without record/audit changes; ASCII duplicates conflict, existing non-ASCII behavior stays.
-- [ ] **Step 2: Run red.** `go test ./internal/equipotest -run 'TestConnections|TestConnectionSelection|TestReviewWaits|TestAccountFailover|TestProjectAccountNoDeleteAndASCIILabels' -count=1`. Seed sanitized reports and observed-identity fixtures here; runner discovery is tested in Task 17.
-- [ ] **Step 3: Implement identity and selection.** Reports describe signed-in profiles on this local machine only, tied to the authenticated runner person. An operator-maintained runner-local account binding file lists the existing profile IDs this enrolment may report; it contains no credential bytes. Enrolment does not automatically claim every profile visible in a shared daemon. Never infer ownership by email label or import all of another user's daemon accounts. Supported account routing must pin a credential home and report actual account identity with failover disabled before the first prompt; absent capability makes that connection unavailable. Task 9 records the installed routing limitation and Task 17 enforces it. Detecting a changed account after a prompt is not prevention. Never change shared daemon account defaults to make this test pass. Mark reports stale after 90 seconds without heartbeat. Show provider allowance only when a supported read returns it; otherwise show counted Equipo usage with unknown allowance. Revocation disables new work and requests containment. Preserve max-concurrency specialist settings in assignment, without inventing model names.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`; mutate person, pin and excluded-family filters independently.
-- [ ] **Step 5: Commit.** `git commit -m "feat: select allowed connections for each person's tasks"`.
+ `TestUnconfinedConnectionRequiresAcknowledgement`: no ack/member/forged owner/wrong connection denies creation and dispatch; valid current-owner ack permits only eligible Codex, with personal opt-in and all other capabilities. `TestIsolationAcknowledgementLapses`: provider/Paseo upgrade, changed config/revision or revocation denies subsequent claim/turn, including stale tickets; Claude never takes this exception. Assert who/when/connection/provider/versions in audit and no credentials.
+- [ ] **Red/green:** `go test ./internal/equipotest -run 'TestConnections|TestConnectionSelection|TestReviewWaits|TestAccountFailover|TestProjectAccountNoDeleteAndASCIILabels|TestUnconfinedConnection|TestIsolationAcknowledgement' -count=1`; green also migration check. Mutate person/pin/family/owner/version filters.
+- [ ] **Implement:** Reports only cover profiles allowed by an operator-maintained, credential-free runner account-binding file. Enrolment does not claim every shared-daemon profile; email labels do not prove ownership. Supported routing must pin credential home, observe actual account and disable failover before prompting. Never change daemon defaults. Reports stale after 90 seconds without heartbeat. Unknown allowance stays unknown alongside counted Equipo usage. Revocation disables admission and requests containment. Persist acknowledgement and audit transactionally per the ruling; runtime capabilities remain truthful.
+- [ ] **Commit:** `feat: select allowed connections for each person's tasks`.
### Task 7: Create bug tasks and prepare their fixed plan
-**Files:** Create app `tasks.go`, `task_prepare.go`, `internal/equipotest/tasks_test.go`; add `0012_tasks.sql`, models/schema entries; extend core `jobs.go`, `store.go` and new `job_retry_test.go`.
+**Files:** App tasks/task_prepare, migration 0012, `internal/equipotest/tasks_test.go`; core jobs/store, `job_retry_test.go`.
-**Interfaces:** `Task{ID, Requester, Description, RequestID string; ProjectID, Revision int64; JobID team.JobID; State, WaitCode string; BaseCommit, ReviewRef, CheckDefinitionHash string}`. `(*Store).CreateBug(ctx context.Context, actor Actor, projectID int64, description, requestID string) (Task, error)`, `PrepareBug(ctx context.Context, principal RunnerPrincipal, taskID string, expectedRevision int64, prep runnerproto.PreparedBug) (Task, error)`. `PreparedBug`, defined in `runnerproto` by this task, contains repository, saved-default observation, base commit and check-definition bytes/hash. App `BugPreparer` exposes `Prepare(context.Context, team.TargetBinding) (runnerproto.PreparedBug, error)` as the preparation boundary; Task 7 uses a fake and Task 15 connects the runner implementation from Task 10 through Task 8. Add `team.JobSpec.RequestKey string`; unique `(account, requester, request_key)` with canonical input hash returns the original job or `ErrConflict`. `BugJobSpec(task Task, project Project, policy team.Policy, expectedSymptom string) (team.JobSpec, error)` derives Project and GrantRef from that same task/project.
+**Interfaces:** `Task{ID, Requester, Description, RequestID string; ProjectID, Revision int64; JobID JobID; State, WaitCode, BaseCommit, ReviewRef, CheckDefinitionHash string}`. `CreateBug(ctx, actor, projectID, description, requestID) (Task, error)`; `PrepareBug(ctx, principal, taskID, expectedRevision, PreparedBug) (Task, error)`. PreparedBug contains repository/default observation/base/check-definition bytes/hash. `BugPreparer.Prepare(ctx, TargetBinding) (PreparedBug, error)` is fake here. `JobSpec.RequestKey` is unique by account/requester/key with canonical input hash; same input returns original, mismatch ErrConflict. Pure `BugJobSpec(task, project, policy, expectedSymptom) (JobSpec, error)` derives Project/GrantRef together.
-- [ ] **Step 1: Add `TestBugFormCannotChooseAuthority`, `TestBugSubmissionRetry`, `TestBugPreparationCrash`, `TestFixedBugPlan`, `TestJobRequestKey`.** Form accepts only project ID, description and request ID. Forged repository, requester, grant, budget, ref or kind fails. Only a current team owner or that project's work owner can start under today's Authority; other members can read shared tasks. Same request creates one task/job, changed payload conflicts. Crash between core job creation and app linking recovers the same job using the fake preparer. Task 15 repeats `TestBugPreparationCrash` with the real protocol and local Git source. Changed project/connection revision invalidates preparation. Assert five execution steps and one app human step, with the exact capabilities below.
- ```go
- if retried.ID != original.ID || retried.JobID != original.JobID { t.Fatal("submission duplicated work") }
- if len(steps) != 5 || steps[4].Capability != team.CapPublish { t.Fatal("fixed graph changed") }
- ```
+- [ ] **Tests:** `TestBugFormCannotChooseAuthority`, `TestBugSubmissionRetry`, `TestBugPreparationCrash`, `TestFixedBugPlan`, `TestJobRequestKey`: accept only project/description/request ID; reject forged requester/repository/grant/budget/ref/kind. Only current owner or project's work owner starts; members read. Duplicate request yields one task/job; changed payload conflicts. Crash between job creation/app linking recovers same job. Project/connection revision change invalidates preparation. Five execution steps plus one app human step.
+- [ ] **Red/green:** `go test ./internal/equipotest ./internal/equipo/team -run 'TestBug|TestFixedBug|TestJobRequestKey' -count=1`; green also migration check and crashes around each outbox acknowledgement.
+- [ ] **Implement:** Description 1–16,384 UTF-8 bytes. Transaction writes task/outbox/audit before network. Server fixes `equipo/<task-id>` ref and immutable base. After authority/budget checks build reproduce/CapReproduce → implement/CapImplement → review/CapReview → verify/CapVerify → publish/CapPublish. Display Engineering reproduce/fix, Review review/checks, person merge; publish is runner-only and merge never executes in core. Fresh workspace per attempt.
-- [ ] **Step 2: Run red.** `go test ./internal/equipotest ./internal/equipo/team -run 'TestBug|TestFixedBug|TestJobRequestKey' -count=1`.
-- [ ] **Step 3: Implement durable preparation and graph.** Validate description length 1–16,384 UTF-8 bytes. App transaction writes task plus outbox and audit before any network work. Persist a preparation outbox item; test consuming it with `BugPreparer` and authenticated prepared data locally. The real assignment/fetch path is deferred to Task 15 after Tasks 8/10, and starts no agent. Persist a server-generated review ref `equipo/<task-id>` and immutable base. After online authority and budget checks, create `reproduce: CapReproduce`, `implement: CapImplement` depends on reproduce, `review: CapReview` depends on implement, `verify: CapVerify` depends on review, `publish: CapPublish` depends on verify. Display Engineering reproduce/fix, Review review/checks, and person merge; publishing is a runner operation. Person merge is not an executable core step. Every attempt has a fresh workspace identity. Reproduce freezes the symptom string and reproduction before implementation; add a revision-guarded `FreezeBugEvidence(ctx context.Context, scope team.Scope, h team.Handle, expectedSymptom, definitionHash, reproductionHash string) error` that only permits CapReproduce before any candidate. Initial evidence uses the validated bug description until that freeze; hashes/definitions cannot change. Add `FrozenReproductionHash` to `EvidenceRequirement`; the freeze checks a registered reproduction for this attempt, and subsequent registrations must match it. The executor alone produces base/candidate/check result artifacts. Before completing reproduce, require the frozen hash, symptom and base result to agree. No free-form plan editing.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`; inject crashes before/after each outbox acknowledgement. Force mismatched grant/project and verify denial.
-- [ ] **Step 5: Commit.** `git commit -m "feat: create idempotent bug tasks with a fixed review plan"`.
+ `FreezeBugEvidence(ctx, scope, handle, expectedSymptom, definitionHash, reproductionHash) error` requires current revision/CapReproduce, registered reproduction from that attempt, and no candidate. Initial symptom is validated description until freeze. Add `FrozenReproductionHash` to EvidenceRequirement; later registrations must match. Freeze symptom/definition/reproduction before implementation; executor alone attests base/candidate/checks, and reproduce completion requires matching frozen hash/symptom/base failure. Task 15 adds real assignment/fetch integration, without introducing plan editing.
+- [ ] **Commit:** `feat: create idempotent bug tasks with a fixed review plan`.
### Task 8: Expose fenced outbound runner work
-**Files:** Create app `runner_api.go`; extend `execution.go`, core `actions.go` and `store.go`; create core `admit_retry_test.go`; create `internal/equipotest/runner_api_test.go`; extend `runnerproto/types.go`, `validate.go`; add `0013_runner_assignments.sql`, models/schema entries. Production attachment remains disabled until Task 17.
+**Files:** App runner_api/execution; core actions/store, `admit_retry_test.go`; protocol; migration 0013; `internal/equipotest/runner_api_test.go`.
-**Interfaces:** Core adds `AdmitOnce(ctx context.Context, scope Scope, h Handle, id ActionID, requestID string) (AdmissionTicket, error)` and `AdmissionTicket{Dispatch Dispatch; ExpiresAt time.Time; Incarnation int64}`; legacy `Admit` remains for existing callers. `runnerproto.Assignment{ID, TaskID, StepKey, WorkspaceKey string; Scope team.Scope; Selection Selection; Revision int64; Kind string}` where kind is `prepare` or `step`; `Brief` contains saved target, instructions, standing instructions, selection, policy and artifact hashes, with `ConfirmedPreferences []string` empty in plan 2. `ClaimRequest{AssignmentID string; Revision int64}`; `ClaimResponse{Scope team.Scope; Handle team.Handle; Brief Brief; LeaseDeadline time.Time; CleanupToken string}`. App `Execution` owns core, app store and reconciliation adapters. Methods `Poll(ctx context.Context, p RunnerPrincipal, after int64) ([]runnerproto.Assignment, error)`, `Claim(ctx context.Context, p RunnerPrincipal, req runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error)`, `Sync(ctx context.Context) error`. All post-claim requests carry scope, handle, request ID and protocol version.
+**Interfaces:** `AdmitOnce(ctx, scope, handle, actionID, requestID) (AdmissionTicket, error)` preserves legacy Admit; ticket has Dispatch, ExpiresAt, Incarnation. `Assignment{ID, TaskID, StepKey, WorkspaceKey string; Scope Scope; Selection Selection; Revision int64; Kind string}` (`prepare`, `step`). Brief carries target/instructions/standing instructions/selection/policy/artifact hashes; ConfirmedPreferences empty. ClaimRequest carries assignment/revision; response scope/handle/brief/lease deadline/cleanup token. Execution owns stores/reconciliation adapters and `Poll(ctx, principal, after) ([]Assignment, error)`, `Claim(ctx, principal, request) (ClaimResponse, error)`, `Sync(ctx) error`. Post-claim requests carry scope, handle, request ID, protocol version.
-- [ ] **Step 1: Add `TestRunnerCannotClaimOthersWork`, `TestRunnerFenceEveryMutation`, `TestRunnerLongPollRechecksRoster`, `TestSpecialistConcurrency`, `TestDispatchAdmissionExpires`, `TestAdmitLostReplyRetry`.** The same request ID/action/attempt/fence/runner within the original admission window returns the identical stored ticket after a lost response, with no new charge, event or deadline. Changed payload/binding conflicts; expiry, cancellation, revocation, changed grant, budget reduction or incarnation change denies replay. Crash immediately after the core admission commit still recovers that ticket. Two runners race one assignment: one handle wins. Wrong person/machine/connection/fence fails across renew, event, artifact, intent/admit, completion and answers. Revoke during poll: no work returned. Specialist concurrency one permits one matching active attempt across jobs even though core job/team policy permits two. Admission received after five seconds cannot execute. DB/Authority failure produces no assignment or zero-looking status.
- ```go
- if successfulClaims != 1 { t.Fatal("assignment claimed twice") }
- if dispatchesAfterRevoke != 0 { t.Fatal("revoked runner received work") }
- ```
+- [ ] **Tests:** `TestRunnerCannotClaimOthersWork`, `TestRunnerFenceEveryMutation`, `TestRunnerLongPollRechecksRoster`, `TestSpecialistConcurrency`, `TestDispatchAdmissionExpires`, `TestAdmitLostReplyRetry`, `TestRevokedCleanupCannotRefund`. Lost reply retries return identical stored ticket, charge/event/deadline unchanged, including crash immediately after commit. Changed payload/binding conflicts; expired/cancelled/revoked/grant-changed/budget-reduced/incarnation-changed replay denies. Racing runners yield one handle. Wrong person/machine/connection/fence denies every mutation/answer. Revoke while polling returns no assignment. Specialist limit one holds across jobs despite core concurrency two. Five-second stale admission cannot execute. Authority/DB error never becomes assignment or zero status. Forged zero cleanup receipt retains full charge.
+- [ ] **Red/green:** `go test ./internal/equipotest ./internal/equipo/team -run 'TestRunnerCannot|TestRunnerFence|TestRunnerLong|TestSpecialistConcurrency|TestDispatchAdmission|TestAdmitLostReplyRetry|TestRevokedCleanupCannotRefund' -count=1`; green also migration check and per-endpoint binding mutations.
+- [ ] **Implement:** Persist admission request identity/dispatch/deadline/incarnation atomically with intent→dispatching. Retry revalidates authority/handle/budget/expiry and isolation acknowledgement. Runner journals request ID and consumes ticket once. Reserve assignment/specialist slot atomically; reconcile Claim crashes before effects.
-- [ ] **Step 2: Run red.** `go test ./internal/equipotest ./internal/equipo/team -run 'TestRunnerCannot|TestRunnerFence|TestRunnerLong|TestSpecialistConcurrency|TestDispatchAdmission|TestAdmitLostReplyRetry|TestRevokedCleanupCannotRefund' -count=1`.
-- [ ] **Step 3: Implement protocol routes.** Store the admission request identity, dispatch and original deadline/incarnation in the same core transaction that changes intent to dispatching; do not call `Admit` and then write an app ticket in a second transaction. An exact `AdmitOnce` retry revalidates current authority, handle, budget and original expiry before returning the stored ticket. Runner journals request ID and consumes each action ticket once even if HTTP replies duplicate. POST `/api/runner/v1/poll` holds at most 25 seconds, outside transactions. POST routes `/claim`, `/renew`, `/prepare`, `/events`, `/artifacts`, `/intend`, `/admit`, `/receipts`, `/lost`, `/complete`, `/release`, `/stop`, `/contained`, `/connections`, `/heartbeat`; GET scoped artifact download. Derive runner/person/account from authentication and stored assignment; handles alone grant nothing. Reserve assignment plus specialist slot atomically, then call Claim with persisted workspace key, reconciling crashes before enabling side effects. Lease renewals every 15 seconds; delivery includes instance incarnation and a 5-second dispatch deadline. Receipt/containment recovery after cancellation accepts only exact historical attempt/action bindings, never new effects. Each claim issues a separate audience `cleanup` capability for its known owned attempt, retained locally for up to 30 days and accepted after membership/runner revocation only on receipts/lost/contained endpoints; it cannot claim, renew, admit, answer permissions or register successful evidence. After roster/runner revocation, cleanup-only reports are untrusted recovery observations: they cannot lower any reserved or already observed usage/time charge, settle an unknown action for less, or grant success. Keep the reservation open and measured high-water totals; an owner may settle with an audited reason through the existing settlement boundary after corroboration. A forged zero-usage cleanup receipt must leave the full charge in `TestRevokedCleanupCannotRefund`. Containment may release a concurrency slot only after the separately validated process proof; it cannot refund tokens/time. Version mismatch fails closed. Limits: JSON action 64 KiB, event 16 KiB, artifact 1 MiB; no unbounded request buffering.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`. Route tests use explicitly injected fake artifact/question validators here; Task 15 tests their real replacements. Mutate every endpoint's binding check with table-driven subtests. Expire/revoke while the poll sleeps and before it returns.
-- [ ] **Step 5: Commit.** `git commit -m "feat: serve scoped runner assignments and fenced reports"`.
+ POST `/api/runner/v1/poll` waits at most 25 seconds outside transactions. POST suffixes `/claim`, `/renew`, `/prepare`, `/events`, `/artifacts`, `/intend`, `/admit`, `/receipts`, `/lost`, `/complete`, `/release`, `/stop`, `/contained`, `/connections`, `/heartbeat`; scoped artifact GET. Stored assignment/auth determines runner/person/account; handle alone grants nothing. Renew every 15 seconds; delivery includes incarnation/5-second deadline. Reject version mismatch. Bounds: action JSON 64 KiB, event 16 KiB, artifact 1 MiB.
+
+ Historical receipt/containment reporting after cancel permits only exact known bindings. Each claim creates audience `cleanup`, retained locally at most 30 days; after revocation usable only for receipts/lost/contained, never new actions/permissions/evidence. Treat cleanup-only reports as untrusted observations: cannot reduce reserved or observed token/time high-water, cheaply settle unknown action or grant success. Keep charges open; corroborated owner-audited settlement may lower them. Separately validated process proof can release concurrency, not refund charges. Route tests use explicit fake validators until Task 15.
+- [ ] **Commit:** `feat: serve scoped runner assignments and fenced reports`.
### Task 9: Build the version-pinned structured Paseo adapter
-**Files:** Create `internal/runner/paseo/{client,types,client_test}.go`, `runner/paseo/{package.json,package-lock.json,bridge.mjs,bridge.test.mjs}`, `internal/runner/paseo/testdata/` sanitized protocol fixtures. Modify Makefile with `runner-adapter-test` and a matching CI step.
+**Files:** `internal/runner/paseo/{client,types,client_test}.go`, sanitized testdata; `runner/paseo/{package.json,package-lock.json,bridge.mjs,bridge.test.mjs}`; Make `runner-adapter-test` and delegating CI step.
-**Interfaces:** Package `paseo` exports `Client` interface: `Preflight(context.Context, runnerproto.Selection, ReadPolicy) (Capabilities, error)`, `CreateWorkspace(context.Context, WorkspaceRequest) (Workspace, error)`, `CreateAgent(context.Context, AgentRequest) (Agent, error)`, `Subscribe(context.Context, Agent, Cursor) (Subscription, error)`, `Send(context.Context, Agent, string, string) error`, `Respond(context.Context, Agent, PermissionResponse) error`, `Stop(context.Context, Agent) error`, `Archive(context.Context, Agent) error`, `ArchiveWorkspace(context.Context, Workspace) error`. `Subscription` exposes `Ready <-chan error`, `Events <-chan Event`, `Close() error`. `Agent` retains `ServerID, AgentID, ProviderSessionID, WorkspaceID, AccountID, Provider, Model, Family string`; `Workspace` retains server/project/workspace IDs and absolute path. `Cursor{Epoch string; Seq int64}`. `AgentRequest` contains workspace, selection, idempotency key and per-agent `MCPServers map[string]MCPServer`, with no initial prompt. `MCPServer{Type string; Command string; Args []string; Env map[string]string}` serializes `type: "stdio"` explicitly and rejects other types for Equipo tools. Other wire records are defined in `types.go` from the pinned SDK, with no guessed provider-specific fields. `Capabilities{Version string; AccountPinning, ObservedAccount, RecoverableTimeline, ProcessOwnership, MCPAtCreate, ReadIsolation bool; ReadIsolationReason, IsolationConfigHash string}` records verified support. `Event{Kind, ServerID, AgentID, SessionID, TurnID, PermissionID, Epoch string; Seq int64; Payload json.RawMessage}` preserves provider-specific data for strict normalization. `AgentRequest{Workspace Workspace; Selection runnerproto.Selection; IdempotencyKey, ModeID string; ReadPolicy ReadPolicy; Env map[string]string; ProviderOptions json.RawMessage; MCPServers map[string]MCPServer}` is the complete create input. `Env` carries a nonsecret attempt marker; `ProviderOptions` is constructed by the trusted adapter from the verified isolation policy, never from agent input. `ReadPolicy{DeniedPaths []string; ConfigHash string}` contains the trusted canonical policy. `Preflight` takes the selection and policy explicitly and returns per-selection capabilities; one global success must not authorize other providers/modes. `ProcessOwnership` is supplied by Task 15's inspector coverage and combined with adapter capabilities by the supervisor, not asserted from Paseo status alone.
+**Interfaces:** `paseo.Client`: Preflight(selection, ReadPolicy), CreateWorkspace(WorkspaceRequest), CreateAgent(AgentRequest), Subscribe(Agent, Cursor), Send(Agent, message, messageID), Respond(Agent, PermissionResponse), Stop(Agent), Archive(Agent), ArchiveWorkspace(Workspace). All accept context and return errors with their typed results. Subscription exposes Ready error channel, Events channel, Close. Agent retains server/agent/provider-session/workspace/account/provider/model/family IDs; Workspace server/project/workspace IDs and absolute path; Cursor epoch/sequence. `AgentRequest{Workspace; Selection; IdempotencyKey, ModeID string; ReadPolicy; Env map[string]string; ProviderOptions json.RawMessage; MCPServers map[string]MCPServer}` has no initial prompt. MCPServer explicitly serializes stdio type/command/args/env; reject other types for Equipo tools.
-- [ ] **Step 1: Add `TestPaseoAdapterContract`, `TestSubscriptionReadyBeforePrompt`, `TestPaseoUnsupportedCapabilities`; Node tests `structured events`, `permission IDs`, `MCP at creation`, `workspace identity`, `unknown version`, `read isolation required`, `provider option schema`, `cancelAgent export`, `daemon credentials`.** Replay the probe's structured events, full question inputs and completion usage; CLI human logs must be rejected as event JSON. Send before subscription readiness fails. Creation persists both workspace and provider-session identity. No absolute CLI-internal import, plugin installation or remote host routing. Missing account observation, timeline recovery, read isolation or cleanup capability makes preflight unavailable for live dispatch, with a reason code.
- ```go
- if sendsBeforeReady != 0 { t.Fatal("prompt sent before observation was ready") }
- if response.PermissionID != request.PermissionID { t.Fatal("permission identity lost") }
- ```
+Capabilities retain Version, AccountPinning, ObservedAccount, RecoverableTimeline, ProcessOwnership, MCPAtCreate, ReadIsolation, ReadIsolationReason and IsolationConfigHash. `ReadPolicy{DeniedPaths []string; ConfigHash string}` is trusted canonical configuration. Event retains kind/server/agent/session/turn/permission/epoch/sequence and raw bounded payload. Preflight is per selection/policy; ProcessOwnership is combined with Task 15 inspector coverage, never inferred from Paseo status.
-- [ ] **Step 2: Run red.** `go test ./internal/runner/paseo -run 'TestPaseo|TestSubscriptionReady' -count=1` and `node --test runner/paseo/bridge.test.mjs`.
-- [ ] **Step 3: Implement the Go/Node boundary.** Pin `@getpaseo/client@0.14.0`, `@getpaseo/protocol@0.14.0` and `@getpaseo/server@0.14.0` exactly, including the server dependency used solely for exported daemon credential discovery. Lock transitive dependencies, and communicate over child-process stdin/stdout with request IDs and bounded frames. Keep diagnostics on stderr, redact authentication. Connect only to the configured local daemon; the Go runner supervises bridge exits. Use the exported package paths below, never the installed CLI's helper. The deliberately used client `internal/daemon-client` export is version-pinned and covered by a load/contract test; it is not an invented top-level stop API.
+- [ ] **Tests:** `TestPaseoAdapterContract`, `TestSubscriptionReadyBeforePrompt`, `TestPaseoUnsupportedCapabilities`; Node cases `structured events`, `permission IDs`, `MCP at creation`, `workspace identity`, `unknown version`, `read isolation required`, `provider option schema`, `cancelAgent export`, `daemon credentials`. Replay structured probe events/questions/usage; reject human logs. No Send before Ready; preserve workspace/session IDs and permission IDs. Missing required capability denies with reason. Read-isolation case checks Claude refusal and Codex's explicit ack route, never a globally successful preflight.
+- [ ] **Red/green:** `go test ./internal/runner/paseo -run 'TestPaseo|TestSubscriptionReady' -count=1`; `node --test runner/paseo/bridge.test.mjs`. Green through `make runner-adapter-test`, which checks Node/npm and runs locked `npm ci`. Add it to `ci` and `.amadan/ci.d/`; no missing-Node skip. Mutate readiness and permission forwarding.
+- [ ] **Implement:** Pin client/protocol/server exactly 0.14.0, including transitive lock. Go supervises Node bridge; bounded stdin/stdout frames carry request IDs, redacted stderr diagnostics. Only configured local daemon, no start/stop, remote routing or plugin installation.
- | Go boundary | Installed export/method |
- |---|---|
- | Connect/preflight | `createHostClient` from `@getpaseo/client/node`; `readDaemonInstance`, `readLocalCredentialForTarget`, `resolvePaseoHome` from `@getpaseo/server/daemon-control`; endpoint helpers from `@getpaseo/protocol/daemon-endpoints`; client `connect` (await its promise). Discover only the selected local daemon, never start/stop it. |
- | `CreateWorkspace`, `CreateAgent` | `DaemonClient.createWorkspace`, `createAgent` from `@getpaseo/client/internal/daemon-client`; keep `idempotencyKey`, `workspaceId`, `env`, `modeId`, `providerOptions` and MCP type. |
- | `Subscribe` | `DaemonClient.fetchAgentTimeline`, `subscribeAgentTimeline`, plus `subscribe` for control events; unsubscribe on close. |
- | `Send`, `Respond` | `DaemonClient.sendMessage` with client message identity; `respondToPermission` with the original request ID. |
- | `Stop`, `Archive`, `ArchiveWorkspace` | `DaemonClient.cancelAgent`, `archiveAgent`, `archiveWorkspace`, respectively. `Stop` is cancellation, not proof of containment. |
- | Process inventory support | `DaemonClient.listTerminals` filtered by workspace and `killTerminal` for exact owned IDs; Linux process coverage comes from Task 15. |
+| Operation | Pinned exported surface |
+|---|---|
+| Connect | `createHostClient` from `@getpaseo/client/node`; `readDaemonInstance`, `readLocalCredentialForTarget`, `resolvePaseoHome` from `@getpaseo/server/daemon-control`; endpoint helpers from protocol `daemon-endpoints`; await connect promise. |
+| Workspace/agent | `DaemonClient.createWorkspace/createAgent` from exported `@getpaseo/client/internal/daemon-client`; retain idempotencyKey/workspaceId/env/modeId/providerOptions/MCP type. Load/contract-test this pinned internal export. |
+| Observe | `fetchAgentTimeline`, `subscribeAgentTimeline`, `subscribe` for controls; unsubscribe on close. |
+| Prompt/answer | `sendMessage` with message identity; `respondToPermission` with original request ID. |
+| Cleanup | `cancelAgent`, `archiveAgent`, `archiveWorkspace`; cancellation alone is not containment. `listTerminals`/`killTerminal` use exact workspace-owned IDs. |
- Credentials go only to the trusted bridge connection. Never pass a daemon password to `createAgent.env` or MCP env, print it, or import daemon-control from an unpinned package. Persist creation intent before sending, and recover creation by SDK idempotency key/observed identity; if unsupported, classify uncertainty and never create a replacement blindly. CLI JSON is allowed only for bounded discovery/workspace commands with captured separate stdout/stderr fixtures and strict decoding. Unknown versions or undocumented contracts require a Paseo capability request, not screen scraping or invented RPCs. Implement and test the provider eligibility decisions above now; do not defer identifying the unsupported Codex configuration to a live run. Missing `ReadIsolation` refuses agent creation and dispatch. The later live gate verifies the full effective policy, credentials and cleanup; it does not override unsupported settings.
+Daemon credentials go only to the bridge connection, never agent/MCP env or logs. ProviderOptions come only from trusted policy. Persist creation intent first; recover by SDK idempotency/observed identity or remain uncertain without replacement. CLI JSON is limited to bounded discovery/workspace fixtures with separate stdout/stderr and strict decoding. Unknown versions/contracts need upstream capability support.
- Account-routing finding: installed `@kapybara/zerosub@1.3.0` (`shared/rpc.ts`, `server/{routing,service,state}.ts`) exposes `zerosub.state` and `zerosub.agents.account` through plugin RPC, with bindings and observed sessions, but automatically reassigns exhausted/disabled portable accounts. That is not a no-failover contract. Keep such routes unavailable unless a supported per-agent binding/no-failover guarantee is supplied and tested before prompting. Do not call the account-changing RPC during this planning session or silently use its fallback. The implementation must name and pin the selected routing interface in its capability report before enabling a connection; no guessed `AccountID` field on `createAgent`.
-- [ ] **Step 4: Run green.** Repeat Step 2 through `make runner-adapter-test`. Provision Node v24.19.0 (or an explicitly retested version recorded in the manifest) in both local and Amadan CI; the Make target checks Node/npm and runs `npm ci` against the lock before Node tests. Add the shared Make target to `ci` and a delegating `.amadan/ci.d/` step. No test silently skips for missing Node. Break readiness ordering and permission-ID forwarding separately. This task uses fake transports only; live agents wait for Task 18.
-- [ ] **Step 5: Commit.** `git commit -m "feat: drive Paseo through a pinned structured client"`.
+Installed ZeroSub 1.3.0 exposes `zerosub.state` and `zerosub.agents.account` but automatically reassigns exhausted/disabled portable accounts. It does not prove no-failover. Name/pin a supported per-agent binding, pre-prompt account observation and no-failover interface before eligibility; never invent createAgent AccountID or change shared defaults. Codex acknowledgement waives none of this. Implement both current isolation paths and the future profile restoration seam defined above; unsupported settings cannot be smuggled through live tests.
+- [ ] **Commit:** `feat: drive Paseo through a pinned structured client`.
### Task 10: Create credential-free workspaces from exact revisions
-**Files:** Create `internal/runner/workspace/{workspace,workspace_test}.go`, `internal/runner/workspace/testdata/` small repositories generated by tests; extend `runnerproto/types.go` and `paseo/types.go`.
+**Files:** `internal/runner/workspace/{workspace,workspace_test}.go`, test-generated small Git repos; protocol/Paseo types.
-**Interfaces:** `workspace.Manager` uses `paseo.Client` and runner-local forge read access. Methods `Prepare(ctx context.Context, target team.TargetBinding) (runnerproto.PreparedBug, error)`, `Create(ctx context.Context, assignment runnerproto.Assignment, brief runnerproto.Brief) (paseo.Workspace, error)`, `CaptureCandidate(ctx context.Context, ws paseo.Workspace, target team.TargetBinding) (team.GitCandidate, error)`, `ExportCandidate(ctx context.Context, candidate team.GitCandidate, destination string) error`. Create a private clone per project. `WorkspaceRequest` carries explicit base commit, review branch, unique attempt workspace key and isolation `worktree`.
+**Interfaces:** Manager uses paseo.Client and runner forge-read access: Prepare(target) → PreparedBug; Create(assignment, brief) → Workspace; CaptureCandidate(workspace, target) → GitCandidate; ExportCandidate(candidate, destination) → error. WorkspaceRequest carries exact base, review branch, unique attempt key, isolation `worktree`.
-- [ ] **Step 1: Add `TestWorkspacePinsBase`, `TestWorkspaceHasNoCredentials`, `TestCandidateCaptureCleanAndImmutable`, `TestWorkspaceRetryIdentity`.** Default branch moving after preparation does not change the base. Dirty tracked/untracked files, symlink escape or wrong repository refuses capture. Builder commits cannot switch repository/ref. Poisoned hooks, `.gitconfig`, URL rewrite rules and credential helper never run. Process environment/log/agent-visible clone config contains no Amadan bearer. An old workspace is not reused by a new attempt; a repeated creation request resolves the same workspace or remains uncertain. Capture Git commit/tree and verify the commit descends from base.
- ```go
- if actualBase != prepared.BaseCommit { t.Fatal("workspace followed a moving branch") }
- if hookRan || credentialVisible { t.Fatal("workspace crossed runner trust boundary") }
- ```
+- [ ] **Tests:** `TestWorkspacePinsBase`, `TestWorkspaceHasNoCredentials`, `TestCandidateCaptureCleanAndImmutable`, `TestWorkspaceRetryIdentity`, `TestReadIsolationRequired`. Moving default does not change base. Dirty tracked/untracked files, symlink escape, wrong repo/ref refuse capture; commit descends from base and tree matches. Poison hooks/config/URL rewrites/helpers never execute; bearer absent from agent env/config/logs. New attempts never reuse workspaces; creation retry resolves same identity or uncertainty. Denied subtree/alias or changed policy refuses creation; missing ReadIsolation requires the exact valid Codex acknowledgement, never bypasses Claude's gate.
+- [ ] **Red/green:** `go test ./internal/runner/workspace -run 'TestWorkspace|TestCandidateCapture|TestReadIsolationRequired' -count=1`. Use local disposable remotes and credential sentinels; remove repos.
+- [ ] **Implement:** Private project clone fetched from saved canonical repository by credential-scoped runner subprocess. No credentials in URLs/argv/shared config or inherited agent environment. Give Paseo a credential-free source clone; disable system/global Git config, hooks and credential helpers for agents/checks; validate args/paths without shell interpolation. Read-policy preflight and acknowledgement checks precede every turn. Same-user harness confinement is not OS-user isolation; acknowledged Codex reads remain explicitly unconfined.
-- [ ] **Step 2: Run red.** `go test ./internal/runner/workspace -run 'TestWorkspace|TestCandidateCapture|TestReadIsolationRequired' -count=1`.
-- [ ] **Step 3: Implement trust separation.** Fetch the saved canonical Amadan repository using a runner subprocess with scoped credential access; no secrets in URLs, argv, shared clone configuration or inherited agent environment. Create a credential-free source clone for Paseo and verify its remote. Disable system/global Git config, hooks and credential helpers in all agent/check workspaces; validate command arguments and paths without shell interpolation. Keep publication credentials outside all worktrees. Pass the canonical denied-path set to Task 9 at agent creation; require `ReadIsolation` before any model turn. Add `TestReadIsolationRequired` to this task's test command: missing capability, denied path nested in a workspace, symlink alias or a changed policy refuses creation before prompting. Local same-user harness sandboxes are the milestone's trust boundary, not a claim of OS-user isolation. Reproduction/implementation use fresh Paseo workspaces on the bound review branch from the explicit base; import frozen reproduction into the implementation brief. Review uses a fresh candidate checkout and no builder conversation. Export candidate into runner-owned immutable staging before builder cleanup, as local verified Git objects on this same docs-t1 runner. Review/check workspaces consume that immutable local staging, not the builder worktree. No cross-machine transfer, Git bundles, chunk manifests or pre-review forge push. Task 11 validates all reproduction paths and evidence hashes.
-- [ ] **Step 4: Run green.** Repeat Step 2 with local disposable Git remotes only. Assert hook sentinel absent and no credential marker in agent environment/config/logs. Delete test-owned repositories.
-- [ ] **Step 5: Commit.** `git commit -m "feat: isolate task workspaces and capture exact Git candidates"`.
+ Reproduction/implementation use fresh base workspaces; implementation receives frozen reproduction. Capture immutable local Git objects into runner-owned staging before builder cleanup. Fresh review/check checkouts consume staging, not builder workspace or conversation. No pre-review push, bundle or cross-machine transfer. Task 11 validates evidence paths/hashes; this task injects prepared-definition fixtures, avoiding an executor dependency.
+- [ ] **Commit:** `feat: isolate task workspaces and capture exact Git candidates`.
### Task 11: Freeze reproductions and run trusted checks
-**Files:** Create `internal/runner/checks/{executor,definition,goresults,sandbox,executor_test,sandbox_test}.go`, app `artifacts.go`, `internal/equipotest/artifacts_test.go`; add `0014_artifact_blobs.sql`, models/schema entries; extend `runnerproto/types.go`.
+**Files:** `internal/runner/checks/{executor,definition,goresults,sandbox}.go` and tests; app artifacts, migration 0014; `internal/equipotest/artifacts_test.go`; protocol.
-**Interfaces:** `checks.Definition{Version int; Repository, BaseCommit string; Commands []Command; Reproduction Command; Baseline TestBaseline}`; `TestIdentity{Package, Name string}`, `TestBaseline{Names []TestIdentity; Hash string}`; `CaptureBaseline(ctx context.Context, def Definition) (TestBaseline, error)` runs the base and records the required identities; `Command{Argv []string; Dir, Parser string; TimeoutSeconds int}`; `checks.Reproduction{ExpectedSymptom string; Files []File; TestNames []string}`; `File{Path string; Bytes []byte}`. `CommandSandbox.Run(ctx context.Context, command Command, workspace string, policy paseo.ReadPolicy, stdout, stderr io.Writer) (int, error)` returns the exit code and streams output to executor-owned parsers before bounded log retention. Its production implementation uses the verified local Codex command sandbox with a runner-built profile, while ordinary unit tests inject a fake. `ParseDefinition(raw []byte, repository, baseCommit string) (Definition, error)`, `(*Executor).Reproduce(ctx context.Context, def Definition, repro Reproduction, subjectCommit, candidateHash string) (team.CheckResult, error)`, `(*Executor).RepositoryChecks(ctx context.Context, def Definition, candidate team.GitCandidate, candidateHash string) (team.RepositoryCheckResult, error)`. Instance `(*Store).PutBlob(ctx context.Context, principal RunnerPrincipal, scope team.Scope, h team.Handle, digest string, body []byte) error`, `Blob(ctx context.Context, principal RunnerPrincipal, scope team.Scope, digest string) ([]byte, error)` use scoped content-addressed immutable rows. Artifact registration continues through `team.Store.Register`.
+**Interfaces:** Definition has version/repository/base, Commands, Reproduction command, Baseline `{Names []TestIdentity; Hash string}`; identity is package/name. Command has argv/dir/parser/timeout seconds. Reproduction has expected symptom, files `{Path; Bytes}`, test names. CaptureBaseline(def) → TestBaseline; ParseDefinition(bytes, repo, base) → Definition; Executor.Reproduce(def, repro, subjectCommit, candidateHash) → CheckResult; RepositoryChecks(def, candidate, candidateHash) → RepositoryCheckResult. CommandSandbox.Run(command, workspace, ReadPolicy, stdout, stderr) returns exit/error. Store PutBlob(principal, scope, handle, digest, bytes), Blob(principal, scope, digest); Register remains core artifact boundary.
-- [ ] **Step 1: Add `TestFrozenReproduction`, `TestTrustedBaseCheckDefinitions`, `TestExecutorEvidenceOutcomes`, `TestArtifactScopeAndLimits`, `TestReproductionOverlayCollision`, `TestRepositoryTestSetSuperset`, `TestRepositoryDeletedTestFile`, `TestRepositoryTSkipRejected`.** Freeze valid bytes outside every worktree; changed bytes under the digest conflict. Later candidate edits cannot change frozen files or check commands. Base test failure must match the symptom with `TestsRun > 0`, `TestsFailed > 0`; candidate must pass the same frozen tests. Parse real `go test -json` test events; compile errors, skips, no tests, incomplete JSON, timeout, log truncation affecting parsing and exit zero without tests are not passes. Repository checks are a separate result. Traversal, absolute paths, symlinks, duplicate file paths, corrupt blob hashes, wrong base and oversized uploads fail before execution. Record the base test-name set by package, test and subtest under the same build tags/platform; candidate successful execution must contain that set and the frozen reproduction names, with every required member passing. A deleted `_test.go` file, renamed-away baseline test, `t.Skip`, skipped package or subtest, or zero tests fails even if the process exits zero. Additional passing tests are allowed. Persist the baseline set/hash in the check definition and the observed set/hash in the result. Agents cannot submit executor-attested results through their tool capability.
- ```go
- if base.Outcome != team.CheckFail || base.TestsFailed == 0 { t.Fatal("base did not reproduce") }
- if candidate.Outcome != team.CheckPass || candidate.TestsRun == 0 { t.Fatal("candidate lacks passing tests") }
- ```
+- [ ] **Tests:** `TestFrozenReproduction`, `TestTrustedBaseCheckDefinitions`, `TestExecutorEvidenceOutcomes`, `TestArtifactScopeAndLimits`, `TestReproductionOverlayCollision`, `TestRepositoryTestSetSuperset`, `TestRepositoryDeletedTestFile`, `TestRepositoryTSkipRejected`, `TestCheckSandboxDeniedPaths`. Changed frozen bytes/hash/commands fail. Base failure matches symptom with positive run/fail counts; candidate passes identical frozen tests. Compile failure, skips, zero tests, incomplete JSON, timeout, truncated-before-parsing output or zero-exit without tests fails. Reject traversal/absolute/symlink/duplicate paths, corruption, wrong base and oversized blobs. Candidate must pass baseline package/test/subtest set plus reproduction under identical tags/platform; renamed/deleted tests, skipped packages/subtests and t.Skip fail; extra passing tests are allowed. Agents cannot submit executor-attested results. Assert base SubjectHash is base commit, candidate SubjectHash is artifact hash.
+- [ ] **Red/green:** `go test ./internal/runner/checks ./internal/equipotest -run 'TestFrozen|TestTrusted|TestExecutor|TestArtifact|TestReproductionOverlay|TestRepositoryTest|TestRepositoryDeleted|TestRepositoryTSkip|TestCheckSandboxDeniedPaths' -count=1`; green also migration check. Use actual small Go fixtures; mutate definition/symptom/count/hash guards.
+- [ ] **Implement:** Read base `.equipo/checks.json` v1; `go-test-json` measures tests, `exit` only non-test gates. Base `.amadan/ci.d/` or `.amadan/ci` needs an explicit reviewed Go adapter preserving structured results; otherwise wait for setup. Freeze manifest and transitive scripts/Makefiles. Baseline includes required names/hash; result includes observed names/hash. Known failing bug test may be baseline; incomplete discovery/build failure is setup failure.
-- [ ] **Step 2: Run red.** `go test ./internal/runner/checks ./internal/equipotest -run 'TestFrozen|TestTrusted|TestExecutor|TestArtifact|TestReproductionOverlay|TestRepositoryTest|TestRepositoryDeleted|TestRepositoryTSkip|TestCheckSandboxDeniedPaths' -count=1`.
-- [ ] **Step 3: Implement pinned execution and artifact persistence.** Read `.equipo/checks.json` from the immutable base; require version 1 and supported parser `go-test-json` for reproduction/test counts, `exit` only for non-test gates. If absent, support the repository's base `.amadan/ci.d/` or `.amadan/ci` only through a reviewed, explicit Go adapter that captures structured test results; unsupported repositories wait with a setup reason, never guess success. Pin the manifest plus transitively invoked repository scripts/Makefiles in a base-derived check-definition bundle. Keep the immutable candidate export untouched. Execute repository gates from trusted material against a fresh scratch copy of that export. For reproduction only, overlay the frozen test files into a separate scratch copy of the base or candidate. An absent path may be added; an existing file may be replaced only if its bytes exactly match the recorded base version (or already equal the frozen bytes). Reject a candidate-edited collision, non-test path, symlink or traversal; never silently overwrite a candidate fix. Record the subject commit, overlay hash and collision checks. Destroy the scratch copies after each run. `Reproduce` receives empty `candidateHash` for base and writes `SubjectHash = def.BaseCommit`; for candidate it verifies commit against the typed candidate artifact and writes `SubjectHash = candidateHash`, as the core evidence predicate requires. Reject an empty candidate hash on a candidate run; test commit/hash confusion explicitly. Refuse an adapter whose scripts cannot preserve that separation. At least one measured test command and every required repository gate must succeed. During Task 15 preparation integration, combine Task 10's immutable base fetch with `checks.CaptureBaseline(ctx context.Context, def Definition) (TestBaseline, error)` from this task before finalizing `PreparedBug.CheckDefinitionHash`. Task 10 unit tests inject a prepared-definition fixture and do not import this later executor. A known failing bug test may be present in the baseline, but incomplete discovery/build failure requires setup. Candidate modifications to the check harness cannot weaken the baseline gate; candidate new tests may add coverage.
+ Repository checks run trusted material against a fresh immutable-export copy; reproduction runs separate scratch base/candidate copies. Overlay only test files; existing path must equal recorded base bytes or frozen bytes. Candidate-edited collision refuses, never overwrites the fix. Record subject commit/overlay hash/collision checks and delete scratch. Candidate runs require nonempty verified candidateHash; base uses empty candidateHash and base commit subject. At least one measured test command and every required repository gate must succeed. Task 15 combines immutable fetch and CaptureBaseline before final PreparedBug.CheckDefinitionHash.
- Executor processes are supervised process groups, with no model/forge credentials and a minimal environment. Repository tests are untrusted code too: `Executor` requires a `CommandSandbox` which runs the pinned local `codex sandbox -P equipo-checks` command with an explicit trusted filesystem profile, denied paths from Task 9, required runtime/workspace reads and no credential access. This is command execution, not a Codex agent or provider call; the locally verified named-profile support is separate from the ineligible Paseo Codex integration. Add `TestCheckSandboxDeniedPaths` with per-path sentinels and a passing workspace control; no unsandboxed fallback. Runner config records the verified Codex binary path/version; checks may need dependencies but cannot receive publication authority. Each command timeout is at most 1,200 seconds and never exceeds remaining attempt time. Retain exit code, parsed counts, timestamps and bounded logs (64 KiB per stream); parse incrementally before truncating stored logs. Freeze reproduction through `RoleReproduction` before base execution completes and before implementation starts. Cache only hash-verified instance blobs. Each complete reproduction/evidence blob is at most 1 MiB and an attempt's uploaded blobs at most 128 MiB; reject larger work visibly instead of chunking. Persist complete blobs in the activation DB, so backup includes evidence; no external filesystem-only evidence store. Do not garbage-collect referenced task evidence in this plan.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`. Mutate baseline command selection, symptom match, positive test counts and hash verification independently. Use actual small Go fixtures, no external repositories/providers.
-- [ ] **Step 5: Commit.** `git commit -m "feat: execute frozen reproductions and base-pinned checks"`.
+ Production CommandSandbox is pinned command-only `codex sandbox -P equipo-checks` with explicit runner-built filesystem denies, required runtime/workspace reads, minimal env and no credentials. This named-profile CLI support is independent of Paseo agent support; owner acknowledgement cannot relax executor confinement. Per-path sentinel tests and readable workspace control are mandatory, with no unsandboxed fallback. Record configured Codex binary/version. Supervise process groups; command timeout ≤1,200 seconds and remaining attempt time. Parse incrementally before retaining 64 KiB per output stream. Freeze RoleReproduction before base completion/implementation. Blobs are immutable hash-verified activation-DB rows: ≤1 MiB each, ≤128 MiB uploaded/attempt. Reject larger work, no chunking or referenced-evidence GC.
+- [ ] **Commit:** `feat: execute frozen reproductions and base-pinned checks`.
### Task 12: Persist events and usage across reconnects
-**Files:** Create runner `journal.go`, `events.go`, `usage.go`, their `_test.go` files; app `runner_events.go`, `internal/equipotest/runner_events_test.go`; add `0015_runner_events.sql`, models/schema entries.
-
-**Interfaces:** `runner.OpenJournal(path string) (*Journal, error)`, `(*Journal).Append(ctx context.Context, event runnerproto.Event) error`, `Pending(ctx context.Context, limit int) ([]runnerproto.Event, error)`, `Ack(ctx context.Context, eventID string) error`, `Close() error`. `runnerproto.Event{ID, TaskID, ServerID, AgentID, SessionID, Epoch, Kind, TurnID string; Seq int64; Scope team.Scope; Handle team.Handle; Payload json.RawMessage; SourceAt time.Time}`. `(*Store).IngestRunnerEvent(ctx context.Context, principal RunnerPrincipal, event runnerproto.Event) error`. `runner.UsageAccumulator.Observe(event paseo.Event) (*team.Usage, error)` emits a settled total only after a complete verified turn; field completeness is tracked separately from numeric zero.
+**Files:** Runner journal/events/usage and tests; app runner_events, migration 0015; `internal/equipotest/runner_events_test.go`.
-- [ ] **Step 1: Add `TestRunnerEventReplay`, `TestTimelineEpochReplacement`, `TestUsageCumulativeAndMissing`, `TestRunnerJournalCrashBoundaries`, `TestBufferFullStopsWork`.** Crash before local append, after append/before upload, and after server commit/before ACK. No duplicate event or charge; conflicting duplicate ID rejects. Refetch missed timeline before following live events, deduplicate by server/agent/session/epoch/sequence; control events without sequence use stable event/turn/request identity. Epoch replacement invalidates the old projection but never deletes accounting. Cumulative cost 0.0673131 then 0.0758928 is not summed as two independent costs. Missing final usage leaves `Receipt.Usage == nil`, not zero. A later zero LastUsage cannot erase completed-turn events. Full disk/outbox stops admission and initiates containment.
- ```go
- if receipt.Usage != nil { t.Fatal("missing usage became known zero") }
- if chargedTwice { t.Fatal("event replay charged twice") }
- ```
+**Interfaces:** OpenJournal(path) → Journal; Append(Event), Pending(limit), Ack(eventID), Close. Event retains ID/task/server/agent/session/epoch/kind/turn/sequence/scope/handle/payload/source time. IngestRunnerEvent(principal, event). UsageAccumulator.Observe(paseo.Event) returns settled `*team.Usage` only for verified complete turns; field-known flags are separate from numeric zero.
-- [ ] **Step 2: Run red.** `go test ./internal/runner ./internal/equipotest -run 'TestRunnerEvent|TestTimelineEpoch|TestUsageCumulative|TestRunnerJournal|TestBufferFull' -count=1`.
-- [ ] **Step 3: Implement durable intake.** Journal SQLite lives in the runner's persistent private state directory, not scratch. Fsync creation/dispatch identities before effects, then append each event before acknowledging it to local workflow logic. Instance inbox and app projection/audit update transactionally; replay into core receipts/artifacts is idempotent and acknowledged only after core acceptance. Add a unique registration request key to the artifact transport inbox so repeated `Register` cannot append duplicate semantic artifacts. Use live subscriptions plus explicit cursor refetch on reconnect. Detect unrecoverable outcome gaps and stop new dispatch until reconciled. An explicit completed-turn event with missing usage is different: keep its bounded reservation open and allow later work only under Task 3's remaining-headroom rule. Never infer a completed turn from queued/idle status or prose.
+- [ ] **Tests:** `TestRunnerEventReplay`, `TestTimelineEpochReplacement`, `TestUsageCumulativeAndMissing`, `TestRunnerJournalCrashBoundaries`, `TestBufferFullStopsWork`. Crash before append, after append/before upload, after server commit/before ACK: no duplicate effects/charge; changed duplicate payload conflicts. Refetch before following live; deduplicate server/agent/session/epoch/sequence, controls by stable event/turn/request ID. Epoch replacement rebuilds projection without deleting accounting. Cumulative 0.0673131 then 0.0758928 must not be summed. Missing usage stays nil; later zero LastUsage cannot erase completed evidence. Full disk/outbox stops admission and contains.
+- [ ] **Red/green:** `go test ./internal/runner ./internal/equipotest -run 'TestRunnerEvent|TestTimelineEpoch|TestUsageCumulative|TestRunnerJournal|TestBufferFull' -count=1`; green also migration check, reopen both databases, mutate dedup/epoch/nil handling.
+- [ ] **Implement:** Persistent private SQLite journal; fsync creation/dispatch IDs before effects, append events before local workflow ACK. Instance inbox/projection/audit transactionally; acknowledge only after idempotent core acceptance. Unique artifact registration request keys prevent semantic duplicates. Timeline gaps with unknown outcomes block dispatch; explicitly completed turn with missing usage follows Task 3 headroom rule. Idle/queued/prose never proves completion.
- Normalize each provider's measured token fields through versioned fixture tests. Add `runnerproto.TokenUsage{UncachedInput, CachedInput, Output int64; UncachedKnown, CachedKnown, OutputKnown bool}` to the projection/events, separately from core `team.Usage`. Core `InputTokens` is the checked sum of uncached plus cached input, once. If provider input includes cache, subtract it before reporting uncached input; if it excludes cache, add it only for the core total. Cache-write categories must be normalized once too. Display cached input separately and preserve each unknown flag. If cumulative usage semantics are not documented/tested, keep that field unknown. Subscription estimated cost may be displayed separately but is not charged as actual spend. Completed observations may arrive after cancel and settle the known action without changing cancellation state. Buffer at most 128 MiB of unacknowledged events; exponential reconnect backoff 1–30 seconds with jitter while the monotonic lease deadline remains binding. Redact secrets; artifact logs are downloads as escaped text, never active HTML.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`; mutate deduplication, epoch replacement and nil-usage handling separately. Reopen both journal and instance DB during tests.
-- [ ] **Step 5: Commit.** `git commit -m "feat: persist runner events and reconcile measured usage"`.
+ Versioned normalization uses `TokenUsage{UncachedInput, CachedInput, Output int64; UncachedKnown, CachedKnown, OutputKnown bool}`. Core InputTokens sums uncached+cached once with overflow checks; subtract cache from inclusive provider totals or add to exclusive totals; normalize cache writes once. Untested cumulative semantics remain unknown. Estimated subscription cost is display-only. Late completed observations may settle known actions without changing cancellation. Persist isolation labels through replay/replacement. Buffer ≤128 MiB unacknowledged events; reconnect backoff 1–30 seconds plus jitter never extends monotonic lease. Redact secrets; logs download as escaped text.
+- [ ] **Commit:** `feat: persist runner events and reconcile measured usage`.
### Task 13: Relay questions and permissions with scoped tools
-**Files:** Create runner `questions.go`, `tools.go`, `tool_socket.go`, `internal/runner/tool_socket_test.go`, minimal `cmd/equipo-runner/{main,main_test}.go`, app `questions.go`, `internal/equipotest/questions_test.go`, `internal/runner/questions_test.go`; add `0016_questions.sql`, models/schema entries; extend protocol and copy keys.
+**Files:** Runner questions/tools/tool_socket and tests; minimal `cmd/equipo-runner/{main,main_test}.go`; app questions, migration 0016; `internal/equipotest/questions_test.go`; protocol/copy.
-**Interfaces:** `Question{ID, TaskID, AgentID, SessionID, PermissionID, Kind string; Attempt team.AttemptID; Fence, Revision int64; Request json.RawMessage; AnsweredBy string}`. `(*Store).AnswerQuestion(ctx context.Context, actor Actor, questionID string, revision int64, answer json.RawMessage) error`. `runner.DeliverAnswer(ctx context.Context, client paseo.Client, agent paseo.Agent, question runnerproto.Question, answer json.RawMessage) error`. `paseo.PermissionResponse{PermissionID string; Behavior string; UpdatedInput json.RawMessage}`. `runner.ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPath, capabilityPath string) error` serves per-agent stdio Model Context Protocol (MCP) to the harness and forwards typed requests over a per-attempt Unix socket to the runner. `runner.ServeAttemptSocket(ctx context.Context, socketPath string, binding ToolBinding) error` owns that socket; `ToolBinding` binds instance/task/attempt/fence/allowed tool names, current lease and journal request IDs. The capability expires with the lease; runner validates the binding for every call.
+**Interfaces:** Question retains ID/task/agent/session/permission/kind/attempt/fence/revision/raw bounded request/AnsweredBy. AnswerQuestion(actor, questionID, revision, answer); DeliverAnswer(client, agent, question, answer). PermissionResponse retains PermissionID, Behavior, UpdatedInput. ServeTools(input, output, socketPath, capabilityPath) speaks harness stdio MCP and forwards typed socket requests; ServeAttemptSocket(socketPath, ToolBinding). Binding includes instance/task/attempt/fence/tool names/current lease/journal request IDs; validate every call, capability expires with lease.
-- [ ] **Step 1: Add `TestQuestionPermissionID`, `TestQuestionStaleAnswer`, `TestQuestionBrowserAuthority`, `TestAgentToolScope`, `TestToolVerbUnderFakeHarness`, `TestToolSocketIsolation`.** Structured `AskUserQuestion` sends the original permission ID and updated answers through Respond, never Send. Conversational follow-up uses Send only when explicitly classified as such. Cancel/restart/permission replacement invalidates answers. Same answer replay is one effect; changed replay conflicts. Only current requester or current owner may answer execution questions in plan 2; no teammate's coordinator acts for them. Tool capability cannot read another task, publish, attest checks, change budgets or issue runner calls. Copy/sample prompt injection in a tool result cannot widen permissions. A fake harness spawns the real `equipo-runner tool` subprocess from the same `type: "stdio"` MCP config used at creation; initialize and submit a real typed request over its stdin/stdout and assert the runner receives it over the socket exactly once. Its stdio belongs to the harness, not the runner. Test another attempt's capability, expired fence/lease, changed request-ID payload, malformed/oversized frame, missing capability file and disconnected socket. None can create evidence. Inspect the child argv and logs for a capability sentinel: it must be absent.
- ```go
- if sendCalls != 0 || respondCalls != 1 { t.Fatal("structured answer bypassed permission response") }
- if staleAnswerApplied { t.Fatal("old permission answer affected a new attempt") }
- ```
+- [ ] **Tests:** `TestQuestionPermissionID`, `TestQuestionStaleAnswer`, `TestQuestionBrowserAuthority`, `TestAgentToolScope`, `TestToolVerbUnderFakeHarness`, `TestToolSocketIsolation`. AskUserQuestion answers use Respond with original ID/updated answers, never Send; conversational follow-up explicitly uses Send. Cancel/restart/replaced permission invalidates answer. Exact replay has one effect, changed replay conflicts. Only current requester/current owner answers; injection cannot widen tools. No cross-task reads, publish, check attestation, budget edits or runner API authority. Fake harness spawns real `equipo-runner tool` with creation MCP config, initializes and submits over stdio; runner sees one socket request. Reject wrong attempt, expired lease/fence, changed request payload, malformed/oversized frame, missing file/disconnected socket. Capability sentinel absent from argv/logs.
+- [ ] **Red/green:** `go test ./internal/runner ./internal/equipotest -run 'TestQuestion|TestAgentTool|TestToolVerb|TestToolSocket' -count=1`; green also migration check. Build real tool binary under `$TMPDIR`, test and remove it. Mutate Respond→Send. Use sanitized Claude/Codex fixtures; unsupported shapes remain pending until live proof.
+- [ ] **Implement:** POST `/tasks/{id}/questions/{question}/answer` uses session Actor/current roster/revision/CSRF. Persist full bounded sanitized permission input; outbound authenticated answer polling. Errors/unknown formats never imply approval. Creation tools are submit_reproduction, submit_candidate, submit_review, ask_person, narrowed by capability; typed submissions are validated by runner, which derives session/isolation provenance. No coordinator/settlement tools.
-- [ ] **Step 2: Run red.** `go test ./internal/runner ./internal/equipotest -run 'TestQuestion|TestAgentTool|TestToolVerb|TestToolSocket' -count=1`.
-- [ ] **Step 3: Implement direct human relay and tool result submission.** Persist full bounded permission input for display, without secrets; use SDK permission responses keyed by ID. POST `/tasks/{id}/questions/{question}/answer` uses verified actor, current roster, revision and CSRF. Poll answers through the runner's authenticated outbound stream. Treat permission errors/unknown provider formats as pending, not implicit approval. Tools at agent creation are only `submit_reproduction`, `submit_candidate`, `submit_review`, `ask_person`, narrowed by capability. They accept typed data, never raw evidence/provenance fields; runner validates files/commit and derives provenance from the observed session. No plan/coordinator/settlement tools yet. Runner creates `<StateDir>/attempts/<opaque-id>/` with mode 0700, a socket there and an atomically created 0600 capability file. MCP config contains the fixed runner executable, `args: ["tool"]`, `type: "stdio"`, and `EQUIPO_TOOL_SOCKET` / `EQUIPO_TOOL_CAPABILITY_FILE` paths plus the nonsecret attempt marker in its environment. No other runner environment is forwarded. No capability bytes in argv, agent environment, prompt, config JSON or logs. The trusted tool opens the file without following symlinks, verifies owner/mode, and authenticates each bounded socket request with the attempt capability. Runner verifies peer UID as an additional check; UID alone is not authority. Use a bounded versioned request/response protocol and durable request-ID deduplication before acknowledging submission. Replays with changed bytes conflict. Socket path length is checked before agent creation. Remove the attempt socket and capability after verified containment, invalidate them immediately on lease/fence change, and recreate only after fresh authority. Model shell/file tools must be unable to read the entire state directory under Task 9's isolation policy. This local Unix socket is the only tool-to-runner channel; it adds no TCP or inet listener. Each new follow-up turn needs a fresh budgeted admission; answering an existing permission does not secretly launch another turn. On long waits release/contain the attempt if its time limit expires and invalidate its permission ID.
-- [ ] **Step 4: Run green.** Repeat Step 2 and `make migration-check`; build a test-owned runner binary under `$TMPDIR` using the minimal `tool` command dispatcher added here in `cmd/equipo-runner/{main,main_test}.go` (Task 17 expands it). Run the fake-harness test with that real verb, then remove the binary. Deliberately route a structured answer through Send and require the test to fail. Test both Claude and Codex sanitized request fixtures; unsupported shapes stay blocked until the live compatibility test establishes them.
-- [ ] **Step 5: Commit.** `git commit -m "feat: relay fenced questions and permission responses"`.
+ Create 0700 `<StateDir>/attempts/<opaque-id>/`, private socket and atomic 0600 capability file. MCP uses fixed executable, args `["tool"]`, type stdio, env paths EQUIPO_TOOL_SOCKET/EQUIPO_TOOL_CAPABILITY_FILE and nonsecret attempt marker only. Capability bytes never enter argv/agent env/prompt/config/logs. Trusted tool opens without symlink following, checks owner/mode, authenticates each bounded request; runner also checks peer UID, which alone grants nothing. Durable request-ID dedup precedes ACK. Check socket path length before creation. Invalidate on fence/lease change; remove socket/file after containment; recreation requires fresh authority. Claude must be denied state-directory reads; acknowledged Codex carries the explicit unconfined risk, not a false unreadability assertion. Follow-up turns need fresh budget admissions; permission answers cannot launch hidden turns. Expired waits release/contain and invalidate permission ID.
+- [ ] **Commit:** `feat: relay fenced questions and permission responses`.
### Task 14: Publish only the verified review commit
-**Files:** Create `internal/runner/forge/{forge,forge_test}.go`, app `runner_adapters.go`, `internal/equipotest/publish_test.go`; extend protocol with publication/dispatch tickets and receipt lookup.
+**Files:** Runner forge implementation/tests; app runner_adapters, `internal/equipotest/publish_test.go`; protocol tickets/receipt lookup/description provenance.
-**Interfaces:** `forge.Publisher` implements `team.Adapter`: `Classify(team.Operation) (team.ReplayClass, error)`, `Execute(context.Context, team.Dispatch) (team.Receipt, error)`, `Reconcile(context.Context, team.Dispatch) (team.ReconcileResult, error)`. Publication payload is `{repository, ref, head, candidate_hash}` from Task 4. `runnerproto.DispatchTicket{Dispatch team.Dispatch; Scope team.Scope; Handle team.Handle; Incarnation int64; ExpiresAt time.Time}` is issued only by instance Admit. `Execution` installs non-network adapters backed by durable runner observations: provider calls are unsafe to replay without proof, forge pushes are reconcilable. Instance adapters' Execute refuses local execution; the authorized runner receives the ticket.
+**Interfaces:** forge.Publisher implements team.Adapter Classify/Execute/Reconcile. Payload repository/ref/head/candidate_hash from Task 4 plus immutable description/provenance digest. DispatchTicket includes Dispatch/Scope/Handle/Incarnation/ExpiresAt, issued by Admit. Instance adapters reconcile durable runner observations; Execute refuses instance-local effects. Provider actions are unsafe to replay without proof; forge publication is reconcilable.
-- [ ] **Step 1: Add `TestPublishQualifiedRef`, `TestPublishExactEvidence`, `TestPublishLostReceipt`, `TestPublishCredentialIsolation`, `TestPublishCancelRace`.** Target `heads/main` yields destination `refs/heads/heads/main`, never `refs/heads/main`. Equal saved default, forged repository/ref, tag, changed candidate, stale ticket, wrong runner or missing evidence refuses before Git. Local receive hook records the exact commit. Lost Admit response first recovers the exact unexpired ticket via Task 8's request ID; duplicate delivery cannot dispatch twice, and expiry or changed authority prevents Git. Lost push reply followed by remote-ref query matching the expected commit recovers a receipt, without another push. Different remote head conflicts; query failure stays uncertain/charged. Cancellation before dispatch causes no push; cancellation after dispatch reports an in-flight effect and reconciles it without undoing the branch.
+- [ ] **Tests:** `TestPublishQualifiedRef`, `TestPublishExactEvidence`, `TestPublishLostReceipt`, `TestPublishCredentialIsolation`, `TestPublishCancelRace`. `heads/main` maps to `refs/heads/heads/main`. Saved default, forged repo/ref, tags, changed candidate, stale ticket/wrong runner/missing evidence refuse before Git. Local receive hook sees exact commit. Lost Admit recovers same authorized ticket; duplicate delivery dispatches once. Lost push reply reconciles matching remote commit without second push; mismatch conflicts, query failure stays uncertain. Cancel before dispatch prevents push; after dispatch reconciles in-flight effect without branch deletion. TestPublishExactEvidence also checks description labels/readback; Task 16 later adds the combined surface test.
+- [ ] **Red/green:** `go test ./internal/runner/forge ./internal/equipotest -run 'TestPublish' -count=1`; mutate ref/identity/retry guards; retain core replay/receipt-conflict tests.
+- [ ] **Implement:** ReadyToPublish before Intend, revalidate at Admit and immediately before Git. Verify deadline/incarnation/target/local immutable objects and isolation lineage. Credential-isolated Git, canonical HTTPS remote, hooks/helpers off, refspec `<commit>:refs/heads/<Ref>`. First creation uses `--force-with-lease=refs/heads/<Ref>:` expecting absence; never authorize replacement using an existing old head or unguarded force. Retry accepts only identical existing commit. Durable dispatch precedes Git; exact-target readback recovers receipt with disclosed agent identity; lack of visibility is not proven absence.
- ```go
- if gotRefspec != commit+":refs/heads/"+reviewRef { t.Fatal("unqualified push") }
- if remoteHead != candidate.Commit { t.Fatal("published unchecked commit") }
- if secondPushCount != 0 { t.Fatal("replayed an uncertain publication") }
- ```
-
-- [ ] **Step 2: Run red.** `go test ./internal/runner/forge ./internal/equipotest -run 'TestPublish' -count=1`.
-- [ ] **Step 3: Implement publication and reconciliation.** Call `ReadyToPublish` before Intend and revalidate at Admit. Runner verifies ticket deadline/incarnation, target and local immutable object immediately before pushing. Use a credential-isolated Git subprocess, hooks/helpers disabled, canonical HTTPS Amadan remote, and refspec `<commit>:refs/heads/<Ref>`; never `HEAD` or a short destination. First publication uses `--force-with-lease=refs/heads/<Ref>:` with an empty expected old object, so a concurrently created ref refuses instead of overwriting it. This is absence-checked creation only; never supply an existing old head to authorize replacement or use an unguarded force push. Review ref creation expects absence; retry accepts only the identical existing commit. Remote ref observation supplies receipt fields for repository/ref/commit/candidate hash and disclosed agent identity. Keep a local durable dispatch record before Git. Exact-target readback reconciles unknown outcomes; lack of visibility is not definitive absence. A target-branch change or manual merge never grants default-branch push rights. Use supported Amadan agent credential/config surfaces; do not copy a person's forge credential or invent an Amadan API. Tests use a local bare repository and credential sentinels.
-- [ ] **Step 4: Run green.** Repeat Step 2; mutate ref qualification, candidate matching and retry handling separately. Preserve core action replay/receipt-conflict tests.
-- [ ] **Step 5: Commit.** `git commit -m "feat: publish verified commits to qualified review refs"`.
+ Construct review branch description from persisted evidence, listing `unconfined` affected steps/connections/provider versions. Publish/read back via supported Amadan review-description surface using runner-held agent credential; name/verify that interface during implementation, no invented API or person credential. Include description identity in durable reconciliation, so lost replies cannot lose the label or duplicate publication. A pushed ref without confirmed required description is incomplete/uncertain, never delivered success. Default-branch changes/manual merges grant no push authority. Tests use bare local Git plus fake supported description transport.
+- [ ] **Commit:** `feat: publish verified commits to qualified review refs`.
### Task 15: Drive the workflow and prove containment
-**Files:** Create runner `supervisor.go`, `service.go`, `process_linux.go`, `process_linux_test.go`, `supervisor_test.go`, `service_test.go`, app `cancel.go`, `internal/equipotest/cancel_test.go`; extend protocol and journal persistence.
+**Files:** Runner supervisor/service/process_linux and tests, journal/protocol; app cancel, `internal/equipotest/cancel_test.go`.
+
+**Interfaces:** Supervisor.Run(claim), Cancel(scope, handle) → ContainmentProof, Recover(). Proof retains attempt/fence/server/agent/workspace/BootID/process identities/CheckedAt/Empty. ProcessIdentity is host PID/start ticks/boot ID. ProcessInspector.Track(owner), Remaining(owner) → ProcessInventory, Stop(identity); owner binds attempt/marker/agent/workspace/executor groups. Inventory contains processes/terminal IDs/CoverageKnown. Production NewLinuxProcessInspector(procRoot, client, journal) is built here. Extend client ListTerminals(workspace)/KillTerminal(exact ID).
-**Interfaces:** `runner.Supervisor.Run(ctx context.Context, claim runnerproto.ClaimResponse) error`, `Cancel(ctx context.Context, scope team.Scope, h team.Handle) (runnerproto.ContainmentProof, error)`, `Recover(ctx context.Context) error`. `ContainmentProof{Attempt team.AttemptID; Fence int64; ServerID, AgentID, WorkspaceID, BootID string; ProcessIdentities []ProcessIdentity; CheckedAt time.Time; Empty bool}`; `ProcessIdentity{HostPID int; StartTicks uint64; BootID string}`. `ProcessInspector` has `Track(ctx context.Context, owner ProcessOwner) error`, `Remaining(ctx context.Context, owner ProcessOwner) (ProcessInventory, error)` and `Stop(ctx context.Context, identity ProcessIdentity) error`. `ProcessOwner{Attempt team.AttemptID; Marker string; Agent paseo.Agent; Workspace paseo.Workspace; ExecutorGroups []ProcessIdentity}` and `ProcessInventory{Processes []ProcessIdentity; TerminalIDs []string; CoverageKnown bool}` retain both OS and Paseo ownership. Build production `NewLinuxProcessInspector(procRoot string, client paseo.Client, journal *Journal) (ProcessInspector, error)` in this task, not just a fake. It uses `/proc` in production; unreadable coverage/errors cannot produce `Empty=true`. Extend `paseo.Client` with `ListTerminals(ctx context.Context, workspace paseo.Workspace) ([]Terminal, error)` and `KillTerminal(ctx context.Context, id string) error`, mapped to the exports in Task 9; `Terminal` retains exact ID/workspace ownership, not a guessed PID. App `(*Store).CancelTask(ctx context.Context, actor Actor, taskID string, revision int64) (team.CancelReport, error)`.
+- [ ] **Tests:** `TestRunnerBugWorkflow`, `TestCancelStopsArchivesThenVerifies`, `TestCancelSurvivingBackgroundChild`, `TestRunnerLeaseLoss`, `TestRunnerRestartDoesNotDuplicate`, `TestProcessIdentityReuse`, `TestLinuxInspectorEnvironmentStrippedChild`, `TestLinuxInspectorUnknownCoverage`, `TestBugPreparationIntegration`; repeat `TestBugPreparationCrash` with real protocol/local Git. Order stop → archive agent → stop owned checks → archive workspace → verify absence → contain. Surviving child/unknown inventory blocks acknowledgement/reclaim. Namespace PID never signals host; PID reuse must not kill control process. Rollback/suspend exhaust deadline; outage cannot extend authority. Completion-before-containment crash cleans up without new agent.
-- [ ] **Step 1: Add `TestRunnerBugWorkflow`, `TestCancelStopsArchivesThenVerifies`, `TestCancelSurvivingBackgroundChild`, `TestRunnerLeaseLoss`, `TestRunnerRestartDoesNotDuplicate`, `TestProcessIdentityReuse`, `TestLinuxInspectorEnvironmentStrippedChild`, `TestLinuxInspectorUnknownCoverage`, `TestBugPreparationIntegration`.** Observe ordered calls stop → archive agent → stop owned check processes → archive workspace → verify all owned processes absent → contain report. A surviving detached/background child or unknown process inventory prevents acknowledgement and reclaim. Namespace PID is never signalled as a host PID; reused host PID with different start/boot identity is never killed. Wall-clock rollback and suspend exhaust a monotonic deadline; failed renewals stop work before lease expires. Instance outage buffers reports but cannot extend authority. Crash after successful completion but before containment still triggers cleanup on restart, not another agent. The Linux test launches a real test-owned parent with the attempt env marker and a child that clears its environment, detaches and keeps the attempt worktree cwd; after the parent exits, `Remaining` must still find the child and refuse Contain. Then stop that exact PID/start/boot identity and require empty coverage plus a successful dependent-step claim. A second fixture changes cwd after being tracked and remains owned by its recorded identity. Inject unreadable same-user `/proc` entries, PID reuse and inventory interruption: coverage stays unknown, no stopped acknowledgement, and unrelated test-owned control processes survive. These tests must use the production inspector, not a mock returning empty.
- ```go
- if remainingProcesses > 0 && contained { t.Fatal("acknowledged a surviving process") }
- if newAgentAfterUncertainCreate { t.Fatal("restart duplicated an agent") }
- ```
+ Production-inspector subprocess fixture: marked parent spawns environment-stripped detached child retaining attempt cwd, then exits. Remaining finds child and refuses Contain; exact-identity stop enables empty proof and dependent claim. A tracked child later changing cwd remains owned. Unreadable same-user /proc, PID reuse/interrupted inventory stays unknown; unrelated controls survive.
+- [ ] **Red/green:** `go test ./internal/runner ./internal/equipotest -run 'TestRunnerBugWorkflow|TestCancel|TestRunnerLease|TestRunnerRestart|TestProcessIdentity|TestLinuxInspector|TestBugPreparationIntegration|TestBugPreparationCrash' -count=1`. Green uses fake client with real owned subprocesses; mutate cleanup order/process verification. Retain `TestTimeChargeWaitsForContainment`, cancellation/late-receipt regressions.
+- [ ] **Implement:** Wire preparation outbox/assignment/immutable fetch/baseline capture; replace fake validators with Tasks 11–13. Persist transitions/IDs before effects. Reproduce: create scoped agent, Ready, admit/send, freeze, executor verifies expected base failure. Implement: fresh agent returns clean candidate. Review: fresh different family submits verdict on exact candidate. Verify/publish are runner-only. Every model turn gets fresh admission and isolation/ack check; observed session precedes artifacts. Register while handle valid, Complete then archive/verify/Contain before dependents. Failed review/checks ends fixed run without publication or invented replanning. After all attempts contained, Conclude verifies publication and app waits for merge owner.
-- [ ] **Step 2: Run red.** `go test ./internal/runner ./internal/equipotest -run 'TestRunnerBugWorkflow|TestCancel|TestRunnerLease|TestRunnerRestart|TestProcessIdentity|TestLinuxInspector|TestBugPreparationIntegration|TestBugPreparationCrash' -count=1`.
-- [ ] **Step 3: Implement preparation and the state machine.** Wire Task 7's preparation outbox to Task 8's runner assignment, Task 10's local Git preparation and Task 11's baseline capture; now run real protocol/fetch crash cases and replace artifact/question fakes with Tasks 11–13 validators. Persist each transition and all IDs before the next effect. Reproduce: create agent with scoped tools, subscribe/await readiness, admit/send, freeze result, executor runs base and rejects anything except the expected test failure. Implement: fresh agent consumes frozen reproduction and returns a clean captured commit. Review: fresh different-family agent sees exact candidate and submits structured verdict. Verify: runner executor only, no provider call. Publish: runner only, after the complete evidence gate. For model steps, reserve/admit every turn and persist the exact session identity before accepting artifacts. Register artifact results while the handle is valid; Complete then archive/verify/Contain; only then start a dependent step. Rejected review or failed checks ends this fixed run with evidence and no publication; revisions/replanning are not silently invented.
+ Renew every 15 seconds; stop with 10-second margin on 60-second lease using Linux elapsed/boot clock including suspend. Restart treats old authority expired pending instance validation; never reuse cached tickets. Cancel transaction fences/revokes first, reports requested until verified stopped; retain separate in-flight uncertainty. Graceful shutdown drains reports or leaves durable cleanup for service restart.
- Supervisor renews every 15 seconds and starts shutdown with a 10-second safety margin before its 60-second lease, using elapsed/boot time that includes suspension on Linux. Restart treats prior authority as expired until the instance validates it; never reuse a cached dispatch ticket. Cancel transaction first fences work and revokes intents; response is stop requested while containment is pending. Afterwards acknowledge stopped only on process verification, preserving in-flight action uncertainty separately. No PID guessing, broad `pkill` or daemon-wide shutdown on the shared machine. Build the Linux inspector before wiring the supervisor. Set nonsecret `EQUIPO_ATTEMPT_MARKER=<random-attempt-id>` in `createAgent.env` and in executor/tool process environments. Start tracking before the first prompt. Read `/proc/sys/kernel/random/boot_id`; scan same-user `/proc/<pid>/{stat,environ,cwd}` for the exact marker or canonical attempt-worktree cwd (including descendants), and retain descendants/process groups seen while their ancestry is known. Persist PID, `/proc/<pid>/stat` start ticks and boot ID in the journal before signalling. Rescan after stop/archive, include the recorded executor groups and Paseo terminals for the exact workspace, stop those terminal IDs, and require none remain. Never signal on a namespace PID or a stale identity; recheck identity immediately before each signal. A child stripping its environment is still found by cwd or tracked ancestry. A process that loses all attribution before observation, inaccessible same-user entries, a failed terminal list or interrupted monitoring means unknown coverage, never empty. Do not kill another user's processes; inaccessible entries are excluded only when their UID is known to be unrelated. If host permissions or provider behavior prevent complete coverage, dispatch stays unavailable until the ownership gap is fixed. This implements local ownership; it does not assume Paseo owns process trees. A timer or an `idle` status is not proof. Graceful runner shutdown drains reports or leaves durable pending cleanup; the service restarts to finish it. After all successful attempts are contained, `Conclude` verifies publication and the app marks the human merge step waiting.
-- [ ] **Step 4: Run green.** Repeat Step 2 with fake client plus real test-owned subprocesses. Mutate stop/archive ordering and process verification separately. Preserve `TestTimeChargeWaitsForContainment` and cancellation/late-receipt regressions.
-- [ ] **Step 5: Commit.** `git commit -m "feat: supervise bug steps and verify cancellation containment"`.
+ Set EQUIPO_ATTEMPT_MARKER in agent/executor/tool env, track before first prompt. Scan same-user `/proc/<pid>/{stat,environ,cwd}` plus boot_id for marker/canonical workspace/descendants; retain known ancestry/groups. Persist PID/start/boot before signals and recheck immediately before each signal. Rescan after archive, include executor groups and exact Paseo terminals, stop owned IDs only. Lost attribution before observation, inaccessible same-user entries, failed terminal list or monitoring gaps mean unknown coverage. Exclude unreadable entries only with known unrelated UID. No broad pkill, guessed PID, other-user kills or daemon shutdown. Missing ownership coverage blocks dispatch; idle/timers never prove absence.
+- [ ] **Commit:** `feat: supervise bug steps and verify cancellation containment`.
### Task 16: Show live tasks, connections and recovery in the existing shell
-**Files:** Create app `task_views.go`, `task_handlers.go`, templates `tasks.html`, `task.html`, `task_form.html`, `task_card.html`, `connections.html`, `enrol.html`, `recovery.html`; modify `handlers.go`, `app.go`, `navigation.go`, `render.go`, `copy.go`, `copy_test.go`, `static/equipo.css`, templates `specialist.html`, `chrome.html`, `index.html`, `project.html`; create `internal/equipotest/task_pages_test.go`; modify browser/performance tests.
+**Files:** App task_views/task_handlers/live; templates tasks/task/task_form/task_card/connections/enrol/recovery and specialist/chrome/index/project/layout; handlers/app/navigation/render/copy/copy_test/static/equipo.css; `internal/equipotest/task_pages_test.go`, browser/perf tests. Wire notifier into job-changing services from Tasks 2–15.
-**Interfaces:** `(*Store).TaskView(ctx context.Context, actor Actor, taskID string) (TaskView, error)`, `Journey(ctx context.Context, actor Actor) (TaskPage, error)`, `SpecialistWork(ctx context.Context, actor Actor, key string) (SpecialistView, error)`. `TaskView` combines Task, ordered step cards, questions, selection/actual identity, usage availability, evidence links, cancellation state and merge owner. `TaskPage` carries all active/waiting rows and this week's finished rows, with no cursor or pagination; `SpecialistView` carries working/queued/finished-week counts, measured tokens with known/unknown flag, tasks and existing settings. Use `team.Events(ctx, scope, after)` and the durable app projection as change sources.
+**Interfaces:** Store TaskView(actor, taskID), Journey(actor), SpecialistWork(actor, key). Views contain ordered step cards, questions, selected/actual identity, isolation provenance, usage availability, evidence, cancellation and merge owner. Lists cover all active/waiting and this week's finished tasks, no pagination. Specialist counts/usage retain known flags. Durable app projection/core Events supply reads. Add page `Live live.View`; keep existing template map and call `live.Render(w, r, status, pages[name], "layout", data)` for live pages.
-- [ ] **Step 1: Add `TestTaskPages`, `TestTaskPagesUnknownCounts`, `TestTaskFormsCSRFAndRevision`, `TestTaskLiveRefresh`, `TestTaskLayoutRules`.** Form-to-detail works without JavaScript. Shared members see the same tasks; writes use current authorized actor. Journey uses ordered chips beside cards, not a task table, with category/action and model/account when assigned. Only one family produces a visible wait. Cancel requested and stopped differ. Unknown counters are unavailable/503, never zero. Counts match records across all five specialist pages and rail. HTML injection in descriptions, question text, branch names and logs is escaped. Chips use labels/icons as well as color; no percentages, initials or coloured left borders. Live read-only views refresh the whole page every 15 seconds through a plain HTML refresh; every request rechecks membership. Use a separate explicit edit/answer form page without auto-refresh so drafts/focus are not discarded. No EventSource endpoint, fragment replacement or pagination. Tests check refresh presence on live views and absence on editable forms, and deny the next refresh after membership removal.
- ```go
- if response.Code != http.StatusServiceUnavailable { t.Fatal("count error rendered as zero") }
- if horizontalOverflow || coloredLeftAccent { t.Fatal("task layout violates shell rules") }
- ```
+- [ ] **Tests:** `TestTaskPages`, `TestTaskPagesUnknownCounts`, `TestTaskFormsCSRFAndRevision`, `TestTaskLiveRefresh`, `TestTaskLayoutRules`, `TestUnconfinedLabelEverySurface`. Scriptless form-to-detail, shared-member reads/current-actor writes, real counts across five specialists/rail, family wait, distinct requested/stopped, escaped descriptions/questions/refs/logs. Count errors return unavailable/503, never zero. Chips beside cards use category/action/model/account and non-color state, no task table/percentages/initials/accent borders. Test literal `unconfined` in card, each affected Journey chip, task detail/evidence and published description; confined controls have no false label, and replay/restart/expiry cannot strip history.
-- [ ] **Step 2: Run red.** `go test ./internal/equipotest -run 'TestTaskPages|TestTaskForms|TestTaskLive|TestTaskLayout' -count=1`.
-- [ ] **Step 3: Inventory copy before inserting runtime strings.** Apply the copy-review workflow to task/enrolment/connection/recovery forms, wait and error states, permission actions, evidence labels, usage qualifiers, accessible names and runner CLI/service diagnostics. Mark pending keys individually in `copy.go`, including `task.wait.family`, `task.wait.setup`, `task.cancel.requested`, `task.cancel.stopped`, `usage.counted_turns`, `usage.allowance_unknown`, `recovery.unknown_charged`, and `runner.preflight.unavailable`. The task brief permits flagged draft entries; remove markers only after review and apply edits verbatim. Add `TestReleaseCopyReviewed` and Make target `copy-release-check`, required by both release targets, which refuse any pending entries. Export `RunnerText(key string) string` from this copy file for runner display strings. No README changes or unapproved mockup wording.
-- [ ] **Step 4: Implement screens and forms.** GET `/tasks/new`, POST `/tasks`, GET `/tasks/{id}`, POST `/tasks/{id}/cancel`, POST `/tasks/{id}/acknowledge-merge`; replace `/journey`, `/needs-you`, `/connections` and specialist activity. Add owner recovery GET `/settings/recovery`, POST `/settings/recovery/release`, personal choice POST `/projects/{id}/connections`. Merge acknowledgement requires the current saved merge owner, revision and a person-supplied Amadan reference; label it as reported by that person. Team owners cannot impersonate them. Forms return 303, invalid input 422, stale revision 409, forbidden 403 and unavailable 503 through copy keys. Keep Conversation an honest form entry/card destination, with no coordinator claims.
+ `TestTaskLiveRefresh` covers Journey, all specialists and detail: authorized job notification refetches regions from the same URL/handler; forged other-team/job topics deny and other-team writes cause no wake. Removed member/DB error denies next fragment and stream reconnect. Rollback causes no notification; every committed job-changing path notifies after data is readable. Cover new job/list membership, completion/weekly expiry, restart boot ID, write-during-render, unknown counts, and scripts-off full GET. No meta-refresh/custom event feed. Browser editing/focus survives updates.
+- [ ] **Red/green:** `go test ./internal/equipotest -run 'TestTaskPages|TestTaskForms|TestTaskLive|TestTaskLayout|TestUnconfinedLabelEverySurface|TestReleaseCopyReviewed' -count=1`. Browser `go test -tags browser ./internal/equipotest -run TestRunnerTaskBrowserWalk -count=1`, plus `EQUIPO_BROWSER_NO_JS=1` variant, widths 1280/390. Test long names, keyboard/focus and overflow; inspect normal motion. Add every new private GET to TestPerfScreens with sign-in/setup; explicitly exclude streams, long-poll and downloads; `make perf`.
+- [ ] **Implement live:** One `live.New(live.Config{Path: "/live", Topics: ..., Lifetime: 30*time.Second})` hub per app. Middleware precedes all handler reads. Mount Handler only when hub exists, behind existing requireMember; topic Allow also validates current roster and stored team/job association, denying lookup errors. Wire `Options.Live` for shutdown; embedded test servers close hub before Shutdown. `Allow` runs at stream open, so the 30-second lifetime bounds stale open-stream notices; every fragment read independently rechecks current authority immediately.
- Group Journey as needs-person, in-progress, queued and finished this week; show failure/cancellation labels within recent finished records. Needs you contains the current person's actionable questions and merge steps. Specialist pages retain settings and include working/queued/finished-week rows and counted usage. Update account/project totals from real task/usage data with checked arithmetic. Use plain 15-second page refresh on live read-only views. Render active/waiting tasks and recent finished tasks without cursor pagination; keep the defined weekly window and check `make perf`. Editable forms live on non-refreshing pages. Ordinary links and all forms work with scripts disabled. Do not modify vendored JavaScript/CSS. Preserve the phone index/back links and one `aria-current` destination.
-- [ ] **Step 5: Run green and browser checks.** Repeat Step 2. `go test -tags browser ./internal/equipotest -run TestRunnerTaskBrowserWalk -count=1` at widths 1280/390, scripts on/off; require no overflow with long names, keyboard access and readable chips. Add private-page sign-in/setup to `TestPerfScreens` for every new GET screen, explicit exclusions for long-poll/download endpoints, then run `make perf`. Inspect at normal motion too; record the existing framework transition issue if reproducible, never silently mask it.
-- [ ] **Step 6: Commit.** `git commit -m "feat: show live bug tasks and runner status in the app"`.
+ Topic name `jobs`; key is 64-character lowercase SHA-256 of canonical typed `(teamID, jobID)` tuple, within live's single-key grammar. Never concatenate raw IDs with another slash. Team collection uses a distinct typed `(teamID, collection)` key; job creation/preparation without JobID wakes that collection. Detail subscribes to its job; Journey/specialist list regions subscribe to their team's collection, avoiding live's 64-topic limit with unpaginated lists. Allow resolves only authorized stored team/job keys, never caller-supplied team authority. Every job mutation notifies exact job plus team collection after commit in the same service path: preparation/assignments, leases/state, events/usage/evidence, questions/answers, cancel/contain, publication/merge acknowledgement, recovery and connection/ack changes affecting jobs. Inject a notifier into shared write services; deduplicate touched keys, publish nothing on rollback. Schedule weekly-window/staleness changes with NotifyAt and reconstruct schedules at boot. No global unkeyed wakeups.
-### Task 17: Package and wire the runner user service
+ Templates define stable `region:<name>` wrappers/IDs using `hub.View(r).Attrs(...)`; Head uses framework translated paused/unconfirmed keys. Include always-present region:notice. Render only through full-page handlers/checks; live.Render handles no-store/Vary, fragment status/headers and navigation. Take flash only when its data callback says takeFlash; never drain it on background refresh. Use vendored live.js from Task 0, no handwritten EventSource/fragment engine. Keep answer/edit forms on separate ordinary pages and all links/forms functional without scripts. Scriptless pages reflect state at load; no timed whole-page refresh.
-**Files:** Expand `cmd/equipo-runner/{main,main_test}.go` from Task 13; create runner `connections.go`, `connections_test.go`, `config.go`, `client.go`, `config_test.go`, `client_test.go`, `packaging/equipo-runner.service`; modify app `config.go`, `app.go`, `execution.go`, `cmd/equipo/main.go`, Makefile and CI wrappers; create `internal/equipotest/runner_startup_test.go`, `runner_release_test.go`.
+ Rastrillo v0.30.0 live docs exclude hibernating routes: enable hub only for an explicitly always-on deployment. On a hibernating instance use nil hub/static pages; do not silently prevent sleep. Task 18's live UI acceptance uses always-on configuration; Task 17's hibernation/witness tests retain the static mode.
+- [ ] **Implement pages/copy:** GET `/tasks/new`, POST `/tasks`, GET `/tasks/{id}`, POST cancel/acknowledge-merge; replace Journey/Needs you/Connections/specialist activity. Owner recovery GET/POST `/settings/recovery[/release]`; personal project choice POST `/projects/{id}/connections`; owner-only POST `/connections/{id}/acknowledge-unconfined` and `/revoke-isolation-acknowledgement`. Show connection/provider versions and explicit acknowledgement meaning; retain personal opt-in separately. Merge acknowledgement requires current saved merge owner/revision/person-supplied Amadan reference; owners cannot impersonate them. Statuses 303/422/409/403/503 through copy keys.
-**Interfaces:** `runner.Config{Origin, StateDir, PaseoHome, NodePath, BridgePath, AmadanCredentialPath, AccountBindingsPath, CodexPath string}`; `runner.LoadConfig(getenv func(string) string) (Config, error)`, `runner.Enrol(ctx context.Context, cfg Config, output io.Writer) error`, `runner.Run(ctx context.Context, cfg Config) error`. Command verbs: `enrol`, `run`, `preflight`, `tool`, `version`; `tool` uses stdio toward the harness and the private Unix socket toward the runner, from Task 13. App Config adds `ExecutionEnabled bool` and `ExecutionMarkerPath string`; `OpenExecution(ctx context.Context, d *db.DB, path string, cfg Config, store *Store) (*Execution, error)`, `(*Execution).Close() error`. Preserve `App`/`Router` callers by adding explicit `AppWithExecution`/`RouterWithExecution` constructors with `execution *Execution` as the final argument; old constructors build the disabled app.
+ Journey groups needs-person/in-progress/queued/finished-week with failure/cancel labels; Needs you is current person's questions/merge steps. Keep specialist settings, real checked account/project totals, one aria-current and phone back links. Conversation is a form/card entry point, no coordinator claims.
-- [ ] **Step 1: Add `TestRunnerConfig`, `TestRunnerHTTPClient`, `TestRunnerServiceLifecycle`, `TestExecutionStartupClosed`, `TestRunnerReleaseContract`, `TestExecutionHibernateWitness`.** Enrol/run opens no TCP or inet listener; only the per-attempt Unix socket from Task 13 is allowed, no root requirement, state directory 0700/credential file 0600, atomic token writes and process lock prevent two services on one state directory. Reject cross-origin redirects and TLS failures before bearer reuse. Missing/expired credential requires enrolment; rotation cannot bypass revocation. Disabled app opens no core or adapter. Enabled app uses the existing writer, applies schema before attach, synchronizes configured budgets and Resume before dispatch; fresh witness mismatch opens UI/recovery but no work. Construction failure and SIGTERM close core before app DB. Release stamps commit, includes exact adapter lock/package, and refuses dirty tracked source or pending copy. `TestRunnerServiceUsesLinuxInspector` constructs the real service with the Linux inspector and repeats the surviving-child case; fake-only process wiring fails. Discovery accepts only operator-bound, observed accounts with no-failover/read-isolation capability, and never marks the currently unsupported Codex route eligible.
- ```go
- if tcpOrInetListeners != 0 { t.Fatal("runner opened a TCP or inet listener") }
- if attachedDatabasePath != resolvedDatabasePath { t.Fatal("execution uses another database") }
- ```
+ Inventory runtime copy before writing it: forms, waits/errors, permission/evidence/usage/isolation/accessibility and CLI/service diagnostics. Include `task.wait.family`, `task.wait.setup`, `task.cancel.requested`, `task.cancel.stopped`, `usage.counted_turns`, `usage.allowance_unknown`, `recovery.unknown_charged`, `runner.preflight.unavailable`, `isolation.unconfined` and acknowledgement/expiry keys. Flag each draft in copy.go; review before release. Export RunnerText(key). `TestReleaseCopyReviewed` and `copy-release-check` block both releases with pending keys. No unapproved mockup wording or README edits.
+- [ ] **Commit:** `feat: show live bug tasks and runner status in the app`.
-- [ ] **Step 2: Run red.** `go test ./cmd/equipo-runner ./internal/runner ./internal/equipotest -run 'TestRunnerConfig|TestRunnerHTTP|TestRunnerService|TestExecutionStartup|TestRunnerRelease|TestRunnerServiceUsesLinuxInspector|TestExecutionHibernateWitness|TestConnections|TestAccountFailover' -count=1`.
-- [ ] **Step 3: Implement service wiring.** `EQUIPO_EXECUTION_ENABLED=1` opts in; otherwise preserve Foundation's unopened store. Production main resolves activation, opens one DB, builds app schema, attaches execution and clears `opts.DBPath`; shutdown stops background reconciliation before closing core then DB. Keep the witness outside the SQLite file at a stable configured local path; never store it in a row beside the history it witnesses. Missing/lost witness forces quarantine. The `oficina` deployment must preserve the witness and lock on stable storage across hibernation; SQLite backup alone is insufficient and its witness must not be rolled back alongside restored history. Test normal hibernate/wake with the witness preserved and loss of local witness with the same DB: the latter opens recovery only. Hibernation reports/renewals are ordinary wake-up requests; instance downtime never extends a runner lease. Record actual witness survival in the human deployment checklist; if the platform cannot preserve it, wake-up must quarantine rather than auto-release.
+### Task 17: Package and wire the runner user service
- Runner reads origin/state/Paseo home from explicit configuration, keeps provider homes unchanged, and stores machine key, runner credential, journal, attempt capabilities and private sockets in its state directory. The Amadan agent credential is an operator-provisioned local secret opened only by the forge/fetch boundary, never passed to bridge or agents. Device enrolment prints the browser verification address and code via reviewed copy; it does not start a browser server. Wire `NewLinuxProcessInspector("/proc", client, journal)` into the production supervisor, with failed/unknown coverage blocking dispatch. Implement Task 6's deferred discovery/account-binding runner side through Task 9, with sanitized fake SDK tests. Keep the read-isolation decisions enforced in config/preflight; verify the configured command-sandbox Codex binary version before checks. User unit uses `Type=simple`, explicit executable/config paths, `Restart=on-failure`, bounded shutdown and no root install. Make `runner-release` produce a docs-t1 Linux/amd64 bundle with Go binary, bridge and locked production Node dependencies (including server 0.14.0 for daemon-control); keep instance release Linux/arm64 default. Record tested Node v24.19.0 and the installed Codex 0.165.0 command-sandbox prerequisite in the release manifest; the runner must refuse an unverified version. CI provisions Node for `runner-adapter-test` and Codex 0.165.0 for command-only `TestCheckSandboxDeniedPaths`; both prerequisites are checked, with no skipped success. Installing Codex for this check does not authorize a provider session or require login. Unit installation/enabling is a human action after Task 18. No automatic deployment or modification of the shared Paseo daemon.
-- [ ] **Step 4: Run green.** Repeat Step 2; `CGO_ENABLED=0 go build ./cmd/equipo ./cmd/equipo-runner`, `make runner-adapter-test`, `make migration-check`. Use fake executables to inspect release/service commands; do not install the service during tests.
-- [ ] **Step 5: Commit.** `git commit -m "build: package the outbound runner and wire guarded startup"`.
+**Files:** Expand runner command; runner connections/config/client and tests; packaging/equipo-runner.service; app config/app/execution, main, Makefile/CI; `internal/equipotest/runner_startup_test.go`, runner_release_test.go.
-### Task 18: Verify the complete slice and prepare human acceptance
+**Interfaces:** Runner Config includes Origin, StateDir, PaseoHome, NodePath, BridgePath, AmadanCredentialPath, AccountBindingsPath, CodexPath. LoadConfig(getenv), Enrol(cfg, output), Run(cfg); verbs enrol/run/preflight/tool/version. App adds ExecutionEnabled/ExecutionMarkerPath and explicit live always-on configuration. OpenExecution(d, path, cfg, store), Close; AppWithExecution/RouterWithExecution append Execution argument, old constructors remain disabled.
+
+- [ ] **Tests:** `TestRunnerConfig`, `TestRunnerHTTPClient`, `TestRunnerServiceLifecycle`, `TestExecutionStartupClosed`, `TestRunnerReleaseContract`, `TestExecutionHibernateWitness`, `TestRunnerServiceUsesLinuxInspector`, deferred `TestConnections*`/`TestAccountFailover*`. No TCP/inet listener/root; 0700 state/0600 credentials, atomic token writes/process lock. Reject cross-origin redirects/TLS failures before bearer reuse. Expiry needs enrolment; rotation cannot revive revoke. Disabled app opens no core/adapter. Enabled app shares writer, migrates/syncs budgets/Resume before dispatch; witness mismatch allows recovery only. Failure/SIGTERM closes core before DB. Clean stamped release includes exact dependencies and reviewed copy. Real service inspector repeats surviving-child test; fake-only wiring fails. Discovery honors bindings, no-failover, observed accounts and the confined/acknowledged-unconfined distinction, never claims Codex confinement.
+- [ ] **Red/green:** `go test ./cmd/equipo-runner ./internal/runner ./internal/equipotest -run 'TestRunnerConfig|TestRunnerHTTP|TestRunnerService|TestExecutionStartup|TestRunnerRelease|TestRunnerServiceUsesLinuxInspector|TestExecutionHibernateWitness|TestConnections|TestAccountFailover' -count=1`; green also `CGO_ENABLED=0 go build ./cmd/equipo ./cmd/equipo-runner`, `make runner-adapter-test`, `make migration-check`. Fake executables inspect packaging/service commands; do not install service.
+- [ ] **Implement:** `EQUIPO_EXECUTION_ENABLED=1` opts in. Resolve activation, open one DB, apply app schema, attach execution, clear opts.DBPath; stop reconciliation then close core/DB. External witness/lock need stable storage across oficina hibernation, separate from DB history and not rolled back with backup. Preserved witness wakes normally; lost witness quarantines. Downtime cannot extend leases. Human deployment records actual storage survival; inability to preserve it requires quarantine, never auto-release.
-**Files:** Create `internal/equipotest/runner_flow_test.go`, `internal/runner/paseo/live_test.go`; modify `internal/equipotest/browser_test.go`, `perf_test.go`, Makefile and CI wrappers as needed for the same gates. Store the controller's test/mutation/capability report with the implementation review, not in README.
+ Explicit local config leaves provider homes unchanged. State holds machine key/bearer/journal/capabilities/sockets; operator-provisioned forge credential opens only in fetch/publish boundary. Enrol prints reviewed browser address/code, starts no browser server. Wire real Linux inspector, discovery/account bindings and command-sandbox version checks. Missing coverage/capability blocks dispatch; automatic acknowledgement expiry is enforced on startup/reports.
-**Interfaces:** `TestPaseoLiveReadIsolation` and `TestPaseoLiveTurnCalibration` use the same explicit live opt-in as `TestPaseoLiveContract`. `TestRunnerEndToEnd` starts the real HTTP instance and Go runner with fake Paseo transport and local bare forge; no external provider. `TestPaseoLiveContract` uses explicit environment `EQUIPO_LIVE_PASEO=1` and an operator-supplied disposable repository plus their enrolled connections. Ordinary CI does not run or count this live gate.
+ Systemd user unit: Type=simple, explicit executable/config, Restart=on-failure, bounded shutdown. Runner release is Linux/amd64 for docs-t1, with bridge/locked production Node packages including server 0.14.0; instance remains Linux/arm64 default. Manifest records Node v24.19.0 and Codex 0.165.0 command-sandbox prerequisite, refusing unverified versions. CI provisions/checks both; no skipped success or provider login required for command-only sandbox tests. Human installs/enables after Task 18. No shared-daemon modification or autonomous deployment.
+- [ ] **Commit:** `build: package the outbound runner and wire guarded startup`.
+
+### Task 18: Verify the complete slice and prepare human acceptance
-- [ ] **Step 1: Add failing end-to-end acceptance assertions.** Enrol Paul and a second member, report distinct personal connections, configure project/team budgets and personal connection choices, submit bug, observe reproduce → fix → review → checks → publication → merge-owner wait. Verify exact remote commit, frozen reproduction, base fail/candidate pass, repository-check counts, different-family review and provenance. Second member can read but cannot use Paul's connection. One-family setup waits with zero provider dispatches. Repeat task submission, crash runner after dispatch, lose one event/receipt, restart instance, restore older DB with a newer/missing witness, lower budget, change roster/project mid-step, cancel during a permission wait and during a background process. Assert one publication at most and no false stopped/succeeded state.
- ```go
- if remoteHead != checkedCommit || remoteHead != reviewedCommit { t.Fatal("evidence and publication diverged") }
- if providerDispatchesWithOneFamily != 0 { t.Fatal("task ran without independent review capacity") }
- ```
+**Files:** `internal/equipotest/runner_flow_test.go`, `internal/runner/paseo/live_test.go`; browser/perf tests and Make/CI as required. Controller report accompanies implementation review, not README.
-- [ ] **Step 2: Run red.** `go test ./internal/equipotest -run TestRunnerEndToEnd -count=1`; observe the first missing integration behavior rather than marking skipped fixtures as success.
-- [ ] **Step 3: Complete wiring only where acceptance fails.** Reuse Tasks 1–17 contracts; no new coordinator, product view, model guessing or special test-only authentication. Add the live contract assertions for structured events/recovery, Codex/Claude permission responses, per-agent MCP, observed credential-home identity, failover refusal, subscription usage completeness and stop/archive/process cleanup. A missing upstream guarantee is a named blocking capability with its failing assertion, not a substitute implementation.
-- [ ] **Step 4: Run green and the offline release gates once after targeted checks pass.** `make ci`; `make runner-adapter-test` is already part of that target and must also have a matching `.amadan/ci.d/` wrapper. Run `go test -tags browser ./internal/equipotest -run TestRunnerTaskBrowserWalk -count=1`, and once `go test -race ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipotest ./internal/runner/...`. Race tests are verification only and may use the toolchain's required CGO; shipped builds remain `CGO_ENABLED=0`. Verify build/vet/format/staticcheck/govulncheck/gitleaks/budgets/tests/migration/performance all ran, new packages use the repository's budget TestMain pattern, and source/test size limits have not been silently raised. Report mutation commands and restored guards. No full-suite loops without a new failure/change.
-- [ ] **Step 5: Run the authorized live compatibility gate on docs-t1.** Question 1 is ruled. After supported isolation/account-routing interfaces and operator-selected connections/repository exist, run `EQUIPO_LIVE_PASEO=1 go test -tags paseo_live ./internal/runner/paseo -run 'TestPaseoLiveContract|TestPaseoLiveReadIsolation|TestPaseoLiveTurnCalibration' -count=1`. Use a task-owned disposable workspace and the person's actual allowed accounts; preserve another user's daemon/projects/agents. Require both eligible model families, complete account routing evidence, reconnect recovery, and proven absence of agent/background/terminal processes after cancellation. Add `TestPaseoLiveReadIsolation` (include it in the same tagged command): one sentinel test each for runner state, the Amadan credential location, Paseo home credentials/each routed provider credential home, and `~/.ssh`, plus a readable workspace control. Create uniquely named nonsecret sentinels in each actual protected directory, including each routed credential home and `~/.ssh`; for the configured Amadan file use a disposable test credential protected by the identical file rule. Never overwrite credentials, substitute a different home to claim coverage, or ask an agent to print real secrets. Remove only the sentinel files after the test. Exercise shell `cat`, native Read/search tools, symlink aliases and requests to escape sandbox/alter policy for each path. The trusted tool verb must still authenticate using its capability file. Unknown, skipped or readable protected sentinels fail `ReadIsolation`; an unsupported provider is explicitly blocked and the two-family gate is not passed. Repeat for every enabled provider/mode and after restart. This planning revision found Codex blocked on Paseo 0.14.0, so this gate cannot currently pass. Do not weaken it.
+**Interfaces:** TestRunnerEndToEnd starts real HTTP instance/Go runner with fake Paseo and local bare forge. TestPaseoLiveContract/ReadIsolation/TurnCalibration require tag paseo_live, `EQUIPO_LIVE_PASEO=1`, operator-selected disposable repository and enrolled connections; ordinary CI does not count them.
- Add `TestPaseoLiveTurnCalibration` to the same command. Measure at least one real representative turn per eligible family, recording provider/model/config hash, uncached input, cached input and output with completeness flags. The earlier Claude probe reported 18 input + 29,591 cached + 404 output; it is a warning against tiny fixture budgets, not a production calibration. Set each per-turn token reservation to twice the largest measured total input/output, rounded up to 1,000 tokens with checked arithmetic. Set the job allowance to at least 23 of those reservations and explicit project/team period headroom for the accepted run; never overwrite existing lower operator limits silently. If those limits cannot fund the test, leave the gate blocked with the required amount. Use explicit bounded calibration reservations recorded in the report, not the uncalibrated production dispatcher. Test an unknown-usage reservation followed by a known completed turn within remaining headroom, and test exhaustion. Display cached input separately. Record resulting values and measured overruns; subsequent turns may exceed an estimate and remain charged before further work is stopped. If any prerequisite is absent, report the precise blocked gate and product capability needed. Do not call offline fixtures proof of live reliability. This planning session runs none of it.
-- [ ] **Step 6: Commit and hand over release artifacts.** `git commit -m "test: verify the runner workflow and live compatibility gate"`. From the clean reviewed commit run `make release` and `make runner-release`; verify both stamps and package manifests. Human deploys the instance through the existing versioned `oficina` CARLOS release procedure and installs/enables the user service on docs-t1. Human enrols, checks the origin/machine confirmation, submits a real bounded bug, follows Journey/specialists, opens evidence and the Amadan review branch, and merges through Amadan themselves. Repeat cancel on an active task and inspect acknowledged containment. No agent deploys, merges or pushes the default branch. Stop all test processes and remove only task-owned scratch; the human-installed service is the intended persistent process.
+- [ ] **Acceptance tests:** `TestRunnerEndToEnd` enrols Paul/second member, configures personal connections/budgets, then reproduce → fix → review → checks → publish → merge-owner wait. Verify exact remote checked/reviewed commit, frozen base-fail/candidate-pass, repository counts, independent-family provenance and label surfaces. Second member reads but cannot use Paul's connection; one family waits with zero dispatch. Claude confined plus Codex unconfined-acknowledged satisfies the two-family gate if all other capabilities pass. Unacknowledged Codex fails before creation/dispatch; version change invalidates ack. Exercise resubmission, crash after dispatch, lost event/receipt, instance restart/older-DB restore with newer/missing witness, budget lowering, roster/project edits, permission-wait/background-process cancellation. At most one publication, never false stopped/succeeded.
+- [ ] **Red:** `go test ./internal/equipotest -run 'TestRunnerEndToEnd|TestUnconfinedConnectionRequiresAcknowledgement|TestIsolationAcknowledgementLapses|TestUnconfinedLabelEverySurface' -count=1`. Missing integration fails, skipped fixtures do not pass.
+- [ ] **Implement:** Complete existing contracts only. Live assertions cover structured events/recovery, both providers' permission replies, per-agent MCP, observed credential-home/account, no-failover, usage completeness and stop/archive/process cleanup. Name missing upstream capability and failing assertion; no invented interface or test-only auth. Verify live views on always-on mode and scripts-off static fallback.
+- [ ] **Offline green:** After targeted tests, run `make ci` once, browser walk scripts on/off, then once `go test -race ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipotest ./internal/runner/...`. Race verification may use required CGO; shipped builds remain CGO_ENABLED=0. Confirm all build/vet/format/staticcheck/govulncheck/gitleaks/budget/tests/migration/perf and adapter gates ran. New packages use budget TestMain, size limits unchanged. Report mutations/restoration; no full-suite loops without new failures/changes.
+- [ ] **Authorized live gate:** `EQUIPO_LIVE_PASEO=1 go test -tags paseo_live ./internal/runner/paseo -run 'TestPaseoLiveContract|TestPaseoLiveReadIsolation|TestPaseoLiveTurnCalibration' -count=1`. Preserve others' agents/projects/daemon. Claude must pass ReadIsolation: unique nonsecret sentinels in actual runner state, Amadan credential location, Paseo and each routed credential home, ~/.ssh; readable workspace control. For the credential file use disposable test credential under identical rule, never overwrite/read real secrets. Exercise shell cat, native Read/search, symlink aliases and sandbox/policy escape requests for every protected path. Trusted tool still authenticates. Unknown/skipped/readable protected sentinel fails Claude confinement. Repeat after restart/every enabled confined mode; clean only owned sentinels.
-## Questions for Paul
+ Codex subcase explicitly asserts ReadIsolation=false, current exact owner acknowledgement and unconfined provenance; it cannot be counted as a successful deny-read sentinel test. Unsupported reads alone no longer block this pair. Missing acknowledgement or any other capability still blocks; once supported per-agent Codex profiles ship, require its full sentinel gate through Task 9's restoration path. Both families must prove account routing/reconnect and absence of owned agent/background/terminal processes after cancel. Executor sentinel gate remains mandatory independently of agent status.
-No open product questions. The existing question and its binding ruling are retained below.
+ TestPaseoLiveTurnCalibration measures representative turn per eligible family with provider/model/config hash, uncached/cached input/output and completeness flags. Prior Claude 18 input +29,591 cached +404 output is historical, not calibration. Set each input/output reservation to twice the largest corresponding measured total, rounded up to 1,000 with checked arithmetic; job funds at least 23 reservations, project/team explicit period headroom. Never silently raise existing lower operator limits; report required funding if blocked. Calibration uses explicit bounded reservations recorded separately, not uncalibrated production dispatch. Test unknown-usage reservation then known completed turn with headroom, and exhaustion. Record limits/overruns; later overrun stays charged before further work stops. No offline fixture substitutes for live proof; this planning session runs none of these gates.
+- [ ] **Commit/human acceptance:** `test: verify the runner workflow and live compatibility gate`. Clean reviewed commit: `make release`, `make runner-release`; verify stamps/manifests. Human deploys versioned oficina CARLOS release and installs/enables user service, chooses always-on live mode, enrols, confirms origin/machine, records per-connection ack where needed, submits bounded bug, follows Journey/specialists, reads evidence/labelled Amadan branch and merges personally. Repeat active cancel and inspect containment. Stop test processes/remove owned scratch; only human-installed service persists.
-1. **May subscription limits count dispatched Paseo turns, with provider-internal calls/tokens recorded when observable?** An unmodified subscription CLI can make multiple model requests in a turn and cannot promise a hard token/currency cap. This plan reserves before each turn, records measured usage/overruns, enforces time/attempt limits and stops before further work. If “calls” must mean every provider request under a hard ceiling, subscription execution is blocked until Paseo/provider support supplies that boundary. The ruling below settles this question; Task 18 still requires the technical live gates.
+## Decisions and review coverage
- **Ruled by the controller, 2026-11-02:** yes. A subscription "call" is a
- dispatched Paseo turn; provider-internal calls and tokens are recorded
- when observable and shown, never enforced as a hard cap. This is spec
- section 6.8 as Paul approved it ("usage is recorded and shown, and
- Equipo's own limits (calls, time, attempts) still apply"). The subscription call definition does not block Task 18. The technical
- read-isolation/account-routing gates still block live acceptance where
- unsupported.
+No open product questions. Subscription calls count dispatched turns; provider-internal usage is recorded when observable without claiming a hard subscription cap. Paul accepts temporary acknowledged Codex read exposure for his repositories; Claude confinement and all other capabilities remain gates. Unsupported account pinning/identity/no-failover, timeline recovery, process coverage or check adapters require owning-product support, not permission to invent contracts. No project/account deletion or tito-studio enrolment is needed.
-Technical prerequisites are not decisions for Paul: Codex read isolation is currently ineligible through Paseo 0.14.0; Claude has a configuration path but no live sentinel proof yet. Likewise, unsupported account pinning/identity, recoverable completion usage, process ownership/cleanup or base-check adapters must be established by contract tests or requested from the owning product. No permission is sought to invent those interfaces. There is no project/account deletion question: it is not needed for this slice. No tito-studio enrolment is planned.
+Review focus remains: lost replies cannot duplicate submission/creation/publication (7/12/14); stale/wrong-person authority cannot dispatch or answer (5/6/8/13); rollback/sleep/PID reuse cannot retain authority or fake containment (2/15); reconnect cannot undercharge or invent completion (12); candidate changes/check tampering/deleted tests cannot pass evidence (4/10/11). Spec coverage: specialists/fixed plan (4/6/7/15), live views (16), outbound lifecycle (5–15/17), publish/evidence (4/10/11/14), authority/budgets/recovery (1–3/8/12/15/17), personal selection (6/16), acceptance (18).
## Round 1 dispositions
-- **P1-1:** Tasks 13/17 use a per-attempt Unix socket under 0700 state, a 0600 capability file named only by environment path, and the real `tool` verb under a fake harness; no TCP or inet listener.
-- **P1-2:** Task 15 builds the Linux inspector with env marker, `/proc` cwd/ancestry scans, terminal/executor ownership, PID/start/boot identity and unknown-coverage refusal; Task 17 wires it, with a real environment-stripped-child test.
-- **P1-3:** Tasks 9/10/13/17 require `ReadIsolation`; Claude has supported settings pending live proof, Codex is ineligible on Paseo 0.14.0, and Task 18 tests every protected path without weakening the family gate.
-- **P2-1:** Task 2 fences only grants whose version/epoch changes; two-project tests keep unrelated work running, while the existing global roster epoch legitimately affects all bound grants.
-- **P2-2:** Task 9 pins server/client/protocol 0.14.0 and names each export, including daemon-control credentials and `DaemonClient.cancelAgent`.
-- **P2-3:** Task 8 stores admission identity/ticket atomically and replays it only for the same unexpired, currently authorized attempt/fence/request; Task 14 tests lost Admit replies and single execution.
-- **P2-4:** Task 11 freezes the baseline test-name set, requires a passing superset and rejects deleted test files, `t.Skip`, skipped packages/subtests and zero-test success.
-- **P2-5:** Task 11 uses separate scratch copies for reproduction overlays and rejects candidate-edited collisions; the immutable candidate export remains unchanged.
-- **P2-6:** Task 6's runner discovery moves to 17, Task 7's network/fetch preparation to 15, and Task 8 uses explicit fake validators until 15; numbered execution has no hidden forward implementation dependency.
-- **P2-7:** Tasks 2/3/7/8 own ordered core bumps 4/5/6/7, app migration mirrors and upgrade/parity tests against `team.SchemaVersion`.
-- **P2-8:** Tasks 3/12 bound per-turn reservations, retain unknown charges and report cached input separately; Task 18 measures real turns and configures job/project/team limits from the measurements.
-- **P3 carry 7:** Task 6 adds `TestProjectAccountNoDeleteAndASCIILabels` to pin the absent deletion paths and existing label behavior.
-- **P3 reproduction identity:** Task 11 adds `candidateHash` to `Reproduce`, with base-commit versus candidate-artifact subject assertions.
-- **P3 writer DSN:** Task 1 explicitly requires and asserts one writer connection for Rastrillo's DSN; larger pools are refused.
-- **P3 hibernation:** Task 17 tests preserved/lost witnesses across `oficina` wake-up and requires stable external witness storage or quarantine.
-- **P3 CI Node:** Tasks 9/17 provision and check Node v24.19.0 for the same `runner-adapter-test` Make/CI gate and release manifest.
-- **P3 MCP type:** Tasks 9/13 serialize `type: "stdio"` and exercise the actual spawn contract.
-- **P3 cleanup accounting:** Task 8's `TestRevokedCleanupCannotRefund` prevents cleanup-only reports from reducing charges; lower settlement requires corroboration and owner audit.
-- **P3 account routing:** Tasks 9/17 identify ZeroSub 1.3.0's automatic failover and refuse eligibility without a proven per-agent no-failover/account observation interface; full live proof remains a named technical prerequisite, not assumed support.
-- **Cut cross-machine transfer:** Tasks 6/10/11 bind the whole run to one docs-t1 runner with local candidate staging and complete bounded blobs; remove Git bundles and chunked transfer.
-- **Cut enrolment-response recovery:** Task 5 requires fresh browser-approved enrolment after a lost exchange; retain only credential hashes.
-- **Cut EventSource and pagination:** Task 16 uses plain 15-second page refresh on read-only live views and separate forms, with no Journey cursor or event feed.
-- **Cut owner allowlist:** Tasks 6/16 defer provider/family policy editing to plan 4; personal selection and different-family review remain.
-
-No P3 sentence/test is left unapplied. Read isolation, process coverage and account routing remain release gates whose live success is not claimed by this planning revision.
-
-## Self-review
-
-1. **Spec coverage:** §3.2 independent Review → Tasks 4/6/15; §3.4 fixed immutable bug path/person at end → 7/16; §§4.1–4.4 live rail/Journey/specialists/task cards → 16; §§6.1/6.8/6.9 runner/enrolment/claim/workspaces/client/questions/finish/cancel → 5–15/17; §§6.2/6.5 exact review-branch publication → 4/10/14; §§6.3–6.4 frozen bug evidence/trusted checks → 4/11; §6.7 authority/budgets/recovery/hibernation → 1–3/8/12/15/17; §7 personal connections and deterministic selection → 6/16; §§9–10 gates and Paul's bug/cancel try-out → 18. Coordinators, plan editing, preferences, settlement, recommendations and product ranking remain roadmap rows 3–4. Copy/design and feature predicates are deliberately absent.
-2. **Carries covered:** qualified `refs/heads/<Ref>` → 14; Project/grant agreement → 2/7; five-second admissions → 2/3/8/14; stale project/roster edits until Resume → 2/8/15; lowering limits blocks reserved undispatched work → 3; clock-back containment/time uncertainty → 2/15; no project/account deletion and unchanged ASCII label semantics → boundary decision and Task 6 pinning test; period full scan → 3. None is left as an unassigned reminder.
-3. **Contradictions resolved:** (a) spec CLI event-following versus probe's structured client: probe wins, Task 9; (b) spec ordinary send for questions versus permission-ID responses: probe wins, Task 13; (c) stop/archive receipt versus real containment: verify processes, Task 15; (d) core provider independence versus required family independence: version-2 family rule, Task 4; (e) fixture candidate-content digest versus Git commit identity: retain both, Task 4; (f) core reproduction-only check result versus separate repository checks: add a required role, Tasks 4/11; (g) core standalone SQLite open versus activation database ownership: borrowed writer and migration mirrors, Task 1; (h) spec hard calls/tokens language versus unmodified subscriptions: explicit accounting contract and the controller's settled turn-count ruling; (i) older first-team sandbox/egress reservations versus this approved runner scope: implement the scoped subscription/harness milestone, with explicit personal connection consent and required deny-read isolation; the suite amendment remains separate roadmap work, not a second approval request. Older mockup initials/navigation/colored accents are already superseded by the brief and mockup README, not new product choices.
-4. **Type and dependency check:** Existing core APIs retain their signatures unless an extension is named. The shared app transaction wrapper preserves the core witness; recovery snapshots use a semantic generation rather than the read-advancing witness revision. Core schema changes have ordered version owners, and the dependency split above separates local unit work from Tasks 15/17 integration. New wire DTOs are shared through `runnerproto`; local SDK types stay in `runner/paseo`. Core scope uses persisted Team.ID, never CARLOS account labels. Production construction waits until recovery, policy, adapters and supervisor exist; UI reads can be tested with projections earlier. Definition hash and immutable base exist before job creation; reproduction and symptom freeze precede candidate creation. Candidate artifact hash never substitutes for Git commit at push. A preparation assignment is not a provider action or an executable plan step. Artifact uploads and late recovery reports have distinct authorization paths.
-5. **Review Focus and step scan:** Each of the five failure classes has named tests and owning tasks. Every task has an explicit red command, implementation interface, green check and future commit; task 16 adds its copy/browser gates. Guard mutations are required and recorded. No product function bodies, fabricated model IDs, invented forge endpoints, anonymous “handle errors” steps or unbounded live test instructions are supplied.
-6. **Proportion and verification honesty:** Eighteen independently reviewable tasks cover this one runner slice, rather than four roadmap plans. Assertions and interface declarations supply decisions; implementers write function bodies. The original plan inspected the spec/roadmap/probe/Foundation plan/controller and mockups. This revision rechecked HEAD `a66c96e`, the revision brief/findings, relevant spec/roadmap/probe, discussion 2, app/core source, pinned Rastrillo DB APIs, installed Paseo/ZeroSub exports, local CLI help and official sandbox documentation. Local schema-validation and command-only sentinel probes ran as recorded above; `git diff --check` and the task/disposition checks passed. It did not run implementation tests, provider sessions, pushes, deployment, or a live cancellation experiment. All implementation and live verification commands above remain unchecked until execution. The four cuts are reflected throughout the tasks; the current live blocker is stated explicitly instead of weakening acceptance. The only requested artifact is this plan; no README, handoff file or product code changes are part of this session.
+- P1-1: Tasks 13/17, private Unix socket/0600 capability, actual tool subprocess; no TCP/inet listener.
+- P1-2: Tasks 15/17, production Linux inspector and real environment-stripped child, unknown coverage refuses.
+- P1-3: Superseded only by Paul's R1b acknowledgement rule; Claude sentinel gate remains, Codex is explicitly unconfined.
+- P2-1: Task 2 fences changed grants only; global roster epoch still stales its grants.
+- P2-2: Task 9 pins exports including daemon-control and cancelAgent.
+- P2-3: Tasks 8/14 atomically persist/recover admission ticket; one dispatch.
+- P2-4: Task 11 requires passing baseline superset; deleted/skipped tests fail.
+- P2-5: Task 11 separate reproduction scratch and collision refusal preserve candidate.
+- P2-6: Tasks 6/7/8 defer integration to 15/17; no forward implementation dependency.
+- P2-7: Tasks 2/3/7/8 own ordered core versions 4/5/6/7 and parity/upgrades.
+- P2-8: Tasks 3/12/18 bounded reservations, cache accounting and measured calibration.
+- P3 carry 7: Task 6 pins absent deletion and existing ASCII/non-ASCII labels.
+- P3 reproduction identity: Task 11 distinguishes base commit/candidate artifact subjects.
+- P3 writer DSN: Task 1 requires one writer connection.
+- P3 hibernation: Task 17 preserves witness or quarantines.
+- P3 CI Node: Tasks 9/17 check/provision Node and package manifest.
+- P3 MCP type: Tasks 9/13 retain stdio and real spawn contract.
+- P3 cleanup accounting: Task 8 prevents revoked cleanup refunds; corroborated owner settlement only.
+- P3 account routing: Tasks 9/17 reject ZeroSub automatic failover without supported guarantees.
+- Cut cross-machine transfer: single docs-t1 runner/local immutable staging/bounded blobs.
+- Cut enrolment-response recovery: fresh browser approval, hashes only.
+- Cut EventSource/pagination: R1b replaces page refresh with Rastrillo live; no custom event feed or Journey pagination.
+- Cut owner allowlist: deferred to plan 4; personal opt-in and independent family retained.
+
+No Round 1 P3 decision/test is dropped. Original conflicting contracts remain resolved: structured SDK events, permission-ID answers, verified containment, family independence, distinct artifact/Git identity, separate repository checks and borrowed activation writer. Definitions/base precede job creation; reproduction freeze precedes candidate; uploads/recovery use distinct authorization.
+
+## Round 1b changes
+
+- Added first Task 0: Rastrillo v0.30.0/Go 1.26.0 upgrade, source-checked API inventory, locale/assets/browser migration and full Foundation/CI safety net. Existing Task 18 remains numbered 18; total 19 tasks.
+- Applied Paul's Codex ruling: owner-only connection acknowledgement with actor/time/provider/version audit, automatic version expiry, truthful capability, historical unconfined provenance and labels on every required surface. Added refusal/expiry/label tests and future supported-profile confinement gate.
+- Replaced timed page refresh with Rastrillo live regions, authorized team/job keys, post-commit notifications, scriptless fallback, stream shutdown and always-on deployment constraint.
+- Consolidated repeated rationale/assertion snippets into interfaces, tests, commands and shared rules; retained named tests, numerical bounds, migration ownership, security decisions and review dispositions.
+- Verification for this planning revision: inspected repository HEAD and local Rastrillo tag/docs/source; compared old/new test inventories and checked task references, command selections and diff whitespace. Product tests, upgrades and live gates above remain future implementation work. Only this plan is edited; no agents, services, commits, pushes or deployment were started.