# S1 progress: metered connections

Branch `connections-s1-metered` from main 1d7b4e41. Spec:
`docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md`
revision 3.1 (on `connections-slice2-design`, 629221f6), approved by Paul
as recommended, all eight decisions. Slice S1 (§11): §0 decisions 3, 4
and 7, §2.1 to §2.3, the S1 parts of §3, §7's metered guard for Ask, and
§10's wire, API and fixtures for them. Builds on the Claude token
connection (2e5a6103 to 92105191) and Connections rev 3 §2.4.

There is no real harness in S1: Pi arrives in S2. The metered provider is
TensorX (`https://api.tensorx.ai`, harness Pi) with a versioned price
table; tests use a fake harness (functions standing in for the S2
adapter) and a fake OpenAI-compatible provider on 127.0.0.1. No real
provider, key or sign-in was used.

## Done

1. Wire (b5720ae5). Protocol 12, `ProtocolMetered`. `KindAPIKey`
   (`api_key`), prompts `api_key` and `model` (`ConnectPrompt.models`),
   billing `subscription | metered`, the provider table
   `wire.APIKeyProviders` (TensorX: Pi, upstream, `/v1`, endpoint
   `https://api.tensorx.ai:443`, per token, USD), the §2.1 rule
   (`CheckConfirmations`, `Billing`), `Budget` and `Spend`.
   `Connection` gains `harness`, `upstream`, `billing`, `model`,
   `limit_confirmed_at`, `payg_off_confirmed_at`, `budget`, `spend`,
   `budget_pending`; `Connect` gains `limit_confirmed`,
   `payg_off_confirmed`, `budget`; `ConnectCommand` `billing`, `budget`;
   `HeldConnection` the metered facts; `Usage` gains `cost_micros`,
   `currency`, `price_version`, `cost_reported_micros`; `UsageReport`
   gains `probe_id`. Frames (instance to runner, durable): `model`,
   `budget` (acked when applied), `resume_spend`. Hold reasons `busy`,
   `budget`, `spend_unknown` (also question reasons); connect reasons
   `key_refused`, `no_priced_model`. All new fields are omitempty, so
   every earlier fixture is byte-identical. Below 12, `Encode` drops
   API-key connections from hello and sync and the cost fields from
   usage rows, says a probe's usage as a check, and refuses the new
   frames, an API-key connect and a held question's report: an older
   runner is refused metered connections rather than downgraded.
   Fixtures: `api/connection-metered.json`, `api/connection-choose-model.json`,
   `api/connect-request-api-key.json`, `api/budget.json`,
   `api/resume-request.json`, `api/model-request.json`,
   `frames/budget.json`, `frames/model.json`, `frames/resume_spend.json`,
   `frames/connect-api-key.json`, `frames/usage-probe.json`,
   `frames/hello-metered.json`; the secret-field guard covers every new
   type and fixture (the only allowance: `"kind":"api_key"`, a value).

2. Egress (0268db20). `egress.ProviderPolicy` and `Policy.Hash` read one
   table keyed by `(harness, provider)`: `(claude, claude)`,
   `(codex, codex)`, `(pi, tensorx)` to `api.tensorx.ai` only.
   `NetworkContract` and `Policy` gain `Harness` (empty for a provider's
   own CLI), so the Claude and Codex policy hashes are unchanged; a pair
   that is not a row is refused. A test ties each API-key provider's row
   to its upstream host.

