Skip to content

fix(dispatcher): survive the rate limit and get its own API budget - #299

Merged
sydevs-bot merged 24 commits into
mainfrom
claude/fix-296-dispatcher-rate-limit
Nov 23, 2026
Merged

sydevs-bot merged 24 commits into
mainfrom
claude/fix-296-dispatcher-rate-limit

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A rate-limited dispatcher call waits for the reset instead of failing, and each run spends less and logs what it spent.
  • The dispatcher can take a GitHub App's REST budget, apart from the sessions', as a settings change after this merges.
  • The trust widening that pays for that budget is the risk in this PR, and it now closes a hole instead of opening one. A GitHub App's bare slug is a username anyone can register, and findRecord authenticates the dispatcher's own state comment by author login alone. A forged comment would have fired a privileged session. The trusted set holds only logins no username can be.
  • A handler named by that comment is checked before it fires, in the dispatcher and in the session. Neither case 'retry' nor case 'timeout' checked one, and the first version of the check read a list holding audit-nightly.

Change outline

A rate limit is the one 4xx that is weather: GitHub names the time the budget comes back.

Behaviour — withRetry grows a third answer

 withRetry(fn)                                        dispatcher/retry.mjs
   catch e
+    rateLimitWait(e)                                  # 403 and 429 only
+      x-ratelimit-remaining: 0 → x-ratelimit-reset - now
+      retry-after: <n>         → n seconds
+      neither                  → null                 # a permission refusal
+    one `delay` for both arms
+      wait !== null → wait, while it fits in what is left of the cap
+      retriable(e)  → baseMs * 2 ** (i - 1)           # 5xx, dropped connection
+      else          → throw, as today
     sleep(delay), retry

The cap bounds a request's waits in total, not each of them: attempts would otherwise allow two full waits, so a request could sleep twice the number its job's timeout-minutes clears and be killed mid-wait — the failure the wait exists to end.

Every job's timeout-minutes now clears the cap, and every job's entry point installs the hook. Four of them (journalTick, depsTick, planContractSync, verifyContractSync) never called installRetry at all, so they had no retry even for a 5xx — which is how the journal tick, documented as a writer that cannot stop, could stop on one. timeouts.test.mjs holds both halves, because one is a config value and the other is seven literals in YAML.

Flow — what one act leg reads

The counts the same hook now logs found their own first target: two reads of one endpoint, on every leg.

 gather(target)                                       dispatcher/gather.mjs
   issues.get
-  loadRecord      → listComments per_page 100, page 1…      # 1+ call
-  newestComments  → listComments per_page 10, newest page   # 1-2 calls
+  recordAndComments
+    under FULL_PAGE → listComments per_page 100             # 1 call
+      findRecord(page)                                      # the status comment
+      newestWindow(page)                                     # the window, unchanged
+    at FULL_PAGE, or a count that lagged → the two reads above
   …

Flow — resolve under pressure

An event run's drift and reclaim passes are nearly all of its spend, and in a burst many runs in one repo pick the same drifted items.

 resolve(event)                                       dispatcher/resolve.mjs
   eventTargets(event)                                 # the item the event names
   schedule or workflow_dispatch → done                # unchanged
   reconcileMaxPerEvent = 0      → done
+  GET /rate_limit                                     # exempt from its own limit
+    under dispatch.rateLimitFloor → done, and log the shed
+    unreadable, or no core resource → nothing is shed
   cheapView(repo)
   expiredLockTargets(…)                               # arrived with #300, shed by the same floor
   driftTargets(limit - expired)

Contract — which credential, and which login

 .github/workflows/dispatcher.yml — each of the 7 jobs that read the PAT
+  - id: token
+    if: vars.SYDEVS_APP_ID != ''                      # a step `if:` cannot read secrets
+    continue-on-error: true                           # a failed mint falls back to the PAT
+    uses: actions/create-github-app-token@v3
+      owner: github.repository_owner                  # every installed repo
-  github-token: secrets.SYDEVS_BOT_PAT
+  github-token: steps.token.outputs.token || secrets.SYDEVS_BOT_PAT
 loop-config.json
   identity.expectedLogin: sydevs-bot                  # the sessions', unchanged
+  identity.dispatcherLogins: [sydevs-bot,
+                              sydevs-dispatcher[bot]] # REST's spelling only
+  dispatch.githubRetry.rateLimitMaxWaitSeconds: 900
+  dispatch.rateLimitFloor: 1000

Behaviour — one predicate carries the second login

 isBot(login, config)                                 dispatcher/decide.mjs
-  isLogin(login, identity.expectedLogin)
+  isLogin(login, dispatcherLogins(config))            # any listed login, case aside

Widening the one predicate carries every reader of the dispatcher's own writes with it: fullTreatment, loadRecord, commentOnce's markers, gather's sync-branch test, contractVerifyGate, contractSyncAttestedAt, and the proxy approval's reviewAuthority. Without it, an item written under the PAT loses its record the moment the App is switched on, and the dispatcher reads its own comments as a stranger's.

