opencode-model-router 2.7.0 → 2.9.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 (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
@@ -0,0 +1,488 @@
1
+ // UnattendedPolicy (task 4.2.2): the inbox, parking, answers and the circuit breaker (memo phase-4.2.md §1-§3).
2
+ import type {
3
+ Attempt, ExecutorConfig, ExecutorEventInput, InboxItem, InboxKind, IsoTime, JsonValue, LeaseService, LedgerV1,
4
+ LedgerWriter, PhaseId, QaLoop, TaskId, TaskState, TransitionTrigger, UnattendedPolicy, Waker, Clock,
5
+ } from "./types.js";
6
+ import {
7
+ ExecutorError, QA_CAP_OPTIONS, TRANSITION_TRIGGERS, countsTowardMaxAttempts, formatInboxId, isBreakerFailure,
8
+ nextInboxNumber,
9
+ } from "./types.js";
10
+ import { edgeSatisfied } from "./schedule.js";
11
+
12
+ /** Diagnostics sink with the shape of `RuntimeDeps.log`. */
13
+ export type UnattendedLog = (level: "info" | "warn" | "error", msg: string, detail?: JsonValue) => void;
14
+
15
+ export interface UnattendedDeps {
16
+ writer: LedgerWriter;
17
+ /** Only `releaseTask` is used (P3). */
18
+ leases: Pick<LeaseService, "releaseTask">;
19
+ waker: Waker;
20
+ /** Only `onCapAnswer` is used (U4, QA9). */
21
+ qa: Pick<QaLoop, "onCapAnswer">;
22
+ clock: Clock;
23
+ log: UnattendedLog;
24
+ /**
25
+ * pdf2-1 (b): called by `park` before the batch that clears the task's slot (`task-slot slot:null`), while the task still
26
+ * holds `slot`; the runtime saves the slot's work there. QA-PDF21-3: `false` or a throw means the work could not be
27
+ * saved: the park goes on but keeps the slot (no `task-slot slot:null`, no lease release), so nothing resets or
28
+ * releases it; the runtime raises the blocking item that names the slot.
29
+ */
30
+ beforeSlotRelease?(taskId: TaskId, slot: string, cause: ParkCause): Promise<boolean | void>;
31
+ /** QA-PDF21-7: the options of the park item `park` writes for `taskId` (none by default). */
32
+ parkOptions?(taskId: TaskId, cause: ParkCause): readonly string[];
33
+ }
34
+
35
+ export const INBOX_TEXT_MAX = 4000; // U3
36
+
37
+ /** Counter key of the "attempt fed to the breaker" marker; the runtime's `BREAKER_FED` (runtime.ts) uses the same key. */
38
+ export const BREAKER_FED = "breaker-fed";
39
+
40
+ export function boundInboxText(s: string): string {
41
+ return s.length <= INBOX_TEXT_MAX ? s : `${s.slice(0, INBOX_TEXT_MAX)}…`;
42
+ }
43
+
44
+ /** The cause of a park, as `UnattendedPolicy.park` takes it (rows 17, 36). */
45
+ export type ParkCause = Parameters<UnattendedPolicy["park"]>[1];
46
+
47
+ /** U1: escalate and ambiguity are questions; qa-unparsable and exhausted are failures. All blocking. */
48
+ export function parkItemKind(cause: ParkCause): { kind: InboxKind; severity: "blocking" } {
49
+ return { kind: cause === "escalate" || cause === "ambiguity" ? "question" : "failure", severity: "blocking" };
50
+ }
51
+
52
+ /**
53
+ * P2: the pending transitive dependents of `taskId` over dependency edges. A direct dependent gets `dep-parked`, a deeper one
54
+ * `dep-blocked`. Only pending tasks are included and traversed; breadth-first, sorted by id per level.
55
+ */
56
+ export function pendingDependentsClosure(
57
+ l: Readonly<LedgerV1>, taskId: TaskId,
58
+ ): Array<{ id: TaskId; trigger: "dep-parked" | "dep-blocked" }> {
59
+ const out: Array<{ id: TaskId; trigger: "dep-parked" | "dep-blocked" }> = [];
60
+ const seen = new Set<TaskId>([taskId]);
61
+ let level: TaskId[] = [taskId];
62
+ let direct = true;
63
+ while (level.length > 0) {
64
+ const next = new Set<TaskId>();
65
+ for (const from of level) {
66
+ for (const e of l.edges) {
67
+ if (e.from !== from || seen.has(e.to)) continue;
68
+ const t = Object.hasOwn(l.tasks, e.to) ? l.tasks[e.to] : undefined;
69
+ if (t !== undefined && t.state === "pending") next.add(e.to);
70
+ }
71
+ }
72
+ const sorted = [...next].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
73
+ for (const id of sorted) {
74
+ seen.add(id);
75
+ out.push({ id, trigger: direct ? "dep-parked" : "dep-blocked" });
76
+ }
77
+ level = sorted;
78
+ direct = false;
79
+ }
80
+ return out;
81
+ }
82
+
83
+ const SUCCESS_STATES: readonly TaskState[] = ["done", "verified", "integrating", "integrated"];
84
+
85
+ function ms(t: IsoTime): number {
86
+ return Date.parse(t);
87
+ }
88
+
89
+ /** B1: the breaker window start of a phase: the createdAt of its newest breaker item (null = all attempts). */
90
+ function breakerWindowStart(l: Readonly<LedgerV1>, phaseId: PhaseId): number | null {
91
+ let start: number | null = null;
92
+ for (const item of l.inbox) {
93
+ if (item.kind !== "breaker" || item.taskId === null) continue;
94
+ const t = Object.hasOwn(l.tasks, item.taskId) ? l.tasks[item.taskId] : undefined;
95
+ if (t === undefined || t.phase !== phaseId) continue;
96
+ const at = ms(item.createdAt);
97
+ if (start === null || at >= start) start = at;
98
+ }
99
+ return start;
100
+ }
101
+
102
+ /**
103
+ * QA-4.2-19: states a task with a succeeded, verdict-less latest attempt can hold without a commit failure: still
104
+ * committing, verifying, landing or finished, and `conflict`/`reverted`, which only follow a landed commit.
105
+ */
106
+ const NOT_COMMIT_FAILED_STATES: readonly TaskState[] =
107
+ ["completed", "verifying", "verified", "integrating", "integrated", "done", "cancelled", "conflict", "reverted"];
108
+
109
+ /**
110
+ * A2 (amendment A-4.2-2 to B1): a systemic post-child failure is a breaker FAILURE. The child succeeded without a
111
+ * verdict, yet its task went `completed -> failed` (trigger `commit-failed`: E_IDENTITY / E_GIT, or "no changes" while
112
+ * writes were declared). The ledger keeps no transition list, so the fact is derived. A non-latest succeeded attempt
113
+ * with no verdict was followed by a retry, which only `commit-failed` allows (`completed` leaves for `failed` only
114
+ * that way). The latest one counts whenever the task is outside `NOT_COMMIT_FAILED_STATES` (QA-4.2-19): `failed`, or
115
+ * the `ready`/`parked`/`blocked` the retry decision moves it to right after the feed, so the sample outlives the move.
116
+ */
117
+ export function isCommitFailure(t: Readonly<LedgerV1["tasks"][string]>, a: Attempt): boolean {
118
+ if (a.outcome !== "succeeded" || a.verdict !== null) return false;
119
+ return a !== t.attempts[t.attempts.length - 1] || !NOT_COMMIT_FAILED_STATES.includes(t.state);
120
+ }
121
+
122
+ /**
123
+ * B1: the counted samples of a phase since its newest breaker item, ordered by endedAt, then (taskId, n).
124
+ * Pure function of the ledger, so a restart rebuilds it exactly.
125
+ */
126
+ export function breakerSamples(
127
+ l: Readonly<LedgerV1>, phaseId: PhaseId,
128
+ ): Array<{ taskId: TaskId; n: number; endedAt: IsoTime; failure: boolean }> {
129
+ const start = breakerWindowStart(l, phaseId);
130
+ const out: Array<{ taskId: TaskId; n: number; endedAt: IsoTime; failure: boolean }> = [];
131
+ for (const t of Object.values(l.tasks)) {
132
+ if (t.phase !== phaseId) continue;
133
+ t.attempts.forEach((a, i) => {
134
+ if (a.endedAt === null || !countsTowardMaxAttempts(a)) return;
135
+ if (start !== null && !(ms(a.endedAt) > start)) return;
136
+ const nextStart = t.attempts[i + 1]?.startedAt ?? null;
137
+ const lo = ms(a.startedAt);
138
+ const hi = nextStart === null ? Number.POSITIVE_INFINITY : ms(nextStart);
139
+ const flaky = l.inbox.some((it) => {
140
+ if (it.kind !== "flaky" || it.taskId !== t.id) return false;
141
+ const at = ms(it.createdAt);
142
+ return at >= lo && at < hi;
143
+ });
144
+ if (flaky) return;
145
+ const failure = isBreakerFailure(a) || isCommitFailure(t, a);
146
+ const latest = i === t.attempts.length - 1;
147
+ const success = !failure && a.outcome === "succeeded" &&
148
+ (a.verdict === "pass" || (a.verdict === null && latest && SUCCESS_STATES.includes(t.state)));
149
+ if (!failure && !success) return;
150
+ out.push({ taskId: t.id, n: a.n, endedAt: a.endedAt, failure });
151
+ });
152
+ }
153
+ out.sort((x, y) => {
154
+ const d = ms(x.endedAt) - ms(y.endedAt);
155
+ if (d !== 0) return d;
156
+ if (x.taskId !== y.taskId) return x.taskId < y.taskId ? -1 : 1;
157
+ return x.n - y.n;
158
+ });
159
+ return out;
160
+ }
161
+
162
+ /**
163
+ * B2 (amendment X11): N samples, F failures, C trailing run of failures. The ratio rule is STRICT: F > failureRatio * N
164
+ * (the epsilon keeps 6/15 at ratio 0.4 from tripping on float noise); the consecutive rule is C >= consecutiveFailures.
165
+ */
166
+ export function breakerTrips(
167
+ s: ReturnType<typeof breakerSamples>, c: ExecutorConfig["circuitBreaker"],
168
+ ): { tripped: boolean; reason: "ratio" | "consecutive" | null; failures: number; attempts: number; consecutive: number } {
169
+ const attempts = s.length;
170
+ let failures = 0;
171
+ let consecutive = 0;
172
+ for (const x of s) {
173
+ if (x.failure) { failures += 1; consecutive += 1; } else consecutive = 0;
174
+ }
175
+ const ratio = attempts >= c.minAttempts && failures > c.failureRatio * attempts + 1e-9;
176
+ const run = consecutive >= c.consecutiveFailures;
177
+ const reason = ratio ? "ratio" : run ? "consecutive" : null;
178
+ return { tripped: reason !== null, reason, failures, attempts, consecutive };
179
+ }
180
+
181
+ function taskOf(l: Readonly<LedgerV1>, id: TaskId | null): Readonly<LedgerV1["tasks"][string]> | undefined {
182
+ if (id === null) return undefined;
183
+ return Object.hasOwn(l.tasks, id) ? l.tasks[id] : undefined;
184
+ }
185
+
186
+ /** The phase an inbox item belongs to: the phase of its task. */
187
+ function itemPhase(l: Readonly<LedgerV1>, item: InboxItem): PhaseId | null {
188
+ return taskOf(l, item.taskId)?.phase ?? null;
189
+ }
190
+
191
+ function openItemOf(l: Readonly<LedgerV1>, taskId: TaskId): InboxItem | undefined {
192
+ for (let i = l.inbox.length - 1; i >= 0; i -= 1) {
193
+ const it = l.inbox[i];
194
+ if (it !== undefined && it.taskId === taskId && it.answer === null) return it;
195
+ }
196
+ return undefined;
197
+ }
198
+
199
+ /**
200
+ * QA-4.2-5: the item the park batch of a parked task created. `park` writes the item text and the latest attempt's
201
+ * context from the same bounded string, so the park item is the newest open question/failure item of the task whose
202
+ * text equals that context. If no item matches (a later writer changed the context), the oldest open question/failure
203
+ * item of the task is used: the park item is older than anything raised after the park.
204
+ */
205
+ export function parkItemOf(l: Readonly<LedgerV1>, t: Readonly<LedgerV1["tasks"][string]>): InboxItem | undefined {
206
+ const last = t.attempts[t.attempts.length - 1];
207
+ const cands = l.inbox.filter((x) => x.taskId === t.id && x.answer === null && (x.kind === "question" || x.kind === "failure"));
208
+ if (last !== undefined) {
209
+ // Both sides bounded: a legacy context longer than INBOX_TEXT_MAX still matches its (bounded) park item.
210
+ const marker = boundInboxText(last.context);
211
+ for (const c of [...cands].reverse()) {
212
+ if (boundInboxText(c.text) === marker) return c;
213
+ }
214
+ }
215
+ return cands[0];
216
+ }
217
+
218
+ const RUNNING_CAUSES: readonly ParkCause[] = ["escalate", "ambiguity", "qa-unparsable", "budget-cap"];
219
+
220
+ /**
221
+ * pdf2-1 (a): the `running -> parked` trigger of a running cause: the cause itself (`budget-cap` included, which
222
+ * `TRANSITION_TRIGGERS["running>parked"]` admits). A cause the table does not admit for that pair is refused here, before
223
+ * any batch, rather than by the ledger's replay.
224
+ */
225
+ export function runningParkTrigger(cause: ParkCause): { trigger: TransitionTrigger; detail: string | null } {
226
+ if (TRANSITION_TRIGGERS["running>parked"]?.includes(cause) !== true) {
227
+ throw new ExecutorError("E_INVALID_INPUT", `${cause} does not park a running task`, { cause });
228
+ }
229
+ return { trigger: cause, detail: null };
230
+ }
231
+ const EXHAUSTED_FROM: readonly TaskState[] = ["conflict", "failed", "reverted"];
232
+
233
+ export function createUnattendedPolicy(d: UnattendedDeps): UnattendedPolicy {
234
+ const wakeInbox = async (id: string): Promise<void> => {
235
+ try {
236
+ await d.waker.wake("inbox", `inbox:${id}`);
237
+ } catch (e) {
238
+ d.log("warn", "inbox wake failed", e instanceof Error ? e.message : String(e));
239
+ }
240
+ };
241
+ const releaseLeases = (taskId: TaskId): void => {
242
+ try {
243
+ d.leases.releaseTask(taskId);
244
+ } catch (e) {
245
+ d.log("warn", "lease release failed", e instanceof Error ? e.message : String(e));
246
+ }
247
+ };
248
+
249
+ /**
250
+ * QA-4.2-22: journals that attempt `n` of `taskId` was fed to `recordAttempt`, with the exact shape of the runtime's
251
+ * `markFed` (a `counter` metric, a history event), so the runtime's breaker re-feed does not feed it again.
252
+ * A failed append is logged: the worst case is one duplicate evaluation, which trips at most once per window.
253
+ */
254
+ const markFed = async (phaseId: PhaseId, taskId: TaskId, n: number): Promise<void> => {
255
+ try {
256
+ await d.writer.append([{
257
+ type: "metric", metric: { name: "counter", key: BREAKER_FED, value: 1, labels: { phaseId, taskId, n: String(n) } },
258
+ }]);
259
+ } catch (e) {
260
+ d.log("warn", "breaker-fed marker append failed", e instanceof Error ? e.message : String(e));
261
+ }
262
+ };
263
+
264
+ const raise: UnattendedPolicy["raise"] = async (i) => {
265
+ const text = boundInboxText(i.text);
266
+ const out: { item: InboxItem | null; written: boolean } = { item: null, written: false };
267
+ await d.writer.append((l) => {
268
+ const dup = l.inbox.find((x) => x.answer === null && x.kind === i.kind && x.taskId === i.taskId && x.text === text);
269
+ if (dup !== undefined) {
270
+ out.item = dup;
271
+ out.written = false;
272
+ return [];
273
+ }
274
+ const item: InboxItem = {
275
+ id: formatInboxId(i.kind, nextInboxNumber(l)), kind: i.kind, severity: i.severity, taskId: i.taskId, text,
276
+ options: [...i.options], answer: i.answer ?? null, createdAt: d.clock.iso(),
277
+ };
278
+ out.item = item;
279
+ out.written = true;
280
+ return [{ type: "inbox-added", item }];
281
+ });
282
+ const item = out.item;
283
+ if (item === null) throw new ExecutorError("E_PLAN_STATE", "inbox item was not produced");
284
+ if (out.written && item.answer === null) await wakeInbox(item.id);
285
+ return item;
286
+ };
287
+
288
+ const park: UnattendedPolicy["park"] = async (taskId, cause, text) => {
289
+ const bounded = boundInboxText(text);
290
+ const out: {
291
+ item: InboxItem | null; written: boolean; releaseSlot: boolean; feed: { phaseId: PhaseId; nonce: string } | null;
292
+ } = { item: null, written: false, releaseSlot: false, feed: null };
293
+ const t0 = taskOf(d.writer.ledger, taskId);
294
+ if (t0 === undefined) {
295
+ throw new ExecutorError("E_INVALID_INPUT", `unknown task ${taskId}`, { taskId });
296
+ }
297
+ // pdf2-1 (b): the slot's work is saved before the batch below clears the slot. QA-PDF21-3: a failed save keeps it on
298
+ // the parked task (A1-7 lets a parked task hold a slot for this; before that amendment the batch was refused).
299
+ let keptSlot: string | null = null;
300
+ if (t0.slot !== null && d.beforeSlotRelease !== undefined) {
301
+ try {
302
+ if ((await d.beforeSlotRelease(taskId, t0.slot, cause)) === false) keptSlot = t0.slot;
303
+ } catch (e) {
304
+ keptSlot = t0.slot;
305
+ d.log("warn", "saving the slot's work before the park failed; the slot is kept", e instanceof Error ? e.message : String(e));
306
+ }
307
+ }
308
+ let options: string[] = [];
309
+ try {
310
+ options = [...(d.parkOptions?.(taskId, cause) ?? [])];
311
+ } catch (e) {
312
+ d.log("warn", "park options failed", e instanceof Error ? e.message : String(e));
313
+ }
314
+ await d.writer.append((l) => {
315
+ out.written = false;
316
+ out.releaseSlot = false;
317
+ out.feed = null;
318
+ const t = taskOf(l, taskId);
319
+ if (t === undefined) throw new ExecutorError("E_INVALID_INPUT", `unknown task ${taskId}`, { taskId });
320
+ const legal = RUNNING_CAUSES.includes(cause)
321
+ ? t.state === "running"
322
+ : cause === "exhausted" && EXHAUSTED_FROM.includes(t.state);
323
+ if (!legal) {
324
+ const open = openItemOf(l, taskId);
325
+ if (open === undefined) {
326
+ throw new ExecutorError("E_PLAN_STATE", `task ${taskId} is ${t.state}: cannot park (${cause})`, { taskId });
327
+ }
328
+ out.item = open;
329
+ return [];
330
+ }
331
+ const events: ExecutorEventInput[] = [];
332
+ const now = d.clock.iso();
333
+ if (RUNNING_CAUSES.includes(cause)) {
334
+ const last = t.attempts[t.attempts.length - 1];
335
+ if (last !== undefined) {
336
+ if (last.endedAt === null) {
337
+ events.push({
338
+ type: "attempt-ended", taskId, n: last.n, outcome: cause === "qa-unparsable" ? "failed" : "interrupted",
339
+ endedAt: now, detail: cause,
340
+ });
341
+ }
342
+ events.push({ type: "attempt-context", taskId, n: last.n, context: bounded });
343
+ if (cause === "qa-unparsable") out.feed = { phaseId: t.phase ?? "", nonce: last.nonce };
344
+ }
345
+ events.push({ type: "task-transition", taskId, from: "running", to: "parked", ...runningParkTrigger(cause) });
346
+ } else {
347
+ // QA-4.2-5: the same marker as the running causes, so `answer` can tell the park item from any other item.
348
+ const last = t.attempts[t.attempts.length - 1];
349
+ if (last !== undefined) events.push({ type: "attempt-context", taskId, n: last.n, context: bounded });
350
+ events.push({ type: "task-transition", taskId, from: t.state, to: "parked", trigger: "exhausted", detail: null });
351
+ }
352
+ if (t.slot !== null && t.slot !== keptSlot) {
353
+ events.push({ type: "task-slot", taskId, slot: null, branch: t.branch });
354
+ out.releaseSlot = true;
355
+ }
356
+ if (cause !== "exhausted" && t.kind === "qa" && t.phase !== null) {
357
+ const ph = l.phases.find((p) => p.id === t.phase);
358
+ if (ph !== undefined && ph.gate === "qa-running") {
359
+ events.push({
360
+ type: "gate-changed", phaseId: ph.id, from: "qa-running", to: "awaiting-qa", trigger: "qa-requeued",
361
+ qaRound: ph.qaRound,
362
+ });
363
+ }
364
+ }
365
+ const kind = parkItemKind(cause);
366
+ const item: InboxItem = {
367
+ id: formatInboxId(kind.kind, nextInboxNumber(l)), kind: kind.kind, severity: kind.severity, taskId, text: bounded,
368
+ options: [...options], answer: null, createdAt: now,
369
+ };
370
+ events.push({ type: "inbox-added", item });
371
+ for (const dep of pendingDependentsClosure(l, taskId)) {
372
+ events.push({
373
+ type: "task-transition", taskId: dep.id, from: "pending", to: "blocked", trigger: dep.trigger, detail: taskId,
374
+ });
375
+ }
376
+ out.item = item;
377
+ out.written = true;
378
+ return events;
379
+ });
380
+ const item = out.item;
381
+ if (item === null) throw new ExecutorError("E_PLAN_STATE", "park produced no inbox item");
382
+ if (!out.written) return item;
383
+ if (out.releaseSlot) releaseLeases(taskId);
384
+ await wakeInbox(item.id);
385
+ if (out.feed !== null && out.feed.phaseId !== "") {
386
+ const t = taskOf(d.writer.ledger, taskId);
387
+ const a = t?.attempts.find((x) => x.nonce === out.feed?.nonce);
388
+ if (a !== undefined) {
389
+ await recordAttempt(out.feed.phaseId, a);
390
+ await markFed(out.feed.phaseId, taskId, a.n);
391
+ }
392
+ }
393
+ return item;
394
+ };
395
+
396
+ const answer: UnattendedPolicy["answer"] = async (inboxId, text) => {
397
+ const item0 = d.writer.ledger.inbox.find((x) => x.id === inboxId);
398
+ if (item0 === undefined || item0.answer !== null) {
399
+ throw new ExecutorError("E_INVALID_INPUT", `inbox item ${inboxId} is not open`, { inboxId });
400
+ }
401
+ if (item0.kind === "qa-cap" && item0.severity === "critical") {
402
+ const choice = text.trim().toLowerCase();
403
+ const opt = QA_CAP_OPTIONS.find((o) => o === choice && item0.options.includes(o));
404
+ if (opt === undefined) {
405
+ throw new ExecutorError("E_INVALID_INPUT", `answer must be one of ${item0.options.join(", ")}`, { inboxId });
406
+ }
407
+ await d.qa.onCapAnswer(inboxId, opt);
408
+ return { resumed: null };
409
+ }
410
+ const out: { resumed: TaskId | null } = { resumed: null };
411
+ await d.writer.append((l) => {
412
+ out.resumed = null;
413
+ const item = l.inbox.find((x) => x.id === inboxId);
414
+ if (item === undefined || item.answer !== null) {
415
+ throw new ExecutorError("E_INVALID_INPUT", `inbox item ${inboxId} is not open`, { inboxId });
416
+ }
417
+ const events: ExecutorEventInput[] = [{ type: "inbox-answered", id: inboxId, answer: text }];
418
+ const t = taskOf(l, item.taskId);
419
+ if (item.kind === "breaker") {
420
+ const phaseId = itemPhase(l, item);
421
+ const ph = phaseId === null ? undefined : l.phases.find((p) => p.id === phaseId);
422
+ if (ph !== undefined && ph.paused) {
423
+ const other = l.inbox.some((x) =>
424
+ x.id !== inboxId && x.answer === null && x.severity === "critical" && itemPhase(l, x) === ph.id);
425
+ if (!other) events.push({ type: "phase-paused", phaseId: ph.id, paused: false, reason: "breaker answered" });
426
+ }
427
+ } else if (t !== undefined && t.state === "parked" && parkItemOf(l, t)?.id === item.id) {
428
+ const last = t.attempts[t.attempts.length - 1];
429
+ if (last !== undefined) events.push({ type: "attempt-context", taskId: t.id, n: last.n, context: text });
430
+ events.push({ type: "task-transition", taskId: t.id, from: "parked", to: "ready", trigger: "answered", detail: inboxId });
431
+ out.resumed = t.id;
432
+ }
433
+ return events;
434
+ });
435
+ return { resumed: out.resumed };
436
+ };
437
+
438
+ const unblock: UnattendedPolicy["unblock"] = async () => {
439
+ const ids: TaskId[] = [];
440
+ await d.writer.append((l) => {
441
+ ids.length = 0;
442
+ const events: ExecutorEventInput[] = [];
443
+ for (const t of Object.values(l.tasks)) {
444
+ if (t.state !== "blocked") continue;
445
+ const ok = l.edges.every((e) => e.to !== t.id || edgeSatisfied(l, e));
446
+ if (!ok) continue;
447
+ ids.push(t.id);
448
+ events.push({ type: "task-transition", taskId: t.id, from: "blocked", to: "ready", trigger: "dep-recovered", detail: null });
449
+ }
450
+ return events;
451
+ });
452
+ return [...ids];
453
+ };
454
+
455
+ const recordAttempt: UnattendedPolicy["recordAttempt"] = async (phaseId, a) => {
456
+ const l0 = d.writer.ledger;
457
+ const owner = Object.values(l0.tasks).find((t) => t.attempts.some((x) => x.nonce === a.nonce));
458
+ if (owner === undefined) return { tripped: false };
459
+ const att: Attempt = owner.attempts.find((x) => x.nonce === a.nonce) ?? a;
460
+ if (!isBreakerFailure(att) && !isCommitFailure(owner, att)) return { tripped: false };
461
+ const out: { item: InboxItem | null } = { item: null };
462
+ await d.writer.append((l) => {
463
+ out.item = null;
464
+ const ph = l.phases.find((p) => p.id === phaseId);
465
+ if (ph === undefined || ph.paused) return [];
466
+ const open = l.inbox.some((x) => x.kind === "breaker" && x.answer === null && itemPhase(l, x) === phaseId);
467
+ if (open) return [];
468
+ const r = breakerTrips(breakerSamples(l, phaseId), l.config.circuitBreaker);
469
+ if (!r.tripped) return [];
470
+ const kind: InboxKind = "breaker";
471
+ const item: InboxItem = {
472
+ id: formatInboxId(kind, nextInboxNumber(l)), kind, severity: "critical", taskId: owner.id,
473
+ text: `phase ${phaseId} circuit breaker: ${r.failures}/${r.attempts} failed (${r.reason ?? "none"}), ${r.consecutive} consecutive`,
474
+ options: [], answer: null, createdAt: d.clock.iso(),
475
+ };
476
+ out.item = item;
477
+ return [
478
+ { type: "phase-paused", phaseId, paused: true, reason: "breaker" },
479
+ { type: "inbox-added", item },
480
+ ];
481
+ });
482
+ if (out.item === null) return { tripped: false };
483
+ await wakeInbox(out.item.id);
484
+ return { tripped: true };
485
+ };
486
+
487
+ return { raise, park, answer, unblock, recordAttempt };
488
+ }
@@ -65,7 +65,9 @@ export function createGuardStore(options: GuardStoreOptions = {}) {
65
65
  * Start a new dispatch round for an existing session: reset the
66
66
  * per-dispatch tool-call count while preserving cumulative totals,
67
67
  * redundancy fingerprints and deliverable state. No-op for sessions
68
- * that were never guarded (nothing to reset).
68
+ * that were never guarded (nothing to reset). Every resume opens one:
69
+ * a routed task-tool resume, a tier `chat.message` resume and an
70
+ * executor budget resume (QA-PDF21-2-11, `DispatchBookkeeping.beginResumeRound`).
69
71
  */
70
72
  beginDispatch(sessionID: string): void {
71
73
  const s = states.get(sessionID);