oficina / equipo Public

Spec rev 3.2: rulings 7 and 8; S4 progress

The connectors spec comes onto the branch as revision 3.2: Claude
readings may be stale while Codex's are refreshed without a turn, each
reading's age shown (6, 7, 12); a kept session may also move when its
spending permission is withdrawn (7 rule 1); S1 to S3 built. Its
findings files and allowlist entries come with it. Budget lines and the
S4 progress file with every mutation observed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev fd99586c73d0e0fbb55f566600534ec4722edb06 parent 71774cf
7 files changed, +1,344 −5
  • .rastrillo/budgets.txt +5 −5
  • docs/superpowers/plans/S4-USAGE-PROGRESS.md +274 −0
  • docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md +888 −0
  • docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R2.md +37 −0
  • docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R3.md +41 −0
  • docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING.md +57 −0
  • scripts/runner-reference-allowlist.json +42 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index db16c43f..9cfb85f0 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 18647 - The instance web layer: pages, handlers, templates and copy for every screen. Measured 18647 source lines.
-size internal/wire 5041 - The runner and person API protocol: every frame, resource and its downgrade up to protocol 14 (the scheduler), one package so Encode sees every type. Measured 5041 source lines.
+size internal/equipo 19056 - The instance web layer: pages, handlers, templates and copy for every screen, the Usage page included. Measured 19056 source lines.
+size internal/wire 5242 - The runner and person API protocol: every frame, resource and its downgrade up to protocol 15 (readings with their time; usage and advice), one package so Encode sees every type. Measured 5242 source lines.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -36,7 +36,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 22059 13276 The thin runner: steps, link, coordinator, Mac worker, previews, merges, metered connections, Research and the scheduler. Measured 22059 source and 13276 test lines.
+size internal/runner/thin 22157 13425 The thin runner: steps, link, coordinator, Mac worker, previews, merges, metered connections, Research, the scheduler and its Codex reading probe. Measured 22157 source and 13425 test lines.
time internal/thintest 180s Contract tests for Mac runners, transitions and the thin core share one instance harness; loaded CI needs 180s.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -51,7 +51,7 @@ perf GET /api/v1/notebook skip Thin v1 person API: bearer-only JSON for devices;
perf GET /api/v1/thinking skip Thin v1 person API: bearer-only JSON for devices; the browser reads thinking words on /settings/thinking.
perf GET /api/v1/tasks skip Thin v1 person API: bearer-only JSON for devices; the browser reads tasks through /tasks.
perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads a task through /tasks/{id}.
-size internal/equipo/chat 20415 - The instance store: tasks, steps, cards, merge authority, housekeeping, placement, metered connections, Research and the scheduler. Measured 20415 source lines.
+size internal/equipo/chat 21262 - The instance store: tasks, steps, cards, merge authority, housekeeping, placement, metered connections, Research, the scheduler, usage and advice. Measured 21262 source lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -66,5 +66,5 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 9766 End-to-end scenarios through a real runner and instance, plus browser drives. Measured 9766 test lines.
-size internal/thintest - 20135 Thin v1 contract and page tests; one package keeps one instance harness. Measured 20135 test lines.
+size internal/thintest - 20295 Thin v1 contract and page tests; one package keeps one instance harness. Measured 20295 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
diff --git a/docs/superpowers/plans/S4-USAGE-PROGRESS.md b/docs/superpowers/plans/S4-USAGE-PROGRESS.md
new file mode 100644
index 00000000..f12b197e
--- /dev/null
+++ b/docs/superpowers/plans/S4-USAGE-PROGRESS.md
@@ -0,0 +1,274 @@
+# S4 progress: the Usage page and advice
+
+Branch `connections-s4-usage` from main 75ba4863 (S1, S2 and S3 merged).
+Spec: `docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md`,
+now on this branch as **revision 3.2**, §11 row S4: §9 (advice), §2.3's
+spend line, §10's advice API, and the Usage page of the Connections rev 3
+spec §6 (availability now, spend this month, token use by connection,
+role, project and task; the sidebar dot). Also the controller's rulings
+on S3's review: #7 (reading freshness) built, #8 (a kept metered
+session moving) a spec amendment only. No real key, sign-in or
+provider: fakes only.
+
+## Done
+
+1. **Readings and their age (ruling #7).** Protocol 15
+ (`ProtocolReadings`): `Headroom.checked_at`, the time the runner took
+ a reading. `Conns.Observe` and `Conns.Limit` stamp every reading
+ (a turn's, a notification's, a probe's) with a copy, so the caller's
+ value is untouched; a reading that says the same again moves only its
+ time and wakes no held step. The scheduler's staleness check reads the
+ reading's own time (the row's write time only for a row from before).
+ Below 15, `Encode` drops the time from hello, sync and connection
+ reports (`downgradeReadings`), and the runner's first hello never
+ carries it (`WithoutReadingTimes`, a prompt hello after a 15 welcome).
+2. **The Codex reading probe (ruling #7).** `provider.ReadCodexLimits`:
+ the login probe's unconfined app-server in the source home, its
+ environment and egress, `initialize`, `account/read` then
+ `account/rateLimits/read`, no thread and no turn. `thin.CodexReading`
+ runs it through `provider.OpenRuntimeCopy` (the hourly refresh's lock
+ and identity check) and is now `Conns.Reading` in production, so a
+ Codex reading older than 15 minutes is refreshed before `Decide`, at
+ most once per 15 minutes a connection. Claude, token and metered
+ connections return nothing: Claude stays as last reported.
+3. **`internal/advice`**, pure: `Compute(facts, now)` gives every piece
+ of advice whose facts hold, in §9's order (kind; a connection's id, a
+ role's fixed place, a task set's earliest task then id; the key);
+ `Choose` applies the rules (none while one is open, one new card a
+ day in the person's zone counted on the day it shows, Not now silences
+ a key 14 days and 60 after a second); `Holds` says whether open
+ advice still holds. The four kinds with their triggers as §9 says.
+4. **The instance** (`chat/advice.go`, migration 0074): the forward-only
+ `chat_advice` table (open, then acted, dismissed or withdrawn);
+ `RefreshAdvice` on the housekeeping loop's minute (so on fact changes
+ within a minute, and at 08:00): open advice whose facts stopped
+ holding is withdrawn silently (its card resolved, nothing said), open
+ advice whose facts moved but hold follows them at a new revision, and
+ with none open the first eligible key not silenced becomes the day's
+ card, held through quiet hours with housekeeping's `VisibleAt`. One
+ quiet `advice` card in the conversation, never Needs you, never a
+ push; the coordinator has no tool for it. Actions are the ordinary
+ calls, in the advice's transaction, at the revision the advice read,
+ after checking the facts still hold: `SetBudget`, `SetPreference`
+ (with `until`), `SetPriority` per task (each through a `txn` form of
+ the store call). Each is audited as the call and as `advice.act` (or
+ `advice.dismiss`) with `source=advice`, the advice id and its key.
+ `chat_steps.held_at` keeps when a hold began. API: `GET
+ /api/v1/advice`, `POST /api/v1/advice/{id}/act`, `POST
+ /api/v1/advice/{id}/dismiss` (409 `revision_conflict` when it moved,
+ was answered, or its facts no longer hold), and `GET
+ /api/v1/usage?period=&by=`. Fixtures `api/advice.json`,
+ `api/advice-action.json`, `api/card-advice.json`,
+ `api/usage-month.json`, `frames/hello-readings.json`.
+5. **The Usage page** (`/usage`, `usage_page.go`, `usage.html`): advice
+ at the top with its action and Not now; available now (each
+ connection's state, its provider's meters and the reading's age, "as
+ of 2 h ago" for Codex, "as last reported 2 h ago" for Claude, none
+ from an older runner; "Headroom not reported" otherwise); spend this
+ month (S1's spend line per metered connection, reported by its
+ harness, where prices come from read from the price table's version:
+ "TensorX prices taken from the public page on 12 Nov 2026.";
+ subscriptions as plan and tokens, never money); token use with tabs
+ (today, this week, this month) by connection, role, project or task,
+ columns input, cached input, output and the estimate where priced.
+ The sidebar has Usage with a dot when a connection is limited or needs
+ a sign-in, or a metered one is paused. A step held for headroom says
+ its reading's age on its line ("… · as last reported 2 h ago").
+6. **Spec revision 3.2** on this branch, with its Astra findings files
+ and the dead-reference allowlist entries: §6, §7, §12 and the status
+ line for ruling #7; §7 rule 1 adds spending permission withdrawn as a
+ switch reason for a kept session (ruling #8, no code change); §10's
+ `Headroom.checked_at`.
+
+## Tests
+
+- `internal/advice`: `TestEachKindFiresOnce` (each kind from its fixture,
+ only it), `TestEachKindsLine` (each trigger just short of its line),
+ `TestTiesPickTheSameCard` (all kinds at once, 500 shuffles, the same
+ order and the same card), `TestNotNowSilences` (14 days, then 60),
+ `TestNoDayShowsTwoCards` (open, acted, withdrawn or dismissed today;
+ quiet hours; the person's zone).
+- `internal/equipo/chat`: `TestAdviceStoreActsThroughTheOrdinaryCall`,
+ `TestAdviceStoreNotNowAndWithdrawal`, `TestAdviceStoreQuietHours`,
+ `TestAdviceStoreTaskActions`, `TestAdviceStorePreferSwitch`,
+ `TestAcceptHoldKeepsHeldSince`.
+- `internal/equipo`: `TestUsagePage`, `TestPriceSource`,
+ `TestUsageAttention`, `TestHoldLineSaysTheReadingsAge`.
+- `internal/wire`: `TestEncodeBelowProtocol15DropsReadingTimes` (frozen
+ protocol 14 headroom), `TestWithoutReadingTimes`,
+ `TestAdviceTypesCarryNoSecrets`, fixture round trips.
+- `internal/runner`: `TestReadCodexLimitsWithoutTurn` (provider: a fake
+ app-server that fails on anything but its four requests),
+ `TestCodexReadingInProduction`, `TestScheduleRefreshUsesReadingTime`,
+ `TestHandshakeHelloWithholdsReadingTimes` (thin).
+- `internal/thintest`: `TestContractUsage` (page, advice in both places,
+ API, act from the page reaching the runner, the hold line's age, the
+ dot), `TestContractUsageOlderRunner` (protocol 14).
+- `internal/headless` (`-tags browser`): `TestBrowserUsageAndAdvice` at
+ 1280 and 390: the sidebar, the card at the top, the action in reach,
+ the reading age, the spend line, the tabs, no sideways scroll; Raise
+ today's budget reaches the runner at twice the figure.
+- `internal/plan3test`: the four person API routes registered.
+- Local runs were targeted (`-run`) on the changed packages, plus gofmt,
+ go vet, staticcheck on the changed packages, `make budget` (lines
+ updated), `scripts/ci-test.py check` and the dead-reference scan.
+
+## Mutations, each observed failing
+
+### wire and runner
+- WM1 readings downgrade removed -> TestEncodeBelowProtocol15DropsReadingTimes (hello carries checked_at)
+- PM1 reading probe asks turn/start -> TestReadCodexLimitsWithoutTurn
+- PM2 reading probe skips rateLimits/read -> TestReadCodexLimitsWithoutTurn
+- RM1 Observe/Limit not stamping the reading time -> TestCodexReadingInProduction (CheckedAt nil), TestScheduleRefreshUsesReadingTime
+- RM2 staleness read from the row's updated_at, not the reading's time -> TestScheduleRefreshUsesReadingTime (0 probes)
+- RM3 a reading that says the same again counted as new (time compared) -> TestCodexReadingInProduction (woke 1)
+- RM4 CodexReading reads any provider (Claude too) -> TestCodexReadingInProduction (claude-1 read)
+- RM5 first hello carries the reading times -> TestHandshakeHelloWithholdsReadingTimes (handshake hello)
+- RM6 no prompt hello after a protocol 15 welcome -> TestHandshakeHelloWithholdsReadingTimes
+### advice (internal/advice)
+- AM1 near-budget line moved above 80% -> TestEachKindFiresOnce (budget_near: []), TestEachKindsLine
+- AM2 first Not now silences 7 days -> TestNotNowSilences (day 13 shown)
+- AM3 second Not now silences 14 days, not 60 -> TestNotNowSilences (day 29 shown)
+- AM4 a second card on the same day allowed -> TestNoDayShowsTwoCards
+- AM5 a card while one is open -> TestNoDayShowsTwoCards
+- AM6 budget_near's connection order dropped -> first MISSED: equivalent (the key holds the id and breaks the tie the same way); reversed instead -> TestTiesPickTheSameCard
+- AM7 no sort (facts' order decides) -> TestTiesPickTheSameCard
+- AM8 prefer_switch ignores the 24 h reset bound -> TestEachKindsLine (reset within a day)
+- AM9 prefer_switch ignores the target's 0.50 -> TestEachKindsLine (target at 0.50)
+- AM10 held_long ignores the week -> TestEachKindFiresOnce (tk5,tk6)
+- AM11 defer_tasks takes any hold, not headroom -> TestEachKindsLine (held for the budget)
+- AM12 the day read in UTC, not the person's zone -> first MISSED (the zone case only crossed one way); a case shown just after the person's midnight added, then caught
+- AM13 prefer_switch ignores the runner rule -> TestEachKindsLine (another runner)
+- AM14 role order reversed -> TestTiesPickTheSameCard
+### instance store (internal/equipo/chat)
+- IM1 act's revision not checked -> TestAdviceStoreActsThroughTheOrdinaryCall (a stale revision)
+- IM2 act does not recheck that the facts hold -> first MISSED; a case acting on facts that stopped holding before the next look added, then caught
+- IM3 the advice audit (source and key) left out -> TestAdviceStoreActsThroughTheOrdinaryCall, TestAdviceStoreTaskActions
+- IM4 the day of a quiet-hours card counted as tonight, not the morning -> first MISSED; a night card after the day's card added, then caught
+- IM5 quiet-hours card not held -> TestAdviceStoreQuietHours
+- IM6 advice whose facts stopped holding not withdrawn -> TestAdviceStoreNotNowAndWithdrawal (first tried as a deletion, a compile error; then as a dead branch, caught)
+- IM7 Not now not recorded with its time -> TestAdviceStoreNotNowAndWithdrawal (shown again within 14 days)
+- IM8 open advice not following facts that moved -> TestAdviceStoreTaskActions (revision 1)
+- IM9 a card in quiet hours answerable -> TestAdviceStoreQuietHours
+- IM10 advice looked up without its person -> TestAdviceStoreActsThroughTheOrdinaryCall (another person's act)
+- IM11 a hold's start reset by every report -> first MISSED; TestAcceptHoldKeepsHeldSince added, then caught
+- IM12 a hold's start kept after the hold -> TestAcceptHoldKeepsHeldSince
+### pages and wiring (internal/equipo, internal/thintest)
+- PG1 Claude's age said as refreshed ("as of") -> TestUsagePage, TestHoldLineSaysTheReadingsAge
+- PG2 the price source written as a fixed sentence -> first MISSED (the fixture's version gave the same words); a second price table version added, then caught
+- PG3 a version without its dash accepted -> TestPriceSource
+- PG4 the dot ignores the month's budget -> TestUsageAttention
+- PG5 the task pages not adding the reading's age to a hold -> TestContractUsage (first tried as a deletion, a compile error; then as a dead read, caught)
+- PG6 a reading with no time said "as of just now" -> TestUsagePage, TestHoldLineSaysTheReadingsAge
+- PG7 the sidebar dot never set -> TestContractUsage (no dot for a limited connection)
+- PG8 the loop's minute not looking at advice -> TestContractUsage (advice [])
+- PG10 the conversation's advice card never open -> TestContractUsage (no quiet advice card)
+- BM1 the advice action posting to Not now -> TestBrowserUsageAndAdvice (no budget frame)
+
+## Decisions where the spec was open
+
+- A reading's time rides the wire (`Headroom.checked_at`) rather than
+ being the instance's receipt time: a fresh reading that says the same
+ again would otherwise look old.
+- The routing line is the task's hold line for headroom; its age is the
+ named connection's current reading on the instance, not the reading the
+ hold was decided on (a newer reading may have come without a new hold
+ report).
+- The Codex probe asks `account/read` without a token refresh, then the
+ rate limits, under the same lock and runtime copy as the hourly check.
+- `budget_near` names today's budget first, this month's when today's
+ is not near or cannot be raised; its action doubles that budget (a
+ day's never above the month's, both within S1's bounds). Leave it is
+ its Not now and silences the same way.
+- `prefer_switch` fires only with a preference set (Automatic already
+ picks the most room). The preference is one provider for every role
+ (as built), so the card names no role; the key carries the first
+ waiting role in the fixed order. The preferred provider is near its
+ limit when each of its connections has a window at or above 0.80
+ resetting more than 24 h away; until is the earliest of those resets.
+ The other subscription must be healthy, report at least one window,
+ all below 0.50, and sit on a runner holding a waiting step of the role
+ (the primary for one not placed yet). Its act is refused by a runner
+ below protocol 14, as `SetPreference` with `until` is.
+- `defer_tasks` per role: the normal tasks without a deadline whose step
+ for that role is queued or held, the person's own, housekeeping's
+ attempts never counted; the day it names is the earliest reset among
+ the held urgent steps (no day when none was reported).
+- `held_long` counts a hold without a break (`held_at`, set when a hold
+ begins, kept while held, cleared with it).
+- The day is the person's zone (UTC until one is known); a card made in
+ quiet hours counts for the day it shows; a withdrawn card still counts.
+- Quiet hours are the person's housekeeping quiet hours (22:00 to 08:00
+ by default), released by housekeeping's minute; a person who paused
+ housekeeping sees a night card after Resume or their first message, as
+ housekeeping's own receipts.
+- Usage periods are calendar ones in the person's zone (today, since
+ Monday, since the 1st), the person's own rows only; rows that
+ overcount are left out with the existing note; the estimate sums priced
+ rows only.
+- Where prices come from is the price table each metered connection was
+ last charged by, from its usage rows.
+- `GET /api/v1/usage` is built (Connections rev 3 §6) because the page
+ reads the same totals.
+
+## Open, or not as the spec says
+
+- Connections rev 3 §6's routing sum lines and a subscription's typed
+ plan price are not built (not in the S4 row).
+- The Usage page does not follow the event stream; it is current on each
+ load and after each form.
+- The staging witness waits for a release.
+
+## Copy keys (COPY REVIEW REQUIRED (S4 usage), in the Plan 3 inventory)
+
+- `nav.usage`: Usage
+- `nav.usage_attention`: Something on Usage needs a look
+- `usage.title`: Usage
+- `usage.lede`: What can run now, what it costs, and where the tokens went.
+- `usage.advice`: Advice
+- `usage.now`: Available now
+- `usage.reading.as_of`: as of %s
+- `usage.reading.last_reported`: as last reported %s
+- `usage.reading.none`: Headroom not reported
+- `usage.no_connections`: Nothing is connected yet.
+- `usage.connect`: Add a connection
+- `usage.spend`: Spend this month
+- `usage.price_source`: %s prices taken from the public page on %s.
+- `usage.plan_tokens`: %s tokens this month
+- `usage.plan`: %s plan
+- `usage.spend_none`: Nothing here spends money: every connection is a subscription.
+- `usage.tokens`: Token use
+- `usage.period.day`: Today
+- `usage.period.week`: This week
+- `usage.period.month`: This month
+- `usage.by.connection`: Connection
+- `usage.by.role`: Role
+- `usage.by.project`: Project
+- `usage.by.task`: Task
+- `usage.col.input`: Input
+- `usage.col.cached`: Cached input
+- `usage.col.output`: Output
+- `usage.col.estimate`: Estimate
+- `usage.tokens_empty`: No tokens recorded for this period.
+- `usage.no_task`: The conversation
+- `usage.role.probe`: Connection checks
+- `usage.at_least`: at least %s
+- `work.hold.reading`: %s · %s
+- `advice.not_now`: Not now
+- `advice.leave_it`: Leave it
+- `advice.budget_near.day`: %s: %s of today’s %s.
+- `advice.budget_near.month`: %s: %s of this month’s %s.
+- `advice.budget_near.raise_day`: Raise today’s budget to %s
+- `advice.budget_near.raise_month`: Raise this month’s budget to %s
+- `advice.prefer_switch`: %s is near its limit until %s. %s has room. Prefer %s until then?
+- `advice.prefer_switch.act`: Prefer %s until %s
+- `advice.defer_tasks.one`: One task could wait until %s so the urgent work goes first. Let it wait?
+- `advice.defer_tasks.many`: %d tasks could wait until %s so the urgent work goes first. Let them wait?
+- `advice.defer_tasks.one_no_reset`: One task could wait so the urgent work goes first. Let it wait?
+- `advice.defer_tasks.many_no_reset`: %d tasks could wait so the urgent work goes first. Let them wait?
+- `advice.defer_tasks.act_one`: Make it low priority
+- `advice.defer_tasks.act_many`: Make them low priority
+- `advice.held_long.one`: A low-priority task has waited a week.
+- `advice.held_long.many`: %d low-priority tasks have waited a week.
+- `advice.held_long.act_one`: Make it normal
+- `advice.held_long.act_many`: Make them normal
diff --git a/docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md b/docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md
new file mode 100644
index 00000000..a15e0a44
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md
@@ -0,0 +1,888 @@
+# Equipo connectors and token-aware scheduling
+
+Status: approved, **revision 3.2** (2026-11-12, the controller's rulings
+#7 and #8 on S3's review). S1 (metered connections), S2 (Pi on TensorX)
+and S3 (the scheduler) are built and merged: `S1-METERED-PROGRESS.md`,
+`S2-PI-PROGRESS.md`, `S3-SCHEDULER-PROGRESS.md`. S4 (Usage and advice)
+builds on this revision. Ruling #7: Codex readings older than 15 minutes
+are refreshed by `account/rateLimits/read` with no model turn, Claude's
+stay as last reported, and every reading's age is shown (§6, §7, §12).
+Ruling #8: a kept metered session whose step lost its leave to spend
+starts afresh on a subscription, as built (§7 rule 1). Drafted by
+Claude (Opus 5.5) on `connections-slice2-design` from main 1d7b4e4.
+
+**History.**
+
+- Revision 1 (732d7d6): Astra round 1 said NOT READY.
+- Revision 2 (6591b33) added a metering gateway on the runner. Astra
+ round 2 also said NOT READY, with a new Critical (the gateway did not
+ bound request bodies) and an Important (no namespace transport for
+ it). The full texts are in `CODEX-FINDINGS-CONNECTORS-SCHEDULING.md`
+ and `-R2.md`.
+- Revision 3, on the controller's direction, **cuts the gateway from
+ v1**:
+ - hard caps live at the provider;
+ - Equipo keeps a soft budget from reported usage;
+ - keys reach the harness as Claude's and Codex's credentials do;
+ - scheduling decides admission from the readings taken at admission
+ and claims nothing about what a step will go on to consume.
+
+- Astra round 3, the last, on revision 3 (e9f1bc7): **READY WITH
+ CHANGES**, no Critical. Its ten Important findings are folded into
+ revision 3.1 (`-R3.md`, §15), with no further round.
+- Revision 3.2 (2026-11-12) records the controller's two rulings on
+ S3's security review (#7 reading freshness, #8 a kept metered session
+ moving) and that S1 to S3 are built. Nothing else changes.
+
+§15 maps all three rounds' findings.
+
+This builds on:
+
+- Connections rev 3 (`2026-11-08-equipo-connections.md`, "rev 3"), as
+ built in `CONN1-PROGRESS.md`;
+- the spend lines (`chat_usage`, migration 0059);
+- the housekeeping budgets (`2026-11-08-equipo-housekeeping.md` §4);
+- merge authority (`2026-11-11-equipo-merge-authority.md`): a
+ deterministic gate, the coordinator can only tighten, and asks come
+ with a recommendation.
+
+Provider facts were read from official docs and source on 2026-11-12
+(§14).
+
+## 0. Decisions for Paul
+
+Each has a recommendation. Nothing is built until these are answered.
+
+1. **"Pi" means Pi as the harness, with TensorX as the paid
+ connection.** Pi has no subscription of its own. *Recommend: yes.*
+2. **Command Code comes in as a provider behind Pi, for now.** You
+ already use its models through Pi, and its Provider API is a plain
+ API key. Its own CLI has undocumented hosts and output, so it is a
+ later design. *Recommend: yes.* Please check in Command Code Studio
+ whether Provider API calls draw on your plan's windows or on credits.
+ Until then it counts as metered.
+3. **The hard cap is the provider's, never Equipo's.** A metered
+ connection is accepted only after you confirm, on the add-connection
+ screen, that the key has a provider-side limit (§2.1 shows how for
+ each provider). For TensorX that limit is the prepaid balance, so
+ keep it at what you are willing to spend. A shell inside a step
+ could use the key up to that limit. *Recommend: accept this.* The
+ alternative, Equipo enforcing a hard cap itself, needs the gateway
+ that failed two reviews (§5).
+4. **Equipo's own budget is soft.** It is a daily and a monthly figure
+ per metered connection. Equipo stops starting new steps when the
+ **reported** spend reaches either. A metered connection runs one
+ step at a time, so it can overshoot by at most one step, and the
+ screen says so. *Recommend: $1 a day and $10 a month* as the
+ pre-filled defaults.
+5. **When does metered money get spent?** Only on tasks you mark
+ `urgent` (your tap, never the coordinator's), or a step you release
+ with "Run it now anyway". `normal` and `low` work waits for a
+ subscription. *Recommend: yes.*
+6. **The reserve thresholds.** A `low` step starts only while every
+ reported window of a subscription is below 60%, and a `normal` step
+ below 80%. `urgent` steps start on any connection that is not
+ limited. The thresholds are the margin, because Equipo does not
+ predict a step's consumption. *Recommend: these numbers.*
+7. **Subscriptions that can bill overflow** count as metered unless you
+ confirm on the add-connection screen that a **standing setting**
+ turns overflow off. For a Mistral plan that setting is pay-as-you-go
+ off. For OpenCode Go, a zero Console balance is a snapshot rather
+ than a setting, and no overflow switch is documented, so Go counts
+ as **metered** until you find one in the Console. *Recommend:* turn
+ Mistral's pay-as-you-go off and confirm it; leave OpenCode Go
+ metered until a switch is confirmed.
+8. **The coordinator stays on Claude and Codex.** The new connectors
+ take Engineering, Review and Ask. *Recommend: yes.*
+9. **Order.** *Recommend:* metered connections and the budget, Pi on
+ TensorX, the scheduler, Usage and advice, OpenCode Go, Mistral Vibe,
+ then the Command Code provider. The gateway, Command Code's CLI and
+ Mac are later (§5).
+
+## 1. Why, and the shape
+
+Paul, 2026-11-12: the coordinator should "prioritise tasks according to
+token availability… deciding what can wait etc, and … proactively offer
+advice on how to handle tokens", and "can I get connectors for my
+Mistral, Pi, Opencode and Command Code subscriptions? … Pi I guess would
+then use… my TensorX? But I don't want to run that down too much."
+
+**Part A** adds three harnesses (Pi, OpenCode, Mistral Vibe) over four
+accounts: TensorX, the Command Code Provider API, OpenCode Go and the
+Mistral plan. The provider holds the hard cap, and Equipo keeps a soft
+budget.
+
+**Part B** adds `schedule.Decide`, a pure function on the runner that
+starts or holds each step from the readings taken at admission, and
+`advice.Compute`, a pure function on the instance that turns recorded
+facts into quiet cards. No model decides anything.
+
+**Reused, not redesigned:**
+
+- connections, homes and `connect.Choose`;
+- the sealed paste, with `sealbox`, `seen_seals` and the delivery state
+ machine (rev 3 §2.4, built for Claude tokens);
+- the token's delivery to the CLI, via a 0600 file outside
+ model-readable paths and bubblewrap's `--args` pipe;
+- the egress relay (`internal/runner/egress`), CONNECT to allowlisted
+ public hosts on 443;
+- usage rows (`wire.Usage`, `chat_usage`);
+- the step deferral (`stepDeferred`);
+- the policy and manifest digests;
+- srt's committed-digest pinning.
+
+# Part A: connectors
+
+## 2. Metered connections
+
+### 2.1 The provider's limit is the only hard cap
+
+A connection is **metered** when its key is billed per token, or when it
+is a subscription that can bill overflow and Paul has not confirmed that
+pay-as-you-go is off. The add-connection screen for a metered connection
+has one required confirmation, "This key has a spending limit at
+<provider>", with a line and a link saying how, from the provider's
+docs:
+
+| Provider | The provider-side limit | Source |
+|---|---|---|
+| TensorX | The prepaid balance. Keys are disabled when it falls under $0.05. Keep it at what you are willing to spend. Whether TensorX has automatic top-up, and per-key spend limits, is not documented; check that no top-up is set. | [T3] |
+| Command Code Provider API | A pay-as-you-go account has only its credit balance, and a plan has dollar caps per 5 hours and per week. Either is a limit, if auto-purchase of credits is off (not documented; check in Studio). | [CC4] |
+| OpenCode Go | The Go plan's per-model limits, and then the prepaid Console credit that overflow draws on (top-ups carry a fee). The Console balance is the hard limit. It is a balance, not a setting, so Go stays metered (§0 decision 7). | [OC2, OC12] |
+| Mistral plan | The plan's monthly usage. Overflow needs pay-as-you-go to be enabled, so pay-as-you-go off is the limit. | [V13] |
+
+The confirmation is recorded with the person, the time and the provider.
+Equipo cannot verify it, and the screen says so:
+
+> "Equipo can't see this limit. It is the only thing that stops spending
+> for certain: Equipo's own budget is checked between steps, and a step
+> that is running can use this key up to the limit you set at
+> <provider>."
+
+**Why a step can use the key.** These harnesses have no sandbox of
+their own for shell commands, unlike Claude Code's nested sandbox, which
+keeps its token out of reach (rev 3 §2.4). A command a model runs is in
+the same namespace and user as the harness, so it can read the harness's
+environment and spend the key. It can spend it only at the provider's
+host, because the relay allows nothing else. That is stated, not
+mitigated, in v1. Keeping the key out of the namespace altogether is the
+gateway, which is later (§5).
+
+### 2.2 Delivery, as Claude and Codex credentials are delivered
+
+- **Sign-in is a sealed paste only:** rev 3 §2.4 as built, generalised
+ from `KindToken` to `KindAPIKey`, with `endpoint` the provider's
+ origin. The key lands as a 0600 file in the connection's home,
+ outside every path a model tool is given.
+- **Each launch** gets the key as the harness's environment variable
+ through bubblewrap's `--args` pipe, never in argv, a manifest or a
+ record. The harness's config names that variable and never holds the
+ key.
+- **Egress** goes through the relay, allowed to the provider's host
+ only: `api.tensorx.ai`, `api.commandcode.ai`, `opencode.ai`,
+ `api.mistral.ai`. `egress.ProviderPolicy` and `Policy.Hash` become a
+ table keyed by `(harness, provider)`. There is no other network.
+- **Health (round 3, finding 10):** the runner, outside the namespace,
+ calls `GET /v1/models` with the key, and Paul picks the connection's
+ one model from the list on the connect card. A second model is a
+ second connection, since rev 3's model-pair routing is unbuilt. The
+ connection is `healthy` only after a **one-token completion** on the
+ selected model (`POST …/chat/completions`, `max_tokens: 1`, at the
+ provider's own path in §4) succeeds. That is the selected-model proof
+ rev 3 §2.5 requires. It runs at connect and on Check again only, as
+ Claude's token check does, never hourly. It is billable, so it is
+ recorded as a usage row with role `probe` and charged to the budget
+ like any other.
+
+### 2.3 The soft budget
+
+- **Figures.** Each metered connection has `budget {day, month}` in the
+ price table's currency, with both required and pre-filled (§0
+ decision 4). Day and month are in the person's zone, UTC until one is
+ known.
+- **Spend is what the harness reported (round 3, finding 5).** Each
+ attempt's usage becomes **normalised billable components**:
+ `uncached_input`, `cached_input`, `cache_write`, `output` and
+ `reasoning`. `reasoning` is counted apart from `output` only where
+ the provider's price-table entry says it bills separately; otherwise
+ it is treated as included in `output` and not added. Per adapter:
+ - **Pi:** `message_end.usage` is per request. The attempt's figure is
+ the sum over its assistant messages, and it is `complete` when
+ `agent_end` was seen.
+ - **OpenCode:** whether `session.usage.updated` is cumulative or
+ incremental is probe OC-P4. If cumulative, the attempt is the last
+ total less the total at the attempt's start, as `CodexTally` does;
+ if incremental, the sum. It is `complete` when the session went
+ idle.
+ - **Vibe:** one attempt is one run. It is `export.json`'s totals,
+ `complete` when the file is present and parses.
+
+ Price tables are versioned per connection: `{model, currency,
+ micros per million for each component, price_version}`. Cost is
+ int64 micro-units with overflow checks. A model with no price, or a
+ component the table cannot price, makes the attempt's spend unknown
+ (above). Where the harness reports its own cost (Pi `usage.cost`,
+ OpenCode `cost`, Vibe's export), the larger figure is charged and
+ both are recorded. `wire.Usage` gains `cost_micros`, `currency`,
+ `price_version` and `cost_reported_micros`. Spend is charged to the
+ day and month in which the attempt's usage row was recorded.
+- **The ledger:** `budget_charge` rows in `thin.db`, keyed by the usage
+ row's existing key `(turn, step, attempt, connection, model)`, so a
+ resent row charges once.
+- **One slot per metered connection (round 3, finding 1).** A metered
+ connection has one durable `metered_slot` row in `thin.db`. Every
+ attempt on it claims the slot in the same transaction as its
+ admission, whatever it is: an Engineering or Review step, a question,
+ a probe. Admission requires the slot to be free and `reported spend <
+ budget` for both the day and the month. The slot is released only
+ after the attempt's **termination proof** and either a committed
+ charge or `spend_unknown`, in one transaction. Cancellation and
+ failure take the same path.
+- **Restart recovery.** At start-up, before anything is admitted, a
+ claimed slot is reconciled:
+ 1. the attempt's namespace is recovered and killed, with the exit
+ proven, as the existing recovery does;
+ 2. a usage row already committed is charged;
+ 3. otherwise the connection becomes `spend_unknown`;
+ 4. then the slot is released.
+
+ The overshoot is therefore at most what one attempt spends, which the
+ provider's limit bounds.
+- **Unknown spend pauses.** An attempt that ends without a complete,
+ priced usage figure marks the connection **"spend unknown"**, with a
+ `pause_revision`. Nothing more is admitted to it until Paul taps
+ Resume, after looking at the provider's dashboard. **Resume (finding
+ 3)** carries the `pause_revision` it saw. The runner consumes it
+ atomically once, and only if that is still the current pause. A stale
+ or repeated Resume leaves a newer pause in place.
+- **Budget changes** take effect when the runner applies the durable
+ `budget` frame. Until then the page shows "applies when <runner>
+ confirms". A running step is not stopped by a change.
+- **The screen** shows, for example, "TensorX: $0.84 today of $1 ·
+ $6.20 this month of $10 · reported by Pi, can go over by one step",
+ with "Paused until tomorrow", "Paused until 1 Dec" or "Spend unknown:
+ check TensorX, then Resume".
+
+## 3. What every connector must have
+
+- **Isolated configuration.** Each harness loads only Equipo's
+ configuration: fixed config and home directories; project-local
+ configuration, extensions, plugins and hooks disabled by flag or
+ environment; and `check_policy.go`'s effective-policy check extended
+ to each harness. A hostile-repository fixture (a project config, an
+ extension, an `AGENTS.md` asking for a tool) proves it.
+- **Containment (Linux).** The existing bubblewrap namespace: the
+ credential home mounted to the harness, the relay to the provider
+ host only, a runtime copy, no inherited environment, pidfd
+ termination. The harness's approval layer is set to "allow inside the
+ namespace", because the namespace is the containment. Update checks,
+ telemetry and catalogue fetches are switched off by configuration,
+ and on a host other than the provider's they are also refused by the
+ relay.
+- **Pinning.** Expected digests are **committed per supported
+ platform**, as srt's tree digest is:
+ - npm trees (Pi, OpenCode): a committed `package-lock.json` installed
+ with `npm ci --ignore-scripts`, plus a committed SHA-256 over every
+ file's path, mode and content, symlinks included (each must resolve
+ inside the tree), and the platform binary's own SHA-256 where there
+ is one;
+ - the PyPI tree (Vibe): `uv pip install --require-hashes` from a
+ committed lock, a pinned Python, and the same tree digest.
+
+ The digest is verified before every launch, and the install directory
+ is read-only.
+- **Mapping.** Each adapter's `Decode` yields Equipo's existing kinds:
+ `delta`, `tool_call`, `tool_result`, `ask`, `usage`, `done`
+ (`completed`, `failed` or `interrupted`) and the failure classes.
+ Unknown events are counted and dropped, type names only.
+- **Families.** Review's `other_family` is judged on the model that ran.
+- **Acceptance**, per supported cell, in CI with the fake and once on
+ staging with the pinned binary:
+ - the hostile-repository fixture loads nothing;
+ - only the provider host is reachable;
+ - Review has no write or shell tool;
+ - killing the namespace ends every descendant;
+ - the budget stops the next step when the reported spend reaches it;
+ - a step with no usage figure pauses the connection;
+ - a resent usage row charges once.
+
+ Unlike Claude's acceptance, there is **no** "a model `cat` finds no
+ key" check, because §2.1 says it can. The test asserts the opposite
+ plainly, so the statement stays true.
+
+## 4. The connectors
+
+### 4.1 Pi on TensorX, and on the Command Code Provider API
+
+Pi is `@earendil-works/pi-coding-agent` 1.5.2. The `@mariozechner`
+package is deprecated. It needs Node 22.19 or later and has no install
+scripts. [P1]
+
+- **Provider config:** `PI_CODING_AGENT_DIR` points at the home. [P2]
+ `models.json` declares the provider as `openai-completions` with
+ `apiKey: "$TENSORX_API_KEY"`, or Command Code's variable. [P3]
+ - TensorX is OpenAI-compatible at `https://api.tensorx.ai/v1`. [T1]
+ - Command Code's Provider API is at `api.commandcode.ai/provider/v1`,
+ and its Claude models need `/messages`, which is not used. [CC6]
+ That other models are served on chat completions is inferred. Probe
+ CC-P1 checks it, and S7 is dropped if it fails.
+- **Switches:** `PI_OFFLINE=1`, `PI_SKIP_VERSION_CHECK=1`,
+ `PI_TELEMETRY=0` and `--no-approve`. [P4] Pi has no permission layer.
+ [P5] Gating is Equipo's own extension (`-e`, hashed in the manifest),
+ and Review runs with `--tools read,grep,find,ls`.
+- **Mapping:** RPC mode. `message_update` is `delta`.
+ `tool_execution_start` and `_end` are `tool_call` and `tool_result`.
+ `extension_ui_request` is `ask`, `agent_end` is `done`, and
+ `message_end.usage` gives `usage`, with `cost`. [P6, P7] Rev 3's
+ probes P1 to P5 gate every cell.
+- **Headroom:** none reported. TensorX shows only per-minute rate
+ limits, and a key whose balance is under $0.05 fails as an
+ authentication error. [T2, T3] Such a failure reads "TensorX refused
+ the key: the balance may be empty, or the key was revoked".
+- **Families:** from the model id (`z-ai/glm-5.3` is `glm`,
+ `moonshotai/kimi-k3.1-pro` is `kimi`, `deepseek/…` is `deepseek`).
+ [T4, CC7]
+
+### 4.2 OpenCode on OpenCode Go
+
+OpenCode v2 is `@opencode/cli` 2.2.7. It has a `postinstall` script and
+platform binaries as optional dependencies, so the platform binary is
+pinned by SHA-256. [OC1] Paul's subscription is presumably **OpenCode
+Go** ($10, Plus $40 a month): a dollar limit per model, with the 5-hour
+limit at 20% of the monthly one and the weekly at 50%. On a limit it can
+fall back to Console credit. [OC2]
+
+- **Provider config:** a custom `openai-compatible` provider, its
+ package pre-installed in the pinned tree, with the key in an
+ environment variable it names. [OC3, OC9] The upstream is
+ `https://opencode.ai/inference/go`, chat completions only. [OC10]
+- **Switches:** `update: "disable"`, with `XDG_CONFIG_HOME` and
+ `OPENCODE_DB` in the home. [OC5, OC6] The permissions list ends in an
+ explicit deny, and Review gets explicit `edit` and `shell` denies.
+ [OC7] Catalogue and telemetry switches are unconfirmed in v2. Probe
+ OC-P1 checks that OpenCode works with only `opencode.ai` reachable.
+ If the catalogue lives on `opencode.ai` too, its fetch is a known,
+ stated leak of the model list request, not of data.
+- **Driving it (round 3, finding 9):** `opencode serve --standalone
+ --hostname 127.0.0.1 --port <fixed>` inside the namespace, on the
+ namespace's own loopback, which the runner cannot reach. The control
+ path is therefore an **in-namespace stdio bridge**: a small mode of
+ the certified namespace helper (the binary that is already PID 1). It
+ connects only to `127.0.0.1:<fixed>` inside the namespace, allows only
+ the OpenCode paths the adapter uses (create session, prompt, the SSE
+ event stream, the permission reply, abort), and relays them as framed
+ JSON over the helper's stdio, which the runner already owns as the
+ capture. Its mode, port and path list are part of the policy manifest
+ and its hash, and it exits with the namespace. The SSE `GET
+ /api/event` gives text, tool calls, results and `permission.asked`,
+ answered at the reply endpoint. Usage comes from
+ `session.usage.updated`. [OC4] If probe OC-P2 finds a stdio mode in
+ OpenCode v2 (`acp`, unconfirmed), the bridge is not built.
+- **Billing:** metered (§0 decision 7), unless Paul confirms a standing
+ Console setting that disables overflow, which is undocumented today.
+ Headroom is "not reported" unless probe OC-P3 finds the Go allowance
+ in OpenCode's events.
+- **Fallback:** if Pi fails its probes, a TensorX connection may use
+ `harness: opencode`. [T5]
+
+### 4.3 Mistral Vibe on the Mistral plan
+
+Vibe 3.1.2 (PyPI, 2026-11-10) is Apache 2.0. [V1, V2]
+
+- **Provider config:** `VIBE_HOME` is the home. [V6] The plan key, from
+ chat.mistral.ai/code/extensions, "works … with a paid plan". [V5] It
+ reaches the launch as `MISTRAL_API_KEY`, through the pipe.
+- **Switches:** `enable_telemetry = false` (which also stops crash
+ reports), `enable_update_checks = false` and `outside_workdir =
+ "deny"`. [V7, V8, V9] Telemetry would otherwise post to
+ `api.mistral.ai`, the one allowed host, so this switch, checked by the
+ policy test, is what stops it.
+- **Driving it:** Engineering runs `-p --output streaming
+ --auto-approve`, and Review runs `--enabled-tools` with the read tools
+ only. `--output-dir` gives `export.json` with usage and cost. [V12,
+ V16] The line schema is unconfirmed: if probe V-P2 cannot map it, the
+ cells stay No.
+- **Headroom:** the runner, outside the namespace, may read `GET
+ /v1/billing/budget` (`usage_percentage`, `reset_at`) with the key,
+ rev 3 §2.7's probe at most every 15 minutes. That endpoint is from
+ Vibe's source and undocumented. [V15] Probe V-P3 decides whether it is
+ used. If not, headroom is "not reported".
+- **Billing:** a subscription only if Paul confirms pay-as-you-go is
+ off. Otherwise it is metered.
+- **Families:** `mistral-large-4-0` and `mistral-medium-latest` are
+ `mistral`, and `zai-glm-5-3` is `glm`. [V6]
+
+### 4.4 The capability matrix, added rows
+
+| Connection | Coordinator | Engineering | Review | Ask | Headroom | Billing |
+|---|---|---|---|---|---|---|
+| Pi → TensorX | No | Yes, after §3 acceptance | Yes | Yes | Not reported | Metered |
+| Pi → Command Code Provider API | No | Yes, if CC-P1 | Yes | Yes | Not reported | Metered until §0 decision 2 |
+| OpenCode → OpenCode Go | No | Yes | Yes | Yes | OC-P3, else not reported | Metered, unless a standing overflow-off setting is confirmed |
+| Vibe → Mistral plan | No | Yes, if V-P2 | Yes, if V-P2 | Yes (`--resume`) | V-P3, else not reported | Subscription if pay-as-you-go is off, else metered |
+| OpenCode → TensorX | No | only if Pi fails | as Pi | as Pi | as Pi | Metered |
+
+Mac cells are all "later".
+
+## 5. Later, named so nothing is lost
+
+- **The metering gateway.** Its requirements, from Astra round 2:
+ - a strict request schema per provider, forcing the priced model, a
+ single completion and text-only input, rejecting unpriced features,
+ and bounding every billable component;
+ - a per-attempt socket bridge into the namespace, with fixed
+ connection and attempt authority, lifecycle and policy attestation;
+ - dialing the validated address without resolving again.
+
+ It is the only route to a cap Equipo enforces, and to keeping the key
+ out of the namespace.
+- Command Code's own CLI (over ACP, after host discovery).
+- Mac srt profiles.
+- Coordinator cells.
+- Sign-in by link or device code for these providers.
+- Model-pair routing and tiers (rev 3 slice 3).
+- Step estimates (tokens, cost, duration), the "too big" outcome, and
+ calibration.
+- The "cheap and short" rule, token-denominated budgets, OpenRouter and
+ local endpoints.
+- Advice about buying or swapping accounts.
+
+# Part B: token-aware scheduling and advice
+
+## 6. Facts
+
+**Connections:** `state`; `billing` (`subscription | metered`); the
+windows as reported (`used` from 0 to 1, `minutes`, `resets_at`,
+`checked_at`); and, for metered connections, the budget, the reported
+spend, `spend_unknown` and whether a step is running.
+
+**Readings and their age (rev 3.2, ruling #7).** A Codex reading older
+than 15 minutes is refreshed **before** `Decide` is called by the
+app-server's `account/rateLimits/read`: no thread and no model turn,
+run as the hourly refresh runs (the source home under its lock, the
+same containment and egress), at most once per 15 minutes a
+connection. Claude has no read without a model turn, so a **Claude
+reading may be stale**: it is used as last reported, and a window past
+its reset counts as not reported (§7). Every reading carries the time
+the runner took it (`Headroom.checked_at`, protocol 15), and its age is
+shown on the routing line of a step held for headroom and on the Usage
+page's availability rows: "as of 2 h ago" for Codex, "as last reported
+2 h ago" for Claude.
+
+**Tasks:**
+
+- `priority` is `urgent`, `normal` or `low`, default `normal`.
+- `by` is an optional date.
+- The coordinator may set `low` or `normal`, and `by`, **only when it
+ creates the task**, from what Paul said. Every later change, and
+ every `urgent`, is Paul's tap. That keeps merge authority's rule: the
+ model can describe, never loosen.
+- Values the coordinator set are labelled "set from your message".
+
+## 7. `schedule.Decide`
+
+**Contract.** `Decide(in Input) Decision` is a pure function in
+`internal/schedule`. Its input is a versioned, immutable struct:
+
+- the step: role, priority, `by`, `kept_session` (the connection whose
+ session it resumes, or none), `avoid`, and `release` (a Run now id,
+ or none);
+- the person's connections on this runner, with the facts of §6 and
+ each one's capability for the role and family;
+- the role's preference and its `until`;
+- `now`.
+
+The output is `{run | hold, connection, reason, wake_at, needs_person}`.
+The runner calls it at admission and writes the admission in one
+`thin.db` transaction that rechecks the connections' row revisions it
+read. If any changed, it calls `Decide` again.
+
+**What it claims.** Admission is decided from the readings taken at
+admission. It does not predict or reserve a step's future consumption,
+and several steps admitted against the same reading may together run a
+window out. The reserve thresholds are the margin. A window that runs
+out mid-step is rev 3's quota failover (termination proof, then another
+connection), as today. A Claude reading may be stale (§6): Codex's are
+refreshed without a turn, Claude's are as last reported.
+
+**Bars**, never overridden, Run now included:
+
+- the connection is usable (rev 3 §2.7);
+- the Review family rule;
+- not in `avoid`;
+- for a metered connection: the task is `urgent` or the step carries a
+ release, no other step is running on it, spend is known, and the
+ reported spend is under both the day and the month budget.
+
+**Ask (round 3, finding 2)** never comes through `Decide` for its
+choice: it stays on its step's exact session and connection (rev 3 §3).
+On a metered connection, every question still passes the **metered
+guard**: the slot, the day and month budget, and no `spend_unknown`,
+all in the same admission transaction as a step. Consent is the
+question itself, because Paul asking is his own action. A question the
+guard refuses is held with the step's hold copy ("Waiting: TensorX has
+reached today's budget"), never moved to another connection.
+
+**Thresholds.** A subscription connection **admits** a step at priority
+`p` when every reported window has `used < t(p)`, where `t(low) = 0.60`,
+`t(normal) = 0.80`, `t(urgent) = 1.0` (only "not limited"). A
+A connection with no window reported admits when it is not limited, and
+the routing row says "headroom not reported". A window whose
+`resets_at` has passed with no newer reading counts as not reported,
+never at its old figure. A release (Run now) gives the step the
+**effective priority** `urgent` for thresholds and metered eligibility,
+and the bars still apply.
+
+**Room, with a fixed precedence (finding 16).** Among subscription
+connections that admit the step, the one with the most room is the
+least by these keys, in order (round 3, finding 6):
+
+1. connections with at least one reported window before those with
+ none; the rest of the keys apply only between two connections that
+ both have windows;
+2. the largest `used` among its reported windows (lower is more room);
+3. the `used` of its first window when its windows are sorted by
+ `minutes` ascending (missing `minutes` sorts last), then by name;
+4. the connection id, bytewise.
+
+Among metered connections, the most room is the least by:
+
+1. the larger of day and month spend as a fraction of its budget;
+2. the connection id, bytewise.
+
+A subscription always ranks before a metered connection. A preference
+for a metered connection does not change that: it orders metered
+connections first among themselves, in rule 4.
+
+**Order of rules.** The first that yields a connection wins.
+
+1. **Kept session (findings 15 and round 3, finding 4).** A step that
+ resumes a kept session (a fix round on its Engineering session) stays
+ on that connection, whatever the threshold, while it is usable. When
+ a **spending bar** blocks it (busy slot, budget, spend unknown), the
+ step is **held** on that connection, not moved. It switches only as
+ rev 3 allows: a quota or auth failure (the connection is then not
+ usable and is in `avoid`), Paul's explicit per-task "Run on …", or
+ **spending permission withdrawn** (rev 3.2, ruling #8): a kept
+ metered session whose step no longer has leave to spend (neither
+ `urgent` nor a release) starts afresh on a subscription rather than
+ being held on the metered connection. Reason `sticky`.
+2. **Preferred.** The role's preferred connection, if it admits the
+ step. Reason `preference`.
+3. **Subscription.** The subscription with the most room. Reason
+ `headroom`.
+4. **Metered.** The metered connection with the most room. Reason
+ `metered_urgent` or `metered_release`.
+5. **Hold.** Reason `headroom` (naming the admitting candidate whose
+ reset comes first), `budget`, `spend_unknown` or `no_connection`.
+
+Every attempt, failover included, is admitted through `Decide`, with
+the failed connection in `avoid`. A consumed release becomes a durable
+**grant** for `(step, step_revision)`. It covers every attempt of that
+step revision, failover attempts included, and ends when the step ends.
+A second admission for the same step revision is refused by a unique
+key, so a replayed release cannot start another execution.
+
+**Wake-ups (round 3, finding 7).** `wake_at` is the earliest time
+**strictly after `now`** among:
+
+- every future `resets_at` of every capable connection, limited ones
+ included;
+- the next budget day or month boundary;
+- the preference's `until`, while it is in the future (an expired
+ preference is cleared and treated as absent);
+- `by` minus 24 h, unless the deadline check has already fired for
+ this step, which is recorded as `deadline_notified`.
+
+When none exists, `wake_at` is null and only a fact change wakes the
+step.
+
+The runner persists it with the hold, re-runs `Decide` then, and also
+on any reading, step end, budget change, preference change or release.
+
+**Release order.** `urgent`, then the earliest `by`, then `normal`, then
+`low`, then the oldest, then the step id. A held step never blocks a
+runnable step or a person's turn. Person turns are never held for
+priority.
+
+**Housekeeping.** Its ledger, reservations and 0.8 stand-down stay as
+built. Its turns and retries count as `low` for the threshold, so the
+stricter rule wins, and it never uses a metered connection.
+
+**Invariants**, each a property test:
+
+- (a) no admission on a subscription with a reported, unexpired window
+ at or above `t(effective priority)`, except a kept session;
+- (b) no metered admission without `urgent` or a release;
+- (c) never two attempts (steps, questions or probes) holding one
+ metered connection's slot, and never a slot released before its
+ attempt's termination proof and charge;
+- (d) no metered admission once the reported spend reaches the budget,
+ or while spend is unknown;
+- (e) a hold only when rules 1 to 4 all fail;
+- (f) the same input gives the same output.
+
+## 8. Holds, Needs you, and Run now
+
+A held step reports `step {state: deferred, hold {reason, connection,
+wake_at}}`, an optional extension of today's deferred report. The task
+says one of:
+
+- "Waiting for headroom on Claude, resets Thu 10:00";
+- "Waiting for headroom on Claude" (no reset reported);
+- "Waiting: TensorX has reached today's budget";
+- "Waiting: TensorX spend unknown, check it, then Resume".
+
+Each has **Run it now anyway**, except `budget` and `spend_unknown`,
+which offer **Raise the budget** and **Resume**.
+
+**Needs you**, only where Paul's input changes the outcome:
+
+- the deadline check fires (`by` minus 24 h with the step still held);
+- no reset in sight (no reset-based `wake_at`, or one more than 72 h
+ away);
+- `no_connection` (today's card).
+
+The card asks with a recommendation, composed by the instance as merge
+authority §4.1 does: "I'd wait: Claude resets Thu 10:00, before
+Friday." **Wait** / **Run it now**.
+
+**Run now.** `POST /api/v1/tasks/{id}/run-now {step, step_revision}`,
+from the task's owner only, writes a durable `release{id, task, step,
+step_revision}`. The runner consumes it **atomically with the admission
+it causes**. A release with a stale step revision, or one already
+consumed, is acked and ignored. A release may use a metered connection
+(§0 decision 5), and never passes a bar.
+
+## 9. Advice
+
+`advice.Compute(facts, now) []Advice` is pure, on the instance. It runs
+on fact changes and at 08:00 in the person's zone. The copy is fixed
+templates with slots, so no model turn is involved. The coordinator can
+read open advice through `status`, and cannot create, change or dismiss
+it. Each recommendation is checked with the same capability, runner and
+family rules as `Decide`.
+
+| Kind (arbitration order) | Fires when | Card | Actions |
+|---|---|---|---|
+| `budget_near` | a metered connection's reported spend passes 80% of a budget | "TensorX: $0.84 of today's $1." | **Raise today's budget** / **Leave it** |
+| `prefer_switch` | the role's preferred subscription has a window at or above 0.80 with its reset more than 24 h away, another eligible subscription has every window below 0.50, and steps for the role are held or queued | "Claude is near its limit until Thu. Codex has room. Prefer Codex for Engineering until then?" | **Prefer Codex until Thu** / **Not now** |
+| `defer_tasks` | `urgent` or `by` work is held on `headroom` while `normal` tasks without `by` are queued for the same role | "3 tasks could wait for Thu so the urgent one goes first. Let them wait?" | **Make them low priority** / **Not now** |
+| `held_long` | a `low` task has been held for 7 days | "2 low-priority tasks have waited a week." | **Make them normal** / **Not now** |
+
+**Deterministic choice (finding 24).** Each advice has the key `(person,
+kind, subject)`:
+
+- for `budget_near` and `prefer_switch`, the subject is the connection
+ id (for `prefer_switch`, the role then the target connection id);
+- for `defer_tasks` and `held_long`, it is the sorted task ids.
+
+When several are eligible, the one shown is the least by: the kind's
+arbitration order; then, within a kind, for connection subjects the
+connection id bytewise, for roles the fixed order coordinator,
+engineering, review, and for task sets the earliest task `created_at`,
+then the first task id; then the key string bytewise.
+
+**Rules:**
+
+- At most one new card per person per day, and one open at a time.
+- Not now silences a key for 14 days, and for 60 days after a second
+ Not now.
+- Advice whose facts stop holding is withdrawn silently.
+- Quiet hours are 22:00 to 08:00 (housekeeping's `VisibleAt`).
+- Never Needs you, never a push.
+- An action is the ordinary API call, revision-checked and recorded
+ with `source: advice` and the key.
+
+The `advice` table only moves forward. Cards show at the top of Usage
+and as one quiet card in the conversation.
+
+## 10. Wire, API and fixtures
+
+**`Connection`** gains `harness`, `upstream` (origin only), `billing`,
+`model`, `limit_confirmed_at`, `payg_off_confirmed_at`, `budget`,
+`spend {day, month, currency, unknown}` and `budget_pending`.
+**`Dispatch`** gains `priority`, `by` and `release`. **Step reports**
+gain `hold`. **`Headroom`** gains `checked_at` (rev 3.2, protocol 15;
+dropped below it and from the runner's first hello).
+
+**Frames, instance to runner:** `budget` (durable, acked when applied),
+`release` (durable, consumed once), `preference.until` (durable) and
+`resume_spend{connection, pause_revision}` (durable, consumed once).
+
+**Routing reasons** gain `sticky`, `metered_urgent`, `metered_release`
+and `held`.
+
+**API:**
+
+- `POST /api/v1/connections` gains `kind: api_key`, `sealed`,
+ `limit_confirmed` and `payg_off_confirmed`;
+- `PUT /api/v1/connections/{id}/budget`;
+- `POST /api/v1/connections/{id}/resume`;
+- `PUT /api/v1/tasks/{id}/priority {priority, by, revision}`;
+- `POST /api/v1/tasks/{id}/run-now`;
+- `GET /api/v1/advice`;
+- `POST /api/v1/advice/{id}/act`;
+- `POST /api/v1/advice/{id}/dismiss`;
+- `PUT /api/v1/preferences` gains `until`.
+
+`record_task` and `start_task` gain the optional `priority` (`low` or
+`normal`) and `by`. The protocol is bumped, and an older runner is
+refused metered connections rather than downgraded.
+
+**Fixtures:** `api/connection-metered.json`, `api/budget.json`,
+`api/task-held.json`, `api/advice.json`; `frames/budget.json`,
+`frames/release.json`, `frames/step-held.json`. The secret-field guard
+covers every new type.
+
+## 11. Slices
+
+Each slice runs headless first, then on staging with the real pinned
+binary, then UI. Connector slices open with their probes, and a failed
+probe turns a cell to No with the reason. **Sec** marks a slice that
+needs its own Astra round on its branch.
+
+| # | Slice | Finish line | Sec | Size |
+|---|---|---|---|---|
+| S1 | Metered connections: `KindAPIKey` sealed paste, the limit and overflow confirmations, the selected-model probe, the egress table keyed by `(harness, provider)`, normalised components and price tables, the budget ledger, the durable slot and its restart recovery, spend unknown with bound Resume, the metered guard for questions, the spend line | With a fake harness: the attempt after the budget is crossed is held; a concurrent Engineering, Review and question race admits exactly one; a crash between exit and charge ends in `spend_unknown` before anything else is admitted; a stale Resume leaves a newer pause; a resent usage row charges once; an unpriced model gives spend unknown | **Sec** | 2.5 |
+| S2 | Pi on TensorX: committed pins, isolated config, Equipo's extension, `fakepi`, RPC adapter, rev 3 P1 to P5, the §3 acceptance | A real Review step on TensorX GLM on staging, recorded `other_family`, with the hostile-repository fixture loading nothing | **Sec** | 3 |
+| S3 | Scheduler: priority and `by`, `Decide`, holds, wake-ups, release order, Run now grants with replay refusal, the Needs you rules, `preference.until` | The six invariants pass as property tests; a `low` step holds at 0.61 and starts by itself after the reset; a replayed or stale release starts nothing; a failover attempt inside a grant is admitted; no wake-up is ever in the past | | 2.5 |
+| S4 | Usage page (availability, spend, tokens) and the four advice kinds | From fixtures, each kind fires once, ties pick the same card on every run, and Not now silences it for 14 days | | 2 |
+| S5 | OpenCode on Go: pins, isolated config, the in-namespace stdio bridge (unless OC-P2 finds a stdio mode), serve adapter, OC-P1, OC-P3 and OC-P4 | A real Engineering step on Go on staging, with its usage row; the bridge refuses a path outside its list | **Sec** | 3 |
+| S6 | Vibe on the Mistral plan: PyPI pin, V-P2 and V-P3 | A real Vibe Review of a Claude step on staging | **Sec** | 2 |
+| S7 | Command Code Provider API behind Pi, after CC-P1 | A real Review step through it | **Sec** | 0.5 |
+
+## 12. Risks
+
+- **Claude readings may be stale (rev 3.2).** Claude reports headroom
+ only on a model turn, so its reading can be hours old when `Decide`
+ uses it. Codex readings are refreshed by `account/rateLimits/read`.
+ Each reading's age is shown, so a stale one is visible.
+
+- **A step can spend up to the provider's limit.** The key sits in the
+ namespace, and the soft budget is checked only between steps. This is
+ the trade Paul is asked to accept (§0 decision 3). The gateway (§5) is
+ the remedy.
+- **Reported usage can be wrong or missing.** Wrong usage misleads the
+ soft budget. Missing usage pauses the connection.
+- **The confirmations are Paul's word.** Equipo cannot check a provider
+ limit or a pay-as-you-go setting.
+- **Thresholds are not predictions.** Concurrent steps can run a window
+ out. Failover is the backstop.
+- **Undocumented surfaces:** Command Code's chat-completions route, Go's
+ allowance in events, Vibe's line schema and its budget read. Each is
+ a probe whose failure turns a cell to No or headroom to "not
+ reported".
+- **Three more pinned trees** to keep current. Each bump re-runs that
+ connector's probes.
+
+## 13. Not claimed
+
+- Equipo does not enforce a hard spend cap.
+- It does not keep metered keys from a step's shell.
+- It does not predict a step's consumption.
+- It does not read provider headers or bodies.
+
+## 14. Sources
+
+Read 2026-11-12. Facts from source code rather than docs are marked as
+such in the text.
+
+- [CC1] https://registry.npmjs.org/command-code/latest, https://commandcode.ai/changelog
+- [CC2] https://commandcode.ai/docs/headless
+- [CC3] https://commandcode.ai/docs/quickstart, https://commandcode.ai/docs/settings
+- [CC4] https://commandcode.ai/docs/resources/pricing-limits, https://commandcode.ai/docs/resources/usage-limits
+- [CC5] https://commandcode.ai/docs/permissions, https://commandcode.ai/docs/resources/security
+- [CC6] https://commandcode.ai/docs/provider, https://commandcode.ai/docs/troubleshooting/telemetry
+- [CC7] https://commandcode.ai/docs/reference/cli/models
+- [V1] https://github.com/mistralai/mistral-vibe
+- [V2] https://pypi.org/pypi/mistral-vibe/3.1.2/json
+- [V3] https://github.com/mistralai/mistral-vibe/blob/main/vibe/setup/auth/http_browser_sign_in_gateway.py (source)
+- [V4] https://github.com/mistralai/mistral-vibe/blob/main/vibe/setup/auth/_oidc_config.py (source)
+- [V5] https://docs.mistral.ai/vibe/code/cli/api-keys-profiles
+- [V6] https://docs.mistral.ai/vibe/code/cli/configuration
+- [V7] https://docs.mistral.ai/vibe/code/cli/configuration-reference
+- [V8] https://docs.mistral.ai/vibe/code/safety-approvals-permissions
+- [V9] https://github.com/mistralai/mistral-vibe/blob/main/vibe/core/telemetry/send.py, .../vibe/observability/sentry.py (source)
+- [V10] https://github.com/mistralai/mistral-vibe/blob/main/docs/proxy-setup.md
+- [V11] https://api.github.com/repos/mistralai/mistral-vibe/releases
+- [V12] https://github.com/mistralai/mistral-vibe/blob/main/docs/programmatic-mode.md
+- [V13] https://docs.mistral.ai/admin/billing-usage/subscriptions
+- [V14] https://mistral.ai/pricing/
+- [V15] https://github.com/mistralai/mistral-vibe/blob/main/vibe/app_server/_billing.py (source)
+- [V16] https://github.com/mistralai/mistral-vibe/blob/main/vibe/cli-rust/src/headless_output.rs (source)
+- [P1] https://registry.npmjs.org/@earendil-works/pi-coding-agent/latest
+- [P2] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/configuration.md
+- [P3] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md
+- [P4] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/environment-variables.md, .../docs/settings.md
+- [P5] https://pi.dev
+- [P6] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/json.md
+- [P7] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/rpc.md, .../docs/rpc-commands.md
+- [OC1] https://registry.npmjs.org/@opencode/cli/latest, https://registry.npmjs.org/opencode-ai/latest
+- [OC2] https://opencode.ai/docs/console/go/
+- [OC3] https://opencode.ai/docs/providers/
+- [OC4] https://opencode.ai/docs/api, https://opencode.ai/docs/cli/
+- [OC5] https://opencode.ai/docs/cli/config/, https://opencode.ai/docs/troubleshooting/
+- [OC6] https://opencode.ai/docs/config/
+- [OC7] https://opencode.ai/docs/permissions/
+- [OC8] https://opencode.ai/docs/network/
+- [OC9] https://opencode.ai/docs/providers/ (custom provider package)
+- [OC10] https://opencode.ai/docs/console/api/inference/
+- [OC11] https://opencode.ai/docs/console/models/
+- [OC12] https://opencode.ai/docs/console/billing/
+- [T1] https://docs.tensorx.ai/, https://tensorx.ai/
+- [T2] https://docs.tensorx.ai/api-reference/rate-limits.md
+- [T3] https://docs.tensorx.ai/billing.md
+- [T4] https://tensorx.ai/pricing/
+- [T5] https://github.com/anomalyco/models.dev/tree/dev/providers/tensorx
+
+## 15. Astra rounds 1 and 2, folded in
+
+Round 1 (revision 1) and round 2 (revision 2) both said NOT READY. The
+dispositions below are for revision 3. Round 2 counted items 2 to 6, 9
+to 13 and 20 to 23 resolved under the gateway. Those that depended on
+the gateway are now cut or restated.
+
+| # | Finding, short | Revision 3 |
+|---|---|---|
+| 1 | No hard cap from post-response usage | Not claimed (§13): the provider's limit is the hard cap (§2.1), and Equipo's budget is soft (§2.3) |
+| 2 | The key is reachable from the namespace | Stated (§2.1), and the acceptance asserts it (§3); remedy later (§5) |
+| 3 to 6 | Reservation, crash, cap change, identity | The gateway ledger is gone. The soft budget is keyed by usage rows, changes apply on ack, and periods follow the row time (§2.3) |
+| 7 | Overflow billing | Metered unless Paul confirms pay-as-you-go is off (§2.1, §4.2, §4.3) |
+| 8 | Sign-in flows | Sealed paste only |
+| 9 | Paths on allowed hosts | Vibe telemetry is off by config, under the policy check; OpenCode's catalogue on its own host is stated (§4) |
+| 10, 11 | Pins, isolated config | §3, unchanged from revision 2 (resolved in round 2) |
+| 12 | Run now replay | §8: revision-bound, consumed atomically, refused on replay (S3 finish line) |
+| 13 | The coordinator relaxing priority | Creation only, never `urgent` (§6) |
+| 14 | Unbuilt rev 3 slice 3 | One model per connection; new fields named in §10 and assigned to S1 and S3 |
+| 15 | Switching boundaries | §7 rule 1: kept sessions stay, as rev 3 binds them |
+| 16 | "Most room" undefined | §7: a fixed key precedence for subscriptions and for metered connections |
+| 17 | Estimates | Cut (§5) |
+| 18 | Calibration | Cut (§5) |
+| 19 | A reading after the step starts | Removed: admission uses only the readings taken at admission, and claims nothing further (§7) |
+| 20 | Invariants | §7: restated for the new rules |
+| 21 to 23 | Wake-ups, starvation, housekeeping | §7: wake-ups kept; `too_big` cut with the estimates; `held_long` kept; housekeeping unchanged |
+| 24 | Equal-kind ordering in advice | §9: subject ordering defined |
+| 25 | Adversarial finish lines | §3 acceptance and §11 finish lines name the budget, replay and hostile-config cases |
+| R2 Critical | The gateway does not bound request bodies | Gateway cut (§5), requirement recorded |
+| R2 Important | No namespace transport for the gateway | Gateway cut (§5), requirement recorded |
+
+**Round 3 (revision 3): READY WITH CHANGES.** All ten Important
+findings are folded into 3.1:
+
+| # | Finding, short | Revision 3.1 |
+|---|---|---|
+| 1 | No durable lifecycle for the one-step bound | §2.3: a durable slot for every attempt, released after the proof and the charge; restart reconciliation; S1 race and crash cases |
+| 2 | Ask bypasses the budget | §7: questions pass the metered guard and are held, never moved |
+| 3 | Resume not bound to its pause | §2.3: `pause_revision`, consumed once |
+| 4 | Kept session and release lifetime | §7: a spending bar holds a kept session; a release becomes a grant for the step revision |
+| 5 | Cost accounting underspecified | §2.3: normalised components, per-adapter aggregation, versioned price tables, unpriced means unknown |
+| 6 | Comparator and invariant | §7: known before unknown first, window ordering defined, effective priority, metered preference |
+| 7 | Wake-ups in the past | §7: strictly future, expired preferences cleared, `deadline_notified`, expired readings not reported |
+| 8 | A zero balance is not a setting | §0 decision 7, §2.1, §4.2: Go stays metered without a standing overflow-off setting |
+| 9 | No OpenCode control transport | §4.2: an in-namespace stdio bridge in the certified helper, unless OC-P2 finds a stdio mode |
+| 10 | Model list is not a credential proof | §2.2: a one-token completion on the selected model, charged as a `probe` |
+
+The round 3 statuses it gave "NOT RESOLVED" for round 1 items (#4,
+#7, #12, #15 to #17, #20, #21, #25) are these ten findings, and are
+answered above.
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R2.md b/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R2.md
new file mode 100644
index 00000000..342fe9d0
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R2.md
@@ -0,0 +1,37 @@
+**Verdict: NOT READY.** Reviewed revision 2 at `6591b33`, read-only. The Linux/Pi-first scope is viable, but the gateway’s hard-cap claim and transport need concrete contracts before implementation.
+
+Round-1 dispositions (numbers match §15; High treated as Important):
+
+| # | Status | Section and assessment |
+|---|---|---|
+| 1 | PARTLY | §2: reservation precedes forwarding; worst-case pricing remains unproven. Prepaid balance does not enforce Equipo’s smaller cap. |
+| 2 | RESOLVED | §§2–3: key stays outside the namespace; Mac cut. |
+| 3 | RESOLVED | §2: atomic request reservations protect concurrent commitments. |
+| 4 | RESOLVED | §2: durable identities and conservative recovery sweep. |
+| 5 | RESOLVED | §2: application acknowledgement and in-flight exception defined. |
+| 6 | RESOLVED | §2: persistent budget identity, period allocation and cross-runner limitation stated. |
+| 7 | PARTLY | §§4.2–4.3, 8: reservations help, but subscription-classified overflow bypasses metered consent; a sub-100% reading cannot guarantee no paid crossing. |
+| 8 | CUT | §§3, 5: link/device flows deferred; unknown-event content dropped. |
+| 9 | RESOLVED | §2: HTTP path filtering replaces host-only filtering. |
+| 10 | RESOLVED | §3: committed complete-tree pins and launch verification. |
+| 11 | RESOLVED | §3: isolated configuration and hostile-repository acceptance required. |
+| 12 | RESOLVED | §§8–9: consent independent; releases revision-bound and consumed atomically. |
+| 13 | RESOLVED | §7: coordinator priority changes restricted to creation. |
+| 14 | PARTLY | §§3, 11–12: model-pair routing cut; harness/provider separation and preference contract additions remain incompletely assigned. |
+| 15 | PARTLY | §8: failover re-enters admission, but “sticky if plausible” still changes rev 3’s permitted switching boundaries. |
+| 16 | PARTLY | §8: immutable inputs/revalidation added; Run now’s “most room” lacks comparison across subscription windows, dollars and unknowns. |
+| 17 | PARTLY | §7: no monetary seed; reasoning overlap and aggregation across multiple usage rows remain unclear. |
+| 18 | CUT | §5: calibration deferred. |
+| 19 | NOT RESOLVED | §8: a reading after step **start** cannot account for its future consumption or delayed provider accounting. |
+| 20 | RESOLVED | §8: invariants narrowed to admission, with override exceptions. |
+| 21 | RESOLVED | §8: persisted reset, cap, preference and deadline wakeups. |
+| 22 | RESOLVED | §§8, 10: impossible-fit escalation and aging notification. |
+| 23 | RESOLVED | §8: housekeeping ledger retained; stricter ladder applies. |
+| 24 | PARTLY | §10: arbitration improved; equal-kind subjects still lack deterministic ordering. |
+| 25 | PARTLY | §§3, 12: adversarial matrix improved; release replay omitted and “total charges” does not prove actual upstream spend. |
+
+Only new Critical/Important findings:
+
+- **Critical — §2, request bounds.** Method/path allowlisting does not constrain the inference body. Nothing requires the connection’s selected model, single completion, text-only input, or rejection of unpriced features. A short remote-content reference need not bound billable input; clamping one output field need not bound aggregate output. Require a strict per-provider request schema, force the priced model, reject unsupported fields, and bound all billable components. `min(worst, priced usage)` must not hide an exceeded bound.
+
+- **Important — §§2–3, namespace transport.** A host loopback listener cannot simply be bound into the isolated network namespace. Existing [containment code](/home/paulca/.cache/tmp/equipo/connrev.Hf2G/wt/internal/runner/containment/egress.go:68) imports a private Unix socket and bridges it internally; the [upstream proxy](/home/paulca/.cache/tmp/equipo/connrev.Hf2G/wt/internal/runner/egress/proxy.go:179) accepts CONNECT only. Specify the gateway’s per-attempt socket bridge, fixed connection/attempt authority, lifecycle and policy attestation. Preserve public-address validation and dialing the validated address without resolving again. Key exclusion is sound in principle; this transport is additional implementation, not existing functionality.
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R3.md b/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R3.md
new file mode 100644
index 00000000..91945643
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING-R3.md
@@ -0,0 +1,41 @@
+VERDICT: READY WITH CHANGES
+
+| Earlier findings | Status |
+|---|---|
+| R1 #1–2: hard cap, shell access to keys | STATED |
+| R1 #3: request reservations | CUT |
+| R1 #4: crash recovery | NOT RESOLVED |
+| R1 #5: budget changes | RESOLVED |
+| R1 #6: accounting scope and periods | STATED: per connection, usage-row time |
+| R1 #7: overflow billing | NOT RESOLVED |
+| R1 #8: interactive sign-in | CUT |
+| R1 #9–11: allowed-host paths, pins, isolated configuration | RESOLVED |
+| R1 #12: Run now | NOT RESOLVED: replay addressed; retry authorization unspecified |
+| R1 #13–14: coordinator authority, implementation dependencies | RESOLVED |
+| R1 #15–16: binding and deterministic selection | NOT RESOLVED |
+| R1 #17: estimates and usage normalization | NOT RESOLVED: estimates cut; monetary accounting still needs normalization |
+| R1 #18–19: calibration and subscription reservations | CUT |
+| R1 #20–21: invariants and wakeups | NOT RESOLVED |
+| R1 #22–24: starvation, housekeeping, advice ordering | RESOLVED |
+| R1 #25: adversarial acceptance | NOT RESOLVED: recovery and cross-role admission remain uncovered |
+| R2 Critical and Important: gateway bounds and transport | CUT |
+
+1. **Important — §§2.3, 7, 11: The one-step overshoot bound lacks a durable lifecycle.** Rechecking connection revisions does not establish that concurrent Engineering and Review admissions contend on one slot, or that the slot remains occupied until usage is charged. Restart recovery, cancellation and failure between process exit and charging are unspecified. **Fix:** Atomically claim a durable per-connection slot before launch; release it only after termination proof and a committed charge or `spend_unknown`. Reconcile interrupted admissions before dispatch resumes, with crash and cross-role race acceptance cases.
+
+2. **Important — §§2.3, 7–8: Ask bypasses the budget gate.** Ask explicitly skips `Decide`, while its inherited path checks connection health; no replacement enforces metered consent, serialization, budget or unknown-spend pauses. Repeated questions could therefore spend after the budget is exhausted. **Fix:** Keep Ask’s exact session/model binding, but pass every question through the same transactional metered admission guard, with explicit consent and hold behavior.
+
+3. **Important — §§2.3, 10: Resume is not bound to the pause it clears.** `resume_spend{connection}` carries no unknown-spend generation; two separately issued Resume commands could let a delayed command clear a later attempt’s pause. **Fix:** Bind Resume to the observed pause revision and consume it atomically once; stale commands must leave newer unknown spend untouched.
+
+4. **Important — §§7–8: Binding and release rules conflict at continuation boundaries.** A healthy kept connection that fails a budget or busy bar falls through to another connection, contradicting the stated switching restriction. A consumed Run now also has no defined authorization lifetime for failover attempts. **Fix:** Hold a kept session when a spending bar blocks it unless an expressly permitted switch applies. Consume Run now into durable authorization for the specified step revision, defining which attempts it covers without permitting replay to start another execution.
+
+5. **Important — §§2.3, 4, 10: Cost accounting remains underspecified.** Cutting estimates does not resolve how Pi’s per-message usage, OpenCode’s updates and Vibe’s export become one complete attempt charge. Cached/reasoning overlap, cumulative versus incremental events, missing prices and monetary fields are undefined; existing `wire.Usage` carries no cost. **Fix:** Specify each adapter’s aggregation and completeness rules, normalized billable components, versioned prices and monetary representation; unpriceable usage must produce unknown spend.
+
+6. **Important — §7: `Decide` still lacks a total comparison and consistent invariant.** The room comparator evaluates maximum and shortest-window usage before handling connections with no windows, leaving its first two keys undefined. Invariant (a) also rejects a normal step released under urgent thresholds because its only stated exception is a kept session. **Fix:** Rank known versus unknown headroom before accessing window values and define missing-duration/tie handling. Express the invariant using effective priority after Run now, and clarify whether a metered preference overrides “subscription always ranks before metered.”
+
+7. **Important — §§6–8: Wakeups can select an already-expired time forever.** The minimum includes expired reset times, expired preferences and `by − 24 h` after the deadline check has fired. Re-evaluation can therefore immediately schedule the same past wakeup again. **Fix:** Select only future, unconsumed wakeups, persist deadline notification state, and define how stale window readings are retired when refresh supplies no replacement.
+
+8. **Important — §§0.7, 2.1, 4.2: Zero Console balance is not pay-as-you-go disabled.** OpenCode becomes a subscription on a balance snapshot, although the spec says later Console credit funds overflow. Replenishing that balance would permit paid requests without metered admission or budgeting. **Fix:** Require a persistent overflow-disabled setting for subscription classification; otherwise retain metered classification and make the confirmation describe the actual control.
+
+9. **Important — §4.2: OpenCode’s control transport is missing.** Its HTTP server binds inside the isolated network namespace, so the runner cannot reach its SSE and reply endpoints through host loopback. The existing egress bridge only carries outbound CONNECT traffic. **Fix:** Specify a per-attempt control bridge or an in-namespace stdio adapter, including fixed authority, lifecycle and policy attestation.
+
+10. **Important — §2.2: Model listing replaces the required credential/inference proof.** A successful `GET /v1/models` does not establish that the selected model’s inference route works, contrary to Connections §§2.5–2.7; provider-specific probe routes are also unspecified. **Fix:** Define each provider’s authenticated health probe and selected-model validation, including accounting and admission treatment for any billable validation request.
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING.md b/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING.md
new file mode 100644
index 00000000..e9119a44
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-CONNECTORS-SCHEDULING.md
@@ -0,0 +1,57 @@
+VERDICT: NOT READY
+
+1. **Critical — §§6, 13:** Post-response usage cannot enforce a hard spend cap: billing precedes the event, silent requests remain invisible, and under-reported nonzero usage avoids the fallback charge. Require an enforceable worst-case reservation before every billable request through a trusted boundary or provider-side cap; otherwise describe this as a soft budget.
+
+2. **Critical — §§2, 5.1, 12/S8:** A namespace shared by the harness and its shell children does not protect the harness’s credential files or environment; the proposed Mac profile likewise leaves its own connection home accessible. Require separate tool containment, environment scrubbing and credential/process-read denial equivalent to rev 3 §2.4 before enabling any affected role.
+
+3. **High — §6:** The in-flight rule permits an attempt to exceed its reservation until the cap remainder is spent, potentially consuming money reserved by concurrent attempts. Define `charged + outstanding commitments ≤ cap`, with atomic reservation increases before further requests and no access to another attempt’s reservation.
+
+4. **High — §§6, 8:** The spend ledger has no crash-recovery or event-deduplication state machine, so a restart can lose charges, charge cumulative events twice, or retain reservations indefinitely. Specify durable admission, request and charge identities, recovery before new admission, and reconciliation of interrupted, missing and replayed usage.
+
+5. **High — §6:** Lowering a cap “at once” conflicts with allowing existing reservations to finish and with runners operating offline. Define when a revision becomes effective, expose pending runner acknowledgement, and explicitly choose whether outstanding commitments are grandfathered or further requests stop.
+
+6. **High — §§6, 11:** Connection-local accounting does not bound account depletion when a key is re-added, duplicated or used elsewhere, and reservations crossing midnight or month-end have no allocation rule. Define the budget identity and scope, retain charges across reconnection, and specify timezone changes and cross-period commitments.
+
+7. **High — §§0.5–6, 3–5:** OpenCode overflow is charged only after billing, while Vibe keys can have mixed billing and Command Code’s billing source remains unknown. Treat every potentially paid request as metered before dispatch unless a provider-enforced subscription-only mode is verified; a manually maintained zero balance is not a hard guard.
+
+8. **High — §§2, 4, 11:** New sign-in flows lack the precise URL validation, secret-output filtering and recovery rules of the built Claude flow; logging unknown adapter events also risks recording credentials. Specify provider-specific authorization URL checks, sanitized diagnostics, and cancellation/crash tests covering credential installation and sealed delivery.
+
+9. **High — §§2, 4, 5.2:** Host allowlisting cannot deny telemetry or paid inference paths on an allowed host: Mistral telemetry shares `api.mistral.ai`, and OpenCode Go and Console inference share `opencode.ai`. Replace the “denied by the relay anyway” claim with verified configuration guarantees, and make host discovery iterative so an initial denied bootstrap request cannot conceal later dependencies.
+
+10. **High — §2, Pinning:** Recording an installed tree’s digest establishes a local baseline rather than a release-approved pin, unlike the committed `SRTTreeSHA256`; extra files and executable links are unspecified. Commit expected digests per supported platform and define complete tree coverage, link validation and verification before launch.
+
+11. **High — §§2–5:** Disabling updates does not prevent repository-local configuration, plugins, extensions or startup hooks from changing tools, destinations or executing inside the credential-bearing harness. Require isolated configuration sources and effective-policy checks, with hostile repository fixtures proving that only Equipo’s pinned configuration and extensions load.
+
+12. **High — §§8–9, 11:** Run now precedes the metered permission rule, so a normal task can select TensorX without satisfying §6; its durable release also lacks consumption and stale-replay semantics. Make metered consent a hard eligibility condition and bind each release to an authorized person, task/step revision and atomically consumed admission.
+
+13. **High — §7:** Allowing the coordinator to change `low` to `normal` relaxes the reserve from 30% to 10%, contradicting “can only tighten.” Permit descriptive defaults at creation, but require a person’s action for subsequent priority increases or relaxation of a person-set restriction.
+
+14. **High — §§2, 7–8, 11–12:** The design assumes model-pair selection, tier floors, per-role preferences and pricing that the built `connect.Choose` and wire types do not provide. Make Connections slice 3 an explicit dependency or assign these additions to concrete slices, including separate harness, credential-method and billing-kind fields.
+
+15. **High — §8:** Filtering by plausibility before stickiness changes rev 3’s binding rule, and the existing failover loop can choose another connection without returning through the proposed admission gate. Define the permitted switching boundaries and route every new attempt through scheduling and reservation, while preserving Ask’s exact session/model binding.
+
+16. **High — §§7–8:** `schedule.Decide` lacks a complete input contract and total ordering: current binding, preferences, model prices, consent, unknown-room ranking and tie-breakers are unspecified, while refreshing readings requires side effects. Define a versioned immutable input and deterministic comparators, with probing and transactional revalidation outside the pure function.
+
+17. **High — §§6–7, 9:** Weighted tokens alone cannot determine dollar cost or p90 duration, yet both govern admission and deadline cards; the formula also ignores provider differences in whether cached and reasoning tokens are included in totals. Define normalized token components, complete-attempt aggregation, cost and duration estimates, quantile rules, missing-value handling and checked arithmetic.
+
+18. **Medium — §7, Calibration:** Calibration does not reject zero or negative percentage movement, overlapping attempts, delayed readings or changing window/model scope, so it can produce invalid or optimistic room. Specify valid sample boundaries, positive denominators and matching window scope, then calculate remaining capacity separately for every applicable window.
+
+19. **High — §8, Reservations:** Releasing a reservation after usage arrives can restore apparent capacity while the provider reading remains stale; conversely, a refreshed reading can already include consumption still counted as reserved. Track usage since each reading and the unconsumed part of each reservation so admission neither forgets nor double-counts consumption.
+
+20. **High — §§8, 13:** The stated invariants are false under the stated rules: Run now bypasses the ladder, unknown calibration ignores estimated size, and p90 admission cannot guarantee that low-priority work stays below 70%. Test admission guarantees with explicit override exceptions and describe actual subscription consumption as best effort.
+
+21. **High — §§8–9:** `until` considers only eligible subscriptions, excluding currently limited connections whose future reset may release the hold; cap resets and approaching deadline thresholds also lack explicit wakeups. Compute wakeups from future candidates and all binding windows, and persist timers for cap boundaries, deadlines and preference expiry.
+
+22. **Medium — §§8–9:** Strict priority can starve low work indefinitely, while a task larger than every connection’s maximum admissible room can remain quietly held forever. Define an impossible-to-fit outcome and an aging or notification policy, while ensuring held work never blocks runnable steps or person turns.
+
+23. **High — §§6, 8, 12:** Housekeeping’s 80% stand-down is less restrictive than low work’s 70%, and merely copying its ledger shape does not preserve its per-person budget across attempts and downstream steps. Define how both ledgers compose, retain `caused_by` and remaining-budget enforcement, and preserve housekeeping’s unknown-headroom stand-down and person-first behavior.
+
+24. **Medium — §10:** Advice has no deterministic arbitration or fully specified dismissal input, and account-switch suggestions do not establish runner, role, tier or family eligibility; “another account would cover it” is unsupported. Define stable keys and ordering, persisted cooldown facts and eligibility checks, with revision-checked actions and evidence-qualified recommendations.
+
+25. **High — §12:** The finish lines omit the failures most likely to invalidate the design: dishonest usage, crashes, cap revisions, hostile configuration and release replay; one Pi Review also cannot certify every Mac connector and role. Require an explicit adversarial acceptance matrix per supported cell, and prevent ACP fallbacks from earning cells when mandatory containment or permission-relay proofs fail.
+
+**Cut**
+
+- Defer “cheap and short” routing: subscription-first ordering currently prevents it from saving subscription room.
+- Defer token-denominated caps, OpenRouter and generic local routing until the money-cap path is sound.
+- Defer account-purchase advice until recorded waits can support its recommendation.
\ No newline at end of file
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index bb501b1e..ee8c6607 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -14901,5 +14901,47 @@
"match": "equipo-runner",
"count": 1,
"reason": "Staging installs the release runner's pinned Pi for the owner's runner (install-pi); a release artifact path, not a dead reference."
+ },
+ {
+ "path": "docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md",
+ "line_sha256": "0430629c373c4f3bf24b358b007056f4b7c8e7181ba8c352dea37a2bd7373625",
+ "match": "npm",
+ "count": 2,
+ "reason": "Connectors and token scheduling design: the npm and Node packages of the harnesses it pins are described, not run"
+ },
+ {
+ "path": "docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md",
+ "line_sha256": "0d105a162c32cbb1b5a50f4fe8debf734dc15f605db526a4323f23b29d08bd8b",
+ "match": "npm",
+ "count": 1,
+ "reason": "Connectors and token scheduling design: the npm and Node packages of the harnesses it pins are described, not run"
+ },
+ {
+ "path": "docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md",
+ "line_sha256": "1a21576ad18b55387a739576bea33e7fbdc9faf4d545e00fb02203d1f8a74e98",
+ "match": "npm",
+ "count": 1,
+ "reason": "Connectors and token scheduling design: the npm and Node packages of the harnesses it pins are described, not run"
+ },
+ {
+ "path": "docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md",
+ "line_sha256": "521ae8e3124241926d91db8ede0a575f6fc1b1d9a24f08b0938331a32a9880e8",
+ "match": "npm",
+ "count": 1,
+ "reason": "Connectors and token scheduling design: the npm and Node packages of the harnesses it pins are described, not run"
+ },
+ {
+ "path": "docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md",
+ "line_sha256": "63a178fe9dd1275ed5f162e7987db7d886115027bc3a6543f7d5ba5e8e6b0546",
+ "match": "npm",
+ "count": 1,
+ "reason": "Connectors and token scheduling design: the npm and Node packages of the harnesses it pins are described, not run"
+ },
+ {
+ "path": "docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md",
+ "line_sha256": "f852ffc866bbf0293336463296eaa7413aea1516a27d988404179c79be71f7f3",
+ "match": "Node",
+ "count": 1,
+ "reason": "Connectors and token scheduling design: the npm and Node packages of the harnesses it pins are described, not run"
}
]