# S3 progress: the scheduler

Branch `connections-s3-scheduler` from main 379fe0d2 (S1 and S2 merged).
Spec: `docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md`
revision 3.1 (on `connections-slice2-design`), §11 row S3: §0 decisions
5 and 6, §6, §7, §8, §10 (S3's wire, API and fixtures) and §15 round 3
rows 4, 6 and 7. No real key, sign-in or provider: fakes only.

## Done

1. `internal/schedule`: the pure `Decide(Input) Decision` (§7). Bars
   (usable, not avoided, capable; metered: urgent or a release, slot
   free, spend known, under both budgets), thresholds 0.60/0.80/1.0 on
   the effective priority (a release is urgent), windows past their
   reset not reported, the fixed room precedence for subscriptions and
   for metered connections, the rules in order (kept session, preference,
   subscription, metered, hold), the hold naming the subscription whose
   reset comes first or the most actionable spending bar, wake-ups
   strictly after now (every capable connection's resets, the next budget
   day or month when the step has leave, the preference's end, `by`
   minus 24 h unless `deadline_notified`), and Needs you (deadline, no
   reset in 72 h, no_connection). Review's family rule is applied as
   tiers: another family, then another account, then Engineering's own.
2. Wire, protocol 14 (`ProtocolScheduler`): dispatch `priority`, `by`,
   `release`; a step report's `hold` (`StepHold`: reason, connection,
   provider, resets_at, wake_at, needs_person, step_revision); frames
   `release` and `priority` (durable); `Preferences.until` and
   `PreferenceCommand.until`; record_task and start_task arguments
   `priority` and `by`. Below 14 Encode refuses the two frames, a held
   report and a preference with an end, and drops the dispatch fields and
   the tool arguments. Fixtures `frames/release.json`,
   `frames/priority.json`, `frames/step-held.json`,
   `frames/preference-until.json`, `frames/dispatch-urgent.json`,
   `api/task-held.json`, `api/card-held.json`, `api/priority-request.json`,
   `api/run-now-request.json`, `api/run-now-accepted.json`; the secret
   guards cover every new type and fixture.