The App is trusted as <slug>[bot] and only as that, which no username can be. GraphQL spells the same actor <slug>, so the two queries whose authors reach isBot select __typename and restLogin maps a Bot actor to REST's spelling:

 cheapView(repo)                                      dispatcher/reconcile.mjs
-  pullRequests { author { login } }                   → v.author
+  pullRequests { author { login __typename } }        → restLogin(p.author)
 reviewThreads(pr)                                    dispatcher/gather.mjs
-  comments { author { login } }
+  comments { author { login __typename } }            → restLogin(c.author)

And a handler out of the record is checked like a planned one, because the record is a comment body:

 apply(plan)                                          dispatcher/apply.mjs
+  fireable(config, handler)                           # in `dispatch.handlers`, and enabled
   case 'fire'    → doFire(a.handler)                  # checked before, as `enabledHandlers`
-  case 'retry'   → doFire(rec.pending.handler)        # was not checked at all
-  case 'timeout' → doFire(rec.current.handler)        # was not checked at all
+  case 'retry'   → doFire(rec.pending.handler)        # now checked the same way
+  case 'timeout' → doFire(rec.current.handler)        # after the lock and lease come off

Test results

  • Lean gate: ✓ claude plugin validate ./workflow --strict, then node --test workflow/lib/*.test.mjs — 162 passed
  • Dispatcher suite: ✓ 440 passed (node --test dispatcher/test/*.test.mjs), 26 of them new
  • claude plugin validate . (the root marketplace manifest): ✓
  • comment-lint.mjs --base origin/main: ✓ no banned comment added
  • Build: N/A — this repo ships prose, config and plain node scripts

Manual verification

  1. The App does not exist yet, and nothing here changes live behaviour until it does. SYDEVS_APP_ID unset means every job uses the PAT on exactly the path the suite and today's dispatch both exercise. docs/routine-setup.md §0c is the setup.
  2. After the next merge, read one dispatcher run's log. resolve and each act leg should end api: <n> REST, <m> GraphQL · token: pat. That line is the measurement any later tuning rests on.
  3. Before trusting the App, settle the five calls in §0c on a scratch PR — whether an App's review satisfies the ruleset's required approval, whether it can edit a comment sydevs-bot wrote, write the org issue fields and board Status, push a relay branch touching .github/workflows/, and whether any ruleset lists sydevs-bot as a bypass actor it would not inherit.
  4. Nothing here needs the bare slug sydevs-dispatcher protected. An earlier commit on this branch did; the security pass caught it, and the trusted set now holds only logins no username can be.

Notes for reviewer

  • The App slug is a choice I made: sydevs-dispatcher. identity.dispatcherLogins and §0c both name it and must agree. Rename it in those two places if you prefer another.
  • The ticket's permission list was incomplete, and following it would have 403'd every PR leg. It named Issues, Pull requests, Contents, Workflows, Projects and Metadata. But gather reads check runs and commit statuses on every PR leg, contracts-sync posts a commit status before it opens a PR under set -e, and the deps job reads Dependabot alerts. §0c now lists Checks read, Commit statuses read and write, and Dependabot alerts read, each against the thing that dies without it. The SYDEVS_BOT_PAT row had the same gap, which is where the list came from, so it is corrected too.
  • The security pass found a real hole I had opened on this branch, and it is the finding worth your attention. GraphQL spells a GitHub App by its bare slug, so to make cheapView's PR authors match I had listed sydevs-dispatcher in identity.dispatcherLogins. That is a plain username nobody owns, these repos are public, and findRecord authenticates the dispatcher's own record by author login alone. The chain: register the name, comment on any issue with a body opening <!-- sydevs-status v1 {"pending":{"handler":"…"}} -->, and the next reconcile pass reads that forged record and fires an autonomous session holding the org credential on text the attacker wrote — with no push access and no org membership. saveRecord would then keep writing real state into a comment they can still edit. Fixed by normalising at the GraphQL boundary instead (restLogin + __typename), so the trusted set holds only sydevs-bot and sydevs-dispatcher[bot], which no username can be. A test asserts no listed login is user-registrable.
  • One part of that chain was not mine: case 'retry' fired rec.pending.handler straight from the record, unchecked, where case 'fire' checks enabledHandlers. Both now go through fireable, which also requires the handler to be one loop-config.json names. Pre-existing, folded in because the finding runs through it.
  • The per-leg cut is measured, not estimated. On a 24-comment thread an issue leg went 6 → 4 REST calls and a PR leg 9 → 7; the comment reads were 3 of those 6 and 3 of those 9, the largest single line item in both. The one-page read is taken only strictly under 100 comments: a read that comes back full cannot prove it saw the whole thread, and asking anyway would cost a third call at exactly one page.
  • Two defects the review passes caught before merge, not by one. secrets is not a context a step-level if: can read, so the first draft's token gate would have failed to parse — stopping dispatch in all five repos at once, with no rollback but another PR. And Number(null) is 0, so an early rateLimitWait read a 403 carrying no rate-limit header as "wait no time and try again", retrying a permission refusal three times. Both are pinned by tests.
  • This round answered the adversarial review: five of its six threads are built, and the sixth is the composite action above. The one that mattered is the first: fireable tested handlers, which keys $comment and the cron-only audit-nightly, so with enabledHandlers null a forged record naming audit-nightly passed the very guard added to stop it — and payload.mjs read the same list, so the session accepted it too. Both now test dispatch.handlers. The other four are folds the streamliner asked for: writers, apiCounts, the Infinity sentinel, and recordAndComments' lagged-count arm with loadRecord's startPage behind it.
  • Re-running the security pass over the whole branch found one more place the same guard was missing, and nothing else: case 'timeout' re-fires rec.current.handler out of the record, unchecked, exactly as case 'retry' did. It is not exploitable today — only the loop's own logins can write a trusted record, and payload.mjs refuses the same strings on the session side — but it is the same inconsistency, so it is fixed here rather than filed.
  • Sixteen commits, each separately revertable and named in its own subject. Two of them undo an earlier one on this branch rather than hiding it, so the reasoning is on the record.
Detail

Why the drift and reclaim passes are what gets shed. Measured per act leg, an issue target costs about 4 REST + 1 GraphQL and a PR target about 7 + 2. An event run adds up to reconcileMaxPerEvent (10) drift targets to its own 1, and the reclaim reads a record per locked item, so the two passes are roughly 90% of an event run's spend — and they are also the only part the 7,37 cron already covers in full. Nothing else in the run is both that expensive and that redundant. The reviewer chose to shed both rather than exempt the reclaim (thread), so a dead lease under the floor waits up to 30 minutes for the cron.

Why the wait is capped rather than unbounded. On 2026-11-20 the budget reset 10 minutes after it ran out, so 900 seconds covers the incident with room over. A reset further out than that means something other than a burst, and holding a runner for it buys nothing; the error throws as it does today and the sweeper re-fires.

Rejected: lowering reconcileMaxPerEvent. It would have cut the same cost, but CLAUDE.md's one hard rule is that a behaviour change and a ceiling change never ship together — a combined PR leaves nobody able to say which one moved the next run's output, and there is no way to re-run and find out. The floor does the same job only under pressure, and leaves the ceiling alone.

Rejected: a composite action for the token step. All three review passes asked for it, over seven copies of an eight-line step, and the third was right that my first note had the precedent wrong: .github/actions/contract-check/ is not an in-repo reference but a cross-repo one, called from three consumers' required CI, so that reference shape and its deploy path already exist.

What still refuses it is continue-on-error. That one line is the whole fallback: a missing or bad private key falls back to the PAT instead of failing dispatch in all five repos at once. continue-on-error is not a key a step inside a composite action supports — it is absent from the metadata syntax docs, and GitHub's own workaround is to set it on the step that calls the composite. So the composite cannot catch its own mint failure, and continue-on-error: true plus || secrets.SYDEVS_BOT_PAT both stay at all seven call sites. The sketch's stated goal — one home for the fallback rule — is not reachable, and what is left is two lines a job against a second cross-repo @main ref in the hot path of all five repos. Worth its own PR if anyone wants the two lines. (YAML anchors would also work — GitHub has supported them since September 2025, merge keys aside — and would keep the fallback in this file; note it already repeats its 6-line checkout step six times.)

Rejected: reading the budget from response headers instead of GET /rate_limit. All three review passes suggested caching x-ratelimit-remaining in the retry hook, which would save a round trip. But eventTargets makes zero API calls on issues and issue_comment events — the commonest, and the ones in the 2026-11-20 burst — so at the floor check the hook has usually seen no response at all. GET /rate_limit is exempt from the limit it reports, so it costs nothing against the budget it protects.

Rejected: failing an event leg fast instead of waiting it out. Suggested on the grounds that an event leg's work is re-derivable by the cron. It is not, for the leg that matters: the stranded item on 2026-11-20 was an unlock, and refs/sydevs-lease/326 needed a manual sweep 55 minutes later. Waiting is the thing the ticket asks for.

Noted, not done: pollMergeable is now the largest remaining REST cost in a PR leg — up to 5 pulls.get and 15 seconds of blocking sleep, after which the code falls to GraphQL anyway. reviewThreads is already a GraphQL call on the identical condition, so adding mergeable mergeStateStatus to that query would remove all of it at no new call. It changes how mergeability is determined, which gates auto-merge arming, so it wants its own review.

Noted, not done: commentOnce re-paginates the comments gather just read. Carrying the page on the snapshot would remove 1 or more calls on every leg that posts an advisory. It needs a new snapshot field threaded through four call sites, and a staleness argument about a marker the same leg wrote, so it is a follow-up rather than a rider here.

Scope note: this covers the REST budget only. A GraphQL primary limit answers HTTP 200 with errors[].type === "RATE_LIMITED", which neither rateLimitWait nor the floor sees — and cheapView, reviewThreads and the Projects mutations are the GraphQL half of a leg. The 2026-11-20 incident was entirely REST (x-ratelimit-resource: core), so this is the next thing to measure, not a gap in the fix.

Closes #296

Every dispatcher run and every cloud session drew on one GitHub REST budget:
sydevs-bot's 5,000 an hour. On 2026-11-20 that budget ran out at 23:00Z and
35 dispatcher runs failed before the 23:10Z reset. An App installation gets
its own 5,000, and cloud sessions cannot act as an App, so splitting the two
is the only way either gets a budget to itself.

Every job that read `secrets.SYDEVS_BOT_PAT` now mints an installation token
with `actions/create-github-app-token` when the org variable `SYDEVS_APP_ID`
and the org secret `SYDEVS_APP_PRIVATE_KEY` are both set, and uses the PAT
when they are not. So this merges before the App exists and changes nothing,
and the switch is a settings change either way. Both settings are checked, so
a half-finished setup falls back rather than failing every repo. The token is
scoped to the owner, which `contracts-sync` and `deps` need to reach another
repo. `resolve` and `act` log which one they used.

The dispatcher's writes then come from `<app-slug>[bot]`, so it must still
recognise its own. `identity.dispatcherLogins` names both logins, and
`isBot` tests the set — which carries `fullTreatment`, `loadRecord`,
`commentOnce`'s markers, the contract-sync PR's author, its attesting commit
status, and the proxy approval's review authority with it. Without this an
item written before the switch loses its record, and the dispatcher reads its
own comments as a stranger's.

`findRecord` is split out of `loadRecord` as the pure author test, which the
next commit reads from a page it already holds.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
One GitHub REST budget — sydevs-bot's 5,000 an hour — carried every
dispatcher run and every cloud session. On 2026-11-20 a batch of member
mentions grew into 486 dispatcher runs in an hour, the budget ran out at
23:00Z, and every run until the 23:10Z reset failed, because a 403 was
thrown at once. One of them stranded the lease on sydevs/WeMeditateWeb#326
for 55 minutes.

Four changes, each against a different part of that.

A rate limit now waits. `rateLimitWait` reads the headers GitHub answers
with: `x-ratelimit-remaining: 0` waits until `x-ratelimit-reset`, and
`retry-after` waits that long. Each waits only up to
`dispatch.githubRetry.rateLimitMaxWaitSeconds`, so a reset hours away still
throws, as does a 403 carrying neither header — a permission refusal no wait
fixes. Every job's `timeout-minutes` now clears that wait, since a job killed
mid-wait would waste it and fail anyway.

A run says what it spends. The same request hook counts REST and GraphQL
calls, retries included, and `resolve` and each `act` leg log
`api: <n> REST, <m> GraphQL`, with the credential they spent it on.

One comment read serves a leg, which is what those counts found. `loadRecord`
paged from the oldest comment while the comment window read the newest, so
every leg spent two or three calls on one endpoint: three of an issue leg's
six REST calls, and three of a PR leg's nine, on every leg of every event
run. One page of 100 serves both wherever a thread is strictly under a page.
An issue leg is now 4 REST and a PR leg 7, measured. At exactly one page, and
when GitHub's comment count has lagged the thread, the two reads stand.

And under pressure an event run sheds its drift targets. They are nearly all
of what it spends — up to `reconcileMaxPerEvent` full gathers in their own
`act` legs against the event's one — and in a burst many runs in one repo
pick the same drifted items. Below `dispatch.rateLimitFloor` REST calls left,
an event run returns only its own targets and logs that it shed the rest; the
cron's full pass covers them. `GET /rate_limit` is exempt from the limit, so
asking costs nothing, and a budget that cannot be read sheds nothing.
Schedule and `workflow_dispatch` runs are untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
Three sections for the three things the 2026-11-20 outage changed, and the
setup the App switch needs.

`why.md` gets why a rate limit is the one 4xx that is weather, why one page of
comments serves an `act` leg, and why the dispatcher needs a budget of its
own — including the part that forces it: requests an App makes on a user's
behalf come off that user's limit, so a cloud session cannot use one.

`routine-setup.md` §0c has the App itself: the slug `identity.dispatcherLogins`
expects, the permissions, the two org settings, how to confirm the switch
took, and the five calls nobody has proved the App can make. Each of those
keeps the PAT until someone settles it on a scratch PR.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
…he timeout invariant

Two defects in the token step, both caught before a merge rather than by one.

**The step `if:` read a secret, and `secrets` is not a context a step-level
`if:` can read.** GitHub rejects the expression, so the whole workflow would
have failed to parse — in all five repos at once, on the next event, with no
rollback but another PR. The gate is now `vars.SYDEVS_APP_ID` alone, which a
step `if:` may read, and `continue-on-error: true` does the job the second
clause was for: a missing or bad private key, or a transient failure minting
the token, falls back to the PAT instead of failing the job. The fallback is
visible, not silent — the run logs `token: pat`, and `routine-setup.md` §0c
step 6 is to check for `token: app` after the switch.

**`@v2` is a major behind.** v3.0.0 landed in March 2026 and the action's own
README uses `@v3`.

And the invariant nothing was holding: `rateLimitMaxWaitSeconds` is one value
in `loop-config.json`, while "the job must outlive the wait" was seven
hand-set `timeout-minutes` and seven comments. Lowering a timeout or raising
the wait would silently reinstate the failure this branch exists to end.
`timeouts.test.mjs` reads both — the workflow by the path `dispatch.workflow`
names — and asserts every job clears the wait, and that no `if:` in the file
reads a secret.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
The /simplify pass over this branch, which found that the branch had added
several parallel ways to say one thing.

**One predicate for "is this login ours".** `contracts.mjs` had grown a local
`writers()` Set that re-did `isLogin`'s case-folding membership test, so the
branch shipped three spellings of one question. It now calls `isLogin` with
the list, keeping the soft "no identity is configured" answer the gate needs
where `isLogin` would throw, and computing the list after the cheap `state`
and `draft` guards rather than before them.

**`isLogin` takes a list, not a list or a string.** No production caller
passed a string once `dispatcherLogins` existed, so the union was dead
generality that a reader had to resolve at every call site — and a bare string
now throws with a message saying so, which is the same loud failure the
original guard was for. `pickFeaturePr` keeps the sessions' login and now says
why: a feature PR is a session's, and a session cannot act as the App.

**One home for the comment page sizes and the page arithmetic.** `WINDOW_PAGE`
and `FULL_PAGE` are named once, and `lastPage` is shared, so the one-read path
and the two-read path cannot drift to different windows. `newestWindow` loses a
`page > 1` conjunct that could never change its result — on the first page
`start` is 0, and `slice(-perPage)` of a list that short is the whole list.

**The lagging-count path no longer pays for a read it already made.** It used
to fetch page 1, discard it, and have `loadRecord` re-issue the identical
request. The record is among the oldest comments, so the page in hand almost
always holds it; failing that, `loadRecord` resumes at page 2.

**One delay in `withRetry`.** The rate-limit arm and the 5xx arm each re-tested
the attempt count and owned a `sleep`, with a `continue` to skip the other. One
`delay` value answers both, so a third class of retriable failure is one more
arm rather than one more copy of the bookkeeping.

**`restRemaining` returns `Infinity`, not `null`,** when the budget cannot be
read. The floor check is then one comparison instead of three, and the
`null < 1000` coercion the `!== null` clause existed to guard against cannot
arise.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
…ounded wait

Four defects the review pass found, each of which would have landed with the
App switch and been read as the App "not working".

**The permission list was wrong, and would have 403'd every PR leg.** §0c
listed Issues, Pull requests, Contents, Workflows, Projects and Metadata —
the set the ticket proposed. But `gather` reads check runs and commit statuses
on every PR leg, `contracts-sync` posts a commit status before it opens a PR
under `set -e`, and the `deps` job reads Dependabot alerts. Checks read,
Commit statuses read and write, and Dependabot alerts read are now listed,
each with the thing that dies without it. The `SYDEVS_BOT_PAT` row had the
same gap — which is where §0c's list came from — so it is corrected too.

**One App has two logins, and only one was named.** REST spells a GitHub App
`<slug>[bot]`; GraphQL spells the same actor `<slug>`. `cheapView`'s PR
authors and `reviewThreads`' comment authors are GraphQL, so the App's own
contract-sync and deps PRs would have read as an outsider's — making each one
a permanent drift target on every event run and cron pass, which spends more
API budget rather than less. `isLogin` now compares the bare slug, so one
`dispatcherLogins` entry matches both spellings.

**The wait could run to twice its cap.** `attempts` allowed two rate-limit
sleeps of `rateLimitMaxWaitMs` in one request, so a request could sleep 30
minutes while `resolve`'s job is capped at 20 — killed mid-wait, which is the
failure the wait exists to end. The cap now bounds a request's waits in total.

**Four jobs had a timeout that promised a wait they could not take.**
`installRetry` was called only from `resolveTargets` and `act`, so
`journalTick`, `depsTick`, `planContractSync` and `verifyContractSync` had no
retry at all — not even for a 5xx, which is why the journal tick, documented
as a writer that cannot stop, could stop on one. All four install it now, and
`timeouts.test.mjs` asserts every job's entry point does.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
…e suffix

The previous commit taught `isLogin` to strip a trailing `[bot]` so one config
entry could match REST's `<slug>[bot]` and GraphQL's `<slug>`. That is the
wrong shape for this predicate.

`isBot` gates the contract-sync approval, the proxy approval, mark-ready and
auto-merge arming, so the set of logins it trusts should be exactly what
`loop-config.json` names — reviewable as data, on one screen. Normalising the
suffix instead extends trust to the bare form of every entry anyone adds
later, without that being written down anywhere.

So the comparison is exact again, and `identity.dispatcherLogins` carries both
spellings. The exposure that remains is explicit rather than implied: the bare
slug is a name a user account could hold, which `routine-setup.md` now says
not to let happen, and the firmer fix is GraphQL's `__typename` — trusting a
bare slug only for a `Bot` actor — which is a follow-up.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
The security pass found a hole I had opened two commits earlier, and it is
the one that mattered on this branch.

GraphQL spells a GitHub App by its bare slug, so I had listed
`sydevs-dispatcher` in `identity.dispatcherLogins` to make `cheapView`'s PR
authors and `reviewThreads`' comment authors match. But that is a plain
username nobody owns, these five repos are public, and `findRecord`
authenticates the dispatcher's own record by author login alone. The chain:
register the name, comment on any issue with a body opening
`<!-- sydevs-status v1 {"pending":{"handler":"…"}} -->`, and the next
reconcile pass reads that forged record and fires an autonomous session,
holding the org credential, on text the attacker wrote. No push access, no org
membership, nothing but a free GitHub account. Worse, `saveRecord` would then
keep writing real dispatcher state into a comment the attacker can still edit.

So the bare slug is not trusted. `restLogin` normalises a GraphQL actor to
REST's spelling, the two queries whose authors reach `isBot` now select
`__typename` beside `login`, and `dispatcherLogins` holds only
`sydevs-bot` and `sydevs-dispatcher[bot]` — which no username can be, because
`[` is not legal in one. The App still recognises its own PRs and threads, by
the normalisation rather than by widening the trusted set.

And the part of the chain that was not mine: `case 'retry'` fired
`rec.pending.handler` straight from the record, unchecked, where `case 'fire'`
checks `enabledHandlers`. Both now go through `fireable`, which also requires
the handler to be one `loop-config.json` names — a handler out of a comment
body is data, not a plan.

`routine-setup.md` §0c carried my wrong claim that reaching anything dangerous
with the bare slug still needed push access. It does not, and that sentence is
gone.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
The troubleshooting row said only `identity.expectedLogin` is read back, which
was true before this branch. The dispatcher now reads back every login in
`identity.dispatcherLogins`, and keeping the old one there is what makes a
migration quiet — which is exactly why the App switch adds `sydevs-dispatcher[bot]`
beside `sydevs-bot` instead of replacing it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVYGe4vnCMobKB7FXx
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 21, 2026
@sydevs-bot

sydevs-bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running
CI fix 1

recent dispatches
  • 00:09Z address-review · attempt 1 · session · done
  • 00:09Z address-review · attempt 1 · session
  • 23:51Z resolve-conflicts · attempt 1 · session · done
  • 23:51Z resolve-conflicts · attempt 1 · session
  • 23:28Z resolve-conflicts · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 21, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

The diff is the ticket's four parts and nothing else: the wait, the counts, the one-page read, the floor and the App are each an acceptance criterion, so none is a scope finding, and the ceiling change the cost argument invites is correctly refused instead. The risky half is the widened trust set, and it is handled the right way round — restLogin normalises at the GraphQL boundary, so the list holds only logins no username can be, rather than a bare slug findRecord would authenticate on. What is left is one wrong list inside the new guard, and five pieces that fold.

Findings

  • should-fix — apply.mjs:38: fireable tests config.handlers, which holds $comment and audit-nightly; dispatch.handlers is the dispatchable set.
  • should-fix — the PR body: ## Summary names neither the forged-record hole nor the handler check. That is what a merge decision turns on, and it is read first.
  • should-fix — Streamline, four threads: contracts.mjs:24, retry.mjs:80, resolve.mjs:63, gather.mjs:69.
  • consider — dispatcher.yml:79: seven copies of the token step; the rejection note understates that contract-check is already referenced cross-repo.

What was checked

Ticket #296 against the diff. Read whole on the branch: retry, resolve, gather, record, decide, apply, contracts, reconcile, dispatcher.yml, workflow-state.yml, payload.mjs. newestWindow reproduces the old two-call window at six thread lengths. All three GraphQL author selections checked — contracts.mjs:88 correctly stays expectedLogin. Every isLogin caller passes a list; all 7 jobs mint and fall back, under secrets: inherit. Gate: 423 dispatcher + 156 lib tests pass. No ## Preview, no fixture, no question threads. Streamliner: 21 pieces, 16 kept, 5 flagged, 4 held.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread dispatcher/apply.mjs Resolved
Comment thread dispatcher/contracts.mjs Resolved
Comment thread dispatcher/retry.mjs Resolved
Comment thread dispatcher/resolve.mjs Resolved
Comment thread dispatcher/gather.mjs Resolved
Comment thread .github/workflows/dispatcher.yml Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Nov 21, 2026
sydevs-bot and others added 8 commits November 21, 2026 02:29
`fireable` tested `config.handlers`, which keys `$comment` and
`audit-nightly` beside the nine the dispatcher fires. `enabledHandlers` is
null, so a forged status comment naming `audit-nightly` passed the new guard
and fired the nightly audit routine on the item it was posted to.
`payload.mjs` read the same wide block, so the session accepted it too.

Both now test `dispatch.handlers`, the list the dispatcher's own set lives in.
`audit-nightly` is cron-fired on its own routine and never carries a record,
so narrowing costs nothing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZ4VuydzZWDG2LCJQN
…writers

`writers` in contracts.mjs existed only to re-filter the one arm
`dispatcherLogins` left unfiltered: the fallback `[expectedLogin]`, which is
`[undefined]` when no identity is configured. Filtering it at the source
leaves both callers reading `dispatcherLogins(config)` and testing `.length`
as they already did, and `isLogin` still throws on an empty list.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZ4VuydzZWDG2LCJQN
`apiCounts` had one non-test caller, `apiCountLine`, six lines below it. The
destructuring default carries the "no hook installed" case, and the test
asserts the log string either way, so the behaviour stays pinned.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZ4VuydzZWDG2LCJQN
…ntinel

`restRemaining` had one caller, which already guarded on `floor` — and where
`floor` is 0 the shed cannot fire at all. So the `Infinity` sentinel spared
no comparison a guard. The read is now a try/catch beside its one use, and
the comparison tests `Number.isFinite`. All four budget cases pass unchanged:
an unreadable budget, and now a reply carrying no core resource, shed nothing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZ4VuydzZWDG2LCJQN
The middle arm of `recordAndComments` served only a comment count that lagged
the thread past 100 mid-leg, and it was the sole reason `loadRecord` grew a
`startPage` parameter. A count that lagged now falls through to the paging
tail, which costs one extra call in a race nobody has seen and buys back the
parameter. The lagged-count test still asserts the first read and the record.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZ4VuydzZWDG2LCJQN
…checked

`case 'timeout'` re-fired `rec.current.handler` straight from the record,
where `case 'fire'` and `case 'retry'` now both go through `fireable`. It
reads from the same comment body, so it is data too. The check sits after the
lock and the lease come off, so a refusal leaves the item open rather than
stuck.

Found by the branch's security pass, which rated it a real inconsistency and
not exploitable today: only the loop's own logins can write a trusted record,
and `payload.mjs` refuses the same strings on the session side.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZ4VuydzZWDG2LCJQN
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Five of six threads built, one rebutted. Base merged clean.

Adopted

Rebutted

  • dispatcher.yml:79 — the precedent correction is right and in the body. But a composite step cannot carry continue-on-error.

Gate: 425 + 157 tests pass.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Nov 21, 2026
The `test` check failed on "Plugin files changed but version is still
5.10.0". This branch ships a change to `workflow/lib/payload.mjs`, which an
install reads, and the cache directory is named after `version`, so the
change would never reach an installed plugin.

The branch never bumped the version itself. It merged `main` at 03cd9ea, and
#294 had already taken 5.10.0 there, so base and head arrived at the same
string. The earlier green run on 3afc529 proves the collapse rather than
contradicting it: at that head nothing under `workflow/lib` had changed yet,
so the step exited before comparing. `payload.mjs` changed in b7b72c2, after
the merge.

5.10.1, not 5.11.0: the one shipped change is a guard on a handler name, and
main reserves a minor for a feature.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVt9URFoNsCm6Qw4j9
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 22, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 22, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 22, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 22, 2026
…cher-rate-limit

# Conflicts:
#	docs/routine-setup.md
The merge of main at d0399bb took main's 5.11.2, which #304 had already
set there, so base and head arrived at the same string for the second
time on this branch. This branch still ships `workflow/lib/payload.mjs`,
which an install reads, and the cache directory is named after
`version`, so the `test` check's version step would fail on "Plugin
files changed but version is still 5.11.2" and the change would never
reach an installed plugin.

5.11.3, not 5.12.0: the one shipped change is still the guard on a
handler name.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXfYGHJxHG2zEUyMkk
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main (69c5eb8). One conflict, in docs/routine-setup.md: both sides rewrote the SYDEVS_BOT_PAT row. I kept both — this branch's widened permission set (Commit statuses write, Checks and Dependabot alerts read), plus #306's sentence naming the three contractSync consumers that Commit statuses write must reach.

A second commit bumps the plugin version to 5.11.3. The merge took main's 5.11.2, which #304 had already set there, so base and head collapsed to one string again and the test check's version step would have failed on this branch's payload.mjs change.

Lean gate ✓ 162 lib tests. Dispatcher suite ✓ 425. claude plugin validate . ✓.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 22, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 22, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 22, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 22, 2026
…cher-rate-limit

main's #300 gave the event run a reclaim pass — `expiredLockTargets`, which
reads a record per locked item — and this branch gave the same function a
budget floor and a wider trusted set. Both sides are kept.

# Conflicts:
#	dispatcher/index.mjs
#	dispatcher/resolve.mjs
#	dispatcher/sweep.mjs
#	dispatcher/test/resolve.test.mjs
#	loop-config.json

`dispatcher/sweep.mjs` is the one hunk git merged cleanly and wrongly.
main's new `expiredLockTargets` reads `config.identity.expectedLogin`, a
string, and passes it to `loadRecord`; on this branch `isLogin` throws
unless the trusted set is a list, and the caller swallows that throw with
`catch { continue }`. The textual merge therefore reclaims nothing, for
ever, in silence. The declaration becomes `dispatcherLogins(config)`, and
the one in `listSweepTargets` goes: main moved the only read of it into the
new function. Three of main's own tests fail without this.

`dispatcher/resolve.mjs` keeps both passes behind one floor check, so an
event run under `dispatch.rateLimitFloor` keeps only its own targets and
the cron covers both the reclaim and the drift. Each side had written the
shed as covering what it knew about; the merged comment says what it now
covers. A review thread asks whether the reclaim should be exempt.

`dispatcher/index.mjs` keeps the `try`/`finally` that logs what a resolve
leg spent, with main's `eventLabel(context)` inside it.

`dispatcher/test/resolve.test.mjs` keeps both suites. main's fixture gains
a readable REST budget above the floor: without one it reclaims only
because `resolve` cannot read a budget at all, which would hide a floor
regression rather than test the reclaim.

`loop-config.json` keeps main's sentence on what `reconcileMaxPerEvent`
caps and this branch's two on `githubRetry` and `rateLimitFloor`.

Gates from the worktree: `claude plugin validate ./workflow --strict` ✓,
`node --test workflow/lib/*.test.mjs` 162 ✓, `node --test
dispatcher/test/*.test.mjs` 440 ✓, `claude plugin validate .` ✓,
`comment-lint.mjs --base origin/main` ✓.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYdN4RMqb2w2cA3xjY
The line read "shedding the drift targets" because the floor landed before
main's reclaim pass existed. The early return keeps only the event's own
targets, so it now sheds the expired-lock reclaim as well, and a log that
names one of two is a log that sends a reader to the wrong place.

The budget test matches `under the floor of 1000`, so the tail is free to
say what the code does.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYdN4RMqb2w2cA3xjY

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 question for the reviewer, one per thread.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread dispatcher/resolve.mjs Resolved
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main in. Five files conflicted; the one worth reading is dispatcher/sweep.mjs, which git merged cleanly and wrongly.

main's new expiredLockTargets hands config.identity.expectedLogin — a string — to loadRecord. On this branch isLogin throws unless the trusted set is a list, and the caller swallows that with catch { continue }, so the textual merge reclaims nothing, silently, for ever. Three of main's own tests fail on it. The declaration is now dispatcherLogins(config), and listSweepTargets loses its copy: main moved the only read into the new function.

resolve keeps both passes behind one floor check, so under dispatch.rateLimitFloor an event run keeps only its own targets and the cron covers the reclaim as well as the drift. One review thread asks whether the reclaim should be exempt.

Gates from the worktree: lean gate ✓, dispatcher suite 440 ✓, root manifest ✓, comment-lint ✓.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 23, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 23, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 23, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 23, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Nov 23, 2026
Merged via the queue into main with commit 5e6bf00 Nov 23, 2026
62 of 64 checks passed
@sydevs-bot
sydevs-bot deleted the claude/fix-296-dispatcher-rate-limit branch November 23, 2026 00:12
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Working to Done in SYDevelopers Technical Roadmap Nov 23, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Answered the one open thread. Nothing to push.

  • A — shed both passes (thread): the branch already does that. resolve returns early under dispatch.rateLimitFloor before cheapView, so an event run keeps only its own targets and the 7,37 cron covers the reclaim as well as the drift. No commit — the built option stands. Resolved.

Merged origin/main (a4f3cb1) locally. Clean, one docs line, nothing else to push, so the merge stays local.

Refreshed the body: the resolve outline still read cheapView → driftTargets, from before #300's reclaim pass arrived, and Test results carried the pre-merge counts.

Lean gate ✓ 162 lib tests. Dispatcher suite ✓ 440.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

fix(dispatcher): survive the rate limit and get its own API budget

3 participants