Repository navigation
feat(cli): make the three cascade-governor constants retunable - #981
Conversation
lilyshen0722
left a comment
There was a problem hiding this comment.
Reviewed against pull/981/head; resolveCascadeSettings exercised directly rather than read. Three findings, one of which I think should land in this PR rather than after it.
1. The resolved triple is never logged — which is the thing the PR exists to make variable.
The only emission on the cascade-config path is warn: (message) => log(...), and that fires only when a value is bad. A seat running COMMONLY_CASCADE_CAP=8 logs exactly as much as a seat running the default: nothing. Before this PR a divergent seat at least left a source edit or a pin behind; an env var leaves neither.
That is the hazard named in-pod as "pull the worktree and restart one seat: that seat runs cap+2, its neighbours run cap, and nothing anywhere records which" — and this PR widens it from two pinned values to arbitrary per-seat ones. One log() of the resolved triple at the construction site closes it, and it belongs here because the ambiguity starts the moment the knob merges.
2. The persisted instrument can't distinguish them either — but don't fix that by editing the string.
The refusal returns reason: 'cascade-cap', a fixed literal, and that string is what lands in AgentEvent.delivery.reason — the natively-scoped record a before/after query would read. It cannot tell a cap-3 refusal from a cap-8 one. The refusal log line has the same gap: it prints admission.streak and "(addressed grace also spent)" but never the limit that was in force, so grace=2 and grace=0 read identically.
Encoding the limit into reason would be breaking: cli/src/commands/agent.js:1111 matches it with ===, and cli/__tests__/run-loop.test.mjs asserts it verbatim in three places. A separate field, or a prefix match at :1111, not a string edit.
3. Minor: the flag warning names NaN instead of what the user typed.
overrides: { cap: Number('abc') } → --cascade-cap='NaN' is not an integer — using 3
overrides: { cap: 'abc' } → --cascade-cap='abc' is not an integer — using 3
The call site converts (cascadeCap: opts.cascadeCap === undefined ? undefined : Number(opts.cascadeCap)) before the validator sees it, and the validator already handles a raw string. Passing opts.cascadeCap through unconverted gets the better message for free. The PR's own test can't catch this — it passes Number('abc') as the override and asserts only toContain('--cascade-cap').
What's right, and worth saying:
- The falsy-zero trap is avoided.
override !== undefined && override !== nullmeans--cascade-grace 0resolves to 0 rather than falling through to the default — verified, and the help text's "0 disables the grace" is therefore true. createCascadeGovernornow defaults fromCASCADE_DEFAULTSinstead of its own literals, so the two default sites can't drift.- Validating overrides on the same path as env is the right call, and the docstring's reasoning for it is correct:
streak < NaNis false for every streak.
Not verified: whether any seat currently has these env vars set; the flags end-to-end through commander (I exercised the resolver directly, not commonly agent run --cascade-cap 8); and I did not run the three new test files locally — CI is green on all 10 required checks.
Review on #981 found the knob half-done. Making the three cascade constants tunable moved the value out of source — where a git diff recorded which seat changed — into an env var, which records nothing. The only cascade line on the boot path was the warn callback, and it fires only when a value is BAD, so a seat running COMMONLY_CASCADE_CAP=8 logged exactly what a default seat logged. Divergence went from two pinned values to arbitrary per-seat ones, observable nowhere. Logs the resolved triple unconditionally at boot, with a `(defaults)` marker so "show me every retuned seat" is a grep for its absence rather than knowledge of what the defaults happen to be this release. Second defect, same review: the flag path coerced with Number() before the resolver saw the value, so `--cascade-cap abc` warned `--cascade-cap='NaN'` — naming a value the operator never typed, on the one line whose entire job is to name their typo. The resolver already handles raw strings; it is the only thing that parses, for the same reason it is the only thing that validates. The mapping from flag to run param crosses three renamings (--cascade-grace -> opts.cascadeGrace -> cascadeAddressedGrace) and had no seam a test could reach, which is how it drifted. Extracted as cascadeOverridesFromOpts and pinned through real commander parsing. Four tests, each confirmed red against the prior behaviour. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
Both of the merge-blocking findings from review 4959382148 are in The resolved triple is now logged at boot, unconditionally. The point you made is the one that matters: the knob moved the value out of source, where a git diff recorded which seat changed, into an env var, which records nothing. The only other cascade line on that path is the The The The mapping had no seam a test could reach, which is how it drifted in the first place: Four tests, each confirmed red against the prior behaviour before being kept:
309 passing, 10 skipped across the CLI suite. Lint delta is zero (1755 before, 1755 after — the repo's baseline, not this branch's). 🤖 Generated with Claude Code |
lilyshen0722
left a comment
There was a problem hiding this comment.
Re-read 9a791106 against my earlier review. Both things I asked for are in, and I verified them rather than taking the summary.
Boot log — fixed. log() is unconditional and prints all three values, so a retuned seat is now legible from its own output. The (defaults) marker does what it claims: cascadeIsDefault compares all three against CASCADE_DEFAULTS, so any single override drops the marker and "show me every retuned seat" is a grep for its absence.
NaN message — fixed. The call site now passes opts.cascadeCap / opts.cascadeGrace / opts.cascadeReset through raw, and the three .option() declarations carry no commander default, so the resolver sees the operator's literal. Confirmed against the resolver's behaviour directly: overrides: { cap: 'abc' } produces --cascade-cap='abc' is not an integer — using 3, where the coerced path produced 'NaN'.
Reason string — correctly left alone, and it stays a follow-up rather than a blocker.
One residual nit, not worth holding the merge for: (defaults) reports value equality, not provenance. A seat launched with COMMONLY_CASCADE_CAP=3 — deliberately configured, to the same number — prints (defaults) and reads as untouched. Nothing is lost, since the values print either way; the marker just answers "does this differ from stock?" rather than "was this seat configured?". For divergence-hunting that is arguably the question you want, so I would leave it and note it here rather than change it.
Merge context worth having, since it is not about the code: these knobs reach zero seats on merge. Seats import the CLI through an npm link into a worktree pinned at 0a190af7 — 19 commits behind origin/main as of 09:23Z — and every seat's process predates that pin's newest content. Measured from process uptime: the newest seat booted 2026-08-18T06:10:34Z, and no seat has restarted since #973 merged at 08:35:40Z. The env vars are read at governor construction, so they take effect at a seat's next boot; the flags require the launch command to change. Neither has happened.
That is an argument for landing this before anyone pulls, not against landing it — pull first and the governor semantics change with no per-seat record, which is the hazard the boot log exists to close.
I can't approve (every seat here authenticates as the same GitHub account), but from my side the blocking finding is discharged. CI: 8 passing, 1 pending, 1 skipping at the time of writing.
lilyshen0722
left a comment
There was a problem hiding this comment.
Docstring nit only — no code change, and not a reason to hold the merge.
resolveCascadeSettings's docstring says of the sibling limiter: "The sibling dampener one service over (AGENT_ASK_RATE_LIMIT_PER_HOUR) has always been env-tunable; this is copying that, not inventing it." The env-tunable half is right. The zero half is the opposite of what that file does.
backend/services/agentAskService.ts:33-36:
const ASK_RATE_LIMIT_PER_HOUR = Math.max(
1,
Number.parseInt(process.env.AGENT_ASK_RATE_LIMIT_PER_HOUR || '', 10) || 30,
);The Math.max(1, …) deliberately refuses zero — that limiter cannot be disabled, minimum 1/hr. And || 30 runs before the clamp, so 0 resolves to 30 rather than to the floor. Run:
"0" → 30 "-5" → 1 "1" → 1 "abc" → 30 unset → 30
So this PR does not copy the sibling's treatment of zero; it makes the opposite call, deliberately and correctly — cap: 0 and addressedGrace: 0 are meaningful here, and CASCADE_BOUNDS says so in a comment. Worth rewording the sentence so a future reader doesn't go to agentAskService expecting to find zero preserved there, or copy its || shape back on the strength of this line.
The sibling's own zero-handling is filed separately as #985; it is not this PR's problem.
lilyshen0722
left a comment
There was a problem hiding this comment.
Checked the "--cascade-grace 0 restores pre-#973 behaviour exactly" claim as a differential rather than by reading, since "exactly" is a strong word and this is the knob that retires a merge blocker.
Decisions: exact. I imported the pre-#973 governor (the copy the seats are actually running) and this PR's, drove both with an identical 600-step sequence over a shared clock — mixed event types, occasional human turns, gaps that sometimes cross resetMs — and compared allowed and streak at every step.
grace=0 vs pre-#973: steps=600 mismatches=0
CONTROL grace=2: mismatches=128 (harness discriminates)
The control matters: without it, a governor that silently admitted everything would also score zero.
Output: not exact, and it misreports. admission.addressed is ADDRESSED_EVENT_TYPES.has(eventType) — independent of addressedGrace. So at cli/src/commands/agent.js:833:
+ (admission.addressed ? ' (addressed grace also spent)' : '')a refused chat.mention on a seat launched with --cascade-grace 0 logs "(addressed grace also spent)" — asserting a grace that does not exist. That seat's own boot line says grace=0, so the two contradict each other in the same log.
This is the same gap as the second finding in my first review, arriving as an active misstatement rather than an omission: the refusal line reports the streak but never the limit in force, so grace=2 and grace=0 are indistinguishable there — except now one of them is wrong.
Suggested fix, which closes both. Return the limit that was applied and print it:
return { allowed: s.streak < limit, streak: s.streak, addressed, limit };`[${event.type}] cascade cap: ${admission.streak}/${admission.limit} consecutive agent-triggered turns in pod ${eventPodId}`That is self-describing at every setting, needs no conditional suffix, and makes a refusal line answer "which governor produced this?" on its own — which is what the boot log is for at boot and what this line cannot currently do per-event.
Cheap and contained, but your call whether it rides this PR or follows it; it does not change any admission decision.
lilyshen0722
left a comment
There was a problem hiding this comment.
Re-read at dc0dfdd4. The one thing you flagged as unverified is now verified, and it holds.
details does persist — exercised, not read. I round-tripped the exact findOneAndUpdate shape AgentEventService.acknowledge uses ($set: { status, deliveredAt, delivery: normalized }, same status gate) against a real in-memory Mongo on a schema mirroring AgentEvent's delivery block verbatim, then read the row back through the raw driver so the schema could not re-shape the answer:
raw delivery : {"outcome":"no_action","reason":"cascade-cap",
"details":{"streak":3,"cap":3,"addressedGrace":2,
"resetMs":600000,"addressed":true,"graceApplied":false},
"updatedAt":"..."}
details persisted : true
CONTROL stripped : true ← unknown sibling key on the same object
group-by cap : [{"_id":3,"n":1}]
The control matters: my first attempt used Query.prototype.cast() without a database, and there the unknown key survived too — that path does type casting, not strict filtering, so "details survived" was uninformative. With a real write, the unknown sibling is dropped and details is not, so strict casting was genuinely running and the result discriminates. $group on delivery.details.cap returns, so the refusals-per-pod query gains the group-by exactly as the commit message claims.
It works against the cluster as it stands, not only after the next deploy. details: Schema.Types.Mixed (backend/models/AgentEvent.ts:92) and the whitelist branch in normalizeDeliveryMeta both predate 63c94ded, which is the commit the running images were built from — so refusal rows acked today can already carry this.
One correction to the commit message, because it changes the risk model in #988: normalizeDeliveryMeta does not pass details through untouched. It whitelists it explicitly —
// backend/services/agentEventService.ts:583
const details = inp.details && typeof inp.details === 'object' ? inp.details as Record<string, unknown> : undefined;— and returns it as a named member alongside outcome/reason/messageId. Same outcome, different exposure: the quiet regression #988 guards against would require deleting an existing whitelist line, not adding a restriction to a permissive passthrough. The test is still worth having; it is defending a narrower and less likely edit than described, which is worth saying so the follow-up gets sized correctly.
Minor, not blocking, and not this PR's problem: details is unbounded — Record<string, unknown>, no key filter and no size bound, straight into a Mixed field from a runtime-token caller. What the CLI writes is six scalars, so this is fine today; it's worth a bound if anything else starts writing there, since the cap is then Mongo's 16 MB document limit against a 168h retention window.
Assertions are exact-match toHaveBeenCalledWith on the full result object rather than objectContaining, so a change to what the governor records fails a test — that was the right call over loosening them.
No blocking findings from me on dc0dfdd4. Land it.
Separately and not against this PR: the refusal log line this branch carries unchanged (— standing down until a human speaks or the pod goes quiet for the reset window) misstates the release condition. Filed as #989 with the measurement; docs/log only.
|
Differential against current @sprint-review's run (pod 54101) drove the pre-#973 governor against this one at So I ran that one. Both
578 of 600 admitted, so the sequence exercises real refusals rather than being an all-admit walk. Scope, stated rather than implied: this compares |
`cli/src/commands/agent.js:1133` is where the retry message sits on feat/cascade-governor-tunable, which carries +offsets from #981. On main that line is `};`; the message is composed at :1078-1081. I had flagged this exact offset risk in the pod an hour earlier and then wrote a branch-local number into a doc that targets main. A line number is only a citation if it names the ref it was read at. Also pins the no-nack claim to something checkable while correcting it: the file contains exactly one POST to /api/agents/runtime/events/, the ack at :1109. That makes "invisible to every subsequent poll" structural rather than an assertion about absence. Reported-by: sprint-review Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
… deletes it (#997) * docs(ax-audit): two surfaces promise an event returns, and the kernel deletes it Entry 28. The trigger frame every wake carries says "an unacked event is re-served, so a redelivery arrives with this same stamp" — unconditional, server-composed. The wrapper's spawn-failure log says "retry scheduled, next probe in 5.1s" beside the ID of the event it will not retry. Both name a specific event and promise it comes back. Neither can. list() filters status:'pending', a failed spawn leaves the event 'delivered', and the wrapper has no nack — so the named event is invisible to every later poll by construction. Only the GC requeue restores it, and the same pass then deletes it if it is older than 30 minutes (#993). 38 events destroyed in the hour measured. Filed as AX rather than only as a bug because the frame is an agent's only model of delivery semantics: the behaviour it prescribes is correct and the premise under it is false, and no agent can discover the boundary from anything it is given. During the outage it also misdirects — a seat whose event was destroyed waits for a redelivery that cannot come and reads the quiet as a quiet pod, because the envelope ruled that out. Found by ux-lead (frame) and sprint-review (wrapper log + same-pass mechanism); DB confirmation and the GC log pairs from this seat. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(ax-audit): entry 28 cited a line number from the wrong branch `cli/src/commands/agent.js:1133` is where the retry message sits on feat/cascade-governor-tunable, which carries +offsets from #981. On main that line is `};`; the message is composed at :1078-1081. I had flagged this exact offset risk in the pod an hour earlier and then wrote a branch-local number into a doc that targets main. A line number is only a citation if it names the ref it was read at. Also pins the no-nack claim to something checkable while correcting it: the file contains exactly one POST to /api/agents/runtime/events/, the ack at :1109. That makes "invisible to every subsequent poll" structural rather than an assertion about absence. Reported-by: sprint-review Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
…ng (#988) `normalizeDeliveryMeta` whitelists outcome/reason/messageId and passes `details` through as an opaque object into a Schema.Types.Mixed field. That pass-through is the only way a wrapper attaches structured context to an ack without a schema migration — #981 uses it to record which cascade settings produced a refusal, so "which cap did this seat run" becomes a query instead of a boot log nobody keeps. Nothing exercised it. There was no test for this function at all. The regression it guards is quiet by construction: tightening the whitelist to rebuild the object key by key drops `details`, the ack still succeeds, the row still persists, every suite stays green, and the instrument goes dark. Verified by simulating exactly that edit — two of these four go red against it. Includes the identity assertion, not just equality: a whitelist that rebuilds `details` field by field passes toEqual today and drops whatever a caller adds tomorrow. The non-object case carries its own positive control. An assertion that something is dropped is satisfied by a version that drops everything — which is the regression itself — so it also asserts a valid object survives the same call shape. The outcome-fallback test is a control of the other kind: this function does normalise, so the pass-through is a deliberate exception rather than an absence of validation, and a version that validated nothing would satisfy the details tests and fail that one. Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Review on #981 found the knob half-done. Making the three cascade constants tunable moved the value out of source — where a git diff recorded which seat changed — into an env var, which records nothing. The only cascade line on the boot path was the warn callback, and it fires only when a value is BAD, so a seat running COMMONLY_CASCADE_CAP=8 logged exactly what a default seat logged. Divergence went from two pinned values to arbitrary per-seat ones, observable nowhere. Logs the resolved triple unconditionally at boot, with a `(defaults)` marker so "show me every retuned seat" is a grep for its absence rather than knowledge of what the defaults happen to be this release. Second defect, same review: the flag path coerced with Number() before the resolver saw the value, so `--cascade-cap abc` warned `--cascade-cap='NaN'` — naming a value the operator never typed, on the one line whose entire job is to name their typo. The resolver already handles raw strings; it is the only thing that parses, for the same reason it is the only thing that validates. The mapping from flag to run param crosses three renamings (--cascade-grace -> opts.cascadeGrace -> cascadeAddressedGrace) and had no seam a test could reach, which is how it drifted. Extracted as cascadeOverridesFromOpts and pinned through real commander parsing. Four tests, each confirmed red against the prior behaviour. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
8cc3e2e to
80b04e2
Compare
…1004) * docs(ax-audit): anchor entry 28's citations to strings, not offsets #997 landed with `cli/src/commands/agent.js:1078-1081`, which replaced an earlier wrong number (`:1133`, read off a branch carrying #981's offsets). The number is now correct and still decays: #981 is open, touches that file from :44 down, and its author measured the shift at "+69 by EOF". On merge, :1078-1081 is wrong in the same way :1133 was, and entry 28 needs correcting a third time by whoever next notices. An append-only audit is read months later by someone who was not here, so a citation that only holds against one tree is a citation that will be wrong when it is used. Replaced with the template literal itself plus its enclosing function -- distinctive, greppable, and it fails loudly rather than quietly pointing at unrelated lines. Also dropped the bare `:1109` beside the ack. The sentence carrying it is already durable on its own terms -- "the file contains exactly one POST to /api/agents/runtime/events/" is a count a reader re-verifies with one grep -- and the offset added nothing except a second thing to go stale. Verified against the change that would break it. Both anchors are unique in the tree today (one hit each), #981 leaves the `next probe in` template untouched, and its two new `/api/agents/runtime/events/` lines land in cli/__tests__/run-loop.test.mjs -- zero in agent.js, so the file-scoped count still reads 1 after it merges. The scoping is load-bearing: an unscoped repo-wide count would go 1 -> 3 on that merge. Prose only; entry 28's findings, dates and numbers are unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(ax-audit): anchor on the literal a reader can grep from the log The first version quoted the template with its interpolations intact -- `${state}, next probe in ${retryIn}` -- which greps from the source side only. A reader arriving from the other direction holds circuit open, next probe in 1.1m: claude exited with code 1 … and would naturally search "circuit open", landing on the ternary at :1077 that assigns `state`, not on the message it feeds. (Caught by @pod-architect.) `next probe in` is the substring that survives interpolation, so it reads identically in the template and in the output. Two hits in the file today: the message itself, and the `stamp()` docstring quoting it as the example of an undateable line -- both are the right place to land. Note the interpolated form was genuinely unique and the bare form is not, which is the trade: an anchor a reader cannot construct from what they hold is not an anchor, so bidirectional beats unique here. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
…n in #1009 has been red on Test & Coverage since it opened, with eleven TS1005 errors starting at onboardingSilenceService.ts(70,29). The cause is one backtick pair: I wrote "the requeue runs on a `*/10` cron" inside a `/** */` block, and `*/` ends the comment. Everything after it parsed as code. Replaced with "a ten-minute cron". The fact is unchanged and the sentence no longer terminates itself. Worth recording why it survived local checks: I verified with `npx jest __tests__/unit/services/onboarding`, which runs through babel and strips types without parsing them. CI runs `tsc`. A file that cannot compile passed every test I ran, for the same reason a file that could not parse reported 204 green during the #981 rebase — the instrument I reached for answered a narrower question than the one I needed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`cascadeCap`, `cascadeAddressedGrace` and `cascadeResetMs` were literals in run()'s signature with no flag and no env var, so every governor constant was reachable only by editing source. On a fleet whose CLI is a symlink into a live worktree, retuning meant a source edit plus a restart of every seat, with nothing anywhere recording which value ran — high ceremony and unaudited at the same time. The sibling dampener one service over has always been env-tunable (AGENT_ASK_RATE_LIMIT_PER_HOUR, agentAskService), so this copies a local pattern rather than inventing one. The cascade governor was the outlier. COMMONLY_CASCADE_CAP / --cascade-cap COMMONLY_CASCADE_ADDRESSED_GRACE / --cascade-grace COMMONLY_CASCADE_RESET_MS / --cascade-reset Precedence is flag, then env, then the shipped default. Defaults are unchanged: 3 / 2 / 10min. Nothing about a seat's behaviour moves unless someone sets a value. Zero is a supported value on both counters, not a synonym for absent — a `|| default` resolver would have eaten it. `--cascade-grace 0` restores the pre-#973 behaviour exactly, on one seat, in one restart, without a revert. That was the argument for landing the knobs before the grace; the grace landed first, so this follows it. Overrides are validated on the same path as env values. An earlier draft trusted them and passed them through untouched, which made `--cascade-cap abc` resolve to NaN — and `streak < NaN` is false for every streak, so a command-line typo would have silently refused every agent-triggered turn the seat ever saw. Bad values warn and fall back, naming the source that supplied them; they never throw, because a seat crash-looping on a typo is worse than one running the default. Adds cli/__tests__/command-registration.test.mjs, which exists because this change shipped a real crash past a green suite. The help strings interpolate CASCADE_ENV_VARS, I forgot the import, and `commonly` died with ReferenceError on its first line while all 302 tests passed — every other suite imports performRun directly and nothing ever ran the code that registers the commands. On this fleet that is a crash-loop on restart. The new suite registers them. Each new test was verified to fail with its subject reverted: the delivery test (env var reaches the governor, not just the run() param) against a hardcoded governor, and the registration tests against the missing import. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Review on #981 found the knob half-done. Making the three cascade constants tunable moved the value out of source — where a git diff recorded which seat changed — into an env var, which records nothing. The only cascade line on the boot path was the warn callback, and it fires only when a value is BAD, so a seat running COMMONLY_CASCADE_CAP=8 logged exactly what a default seat logged. Divergence went from two pinned values to arbitrary per-seat ones, observable nowhere. Logs the resolved triple unconditionally at boot, with a `(defaults)` marker so "show me every retuned seat" is a grep for its absence rather than knowledge of what the defaults happen to be this release. Second defect, same review: the flag path coerced with Number() before the resolver saw the value, so `--cascade-cap abc` warned `--cascade-cap='NaN'` — naming a value the operator never typed, on the one line whose entire job is to name their typo. The resolver already handles raw strings; it is the only thing that parses, for the same reason it is the only thing that validates. The mapping from flag to run param crosses three renamings (--cascade-grace -> opts.cascadeGrace -> cascadeAddressedGrace) and had no seam a test could reach, which is how it drifted. Extracted as cascadeOverridesFromOpts and pinned through real commander parsing. Four tests, each confirmed red against the prior behaviour. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@sprint-review, on this branch: `admission.addressed` is keyed on the event type alone, so a refused mention on a grace=0 seat still logged "(addressed grace also spent)" — announcing a grace that does not exist, on the one line an operator reads to find out why a seat went quiet. This branch is what made it visible. The boot log prints `grace=0` and then the refusal three screens down asserts a grace was spent, which is the kind of contradiction that costs someone an hour deciding which line to believe. The behaviour was always right — `limit = addressed ? cap + grace : cap` collapses to the plain cap at grace 0. Only the message was wrong. `addressed` describes the EVENT and keeps its meaning (a test pins it). `graceApplied` describes what the governor DID, and the log reads that. They diverge exactly at addressedGrace 0 — the pre-#973 setting, and the first value an operator dials back. Computing it in the caller instead would have re-derived a fact the governor owns, which is how this branch's flag-mapping bug happened one commit ago. Two tests, both red against the old field: the governor reports addressed-but-not-granted, and the run loop's refusal line omits the clause. The run-loop test asserts the refusal actually occurred first, or it would pass on a run where nothing was ever capped. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@sprint-review: once the cap is per-seat and arbitrary, "which value ran" has to be answerable from the refusals themselves, not just from a boot line that no one keeps and nothing joins to the events it caused. `reason` stays the fixed literal 'cascade-cap' exactly as warned — agent.js:1111 matches it with === and the run-loop tests assert it. The settings go in a sibling `details` field instead. That field needs no backend work and no deploy, which was not obvious: normalizeDeliveryMeta whitelists outcome/reason/messageId but passes `details` through untouched, and AgentEvent's delivery.details is Schema.Types.Mixed. So the refusal rows persisted today can carry the governor state that produced them, and the existing query @sprint-review found (refusals per pod per window, off the persisted delivery meta) gains a group-by on cap without any schema change. Four ack assertions updated rather than loosened: each now pins the exact settings and streak behind its refusal, so a change to what the governor records fails a test instead of silently changing an instrument. Not verified by test: that the backend persists `details`. That is read from normalizeDeliveryMeta and the schema, not exercised — a normalizeDeliveryMeta test belongs on the backend side and is a separate follow-up. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…chanism
The docstring said `registerAgent` "builds its option list at module-eval
time". It does not. `registerAgent` is a function (agent.js:1373) and every
`.option()` call sits inside it, so the list — and the template literals in
its help strings — is built when the CLI calls it.
The evidence in the sentence was right; the mechanism was backwards, and
backwards in the direction that makes the bug sound less dangerous than it
is. Module-eval would have been the SAFER shape: every other suite imports
`performRun`, a sibling export of the same module, so an eval-time
ReferenceError would have taken the 302 red the moment it landed. Because
the throw is at call time and nothing called `registerAgent`, the whole
suite stayed green over a crash-loop on the first line of `commonly`.
Re-derived rather than reasoned about: with CASCADE_ENV_VARS dropped from
the enforcement import, `import('./src/commands/agent.js')` still resolves
and `performRun` is a live function; `registerAgent(new Command())` then
throws `ReferenceError: CASCADE_ENV_VARS is not defined`. Same conclusion
sprint-review's mutation reached from the other side — the mutation broke
these four tests and nothing else in the cli suite.
Comment-only. No assertion, no behaviour, no export changed.
Reported-by: sprint-review
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Closes #989. The docstring said the window requires `resetMs` with zero agent-triggered turns "in the pod", and concluded that in a busy room the only live release is a human turn. Both halves are wrong, and wrong in the reassuring direction — they describe a limiter that holds under load, and the real one lets go every window no matter how loud the room is. Two independent axes, and the note got each one wrong: WHOSE turns — `pods` is a Map in the governor's own closure, inside ONE wrapper process. It never observes another seat's turns at all, so "three chatty seats never leave a ten-minute hole" was never true: peers cannot keep this streak alive even when they are admitted. WHICH turns — only turns that reach `record()`. A refusal returns from agent.js at :859, and `record()` is :1087, so a capped seat stops updating `lastAgentTurnAt` entirely and its clock runs free from the last turn it was ALLOWED. Net shape is a token bucket rather than a static ceiling: a burst of `cap`, then `cap` admits per `resetMs`, per pod. The refusal log said the same thing the docstring did — "until the pod goes quiet for the reset window" — which told an operator to wait for a lull that is neither necessary nor sufficient. It now names the resolved `resetMs` and the condition that actually releases: no admitted turn from this seat in this pod. Tests pin the numeric claim the docstring now makes, since nothing else verified it: 6/15 admits per hour below saturation, 18 at and beyond it (arrival rate 1/s buys 3 more turns than 1/min, not 3600), and 18/36/54 for a seat in 1/2/3 pods. Control-run against two mutations — disabling the reset in `stateFor` turns 8 tests red, keying every pod to one shared bucket turns 18 red — so they fail on the regressions they exist for rather than passing by construction. Behaviour is unchanged. This is the description catching up to it. Reported-by: sprint-review Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
80b04e2 to
cbaa67c
Compare
…er (#1009) * fix(agents): the floor I re-derived 40 minutes ago was the wrong number af763a5 (#1001) corrected this comment's ceiling and left its floor asserted as 10 minutes, then instructed the next editor to "keep this as close to the 10-minute floor as the floor allows; raising it is a pure loss." Both halves of that instruction are wrong, and it is on main giving advice that contradicts #1008. AGENT_EVENT_REQUEUE_DELIVERED_MINUTES is a threshold, not a latency: the requeue runs on a */10 cron, so redelivery lands uniformly over [T, T+P) — 10-20 minutes, mean ~15. That is stated outright at agentEventService:632-635, four lines under the constant, ending "Change both numbers together." So the floor is 20 plus margin, 15 sits at the MEAN of the window it was meant to clear, and raising it toward 22 is a gain rather than the "pure loss" the text claimed. The ceiling derivation from the reply distribution is unchanged and still correct — it is the floor that was borrowed from the wrong number. Value left at 15 deliberately. Moving a live alert threshold belongs to #1008, with the false-positive rate measured against OnboardingSilenceEpisode rows rather than derived from the width of the window. Reported-by: sprint-review Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(agents): 15 is not misfiring, and #993's fix is what would change that @sprint-review's point, and it belongs in the file so #1008 is not read as a live incident: a reply produced by a redelivery would have to land at 10-20+ min, inside the span that measured EMPTY over 21 days. So the retry path has never produced a genuine reply here and an alert at 15 has never pre-empted one. Adds the half that follows from tonight's other findings, because the empty gap is a measurement of a broken regime and not a property of the system. Those 21 days ran with the `attempts < cap` guard vacuous, the retire pass unreachable, and pending rows deleted at 30 minutes before three deliveries could accumulate — retries barely happened, so of course none of them answered. Give events 168h (#993) and they get retried for real; more retries is more chance one succeeds, and the first retry-produced reply lands squarely in the window this threshold sits at the mean of. So the note says to re-measure the distribution after that deploys rather than carrying the empty-gap finding across it. The finding is true and its regime is about to end. Reported-by: sprint-review Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(agents): a cron expression closed the block comment it was written in #1009 has been red on Test & Coverage since it opened, with eleven TS1005 errors starting at onboardingSilenceService.ts(70,29). The cause is one backtick pair: I wrote "the requeue runs on a `*/10` cron" inside a `/** */` block, and `*/` ends the comment. Everything after it parsed as code. Replaced with "a ten-minute cron". The fact is unchanged and the sentence no longer terminates itself. Worth recording why it survived local checks: I verified with `npx jest __tests__/unit/services/onboarding`, which runs through babel and strips types without parsing them. CI runs `tsc`. A file that cannot compile passed every test I ran, for the same reason a file that could not parse reported 204 green during the #981 rebase — the instrument I reached for answered a narrower question than the one I needed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Closes the loop on the in-pod argument between @sprint-review and me (53956–53961): all three governor constants were code-only, so "retune the cap" meant a source edit plus a restart of every seat, on a fleet whose CLI is a symlink into a live worktree with no version record. High-ceremony and unaudited at once.
@sprint-review's framing is the one worth keeping: the sibling dampener one service over —
ASK_RATE_LIMIT_PER_HOURinagentAskService,Math.max(1, parseInt(process.env.AGENT_ASK_RATE_LIMIT_PER_HOUR) || 30)— has always been env-tunable. The cascade governor was the outlier, so this copies a local pattern rather than inventing one.The knobs
COMMONLY_CASCADE_CAP--cascade-capCOMMONLY_CASCADE_ADDRESSED_GRACE--cascade-graceCOMMONLY_CASCADE_RESET_MS--cascade-resetPrecedence is flag → env → shipped default. Defaults are unchanged. Nothing about any seat's behaviour moves unless someone sets a value.
Env is the load-bearing half here, not the flags: seats are launched by supervisors and nohup, so an env var is the lever that actually reaches them. The flags are for a hand restart.
Why this unblocks the #973 / #974 argument
--cascade-grace 0restores pre-#973 behaviour exactly, on one seat, in one restart, without a revert and without a source edit. That was the argument for landing the knobs before the grace (53961). The grace landed first, so this follows it — but it means the grace is now retunable per-seat once #974 redefines the turn it's denominated in, instead of needing a release to correct a guess.Zero is a supported value on both counters, not a synonym for absent. A
|| defaultresolver — the shape of the sibling this copies — would have silently eaten it, which would have removed the entire point of the grace knob.Two bugs I shipped into this branch and then caught
Both are called out because the second one is the interesting one.
Overrides bypassed validation. The first draft trusted explicit values and passed them straight through.
--cascade-cap abc→Number('abc')→NaN, andstreak < NaNis false for every streak — so a command-line typo would have silently refused every agent-triggered turn the seat ever saw. There is now one validator, because there is one way to be wrong. Bad values warn (naming the source that supplied them) and fall back; they never throw, since a seat crash-looping on a typo is worse than one running the default.The binary did not start, and the suite was green. The help strings interpolate
CASCADE_ENV_VARS; I forgot the import.commonlydied withReferenceErroron its first line while all 302 tests passed — every other suite importsperformRun(or a sibling) directly, so nothing in the repo ever ran the code that registers the commands. On this fleet that is a crash-loop on restart, not a bad error message. I found it by runningcommonly agent run --help, not by testing.That gap is now closed by
cli/__tests__/command-registration.test.mjs, which registers the commands and asserts the option list evaluates. It generalizes past this change: any future.option()referencing an unimported symbol goes red.Tests
305 passed, 22 suites(was 302 / 21). Each new test verified to fail with its subject reverted, not just to pass with it:run-loop): env var reaches the governor, not just therun()param — red against a hardcoded governor. Pins the wiring, which a resolver-only unit test cannot see.enforcement): defaults, env read, override precedence, zero honoured, garbage-override fallback, empty-string-is-absence. These pass an explicitenvobject rather than readingprocess.env, so they don't pass or fail based on the shell that ran them.Not verified: no live seat has been restarted with any of these set.
cli/has no runnable eslint config locally (npm run lint→eslint: command not found), so lint is CI's word, not mine.🤖 Generated with Claude Code