opencode-model-router 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
@@ -7,6 +7,7 @@ import {
7
7
  type TierConfig,
8
8
  } from "../router/config";
9
9
  import { getActiveTiers } from "../router/protocol";
10
+ import { isIncompleteReason } from "../verify/checker";
10
11
  import {
11
12
  DEFAULT_VARIANT,
12
13
  buildVariantLadder,
@@ -170,8 +171,14 @@ export interface LadderVerdict {
170
171
  pass: boolean;
171
172
  outcome?: "pass" | "fail" | "unverifiable";
172
173
  reasons?: string[];
174
+ /** The gate classified the return as incomplete (verify/checker.ts isIncompleteVerdict). */
175
+ incomplete?: boolean;
173
176
  }
174
177
 
178
+ /** QA-P15-2-9: the give-up reason of an incomplete return — resume the same session, no escalation. */
179
+ export const INCOMPLETE_GIVE_UP_REASON =
180
+ "incomplete: the producer stopped before a final result; resume the same session to let it finish, no producer escalation";
181
+
175
182
  // ---------------------------------------------------------------------------
176
183
  // Helpers
177
184
  // ---------------------------------------------------------------------------
@@ -393,6 +400,11 @@ export function nextAction(
393
400
  // Strict policy may reject an unavailable check, but paying another producer
394
401
  // cannot repair the verifier. Only actual failures enter the retry ladder.
395
402
  if (verdict?.outcome === "unverifiable") {
403
+ // QA-P15-2-9: an incomplete return (progress note, budget stop) is neither a
404
+ // verifier limitation nor a failure: the same session resumes to finish it.
405
+ if (verdict.incomplete === true || (verdict.reasons ?? []).some(isIncompleteReason)) {
406
+ return { action: "give_up", reason: INCOMPLETE_GIVE_UP_REASON };
407
+ }
396
408
  return { action: "give_up", reason: "verification unavailable; no producer escalation" };
397
409
  }
398
410
 
@@ -2,14 +2,28 @@ import {
2
2
  evaluateGuards,
3
3
  updateState,
4
4
  recordBlock,
5
+ recordDenied,
5
6
  forcingMessage,
6
7
  observationOk,
8
+ guardStopped,
9
+ deniedCapDecision,
7
10
  } from "./guards";
8
11
  import type { GuardPolicy, GuardCall, GuardState } from "./guards";
9
12
  import { scrubText } from "./scrub";
10
13
  import { resolveEnforcementMode } from "../router/enforcement";
11
14
  import type { EnforcementMode } from "../router/enforcement";
12
15
  import type { RouterConfig } from "../router/config";
16
+ import {
17
+ GUARD_CUMULATIVE_MULTIPLIER,
18
+ TIER_GUARD_BUDGET,
19
+ positiveBudget,
20
+ readerReason,
21
+ } from "../router/guard-profile";
22
+ import type { GuardProfile } from "../router/guard-profile";
23
+ import { getActiveTiers } from "../router/protocol";
24
+ import { isReadOnlyTier } from "../router/read-only";
25
+ import { lookupDispatch } from "../router/sessions";
26
+ import type { Cap } from "../router/sessions";
13
27
 
14
28
  /**
15
29
  * Default total tool-call ceiling for an enforced subagent delegation. This is a
@@ -17,14 +31,14 @@ import type { RouterConfig } from "../router/config";
17
31
  * Deliberately generous so enforced mode never false-stops ordinary work;
18
32
  * tuned with field data in Phase 4.3 (preliminary).
19
33
  */
20
- export const DEFAULT_GUARD_BUDGET = 25;
34
+ export const DEFAULT_GUARD_BUDGET = TIER_GUARD_BUDGET;
21
35
 
22
36
  /**
23
37
  * The cumulative ceiling spans resumed dispatches: it is this multiple of the
24
38
  * effective per-dispatch budget (configured or default), giving resumed
25
39
  * subagents bounded room without unbounded same-session loops.
26
40
  */
27
- export const CUMULATIVE_BUDGET_MULTIPLIER = 3;
41
+ export const CUMULATIVE_BUDGET_MULTIPLIER = GUARD_CUMULATIVE_MULTIPLIER;
28
42
 
29
43
  /** Default-case cumulative budget, retained for imports/tests. */
30
44
  export const CUMULATIVE_GUARD_BUDGET =
@@ -39,19 +53,123 @@ export interface GuardStoreLike {
39
53
 
40
54
  /** Build a GuardPolicy from config for a given subagent tier. deliverableSignal
41
55
  * is null in Wave 1 (Mode A/B signal wiring lands in Wave 2/4), which disables
42
- * the deliverable-first clause — the honest common case (M5). */
43
- export function buildGuardPolicy(cfg: RouterConfig, tier: string | null): GuardPolicy {
56
+ * the deliverable-first clause — the honest common case (M5).
57
+ *
58
+ * Without `profile` (tier agents) the result is unchanged: the configured or
59
+ * default budget (25) and cumulative ×3. A role `profile` (§2.6) supplies the
60
+ * total and cumulative budgets, the reader/producer kind, and the
61
+ * `NEED MORE: budget` exhaustion instruction; an invalid profile budget falls
62
+ * back to the tier budget, and the cumulative ceiling is never below it. */
63
+ export function buildGuardPolicy(
64
+ cfg: RouterConfig,
65
+ tier: string | null,
66
+ profile?: GuardProfile | undefined,
67
+ ): GuardPolicy {
44
68
  const g = cfg.enforcement?.guard ?? {};
45
- const budget = g.budget ?? DEFAULT_GUARD_BUDGET;
69
+ const tierBudget = g.budget ?? DEFAULT_GUARD_BUDGET;
70
+ const budget = profile ? (positiveBudget(profile.budget) ?? tierBudget) : tierBudget;
71
+ const cumulative = profile
72
+ ? Math.max(budget, positiveBudget(profile.cumulative) ?? budget * CUMULATIVE_BUDGET_MULTIPLIER)
73
+ : budget * CUMULATIVE_BUDGET_MULTIPLIER;
46
74
  return {
47
75
  budget,
48
- cumulativeBudget: budget * CUMULATIVE_BUDGET_MULTIPLIER,
76
+ cumulativeBudget: cumulative,
49
77
  readDraftCap: g.readDraftCap ?? 3,
50
78
  sameOpRetryCap: g.sameOpRetryCap ?? 1,
51
79
  blockSelfScript: g.blockSelfScript ?? true,
52
80
  deliverableFirst: g.deliverableFirst ?? true,
53
81
  blockScriptWrites: g.blockScriptWrites ?? false,
54
82
  deliverableSignal: null,
83
+ ...(profile ? { reader: profile.kind === "reader", needMoreOnExhaustion: true } : {}),
84
+ };
85
+ }
86
+
87
+ /**
88
+ * §2.9 E6: does this tier dispatch read rather than produce? A role profile
89
+ * decides alone; otherwise a read-only tier (#78), a routed class
90
+ * review/recon/search (the process-wide dispatch registry), or an uncapped
91
+ * dispatch: `cap` is the CURRENT dispatch round's honoured CAP directive, read by
92
+ * the caller from the session store (sessions.ts getCap), which a resume resets
93
+ * (QA-P15-1-3) — so it is known before the first call and never outlives a round.
94
+ */
95
+ function isReaderDispatch(
96
+ cfg: RouterConfig,
97
+ tier: string | null,
98
+ sessionID: string,
99
+ profile: GuardProfile | undefined,
100
+ cap: Cap | null | undefined,
101
+ ): boolean {
102
+ let readOnlyTier = false;
103
+ if (tier !== null && cfg.presets) {
104
+ const tiers = getActiveTiers(cfg);
105
+ const definition = tiers && Object.prototype.hasOwnProperty.call(tiers, tier) ? tiers[tier] : undefined;
106
+ readOnlyTier = definition !== undefined && isReadOnlyTier(tier, definition);
107
+ }
108
+ return (
109
+ readerReason({
110
+ profile,
111
+ readOnlyTier,
112
+ taskClass: lookupDispatch(sessionID)?.facts.class ?? null,
113
+ cap: cap ?? null,
114
+ }) !== null
115
+ );
116
+ }
117
+
118
+ // budgetExhausted: process-wide (one guard store per plugin instance; every instance
119
+ // guards the same child), bounded, most recently guarded sessions kept.
120
+ const MAX_TRACKED_BUDGETS = 1000;
121
+ const trackedBudgets = new Map<string, { state: GuardState; cumulativeBudget?: number }>();
122
+
123
+ function trackBudget(sessionID: string, state: GuardState, policy: GuardPolicy): void {
124
+ trackedBudgets.delete(sessionID);
125
+ trackedBudgets.set(sessionID, { state, cumulativeBudget: policy.cumulativeBudget });
126
+ // Re-inserted above, so the first key is the least recently guarded session.
127
+ while (trackedBudgets.size > MAX_TRACKED_BUDGETS) {
128
+ trackedBudgets.delete(trackedBudgets.keys().next().value as string);
129
+ }
130
+ }
131
+
132
+ /** Guards whose ENFORCED refusal is a stop: the child must return now (QA-P15-2-1). */
133
+ const STOP_GUARDS: ReadonlySet<string> = new Set(["iteration_cap", "cumulative_iteration_cap", "denied_cap"]);
134
+
135
+ /**
136
+ * True when the guard really STOPPED the session in its current dispatch round:
137
+ * an enforced refusal by iteration_cap, cumulative_iteration_cap or denied_cap
138
+ * (QA-P15-2-1). Never in advisory mode (nothing is refused), never for a child
139
+ * that merely finished at exactly its budget, false after a resume and for a
140
+ * session never guarded or no longer tracked. P-5: the after-hook annotates the
141
+ * parent's result from this.
142
+ */
143
+ export function budgetExhausted(sessionID: string): boolean {
144
+ const tracked = trackedBudgets.get(sessionID);
145
+ return tracked !== undefined && tracked.state.stopped?.round === tracked.state.dispatches;
146
+ }
147
+
148
+ /** What the guard knew about a producer session when its task returned (QA-P15-2-2, 2-5). */
149
+ export interface BudgetSnapshot {
150
+ /** The guard tracked the session (false: enforcement off, never guarded, or evicted). */
151
+ tracked: boolean;
152
+ /** budgetExhausted: an enforced stop in the returning round. */
153
+ stopped: boolean;
154
+ /** Budget or refusals used up — validates a `NEED MORE: budget` claim. */
155
+ usedUp: boolean;
156
+ /** The session store's read-only counter reached its cap (calls >= cap). */
157
+ readCapReached?: boolean;
158
+ }
159
+
160
+ /**
161
+ * Capture a producer session's budget state at the moment its task returns
162
+ * (QA-P15-2-5): the gate judges that snapshot, not the live state at
163
+ * verification time. `readCapReached` comes from the session store
164
+ * (sessions.ts readCapReached), which the guard cannot see.
165
+ */
166
+ export function captureBudget(sessionID: string, readCapReached?: boolean): BudgetSnapshot {
167
+ const tracked = sessionID === "" ? undefined : trackedBudgets.get(sessionID);
168
+ return {
169
+ tracked: tracked !== undefined,
170
+ stopped: tracked !== undefined && tracked.state.stopped?.round === tracked.state.dispatches,
171
+ usedUp: tracked !== undefined && guardStopped(tracked.state, tracked),
172
+ ...(readCapReached !== undefined ? { readCapReached } : {}),
55
173
  };
56
174
  }
57
175
 
@@ -74,7 +192,8 @@ export function formatScorecard(state: GuardState, tier: string | null): string
74
192
  * mode this returns immediately WITHOUT creating guard state, so the after-hook
75
193
  * stays a no-op and behaviour is byte-identical (GA-1).
76
194
  */
77
- export function guardBeforeCall(params: {
195
+ /** The inputs of one guarded call (the before-hook's, and those of a call refused outside the guard). */
196
+ export interface GuardCallParams {
78
197
  cfg: RouterConfig;
79
198
  tier: string | null;
80
199
  sessionID: string;
@@ -83,29 +202,42 @@ export function guardBeforeCall(params: {
83
202
  store: GuardStoreLike;
84
203
  env: Record<string, string | undefined>;
85
204
  trivial?: boolean;
86
- }): BeforeResult {
87
- const { cfg, tier, sessionID, tool, toolArgs, store, env, trivial } = params;
88
- let mode = resolveEnforcementMode({ config: cfg, tier: tier ?? undefined, env }).mode;
89
- if (
90
- mode === "enforced" &&
91
- trivial === true &&
92
- cfg.enforcement?.proportional?.trivialBypass !== false
93
- ) {
94
- mode = "advisory";
95
- }
205
+ /** Role dispatch guard profile (§2.6); absent for tier agents. */
206
+ profile?: GuardProfile;
207
+ /** The current dispatch round's honoured CAP directive (sessions.ts getCap); "none" = CAP:none + reason:. */
208
+ cap?: Cap | null;
209
+ }
210
+
211
+ /** The enforcement mode of a guarded call: a trivial dispatch's enforced mode is advisory (unless trivialBypass is off). */
212
+ function callMode(params: Pick<GuardCallParams, "cfg" | "tier" | "env" | "trivial">): EnforcementMode {
213
+ const { cfg, tier, env, trivial } = params;
214
+ const mode = resolveEnforcementMode({ config: cfg, tier: tier ?? undefined, env }).mode;
215
+ return mode === "enforced" && trivial === true && cfg.enforcement?.proportional?.trivialBypass !== false ? "advisory" : mode;
216
+ }
217
+
218
+ export function guardBeforeCall(params: GuardCallParams): BeforeResult {
219
+ const { cfg, tier, sessionID, tool, toolArgs, store, profile, cap } = params;
220
+ const mode = callMode(params);
96
221
  if (mode === "off") return { block: false, mode };
97
222
 
98
- const policy = buildGuardPolicy(cfg, tier);
223
+ const policy = buildGuardPolicy(cfg, tier, profile);
99
224
  const state = store.ensure(sessionID, policy);
225
+ trackBudget(sessionID, state, policy);
226
+ if (isReaderDispatch(cfg, tier, sessionID, profile, cap)) policy.reader = true;
100
227
  const call: GuardCall = { tool, args: (toolArgs ?? {}) as Record<string, unknown> };
101
228
  const decision = evaluateGuards(state, call, policy);
102
229
 
103
230
  if (decision.allow) return { block: false, mode, guard: null };
104
231
 
105
232
  if (mode === "enforced") {
106
- // Count the refused attempt so the budget cannot be spun, then signal a block.
107
- updateState(state, call, { ok: false }, policy);
233
+ // §2.9 E6: the refused call never runs, so it is not charged to the budget
234
+ // and not recorded as executed by the repeat check; CLAUSE 3c bounds a loop
235
+ // of refusals instead.
236
+ recordDenied(state, call, policy);
108
237
  recordBlock(state, decision);
238
+ if (decision.guard !== null && STOP_GUARDS.has(decision.guard)) {
239
+ state.stopped = { round: state.dispatches, guard: decision.guard };
240
+ }
109
241
  const message = scrubText(`${decision.observation}\n${forcingMessage(state, policy)}`);
110
242
  return { block: true, mode, message, guard: decision.guard };
111
243
  }
@@ -120,6 +252,36 @@ export function guardBeforeCall(params: {
120
252
  return { block: false, mode, guard: decision.guard };
121
253
  }
122
254
 
255
+ /**
256
+ * QA-G-A3-2 (§2.9 E6, R7 REFUSAL_CAP): a call refused OUTSIDE the guard — the router's role-authority check in the v2 adapter's
257
+ * `execute.before` (thrown before the guard's own before-hook runs) or a host permission denial — is a refused call of the
258
+ * child's dispatch round all the same. It is counted like the guard's own refusals (`recordDenied`: not charged to the budget,
259
+ * not recorded as executed), in every mode but `off` (the refusal is real whatever the guard's mode), so `denied_cap` bounds a
260
+ * child that keeps retrying refused actions. Once the round's refusals are spent (CLAUSE 3c):
261
+ * - enforced: the guard stops the child as its before-hook would on the next call (`stopped`, denied_cap; budgetExhausted);
262
+ * - advisory: nothing is stopped; the would-stop is recorded and its banner returned.
263
+ * Returns the guard's text to add to the refusal the child sees (the denied_cap refusal, or the advisory banner), else
264
+ * undefined. Off mode: nothing at all (no guard state, GA-1).
265
+ */
266
+ export function guardRefusedCall(params: GuardCallParams): string | undefined {
267
+ const { cfg, tier, sessionID, tool, toolArgs, store, profile, cap } = params;
268
+ const mode = callMode(params);
269
+ if (mode === "off") return undefined;
270
+ const policy = buildGuardPolicy(cfg, tier, profile);
271
+ const state = store.ensure(sessionID, policy);
272
+ trackBudget(sessionID, state, policy);
273
+ if (isReaderDispatch(cfg, tier, sessionID, profile, cap)) policy.reader = true;
274
+ recordDenied(state, { tool, args: (toolArgs ?? {}) as Record<string, unknown> }, policy);
275
+ const decision = deniedCapDecision(state, policy);
276
+ if (decision === null) return undefined;
277
+ recordBlock(state, decision);
278
+ if (mode === "enforced") {
279
+ state.stopped = { round: state.dispatches, guard: "denied_cap" };
280
+ return scrubText(`${decision.observation}\n${forcingMessage(state, policy)}`);
281
+ }
282
+ return scrubText(`[\u26a0 GUARD:${decision.guard}] ${forcingMessage(state, policy)}`);
283
+ }
284
+
123
285
  /**
124
286
  * Update guard state after an ALLOWED call has executed (we now know ok), and
125
287
  * surface any pending advisory banner by appending it to the tool output.
@@ -133,11 +295,13 @@ export function guardAfterCall(params: {
133
295
  toolArgs: unknown;
134
296
  output: { output?: unknown };
135
297
  store: GuardStoreLike;
298
+ /** Role dispatch guard profile (§2.6); absent for tier agents. */
299
+ profile?: GuardProfile;
136
300
  }): void {
137
- const { cfg, tier, sessionID, tool, toolArgs, output, store } = params;
301
+ const { cfg, tier, sessionID, tool, toolArgs, output, store, profile } = params;
138
302
  const state = store.get(sessionID);
139
303
  if (!state) return;
140
- const policy = buildGuardPolicy(cfg, tier);
304
+ const policy = buildGuardPolicy(cfg, tier, profile);
141
305
  const call: GuardCall = { tool, args: (toolArgs ?? {}) as Record<string, unknown> };
142
306
  updateState(state, call, { ok: observationOk(output?.output) }, policy);
143
307
  const note = store.takePendingNote(sessionID);
@@ -1,5 +1,6 @@
1
1
  import { fingerprintToolCall } from "./fingerprint";
2
2
  import { READ_ONLY_TOOLS } from "../router/sessions";
3
+ import { REFUSAL_CAP } from "../router/guard-profile";
3
4
 
4
5
  // ---------------------------------------------------------------------------
5
6
  // Types
@@ -18,6 +19,14 @@ export interface GuardPolicy {
18
19
  deliverableIsScript?: boolean;
19
20
  /** opt-in; default false. When true, WRITE/EDIT/PATCH/MULTIEDIT to a script-extension path is treated as self_script. Off by default because writing source files is the normal coding deliverable. */
20
21
  blockScriptWrites?: boolean;
22
+ /**
23
+ * Reader profile (§2.9 E6): reading is the work, so there is no read/draft
24
+ * (consecutive-non-producing) denial and the forcing message never asks for a
25
+ * write. Absent/false = producer profile (unchanged).
26
+ */
27
+ reader?: boolean;
28
+ /** Role budget (§2.6): on exhaustion the child is told to return `NEED MORE: budget` with a progress summary. */
29
+ needMoreOnExhaustion?: boolean;
21
30
  }
22
31
 
23
32
  export interface GuardCall {
@@ -51,6 +60,20 @@ export interface GuardState {
51
60
  ttfa: number | null;
52
61
  seen: Map<string, number>;
53
62
  lastBlock: string | null;
63
+ /**
64
+ * Enforced denials in dispatch round `round` (§2.9 E6). A denied call is not
65
+ * charged to the budget, so this separate count bounds a loop of refused calls.
66
+ * Set lazily; absent = none.
67
+ */
68
+ denied?: { round: number; count: number };
69
+ /** Dispatch round whose policy last set `budget` (QA-P15-1-9: a resume takes its own budget). Set lazily. */
70
+ budgetRound?: number;
71
+ /**
72
+ * QA-P15-2-1: an ENFORCED stop — a call refused by iteration_cap,
73
+ * cumulative_iteration_cap or denied_cap in dispatch round `round`. Advisory
74
+ * mode never sets it. Set lazily.
75
+ */
76
+ stopped?: { round: number; guard: string };
54
77
  }
55
78
 
56
79
  // ---------------------------------------------------------------------------
@@ -192,7 +215,7 @@ export function evaluateGuards(
192
215
  return {
193
216
  allow: false,
194
217
  guard: "iteration_cap",
195
- observation: `DENIED: tool-call budget ${state.budget} exhausted. Stop now and emit your final answer with what you have.`,
218
+ observation: `DENIED: tool-call budget ${state.budget} exhausted. ${stopInstruction(policy)}`,
196
219
  };
197
220
  }
198
221
 
@@ -206,21 +229,35 @@ export function evaluateGuards(
206
229
  return {
207
230
  allow: false,
208
231
  guard: "cumulative_iteration_cap",
209
- observation: `DENIED: cumulative tool-call budget ${policy.cumulativeBudget} exhausted across ${state.dispatches} dispatches. Stop now and emit your final answer with what you have.`,
232
+ observation: `DENIED: cumulative tool-call budget ${policy.cumulativeBudget} exhausted across ${state.dispatches} dispatches. ${stopInstruction(policy)}`,
210
233
  };
211
234
  }
212
235
 
236
+ // CLAUSE 3c: refused calls. A denied call is not charged to the budget
237
+ // (§2.9 E6), so a model that keeps repeating refused calls would never reach
238
+ // CLAUSE 3; after min(budget, REFUSAL_CAP) refusals in this dispatch every
239
+ // call is refused (QA-P15-1-4).
240
+ const deniedCap = deniedCapDecision(state, policy);
241
+ if (deniedCap !== null) return deniedCap;
242
+
213
243
  // CLAUSE 4: redundancy
214
244
  if (kind === "read" && (state.seen.get(fp) ?? 0) >= policy.sameOpRetryCap) {
245
+ const next = policy.reader === true
246
+ ? "continue with a different call or finish"
247
+ : "take a producing action or finish";
215
248
  return {
216
249
  allow: false,
217
250
  guard: "redundant_read",
218
- observation: `DENIED: you already ran this exact read (${fp}). Reuse the result you already have; take a producing action or finish.`,
251
+ observation: `DENIED: you already ran this exact read (${fp}). Reuse the result you already have; ${next}.`,
219
252
  };
220
253
  }
221
254
 
222
- // CLAUSE 5: read_budget
223
- if (kind === "read" && state.consecutiveNonProducing >= policy.readDraftCap) {
255
+ // CLAUSE 5: read_budget — producer profile only (§2.9 E6: a reader's reads are its work)
256
+ if (
257
+ kind === "read" &&
258
+ policy.reader !== true &&
259
+ state.consecutiveNonProducing >= policy.readDraftCap
260
+ ) {
224
261
  return {
225
262
  allow: false,
226
263
  guard: "read_budget",
@@ -294,6 +331,89 @@ export function updateState(
294
331
  return state;
295
332
  }
296
333
 
334
+ // ---------------------------------------------------------------------------
335
+ // Budget helpers
336
+ // ---------------------------------------------------------------------------
337
+
338
+ /** What a budget denial tells the child to do. */
339
+ function stopInstruction(policy: GuardPolicy): string {
340
+ return policy.needMoreOnExhaustion === true
341
+ ? "Stop now and return `NEED MORE: budget` with a progress summary: what is done, what remains, and the evidence so far."
342
+ : "Stop now and emit your final answer with what you have.";
343
+ }
344
+
345
+ /** Enforced denials counted in the current dispatch round. */
346
+ function deniedThisDispatch(state: GuardState): number {
347
+ return state.denied?.round === state.dispatches ? state.denied.count : 0;
348
+ }
349
+
350
+ /** Refusals allowed in one dispatch round: min(budget, REFUSAL_CAP). */
351
+ export function refusalCap(state: GuardState): number {
352
+ return Math.min(state.budget, REFUSAL_CAP);
353
+ }
354
+
355
+ /**
356
+ * True when this dispatch round reached its refusal cap (CLAUSE 3c): at least
357
+ * refusalCap refusals AND executed + refused calls reach the per-dispatch budget
358
+ * (QA-P15-2-3: refusals never stop a child before its base budget would).
359
+ * Steps stay bounded by budget + REFUSAL_CAP.
360
+ */
361
+ export function refusalsSpent(state: GuardState): boolean {
362
+ const denied = deniedThisDispatch(state);
363
+ return denied >= refusalCap(state) && state.toolCallCount + denied >= state.budget;
364
+ }
365
+
366
+ /** CLAUSE 3c's refusal once this round's refusals are spent ({@link refusalsSpent}), else null. */
367
+ export function deniedCapDecision(state: GuardState, policy: GuardPolicy): GuardDecision | null {
368
+ if (!refusalsSpent(state)) return null;
369
+ return {
370
+ allow: false,
371
+ guard: "denied_cap",
372
+ observation: `DENIED: ${deniedThisDispatch(state)} refused tool calls in this dispatch (limit ${refusalCap(state)}). ${stopInstruction(policy)}`,
373
+ };
374
+ }
375
+
376
+ /** Budget or refusals used up (validates a `NEED MORE: budget` claim; not itself a stop). */
377
+ export function guardStopped(
378
+ state: GuardState,
379
+ policy: Pick<GuardPolicy, "cumulativeBudget">,
380
+ ): boolean {
381
+ return budgetSpent(state, policy) || refusalsSpent(state);
382
+ }
383
+
384
+ /** True when no further call fits the per-dispatch or the cumulative budget. */
385
+ export function budgetSpent(
386
+ state: GuardState,
387
+ policy: Pick<GuardPolicy, "cumulativeBudget">,
388
+ ): boolean {
389
+ return (
390
+ state.toolCallCount >= state.budget ||
391
+ (policy.cumulativeBudget !== undefined &&
392
+ state.totalToolCallCount >= policy.cumulativeBudget)
393
+ );
394
+ }
395
+
396
+ // ---------------------------------------------------------------------------
397
+ // recordDenied
398
+ // ---------------------------------------------------------------------------
399
+
400
+ /**
401
+ * Record a call the guard REFUSED (§2.9 E6). It did not run, so it is not
402
+ * charged: the tool-call counts, the read/draft streak, the repeat-check
403
+ * fingerprints and the deliverable state stay as they were. Only the attempt
404
+ * metrics move: the per-dispatch denial count (CLAUSE 3c) and, for a refused
405
+ * throwaway script, the self-script count the scorecard reports.
406
+ */
407
+ export function recordDenied(
408
+ state: GuardState,
409
+ call: GuardCall,
410
+ policy: GuardPolicy,
411
+ ): GuardState {
412
+ if (classify(call, policy) === "self_script") state.selfScriptCount += 1;
413
+ state.denied = { round: state.dispatches, count: deniedThisDispatch(state) + 1 };
414
+ return state;
415
+ }
416
+
297
417
  // ---------------------------------------------------------------------------
298
418
  // recordBlock
299
419
  // ---------------------------------------------------------------------------
@@ -323,7 +443,13 @@ export function forcingMessage(state: GuardState, policy: GuardPolicy): string {
323
443
  const next =
324
444
  policy.deliverableSignal != null && !state.deliverableExecuted
325
445
  ? `run the deliverable (${policy.deliverableSignal})`
326
- : "take a producing action (write/edit) or emit your final answer";
446
+ : refusalsSpent(state) || (policy.needMoreOnExhaustion === true && budgetSpent(state, policy))
447
+ ? policy.needMoreOnExhaustion === true
448
+ ? "return `NEED MORE: budget` with a progress summary"
449
+ : "emit your final answer"
450
+ : policy.reader === true
451
+ ? "emit your final answer"
452
+ : "take a producing action (write/edit) or emit your final answer";
327
453
 
328
454
  return `[budget ${state.toolCallCount}/${state.budget} | deliverable=${deliverable} | reads_since_produce=${state.consecutiveNonProducing}] NEXT: ${next}`;
329
455
  }
@@ -40,6 +40,11 @@ export function createGuardStore(options: GuardStoreOptions = {}) {
40
40
  if (!s) {
41
41
  s = newGuardState(policy);
42
42
  states.set(sessionID, s);
43
+ } else if (s.dispatches > 1 && s.budgetRound !== s.dispatches) {
44
+ // QA-P15-1-9: a resumed dispatch round takes its own per-dispatch budget
45
+ // (a role's `budget=` raise on the resume), set once per round.
46
+ s.budget = policy.budget;
47
+ s.budgetRound = s.dispatches;
43
48
  }
44
49
  return s;
45
50
  },