3. The ledger (f0f18906), `internal/runner/metered`:
   - price tables, versioned (`tensorx-2026-11-12`), in integer
     micro-units per million tokens; usage normalised into
     `uncached_input`, `cached_input`, `cache_write`, `output` and
     `reasoning` (reasoning apart only where the table says so); each
     part rounded up, 128-bit intermediate, overflow is unknown; an
     unpriced model, an unpriceable component or an incomplete row is
     unknown; the larger of the priced and the reported cost is charged
     and both kept;
   - thin.db tables `metered_connections`, `metered_slot` (one per
     connection) and `budget_charge` keyed by the usage row's key
     `(turn, step, attempt, connection, model)`;
   - `Admit`: the slot free, spend known, reported spend under the day's
     and the month's budget, claimed in the caller's transaction (a
     question's start rides in it); `Charge` with the report in one
     transaction; `Settle` only after the termination proof, releasing
     the slot with the charge or with `spend_unknown` under a new
     `pause_revision`; `Resume` consumed once and only for the current
     pause; `ApplyBudget` above the revision held;
   - `Meter.Run` is the entry a harness adapter (S2's Pi) calls;
     `Meter.Recover` reconciles claimed slots at start-up (in `run.go`,
     before the connector and the step engine start): namespace proven
     gone, committed charges kept, otherwise `spend_unknown`, then the
     slot released; one that cannot be proven stays held. Slots of
     attempts running in this process are never touched;
     `StepEngine.Probe` runs it again for ended, unproven ones.

4. The runner (956f2d59):
   - API-key attempts reuse the token delivery (`Secret`, `keep`, the
     staged and committed file, `seen_seals`, restart recovery), bound to
     the provider's endpoint; the key lands 0600 in the connection's own
     home under the accounts root (`tensorx-N`);
   - the runner, outside any namespace, reads `GET /v1/models` with the
     key (`connect.APIClient`), offers the models the price table knows
     (prompt `model`), waits for the `model` frame, adds the connection
     unvalidated, then runs the one-token probe
     (`POST /v1/chat/completions`, `max_tokens: 1`) through `Meter.Run`
     with role `probe`; its usage row is charged and sent in a usage
     frame with `probe_id`; success validates the connection, a 401/403
     ends the attempt `key_refused`;
   - Check again on a metered connection runs the probe again (through
     the guard; a refused key reads `sign_in_again`); hello carries each
     validated metered connection with its budget and spend; `budget`
     and `resume_spend` frames apply in the transaction that records
     their frame id; sign-out deletes the record, then the home, through
     the durable cleanup;
   - the metered guard for questions (`askmetered.go`): a question whose
     kept session is on a metered connection is admitted through
     `Meter.Admit` with its start in the same transaction; refused, it
     is held (asks `hold`, `not_before`), reports `queued` with the hold
     as its reason once per hold, is never moved, and is looked at again
     on any change of a connection's standing (slot released, budget
     applied, Resume) or, for the budget, at the next UTC day or month.
     With no harness for it (S1), it fails `account_unavailable` without
     claiming the slot.

5. The instance (79f4daad): `POST /api/v1/connections` with
   `kind: api_key` (refused 422 without the limit confirmation, with a
   pay-as-you-go confirmation on a per-token provider, without a budget
   in bounds; 409 `runner_too_old` below protocol 12); the
   confirmations kept with their time on the record; the box on
   `POST /connections/{id}/secret` bound to the provider's endpoint;
   `POST /connections/{id}/model`; `PUT /connections/{id}/budget`
   (revision-checked, pending until the runner's ack);
   `POST /connections/{id}/resume` (bound to the pause shown); hello's
   metered facts recorded; usage rows keep their cost; a probe's row has
   role `probe`; a held question keeps its hold as its reason. Migration
   0068 (additive).

6. The page (68cdc2f6): Add a connection offers TensorX with the
   required confirmation, how TensorX limits a key (its billing docs),
   what Equipo cannot see, and the budget pre-filled at 1 and 10; a
   refusal says why. The key card seals in the page (connections.js,
   `data-key-form`) for TensorX's origin; the model card lists the
   runner's models. A metered row: model, the spend line ("$0.84 of $1
   today · $6.20 of $10 this month", "Reported by Pi. Spending can
   exceed the budget by one step."), "Paused until tomorrow" / "Paused
   until 1 Dec", "Paused: spend unknown. Check your spending at TensorX,
   then choose Resume" with Resume, "Applies when
   <runner> confirms", Change budget, Check again, Sign out. Metered
   connections stay out of the coordinator lines and the preference.

## Tests

- `internal/wire`: `TestEncodeBelowProtocol12DropsMetered` (mixed
  versions: the new frames, an API-key connect and the metered fields
  never reach an older peer), `TestMeteredConfirmations`, the secret
  guards over the new types and fixtures, fixture round trips.
- `internal/runner/egress`: `TestEgressTableKeyedByHarnessAndProvider`.
- `internal/runner/metered`, with a fake harness, the S1 finish line:
  (a) `TestMeteredBudgetHoldsTheNextAttempt`, (b)
  `TestMeteredRaceAdmitsExactlyOne` (Engineering, Review and a question
  race, eight rounds), (c) `TestMeteredCrashBeforeChargeIsSpendUnknown`,
  (d) `TestMeteredStaleResumeLeavesTheNewerPause`, (e)
  `TestMeteredResentUsageChargesOnce`, (f)
  `TestMeteredUnpricedModelIsSpendUnknown`; `TestPricesNormalisedComponents`.
- `internal/runner/connect`: `TestAPIClientModelsAndProbe` (fake
  provider on 127.0.0.1).
- `internal/runner/thin`: `TestAPIKeyConnectionRoundTrip` (sealed paste,
  model list, probe charged as role probe, hello, Check again, a refused
  key, budget frames, sign-out; the key in no frame or log line),
  `TestAPIKeyBoxBoundToTheProvider`, `TestMeteredGuardHoldsQuestions`,
  `TestMeteredQuestionWithNoHarness`.
- `internal/thintest`: `TestContractMeteredConnection` (an older runner
  refused; confirmations, budget and provider refused without; the
  sealed key's binding; the model pick; the probe row charged once when
  resent; budget pending until the ack; Resume bound to its pause; the
  page's add form, refusal, key and model cards, spend line, pending and
  spend unknown; the key nowhere on the instance);
  `TestPagesConnectionsAdd` now expects TensorX offered and two greyed.
- Local runs were targeted only (`-run`), plus gofmt, go vet (linux,
  testbuild, darwin), staticcheck on the changed packages, `make
  budget` and the dead-reference scan.

## Mutations, each observed failing

- wire M1: downgradeMetered kept API-key connections in hello -> TestEncodeBelowProtocol12DropsMetered (hello at protocol 11)
- wire M2: meteredOnly refusal off -> TestEncodeBelowProtocol12DropsMetered (budget encoded at protocol 11)
- wire M3: api_key field on ResumeSpendCommand -> TestConnectionTypesCarryNoSecrets
- wire M4: CheckConfirmations ignores the limit -> TestMeteredConfirmations
- wire M5: probe usage not said as a check below 12 -> TestEncodeBelowProtocol12DropsMetered (usage at 11)
- egress E1: tensorx row allowed a second host -> TestEgressTableKeyedByHarnessAndProvider (tensorx through pi)
- egress E2: an empty harness taken as pi -> TestEgressPolicy, TestEgressPolicyFrozen, TestEgressTableKeyedByHarnessAndProvider (tensorx with no harness admitted)
- egress E3: harness always set on the policy -> TestEgressTableKeyedByHarnessAndProvider (claude policy hash changed)
- metered MM1: Admit ignored a held slot -> TestMeteredRaceAdmitsExactlyOne (round 4: two held, none ran: the claim overwrote; with the conditional UPDATE alone kept the race still admitted one, so the holder check is the guard and the conditional UPDATE is belt and braces)
- metered MM2: budget check disabled -> TestMeteredBudgetHoldsTheNextAttempt (after the budget: admitted, ran)
- metered MM3: Settle never pauses -> TestMeteredCrashBeforeChargeIsSpendUnknown, TestMeteredUnpricedModelIsSpendUnknown
- metered MM4: Resume not bound to pause_revision -> TestMeteredStaleResumeLeavesTheNewerPause (stale resume cleared)
- metered MM5: ledger without the usage key -> TestMeteredResentUsageChargesOnce (charged 700000, 4x)
- metered MM6: an unpriced model priced at zero -> TestMeteredUnpricedModelIsSpendUnknown
- metered MM7: Recover released a slot whose namespace was not proven gone -> TestMeteredCrashBeforeChargeIsSpendUnknown
- runner AK1: an API-key box accepted when bound to Claude's endpoint -> TestAPIKeyBoxBoundToTheProvider (the bad box was taken; the attempt waited for a model)
- runner AK2: the probe's usage not reported -> TestAPIKeyConnectionRoundTrip (probe usage [])
- runner AK3: unpriced models offered -> TestAPIKeyConnectionRoundTrip (offered [vendor/unpriced z-ai/glm-5.3])
- runner AK5: a refused probe not recorded -> TestAPIKeyConnectionRoundTrip (no sign_in_again)
- runner Q1: a metered question sent down the Claude path -> TestMeteredGuardHoldsQuestions (a metered question went to the Claude path)
- runner Q2: holds not looked at again on a change -> TestMeteredGuardHoldsQuestions (q1 stayed queued busy)
- runner Q3: a refused question run anyway -> TestMeteredGuardHoldsQuestions (the slot is not this attempt's; answered while the probe held it)
- instance I1: confirmations not checked -> TestContractMeteredConnection (no limit confirmation accepted)
- instance I2: no protocol check -> TestContractMeteredConnection (a protocol 11 runner accepted)
- instance I3: the budget frame's ack not applied -> TestContractMeteredConnection (timed out waiting for the budget applied)
- instance I4: Resume not bound to the pause -> TestContractMeteredConnection (a stale resume accepted)
- instance I5: probe usage recorded as a check -> TestContractMeteredConnection (probe usage role check)
- page U1: the spend line dropped -> TestContractMeteredConnection (the row lacks the spend line)
- page U2: the add form taken as confirmed -> TestContractMeteredConnection (unconfirmed add went through)

## Decisions where the spec was open

- Metered connections live in thin.db (`metered_connections`), not in
  the bindings file: the bindings file is the certified launcher's
  config and admits only Claude and Codex; S2 adds the Pi launch from
  the metered record.
- The sealed key travels on `POST /connections/{id}/secret`, as the
  token's does, not on `POST /connections` (§10 lists `sealed` there):
  the box is bound to the connection's id, which does not exist before
  the POST.
- The model pick needs a frame the spec does not name: `model`
  (instance to runner, durable, refused below 12).
- The key is kept in the home under the token's file names
  (`.oauth-token`, staged as the token is), so delivery and recovery are
  one code path.
- The probe runs in the runner process (no namespace); a 401/403 is not
  billed (nothing charged, no pause); any other failure after the
  request (no answer, 5xx, no usage reported) is spend unknown.
- Normalisation: input or output not reported, or the row not complete,
  is unknown; a cached or cache-write figure not reported counts as none.
  TensorX's table: the 2026-11-12 published prices of ten models
  (tensorx.ai/pricing, matching models.dev); cache writes unpriced (any
  is unknown), reasoning part of output; to be checked before release.
- A connection keeps the price version it was made with.
- Budgets: UTC days and months; a day at most 1,000 and a month at most
  10,000 in the currency, day not above month; pre-filled 1 and 10.
- `budget_pending` is the person's budget revision above the highest
  the runner applied (its frame's ack, or hello's revision), and is not
  shown while connecting (the first budget rides the connect frame).
- A held question reports `queued` with the hold as its reason, once per
  hold. A runner restart fails it `runner_restarted`, as it already does
  for any question not yet started.
- In S1 no Engineering or Review step can be admitted to a metered
  connection: `Conns.Mine` and `connect.Choose` stay Claude and Codex
  (metered work is `urgent` or released, which is S3). `Meter.Run` is
  the entry S2's adapter calls; the race test runs all three roles
  through it.
- A restart in the middle of the connect probe that leaves the spend
  unknown ends the attempt `provider_refused` (the unvalidated record
  goes; its charge stays in the ledger).
- The slot's holder is `role|turn|step|attempt`.
- Pay-as-you-go off on a per-token provider is refused (422), not
  ignored. The overflow rule is tested with a fake table row only.

## New copy keys (in the Plan 3 inventory; see the delegated review below)

- `chat.connections.metered.title`: Connect %s
- `chat.connections.metered.key_sub`: An API key, billed per token. You set its spending limit at %s.
- `chat.connections.metered.limit_confirm`: This key has a spending limit at %s
- `chat.connections.metered.limit_how.tensorx`: At TensorX the limit is your prepaid balance: keys stop working below $0.05. Keep the balance at what you are willing to spend, and check that no automatic top-up is set.
- `chat.connections.metered.limit_docs`: How TensorX billing works
- `chat.connections.metered.cannot_see`: 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 %s.
- `chat.connections.metered.budget_legend`: Equipo’s budget for this key
- `chat.connections.metered.budget_day`: A day, in $
- `chat.connections.metered.budget_month`: A month, in $
- `chat.connections.metered.budget_note`: Equipo stops starting new steps when the reported spend reaches either figure. A step that is running finishes, so it can go over by one step.
- `chat.connections.metered.continue`: Continue
- `chat.connections.metered.confirm_first`: Confirm the spending limit and set a budget first.
- `chat.connections.metered.too_old`: Your runner needs an update before it can use a metered connection.
- `chat.connections.metered.key_paste`: Paste your %s API key
- `chat.connections.metered.key_bad`: That does not look like an API key. Paste it again.
- `chat.connections.metered.waiting_key`: Reading the models this key can use…
- `chat.connections.metered.model_pick`: Pick the model this connection uses. Another model needs another connection.
- `chat.connections.metered.model_use`: Use this model
- `chat.connections.metered.waiting_probe`: Trying the model with one token. It is charged to the budget.
- `chat.connections.metered.spend`: %s today of %s · %s this month of %s
- `chat.connections.metered.reported_by`: Reported by %s, can go over by one step
- `chat.connections.metered.paused_day`: Paused until tomorrow
- `chat.connections.metered.paused_month`: Paused until %s
- `chat.connections.metered.unknown`: Spend unknown: check %s, then Resume
- `chat.connections.metered.resume`: Resume
- `chat.connections.metered.pending`: Applies when %s confirms
- `chat.connections.metered.change_budget`: Change budget
- `chat.connections.reason.key_refused`: The provider refused the key: the balance may be empty, or the key was revoked.
- `chat.connections.reason.no_priced_model`: None of the models this key can use has a price Equipo knows, so it cannot keep a budget for it.
- `work.ask.held.busy`: Waiting: its connection is running another step
- `work.ask.held.budget`: Waiting: its connection has reached today’s budget
- `work.ask.held.spend_unknown`: Waiting: its connection’s spend is unknown. Check it, then Resume
- `chat.connections.metered.key_failed`: That did not go through. Paste the key again.

## Security round (Astra, read-only, on 789cb8d)

Verdict NOT READY, nine findings, all mechanical; each fixed with a test
written first and a mutation observed:

1. Admission before registration (`meter.go`): `Meter.Admit` registers
   the attempt as running before its admission commits, so `Recover`
   never sees the claim without it.
   `TestMeteredRecoverBetweenAdmissionAndLaunch` runs `Recover` in the
   window after the commit.
2. A repeated holder (`ledger.go`): a holder already claiming the slot
   gets `Claimed` and a hold, never leave to launch; the Meter refuses a
   holder already running in its process too.
   `TestMeteredDuplicateHolderRunsOnce`.
3. Sign-out during a probe (`apikey.go`): the sign-out retires the
   connection (nothing more admitted), waits for the slot (proving an
   ended attempt with `Recover`), so the probe's charge or spend_unknown
   commits, and `metered.Remove` refuses while the slot is held.
   `TestMeteredRetireWaitsForTheSlot`, `TestAPIKeySignOutDuringAProbe`.
4. Frame binding (`apikey.go`, `ledger.go`): API-key homes take a random,
   never reused name (`tensorx-<12 chars>`); the metered record keeps the
   instance's connection id; Budget and Resume check the frame id first,
   then the runner name, the connection id and the person, in one
   transaction; the ledger's updates name the connection too.
   `TestMeteredBindingNamesTheConnection`, `TestAPIKeyConnectionRoundTrip`.
5. The probe's transport (`connect/apikey.go`): `connect.SafeClient`, no
   ambient proxy, the host resolved once and every answer required to be
   public (`egress.PublicAddress`, now exported), the connection made to
   the resolved address, TLS verified for the host name, no redirect
   followed, answers capped at 1 MiB. `TestAPIClientTransport`; the
   runner's tests use the same transport with loopback allowed.
6. The answering model (`connect/apikey.go`): the probe reads the model
   the provider says answered; another model is `ErrModelMismatch`, no
   proof, and the usage row is that model's (unpriced: spend unknown).
   `TestAPIClientModelsAndProbe`, `TestAPIKeyProbeAnsweredByAnotherModel`.
7. Downgrade (`wire/runners.go`): below 12 an API-key attempt's report
   (its provider, the `api_key` and `model` prompts, `key_refused`,
   `no_priced_model`) and a question with a hold reason are refused, not
   translated. `TestEncodeBelowProtocol12AgainstFrozenSchemas` decodes
   what is still sent into frozen pre-12 shapes and value sets.
8. Authority (`chat/metered.go`): `TestMeteredWritesCheckPersonAndRoster`
   (another person, and a roster check failing between authentication
   and the write, change nothing) and the contract test's teammate and
   removed-owner requests.
9. Audit (`chat/metered.go`): `connection.budget` (id@revision),
   `connection.resume` (id@pause) and `connection.limit_confirmed` /
   `connection.payg_off_confirmed` (id@provider) are appended in the
   write's transaction, credential-free.

Mutations observed:

- F1: the attempt registered as running only after its admission commits -> TestMeteredRecoverBetweenAdmissionAndLaunch (the slot was released between the admission and the launch)
- F2: the ledger let a claiming holder in again -> TestMeteredDuplicateHolderRunsOnce (a claimed holder admitted again); with the in-process reservation also off, the same holder ran twice
- F3: a retiring connection admitted with its slot free -> TestMeteredRetireWaitsForTheSlot; Remove with the slot held -> same test (removed with its slot held)
- F4: budget and Resume not bound to the connection -> TestMeteredBindingNamesTheConnection (another connection's budget applied; its resume consumed)
- F3 (runner): the sign-out deleted the record without waiting for the slot -> TestAPIKeySignOutDuringAProbe (removed while its probe ran); the sign-out without retiring -> same test (never retiring)
- F4 (runner): a consumed budget frame applied again -> TestAPIKeyConnectionRoundTrip (budget {4 4 rev 8}); API-key homes from nextHome -> same test (the runner name "tensorx-1" was reused); the runner's binding check alone off -> still held by the ledger's connection check (layered)
- F5: unsafe answers allowed -> TestAPIClientTransport (link-local dialed); the default transport -> same test; redirects followed -> same test; an ambient proxy -> same test
- F6: the answering model ignored by the check -> TestAPIClientModelsAndProbe and TestAPIKeyProbeAnsweredByAnotherModel (made a connection on another model's answer); the row priced under the selected model -> TestAPIKeyProbeAnsweredByAnotherModel (no spend unknown)
- F7: an API-key attempt's report sent below 12 -> TestEncodeBelowProtocol12AgainstFrozenSchemas (a pre-12 instance cannot read a tensorx report); the new reasons sent -> same test (no_priced_model); hold reasons on a failed answer sent -> same test (spend_unknown)
- F8: connections looked up without the person -> TestMeteredWritesCheckPersonAndRoster (another person's model) and TestContractMeteredConnection (a teammate's model pick: 409); the roster check left out of SetBudget -> TestMeteredWritesCheckPersonAndRoster (a removed person's budget)
- F9: the budget's or the Resume's audit left out -> TestMeteredWritesCheckPersonAndRoster (audits)

## Copy: delegated review (Astra, 2026-11-12)

The 33 strings went through Astra as the copy-review gate (Paul's
delegation of 2026-10-25): 17 kept, 16 changed, applied verbatim, each
now `COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)` in `copy.go` and in
the Plan 3 inventory. The changes put Equipo in the first person ("I
can’t see this limit", "I stop starting new steps"), name the budget
fields ("Daily budget", "Monthly budget"), group each amount with its
budget on the spend line ("$0.84 of $1 today · $6.20 of $10 this
month"), say what can exceed what ("Spending can exceed the budget by
one step"), make the probe's charge plain ("This test costs money and
counts towards your budget"), say "Paused: spend unknown" with what to
check, and make the held-question lines cover a busy connection and
either budget. The list above shows the texts as first written; the
final texts are in `copy.go`. Tests that quote them updated.

## Open

- No browser test of the key card's sealing in the page (S1's UI is
  checked server-side and by the runner's own seal test); a `-tags
  browser` test like the token card's is owed with the UI pass.
- The spec's spend line starts "TensorX:"; the row already names TensorX,
  so the line starts at the figures.
- Staging and the real pinned harness are S2.