3. The runner (`thin/schedule.go`): every Engineering, Review and
   Research attempt, failover included, is admitted through Decide.
   Readings are refreshed before the call (an unchecked connection is
   checked; a reading over 15 minutes old goes through `Conns.Reading`,
   at most once per 15 minutes). The admission is one thin.db transaction
   that reads the facts again and decides again if they moved; a pending
   release is consumed there and kept as a grant for (step,
   step_revision); a metered admission commits in S1's guard transaction
   (`Meter.RunAdmitted`). Holds are kept with `wake_at` (or until a
   change), reported once per hold, woken at `wake_at` and on any reading,
   step end, budget, Resume, preference, priority or release. The release
   order (`nextStep`): urgent, earliest `by`, normal, low, oldest, step
   id. Questions stay off Decide and keep S1's guard. A kept metered
   session under a spending bar is held there; without leave it starts
   afresh on a subscription (S2's rule, kept).
4. Leave to spend comes only from `urgent` or a grant. The test-build
   seam (`testLeaveToSpend`, `EQUIPO_TEST_LEAVE_TO_SPEND`) is gone: the Pi
   tests mark their tasks urgent; the release check no longer looks for a
   marker nothing can contain.
5. The instance: `chat_tasks.priority`, `due_by`, `priority_set_by`;
   `chat_steps.hold`; `chat_releases` (one per step revision); migration
   0073. record_task (and start_task, only on a task recorded in that
   turn with nothing set) take `low`/`normal` and `by`; `urgent` is
   refused. `PUT /api/v1/tasks/{id}/priority` is the creator's tap
   (actor from the session, roster in the transaction, revision, audit
   `task.priority`) and sends a `priority` frame to the runner holding the
   step. A held step stays queued with its hold; where the creator's input
   changes the outcome it is Needs you `held` with a `held` card ("I'd
   wait: Claude resets ..."), Wait or Run it now. `POST
   /api/v1/tasks/{id}/run-now {step, step_revision}`: the creator's,
   bound to the hold's revision, one release per revision (a second tap
   answers the first), audited `task.run_now`, refused on a budget or
   spend-unknown hold (409 `hold_bar`) and on a runner before 14 (409
   `runner_too_old`). `PUT /connections/preference` takes `until` (a
   runner before 14 is refused one). Dispatches carry the priority,
   deadline and an open release; housekeeping's go as `low` with none.
6. Pages: the task card and page show the hold line with Run it now
   anyway (headroom, busy, no_connection) or Raise the budget / Resume
   (links to Connections), the priority line ("Low priority · By Fri 20
   Nov · set from your message") with Mark urgent / Not urgent, and the
   Needs you decision from the held card.

## Tests

- `internal/schedule`: `TestDecideRules` (a row per rule and bar),
  `TestDecideReviewFamily`, `TestDecideWakeUps`, `TestDecideNeedsYou`,
  `TestDecideInvariants` ((a) to (f) and wake-ups after now over 20,000
  random inputs), `TestDecideOrderFree`.
- `internal/wire`: `TestEncodeBelowProtocol14DropsScheduler`,
  `TestEncodeBelowProtocol14DropsToolPriority`,
  `TestSchedulerFramesStrict`, fixture round trips, secret guards.
- `internal/runner/thin`: the finish line
  `TestScheduleLowHoldsThenStartsAfterReset` (a low step holds at 0.61,
  said once with a future wake-up, a normal step runs meanwhile, and the
  low one starts by itself after the reset),
  `TestScheduleReleaseOnceAndStaleRefused` (a stale, another person's
  and a replayed release start nothing; the consumed one is a grant),
  `TestScheduleFailoverInsideAGrant`, `TestSchedulePriorityChangeGivesLeave`,
  `TestScheduleReleaseOrder`, `TestScheduleAdmissionRechecksFacts`,
  `TestScheduleRefreshesStaleReadings`, `TestPreferenceUntilEnds`; the
  Pi tests now give leave by an urgent task (`TestPiReviewStep` also
  checks the admission row `metered_urgent`;
  `TestPiReviewWithoutLeaveToSpend` the headroom hold).
- `internal/thintest`: `TestContractScheduler`,
  `TestContractSchedulerOlderRunner`; `internal/equipo/chat`:
  `TestSchedulerWritesCheckCreatorAndRoster`.
- Local runs were targeted (`-run`) on the changed packages, plus
  gofmt, go vet, staticcheck on the changed packages, the darwin runner
  build, `make budget` (budget lines updated; `internal/wire` gets an
  exemption at 5032 lines) and the dead-reference scan.

## Mutations, each observed failing

### schedule mutations (all caught)
- SM1 low threshold 0.70 -> TestDecideRules/low_holds_at_0.61
- SM2 windows past reset still counted -> TestDecideRules/a_window_past_its_reset_is_not_reported
- SM3 leave always granted -> TestDecideRules/kept_metered_without_leave_moves; TestDecideInvariants (b) #34 metered without leave
- SM4 budget bar off -> TestDecideRules/kept_metered_over_budget_holds_there; TestDecideInvariants (d)
- SM5 busy-slot bar off -> TestDecideRules/kept_metered_busy_holds_there; TestDecideInvariants (c)
- SM5b spend-unknown bar off -> TestDecideInvariants (d)
- SM6 kept metered under a spending bar moved instead of held -> TestDecideRules/kept_metered_busy_holds_there (ran on b)
- SM7 wake-up allowed at now -> TestDecideWakeUps, TestDecideInvariants (#76 a wake-up not after now)
- SM8 rule 4 removed -> TestDecideRules/metered_only_with_urgent; TestDecideInvariants (e) held though a candidate admits
- SM9 reported-before-unreported key dropped -> TestDecideRules/reported_before_unreported
- SM10 preference until ignored -> TestDecideRules/an_expired_preference_is_absent
- SM11 deadline check fires again after deadline_notified -> TestDecideNeedsYou
- SM12 Review family tiers removed -> TestDecideReviewFamily
- SM13 kept subscription not sticky -> TestDecideRules/kept_stays_whatever_the_threshold
- SM14 limited always usable -> TestDecideRules/limited_is_not_usable
- SM15 no 72 h bound on reset -> TestDecideNeedsYou (a reset 73 h away)
- SM16 threshold compare > instead of >= -> TestDecideInvariants (a) admitted at 0.60
### wire mutations (TestEncodeBelowProtocol14DropsScheduler)
- WM1 release frame not refused below 14 -> caught (release encoded at 13)
- WM2 held step report not refused below 14 -> caught
- WM3 dispatch priority kept below 14 -> caught (dispatch at 13)
- WM4 preference with until not refused below 14 -> caught
### runner mutations
- RM1 release not consumed / no grant at admission -> TestScheduleReleaseOnceAndStaleRefused (release "pending", grants 0)
- RM2 release accepted for a stale step revision -> TestScheduleReleaseOnceAndStaleRefused (a stale release was kept)
- RM3 release not bound to the person -> TestScheduleReleaseOnceAndStaleRefused (another person's release was kept)
- RM4 release kept for a revision that already holds a grant -> first MISSED (the replay arrived after the step ended, so the step check alone refused it); a case with the step still held and its revision granted was added, then caught
- RM5 admission without the facts recheck -> TestScheduleAdmissionRechecksFacts (admitted on moved facts)
- RM6 fact changes not waking held steps -> TestScheduleReleaseOnceAndStaleRefused, TestScheduleFailoverInsideAGrant (timed out)
- RM7 hold said at every look -> first MISSED (nothing re-decided before the reset); the test now wakes the step three times, then caught (said 4 times)
- RM8 stale readings never probed -> TestScheduleRefreshesStaleReadings (0 probes)
- RM9 grant not read for later attempts -> TestScheduleFailoverInsideAGrant (the failover attempt held)
- RM10 priority frame ignores its revision -> TestSchedulePriorityChangeGivesLeave (an older priority applied)
- RM11 release order back to oldest first -> TestScheduleReleaseOrder
- RM12 preference until ignored -> TestPreferenceUntilEnds
- RM13 dispatch's scheduler facts not recorded -> TestScheduleLowHoldsThenStartsAfterReset (ran at 0.61 as normal)
- RM14 runPi not writing the scheduler's admission in the guard's transaction -> TestPiReviewStep (no admission row)
### instance mutations
- IM1 coordinator allowed urgent -> TestContractScheduler (the coordinator set urgent)
- IM2 coordinator priority changeable after creation (start_task) -> TestContractScheduler (dispatch / start_task changed it)
- IM3 priority revision not checked -> TestContractScheduler (a stale revision accepted)
- IM4 priority/Run now creator check removed -> first MISSED in thintest (the rig cannot make a second owner, and isOwner refused the teammate first); TestSchedulerWritesCheckCreatorAndRoster (chat store, two owners) added, then caught for both
- IM5 roster check left out of SetPriority -> TestSchedulerWritesCheckCreatorAndRoster (a removed creator's priority)
- IM6 priority audit left out -> TestSchedulerWritesCheckCreatorAndRoster (audits [])
- IM7 priority frame not sent -> TestContractScheduler (no priority frame; timed out)
- IM8 release not bound to the held step revision -> TestContractScheduler (a stale step revision accepted)
- IM9 second tap writes a second release -> TestContractScheduler (a second tap)
- IM10 Run now passes a spending bar -> TestContractScheduler (Run now past spend unknown)
- IM11 Run now to a protocol 13 runner -> TestContractSchedulerOlderRunner
- IM12 preference with an end to a protocol 13 runner -> TestContractSchedulerOlderRunner
- IM13 dispatch without priority -> TestContractScheduler (dispatch)
- IM14 a held step marked running -> TestContractScheduler (held: state running)
- IM15 Needs you held dropped -> TestContractScheduler (needs "")
- IM16 held card left open after Run now -> TestContractScheduler
- IM17 page offers Run it now on a spending bar -> TestContractScheduler (spend unknown offers Run now)

## Security round (Astra, read-only, on e38bc7e5)

Verdict NOT READY, twelve findings: ten mechanical, fixed here, each
with a test written first and a mutation observed; two design findings
(#7 and #8) left to the controller unchanged.

1. Cached urgency over a newer dispatch (Critical): the task's priority
   has its own revision (`chat_tasks.priority_revision`), bumped by every
   change; dispatches and priority frames carry it, and the runner keeps a
   frame's value only while no dispatch carries a newer one, then keeps
   the newer dispatch's as the task's.
2. Housekeeping only "dispatched as low" (Critical): the attempt
   housekeeping dispatched is kept on the step
   (`chat_steps.housekeeping_attempt`), so a later placement is still
   housekeeping's; the dispatch says `housekeeping`; the runner keeps it
   per step and Decide treats it as low with no leave to spend whatever
   its priority, a priority frame or a release; Run now on it is refused
   and its held card offers Wait only.
3. Recovery failed held, never-launched steps: a step with a hold and no
   namespace recorded keeps its hold and wake-up across a restart.
4. Duplicate admission was an UPSERT: an attempt admitted and launched
   (its namespace recorded) is refused another admission (`errAdmitted`);
   one that launched nothing may be admitted again, explicitly.
5. Research skipped the scheduler's dispatch fields and holds: both
   Research paths use the shared fields (`schedulerFields`) and hold
   handling; a held Research step stays queued, is Needs you and takes
   Run now.
6. Review's failover launch ignored a guard hold: it is held there, as
   the first attempt is.
9. A repeated start_task could set the priority: the fields are written
   only when the start would go ahead (`startable`).
10. An overdue task could not change priority: an unchanged deadline is
    kept; only a newly given one must be ahead.
11. Frozen protocol 13 schemas: what is sent below 14 (a dispatch, a
    preference, a step report, record_task's and start_task's
    arguments) decodes strictly against the protocol 13 key sets.
12. A hold after failover was written against the original attempt: it
    is kept against the attempt the step moved to.

Not changed (design, for the controller): #7, no production reading
probe (see Open); #8, a kept metered session without leave starting
afresh on a subscription (S2's rule).

Mutations observed:

- #11 each stripping guard below 14 removed (dispatch priority, by, release, housekeeping; record_task priority, by; start_task's arguments; the held report's refusal) -> TestEncodeBelowProtocol14AgainstFrozenSchemas (frozen protocol 13 key sets) or TestEncodeBelowProtocol14DropsScheduler, each caught
- #2 (Decide) housekeeping given leave by urgent or a release -> TestDecideHousekeeping (housekeeping spent), TestDecideInvariants (b); housekeeping not counted as low -> TestDecideHousekeeping (above low's threshold)
- #1 the cached priority taking precedence over a newer dispatch -> TestScheduleNewerDispatchBeatsCachedPriority ("urgent"); a newer dispatch's value not kept as the task's -> first MISSED (the stale frame shared the held revision, so it was refused anyway); the case now sends a frame between the two revisions, then caught
- #2 (runner) the housekeeping flag not read -> TestScheduleHousekeepingNeverSpends (spent on TensorX)
- #3 recovery failing a held, never-launched step -> TestScheduleHoldSurvivesRestart (state reported, 1 report)
- #4 a launched attempt admitted again (the UPSERT) -> TestScheduleDuplicateAdmissionRefused
- #12 the hold persisted against the original attempt -> TestScheduleHoldAfterFailover (the held step ran 2 times)
- #6 a failover Review held by the guard -> TestPiReviewFailoverHeldByTheGuard (failed metered_held), observed before the fix (written first)
- #1 (instance) the dispatch without its priority revision -> TestContractScheduler (dispatch); the priority frame carrying the task's revision, not the priority revision -> TestContractScheduler (priority frame Revision 5)
- #2 (instance) housekeeping provenance not kept on the step -> TestContractSchedulerHousekeeping (retry not housekeeping); the dispatch not saying housekeeping -> same; Run now allowed on housekeeping's attempt -> same (Run now accepted); its held card offering Run it now -> same
- #5 Research dispatch without the scheduler fields -> TestContractSchedulerResearch (research dispatch); its hold not kept -> same (Hold nil); a held Research step marked running -> same (state running); held Research not Needs you -> same (needs "")
- #9 a repeated start_task in the same turn setting the priority -> TestContractScheduler (a second start_task set the priority)
- #10 an unchanged past deadline refused -> TestSchedulerOverdueDeadlineKept

## Decisions where the spec was open

- The step revision is the attempt the instance dispatched (runner
  column `steps.revision`); the runner's failover attempts keep it, a
  Retry is a new revision. The hold carries it, Run now names it.
- The held report is state `running` with `hold` (the instance keeps the
  step queued until a report without it), not a new `deferred` state an
  older instance would refuse; below 14 it is not sent.
- `busy` is a hold reason too: a kept metered session whose slot is
  taken (§7 rule 1) and an admission race.
- The admission rechecks by reading the facts again inside its
  transaction and comparing, not by per-row revision columns; the metered
  slot, spend and budget are rechecked by S1's guard in that same
  transaction.
- A `priority` frame (not in §10) carries a priority change to a step
  the runner already holds, so marking a held task urgent takes effect at
  once.
- Research steps go through Decide too (coordinator's family first, as
  before; never metered). Coordinator turns do not (person turns are
  never held). Housekeeping turns are not dispatched today
  (`TurnHousekeeping` is never created); housekeeping's step dispatches
  go as `low` with no release.
- The preference stays one provider for every role (as built); `until`
  is kept beside it, and an expired preference reads as Automatic on
  both ends rather than being cleared by a write.
- A deadline given as a date is the end of that day, UTC; at most a year
  ahead. start_task's priority applies only to a task recorded in the
  same turn with nothing set.
- Run now is refused on a budget or spend-unknown hold (it never passes
  a bar); those holds link to the Connections page for Raise the budget
  and Resume, and their card offers Wait only.
- The budget day and month boundaries are wake-ups only for a step with
  leave and a capable metered connection. Spend unknown has no reset, so
  it is Needs you.

## Open, or not as the spec says

- No reading probe exists that is not a model turn: Claude reports
  headroom only on a turn, and Codex's `account/rateLimits/read` runs
  only at sign-in. The refresh is built and tested with a fake
  (`Conns.Reading`), but is nil in production, so a reading older than
  15 minutes is used as last reported (a window past its reset counts as
  not reported). A Codex probe over the app-server is the follow-up.
- No browser test of the new forms (the pages are checked server-side).
- The staging witness waits for a release (below).

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

- `work.hold.headroom`: Waiting for headroom on %s
- `work.hold.headroom_reset`: Waiting for headroom on %s, resets %s
- `work.hold.budget`: Waiting: %s has reached today’s budget
- `work.hold.spend_unknown`: Waiting: %s spend unknown, check it, then Resume
- `work.hold.busy`: Waiting: %s is running another step
- `work.hold.no_connection`: Waiting: nothing you connected can run it without spending
- `work.hold.run_now`: Run it now anyway
- `work.hold.raise_budget`: Raise the budget
- `work.hold.resume`: Resume
- `work.priority.urgent`: Urgent
- `work.priority.normal`: Normal priority
- `work.priority.low`: Low priority
- `work.priority.by`: By %s
- `work.priority.from_message`: set from your message
- `work.priority.mark_urgent`: Mark urgent
- `work.priority.make_normal`: Not urgent
- `chat.held.wait.before`: I’d wait: %s resets %s, before %s.
- `chat.held.wait.reset`: I’d wait: %s resets %s.
- `chat.held.run.after_by`: I’d run it now: %s resets %s, after %s.
- `chat.held.run.no_reset`: I’d run it now: %s has no reset in the next three days.
- `chat.held.run.no_connection`: I’d run it now: only a metered connection can run it.
- `chat.held.spend_unknown`: %s spend is unknown. Check it, then Resume.
- `chat.held.budget`: %s has reached its budget. Raise it, or wait for tomorrow.
- `chat.card.wait_reset`: Wait
- `chat.card.run_now`: Run it now

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

The 25 strings went through Astra as the copy-review gate (Paul's
delegation of 2026-10-25): 17 kept, 8 changed, applied verbatim, each
now `COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)` in `copy.go` and in
the Plan 3 inventory. The changes say what the person waits for in
their own terms ("Waiting for your Claude allowance to reset Thu 10:00
UTC"), drop "today's" from the budget hold (the month's budget holds
too), say where to check spending and that Resume is a choice ("Check
your spending at TensorX, then choose Resume"), say "no reported reset",
name a per-token connection rather than "metered", and wait "for the
budget to reset" rather than "tomorrow". The list above shows the texts
as first written; the final texts are in `copy.go`. The one test that
quotes a hold line is updated.

## How Paul tries it

On staging, once this is released (Pi is already installed on the
owner runner):

1. Settings, Connections, Add a connection, TensorX: tick "This key has
   a spending limit at TensorX" (a small prepaid balance, no automatic
   top-up), keep the $1 a day and $10 a month budget, paste the key and
   pick `z-ai/glm-5.3`. The one-token probe makes it Ready and shows on
   its spend line.
2. Ask the coordinator for a small change on a test repository. On the
   task page tap Mark urgent (or, when a step shows "Waiting for your
   Claude allowance to reset", tap Run it now anyway). With Claude doing Engineering,
   Review goes to another family first, so it runs on TensorX.
3. What to see: the Review step on TensorX, family glm, label
   other_family; the Connections spend line moved by that step's cost;
   once today's spend reaches $1 the next step waits with "Waiting:
   TensorX has reached its budget", Raise the budget, and the row says
   "Paused until tomorrow". Ask the Review a question: it answers on TensorX,
   charged. Mark the task Not urgent and a normal step never spends.
