opencode-model-router 2.8.0 → 2.9.1

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 (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -0,0 +1,2064 @@
1
+ // src/executor/types.ts
2
+ // The single cross-phase executor contract (Phase 1.4, memo 1.4.1 in docs/qa/critical-path-execution/phase-1.4.md).
3
+ // Ledger data (JSON only), the task/gate/status state machines, the event union, the guards, the launch-header
4
+ // grammar, the findings format and every interface other executor modules are built against. No I/O: the only
5
+ // runtime code is small, pure and dependency-free (canTransition, counting, guards, header, classification).
6
+
7
+ // QA-PDF21-2-18: the guard's cumulative multiplier (a pure constant) bounds BUDGET_RESUMES.
8
+ import { GUARD_CUMULATIVE_MULTIPLIER } from "../router/guard-profile";
9
+
10
+ // ---------------------------------------------------------------------------------------------------------------
11
+ // §5 Ledger data
12
+ // ---------------------------------------------------------------------------------------------------------------
13
+
14
+ /** JSON-only value: everything the ledger and its journal may hold (§5). */
15
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [k: string]: JsonValue };
16
+ /** UTC "YYYY-MM-DDTHH:mm:ss.sssZ" (§5). */
17
+ export type IsoTime = string;
18
+ export type PlanId = string;
19
+ export type TaskId = string;
20
+ export type PhaseId = string;
21
+ /** Edge source only: satisfied when `phases[id].gate === "passed"` (D-c, §5). */
22
+ export type GateRef = `gate:${string}`;
23
+
24
+ /** Ledger schema version this build reads and writes (§5). */
25
+ export const LEDGER_SCHEMA = 1 as const;
26
+ /** Plan id grammar (Appendix A 4249, §5). */
27
+ export const PLAN_ID_PATTERN = /^[a-z0-9][a-z0-9-]{2,40}$/;
28
+ /** Task id grammar: never integer-like (R14); contains no ':', '#', ']' or space (§5). */
29
+ export const TASK_ID_PATTERN = /^(?!\d+$)[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
30
+ /**
31
+ * Task ids that match `TASK_ID_PATTERN` but collide with `Object.prototype` / function property names (QA-1.4-31).
32
+ * Rejected by `isTaskId` (used by the guard and `isTaskNode`). Maps keyed by task id (`tasks`, `slots`, ...) must
33
+ * still use own-property lookups (`Object.hasOwn`, `Map`), never `obj[id]` or `id in obj`.
34
+ * (`__proto__` already fails the pattern: it starts with `_`.)
35
+ */
36
+ export const RESERVED_TASK_IDS: ReadonlySet<string> = new Set([
37
+ "constructor", "toString", "__proto__", "hasOwnProperty", "valueOf", "prototype",
38
+ "isPrototypeOf", "propertyIsEnumerable", "toLocaleString",
39
+ ]);
40
+ /** True iff `v` is a string that matches `TASK_ID_PATTERN` and is not in `RESERVED_TASK_IDS`. */
41
+ export function isTaskId(v: unknown): v is TaskId {
42
+ return typeof v === "string" && TASK_ID_PATTERN.test(v) && !RESERVED_TASK_IDS.has(v);
43
+ }
44
+ /** Attempt nonce: 128 random bits as lowercase hex (§5). */
45
+ export const NONCE_PATTERN = /^[0-9a-f]{32}$/;
46
+ /** Phase id grammar (A1-7): also a valid git ref component, no "..", no trailing ".", no ".lock" suffix. */
47
+ export const PHASE_ID_PATTERN = /^(?!.*\.\.)(?!.*\.$)(?!.*\.lock$)[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/;
48
+ /** Wave id grammar (A1-7): the same as a phase id. */
49
+ export const WAVE_ID_PATTERN = PHASE_ID_PATTERN;
50
+ /** A full git object id, SHA-1 or SHA-256, lowercase hex (A1-7). */
51
+ export const GIT_ID_PATTERN = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
52
+ /** An absolute path: drive letter, UNC or POSIX root (A1-7). */
53
+ export const ABSOLUTE_PATH_PATTERN = /^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+|\/)/;
54
+
55
+ export type LedgerStatus =
56
+ | "compiling" | "awaiting-residue" | "awaiting-approval" | "running" | "paused" | "completed" | "aborted";
57
+ export type GateState = "pending" | "suite-running" | "suite-failed" | "awaiting-qa" | "qa-running" | "passed";
58
+ export type TaskState =
59
+ | "pending" | "ready" | "dispatched" | "running" | "completed" | "verifying" | "verified"
60
+ | "integrating" | "integrated" | "done" | "failed" | "conflict" | "parked" | "blocked" | "reverted" | "cancelled";
61
+ export type TaskKind = "preflight" | "task" | "tests" | "qa" | "fix" | "manual";
62
+ export type Tier = "fast" | "medium" | "heavy";
63
+
64
+ export interface PhaseRecord {
65
+ id: PhaseId;
66
+ title: string;
67
+ wave: string;
68
+ dependsOn: string[];
69
+ gate: GateState;
70
+ /** 1-based current QA round (compile sets 1); only `qa-next-round` and `cap-fix` change it (+1 each). */
71
+ qaRound: number;
72
+ paused: boolean;
73
+ tag: string | null;
74
+ }
75
+
76
+ export interface LedgerV1 {
77
+ schema: 1;
78
+ planId: PlanId;
79
+ /** Absolute path of the plan file. */
80
+ planPath: string;
81
+ /** sha256 hex, 64 chars. */
82
+ planDigest: string;
83
+ repo: { key: string; toplevel: string; baseBranch: string; baseCommit: string };
84
+ /** `branch` is `omr/<planId>/integration`. */
85
+ integration: { branch: string; worktree: string; head: string };
86
+ launcher: "A";
87
+ status: LedgerStatus;
88
+ orchestrator: { sessionID: string; boundAt: IsoTime };
89
+ /** Resolved at compile, re-snapshotted at approval; `slotsDir` is non-null from approval on. */
90
+ config: ExecutorConfig;
91
+ /** At most `config.sharedContextChars` characters; contains no slot path. */
92
+ sharedContext: string;
93
+ waves: Array<{ id: string; phases: PhaseId[] }>;
94
+ phases: PhaseRecord[];
95
+ /** Insertion order = plan order (R14). */
96
+ tasks: Record<TaskId, TaskNode>;
97
+ edges: Edge[];
98
+ inbox: InboxItem[];
99
+ /** `seq` of the last applied event. */
100
+ seq: number;
101
+ }
102
+
103
+ export interface Footprint {
104
+ /** Repo-relative, '/'-separated, no '.'/'..' segments, no trailing '/'. */
105
+ writes: string[];
106
+ reads: string[];
107
+ confidence: "explicit" | "ownership" | "inferred" | "unknown";
108
+ sources: Array<"path" | "ownership" | "writes-line" | "llm" | "learned">;
109
+ }
110
+
111
+ export interface TaskNode {
112
+ id: TaskId;
113
+ title: string;
114
+ phase: PhaseId | null;
115
+ kind: TaskKind;
116
+ text: string;
117
+ subtasks: string[];
118
+ route: { line: string; role: string; tier: Tier | null; pin: boolean };
119
+ verify: "required" | "deferred" | "none";
120
+ acceptance: string | null;
121
+ footprint: Footprint;
122
+ /** Milliseconds, finite, 0 <= p50 <= p90. */
123
+ estimate: { p50: number; p90: number; source: string };
124
+ state: TaskState;
125
+ attempts: Attempt[];
126
+ slot: string | null;
127
+ /** `omr/<planId>/t/<encoded taskId>`. */
128
+ branch: string | null;
129
+ /** The latest integration range. */
130
+ integrated: { from: string; to: string } | null;
131
+ }
132
+
133
+ export interface Edge {
134
+ from: TaskId | GateRef;
135
+ to: TaskId;
136
+ kind: "structural" | "explicit" | "graph" | "contract" | "conflict" | "llm" | "learned";
137
+ confidence: "high" | "medium" | "low";
138
+ evidence: string;
139
+ }
140
+
141
+ export type AttemptOutcome = "succeeded" | "failed" | "interrupted" | "lost" | "capacity";
142
+ export type Verdict = "pass" | "fail" | "unverifiable";
143
+
144
+ export interface Attempt {
145
+ /** 1-based, = index + 1, for every attempt. */
146
+ n: number;
147
+ nonce: string;
148
+ /** Retained router-call id used for the launch. */
149
+ callID: string | null;
150
+ childSessionID: string | null;
151
+ /** Budget resumes of this attempt (BUDGET_RESUMES cap). */
152
+ resumes?: number;
153
+ startedAt: IsoTime;
154
+ endedAt: IsoTime | null;
155
+ outcome: AttemptOutcome | null;
156
+ verdict: Verdict | null;
157
+ /** The feedback this attempt produced (R13); starts as "". */
158
+ context: string;
159
+ }
160
+
161
+ export type InboxKind = "question" | "failure" | "usage-limit" | "landing" | "flaky" | "qa-cap" | "breaker";
162
+
163
+ /** Id prefix per inbox kind (A1-7): ids are "<P>-<n>". */
164
+ export const INBOX_ID_PREFIX: Readonly<Record<InboxKind, string>> =
165
+ { question: "Q", failure: "F", "usage-limit": "U", landing: "L", flaky: "K", "qa-cap": "R", breaker: "B" };
166
+ /** Inbox id grammar (A1-7): prefix letter, "-", a positive integer without leading zeros. */
167
+ export const INBOX_ID_PATTERN = /^([QFULKRB])-([1-9][0-9]{0,8})$/;
168
+
169
+ /** `"<P>-<n>"` for `kind`; throws E_INVALID_INPUT unless `n` is an integer in 1..999999999. */
170
+ export function formatInboxId(kind: InboxKind, n: number): string {
171
+ if (!Number.isInteger(n) || n < 1 || n > 999_999_999) {
172
+ throw new ExecutorError("E_INVALID_INPUT", "inbox number out of range", { kind, n });
173
+ }
174
+ return `${INBOX_ID_PREFIX[kind]}-${n}`;
175
+ }
176
+
177
+ /** 1 + the largest numeric part across all inbox ids of every prefix (1 for an empty inbox; malformed ids are ignored). */
178
+ export function nextInboxNumber(l: Pick<LedgerV1, "inbox">): number {
179
+ let max = 0;
180
+ for (const item of l.inbox) {
181
+ const m = INBOX_ID_PATTERN.exec(item.id);
182
+ if (m !== null && m[2] !== undefined) max = Math.max(max, Number(m[2]));
183
+ }
184
+ return max + 1;
185
+ }
186
+
187
+ /**
188
+ * `id` is "<P>-<n>" with P in {Q,F,U,L,K,R,B} by kind and n unique per plan.
189
+ * Deferred minor/nit findings (4.2.3.d) are stored as `{kind:"qa-cap", severity:"info", answer:"deferred"}`:
190
+ * they persist in the snapshot, are already closed, and trigger no wake.
191
+ */
192
+ export interface InboxItem {
193
+ id: string;
194
+ kind: InboxKind;
195
+ severity: "info" | "blocking" | "critical";
196
+ taskId: TaskId | null;
197
+ text: string;
198
+ options: string[];
199
+ answer: string | null;
200
+ createdAt: IsoTime;
201
+ }
202
+
203
+ /** Marker `<executor home>\slots\<slot>.json` (2.4.3.a); not part of `LedgerV1` (§5). */
204
+ export interface SlotRecord {
205
+ schema: 1;
206
+ /** "slot-<n>" | "integration" | "ci". */
207
+ slot: string;
208
+ path: string;
209
+ kind: "task" | "integration" | "ci";
210
+ planId: PlanId;
211
+ repoKey: string;
212
+ state: "creating" | "provisioning" | "ready" | "leased" | "resetting" | "broken" | "retired";
213
+ /** A task id or an integration entry id. */
214
+ owner: string | null;
215
+ commit: string | null;
216
+ managers: string[];
217
+ /** Repo-relative manifest path -> sha256. */
218
+ manifests: Record<string, string>;
219
+ createdAt: IsoTime;
220
+ updatedAt: IsoTime;
221
+ }
222
+
223
+ export type IntegrationStep =
224
+ | "rebase" | "checks" | "fast-forward" | "batch-checks" | "bisect" | "phase-suite"
225
+ | "suite-rerun" | "revert-build" | "revert-checks" | "revert-fast-forward" | "rollback" | "tag" | "land";
226
+ export type IntegrationStepResult = "ok" | "conflict" | "failed" | "flaky" | "pre-existing" | "refused" | "rolled-back";
227
+
228
+ /**
229
+ * Payload of `integration-step` events only (D-d, A1-3); the queue is rebuilt from the snapshot, the history journal's open
230
+ * entries and git. `kind`, `phaseId` and `baseHead` are fixed for the entry; `taskIds` and `candidate` may change (latest wins).
231
+ * A step of `fast-forward`, `revert-fast-forward`, `tag` or `land` carries its target commit in `candidate`.
232
+ */
233
+ export interface IntegrationEntry {
234
+ /** "i-<seq of first start>". */
235
+ id: string;
236
+ kind: "task" | "batch" | "revert" | "phase-suite" | "tag" | "land";
237
+ phaseId: PhaseId | null;
238
+ taskIds: TaskId[];
239
+ slot: string | null;
240
+ baseHead: string;
241
+ candidate: string | null;
242
+ }
243
+
244
+ /** An integration entry whose `closes` end has not been journaled yet, as derived from the history journal (A1-3). */
245
+ export interface OpenIntegrationEntry {
246
+ entry: IntegrationEntry;
247
+ /** `seq` of the entry's first start. */
248
+ startSeq: number;
249
+ /** The entry's latest step. */
250
+ step: IntegrationStep;
251
+ edge: "start" | "end";
252
+ result: IntegrationStepResult | null;
253
+ }
254
+
255
+ /** What `IntegrationQueue.resume()` did (A1-3). `halted` is true when the integration branch moved unexpectedly (plan paused). */
256
+ export interface ResumeReport {
257
+ completed: TaskId[];
258
+ rolledBack: TaskId[];
259
+ halted: boolean;
260
+ entries: Array<{
261
+ id: string;
262
+ kind: IntegrationEntry["kind"];
263
+ action: "completed" | "rolled-back" | "rerun" | "tagged" | "none";
264
+ }>;
265
+ }
266
+
267
+ /** A package script plus arguments, run through the allowlisted runner. */
268
+ export interface RunCommandRef {
269
+ script: string;
270
+ args: string[];
271
+ }
272
+
273
+ /** Executor configuration (Appendix C 4381-4399); ranges in `EXECUTOR_LIMITS`. */
274
+ export interface ExecutorConfig {
275
+ /** 1-8 (ADR D13 500-504), default 4. */
276
+ maxParallel: number;
277
+ /** Trusted; null = computed (replaced by the computed path at approval). */
278
+ slotsDir: string | null;
279
+ approve: "ask" | "auto";
280
+ crossPhase: "gate" | "inferred";
281
+ land: "ff-when-clean" | "manual";
282
+ batchMax: number;
283
+ maxAttempts: number;
284
+ qaMaxRounds: number;
285
+ integrationChecks: "auto" | RunCommandRef[];
286
+ phaseSuite: "auto" | "off" | RunCommandRef[];
287
+ provision: "auto" | Record<string, string[][]>;
288
+ python: "auto" | string;
289
+ sharedContextChars: number;
290
+ capacityCooldownMs: number;
291
+ capacityPauseMs: number;
292
+ wakeDebounceMs: number;
293
+ circuitBreaker: { failureRatio: number; minAttempts: number; consecutiveFailures: number };
294
+ }
295
+
296
+ /** Inclusive ranges for the numeric `ExecutorConfig` fields (Appendix C, §5). */
297
+ export const EXECUTOR_LIMITS: {
298
+ maxParallel: [1, 8]; batchMax: [1, 8]; maxAttempts: [1, 6]; qaMaxRounds: [1, 8];
299
+ sharedContextChars: [0, 60000]; capacityCooldownMs: [10000, 3600000]; capacityPauseMs: [60000, 86400000];
300
+ wakeDebounceMs: [1000, 60000]; failureRatio: [0.1, 1]; minAttempts: [1, 50]; consecutiveFailures: [1, 50];
301
+ } = {
302
+ maxParallel: [1, 8], batchMax: [1, 8], maxAttempts: [1, 6], qaMaxRounds: [1, 8],
303
+ sharedContextChars: [0, 60000], capacityCooldownMs: [10000, 3600000], capacityPauseMs: [60000, 86400000],
304
+ wakeDebounceMs: [1000, 60000], failureRatio: [0.1, 1], minAttempts: [1, 50], consecutiveFailures: [1, 50],
305
+ };
306
+
307
+ // ---------------------------------------------------------------------------------------------------------------
308
+ // §3 State machines (data) and §4 attempt counting
309
+ // ---------------------------------------------------------------------------------------------------------------
310
+
311
+ /** Every `TaskState`, in memo order. */
312
+ export const TASK_STATES: readonly TaskState[] = [
313
+ "pending", "ready", "dispatched", "running", "completed", "verifying", "verified",
314
+ "integrating", "integrated", "done", "failed", "conflict", "parked", "blocked", "reverted", "cancelled",
315
+ ];
316
+ /** Every `GateState`, in memo order. */
317
+ export const GATE_STATES: readonly GateState[] = [
318
+ "pending", "suite-running", "suite-failed", "awaiting-qa", "qa-running", "passed",
319
+ ];
320
+ /** Every `LedgerStatus`, in memo order. */
321
+ export const LEDGER_STATUSES: readonly LedgerStatus[] = [
322
+ "compiling", "awaiting-residue", "awaiting-approval", "running", "paused", "completed", "aborted",
323
+ ];
324
+ export const TASK_KINDS: readonly TaskKind[] = ["preflight", "task", "tests", "qa", "fix", "manual"];
325
+ export const ATTEMPT_OUTCOMES: readonly AttemptOutcome[] = ["succeeded", "failed", "interrupted", "lost", "capacity"];
326
+ export const VERDICTS: readonly Verdict[] = ["pass", "fail", "unverifiable"];
327
+
328
+ /** Terminal task states: nothing leaves them (§3.1 rules). */
329
+ export const TERMINAL_TASK_STATES = ["done", "cancelled"] as const;
330
+
331
+ /** Why a task transition happened; one per `task-transition` event (§6). */
332
+ export type TransitionTrigger =
333
+ | "deps-satisfied" | "dep-parked" | "dep-blocked" | "abort" | "launch" | "dep-reverted" | "adopt"
334
+ | "reported-done" | "dep-added" | "child-created" | "launch-lost" | "launch-task-error" | "child-ended" | "child-failed"
335
+ | "lease-unresolvable" | "qa-unparsable" | "escalate" | "ambiguity" | "budget-cap" | "child-lost" | "capacity-stop" | "lease-needed"
336
+ | "committed" | "no-changes" | "commit-failed" | "verify-pass" | "verify-fail" | "dequeued" | "fast-forwarded"
337
+ | "rebase-conflict" | "checks-failed" | "suite-culprit" | "retry" | "exhausted" | "answered" | "dep-recovered";
338
+
339
+ /** Key of a legal task transition: `"<from>><to>"`. */
340
+ export type TransitionKey = `${TaskState}>${TaskState}`;
341
+
342
+ /** The 47 legal task transitions (§3.1); anything else fails `canTransition` and ledger replay. */
343
+ export const TASK_TRANSITIONS: Readonly<Record<TaskState, readonly TaskState[]>> = {
344
+ pending: ["ready", "blocked", "cancelled"],
345
+ ready: ["dispatched", "blocked", "cancelled", "running", "done", "pending"],
346
+ dispatched: ["running", "ready", "failed", "blocked", "cancelled"],
347
+ running: ["completed", "failed", "parked", "ready", "blocked", "cancelled"],
348
+ completed: ["verifying", "done", "failed", "cancelled"],
349
+ verifying: ["verified", "failed", "cancelled"],
350
+ verified: ["integrating", "cancelled"],
351
+ integrating: ["integrated", "conflict", "failed", "cancelled"],
352
+ integrated: ["reverted"],
353
+ done: [],
354
+ failed: ["ready", "parked", "cancelled"],
355
+ conflict: ["ready", "parked", "cancelled"],
356
+ parked: ["ready", "cancelled"],
357
+ blocked: ["ready", "cancelled"],
358
+ reverted: ["ready", "parked", "cancelled"],
359
+ cancelled: [],
360
+ };
361
+
362
+ /**
363
+ * Triggers allowed per legal pair (§3.1 rows). Exactly the 47 keys of `TASK_TRANSITIONS`; an illegal pair has
364
+ * no key. The row's attempt effect and journal batch are described in the memo, not encoded here.
365
+ */
366
+ export const TRANSITION_TRIGGERS: Readonly<Partial<Record<TransitionKey, readonly TransitionTrigger[]>>> = {
367
+ "pending>ready": ["deps-satisfied"],
368
+ "pending>blocked": ["dep-parked", "dep-blocked"],
369
+ "pending>cancelled": ["abort"],
370
+ "ready>dispatched": ["launch"],
371
+ "ready>blocked": ["dep-reverted"],
372
+ "ready>cancelled": ["abort"],
373
+ "ready>running": ["adopt"],
374
+ "ready>done": ["reported-done"],
375
+ "ready>pending": ["dep-added"],
376
+ "dispatched>running": ["child-created"],
377
+ "dispatched>ready": ["launch-lost"],
378
+ "dispatched>failed": ["launch-task-error"],
379
+ "dispatched>blocked": ["dep-reverted"],
380
+ "dispatched>cancelled": ["abort"],
381
+ "running>completed": ["child-ended"],
382
+ "running>failed": ["child-failed", "lease-unresolvable", "qa-unparsable"],
383
+ "running>parked": ["escalate", "ambiguity", "qa-unparsable", "budget-cap"],
384
+ "running>ready": ["child-lost", "capacity-stop", "lease-needed"],
385
+ "running>blocked": ["dep-reverted"],
386
+ "running>cancelled": ["abort"],
387
+ "completed>verifying": ["committed"],
388
+ "completed>done": ["no-changes"],
389
+ "completed>failed": ["commit-failed"],
390
+ "completed>cancelled": ["abort"],
391
+ "verifying>verified": ["verify-pass"],
392
+ "verifying>failed": ["verify-fail"],
393
+ "verifying>cancelled": ["abort"],
394
+ "verified>integrating": ["dequeued"],
395
+ "verified>cancelled": ["abort"],
396
+ "integrating>integrated": ["fast-forwarded"],
397
+ "integrating>conflict": ["rebase-conflict"],
398
+ "integrating>failed": ["checks-failed"],
399
+ "integrating>cancelled": ["abort"],
400
+ "integrated>reverted": ["suite-culprit"],
401
+ "conflict>ready": ["retry"],
402
+ "failed>ready": ["retry"],
403
+ "reverted>ready": ["retry"],
404
+ "conflict>parked": ["exhausted"],
405
+ "failed>parked": ["exhausted"],
406
+ "reverted>parked": ["exhausted"],
407
+ "parked>ready": ["answered"],
408
+ "blocked>ready": ["dep-recovered"],
409
+ "failed>cancelled": ["abort"],
410
+ "conflict>cancelled": ["abort"],
411
+ "reverted>cancelled": ["abort"],
412
+ "parked>cancelled": ["abort"],
413
+ "blocked>cancelled": ["abort"],
414
+ };
415
+
416
+ /** Module that may journal a transition (§3.1 owner codes): Rt runtime, Q queue, P unattended policy, Rc recovery. */
417
+ export type TransitionOwner = "Rt" | "Q" | "P" | "Rc";
418
+
419
+ /** Who writes each legal transition (D-e, §3.1); lets test doubles check each module's boundary. */
420
+ export const TRANSITION_OWNERS: Readonly<Partial<Record<TransitionKey, readonly TransitionOwner[]>>> = {
421
+ "pending>ready": ["Rt"], "pending>blocked": ["P"], "pending>cancelled": ["Rt"],
422
+ // The three `*>blocked` rows are Q: a revert and its dependents are one Q batch (A1-2).
423
+ "ready>dispatched": ["Rt"], "ready>blocked": ["Q"], "ready>cancelled": ["Rt"], "ready>running": ["Rc", "Rt"],
424
+ "ready>done": ["Rt"], "ready>pending": ["Rt"],
425
+ "dispatched>running": ["Rt"], "dispatched>ready": ["Rt"], "dispatched>failed": ["Rt"], "dispatched>blocked": ["Q"],
426
+ "dispatched>cancelled": ["Rt"],
427
+ "running>completed": ["Rt"], "running>failed": ["Rt"], "running>parked": ["P"], "running>ready": ["Rt"],
428
+ "running>blocked": ["Q"], "running>cancelled": ["Rt"],
429
+ "completed>verifying": ["Rt"], "completed>done": ["Rt"], "completed>failed": ["Rt"], "completed>cancelled": ["Rt"],
430
+ "verifying>verified": ["Rt"], "verifying>failed": ["Rt"], "verifying>cancelled": ["Rt"],
431
+ "verified>integrating": ["Q"], "verified>cancelled": ["Rt"],
432
+ "integrating>integrated": ["Q"], "integrating>conflict": ["Q"], "integrating>failed": ["Q"],
433
+ "integrating>cancelled": ["Q"],
434
+ "integrated>reverted": ["Q"],
435
+ "conflict>ready": ["Rt"], "failed>ready": ["Rt"], "reverted>ready": ["Rt"],
436
+ "conflict>parked": ["P"], "failed>parked": ["P"], "reverted>parked": ["P"],
437
+ "parked>ready": ["P"], "blocked>ready": ["P"],
438
+ "failed>cancelled": ["Rt"], "conflict>cancelled": ["Rt"], "reverted>cancelled": ["Rt"], "parked>cancelled": ["Rt"],
439
+ "blocked>cancelled": ["Rt"],
440
+ };
441
+
442
+ /** True iff `from -> to` is a legal task transition; re-entering a state is not a transition (R15). */
443
+ export function canTransition(from: TaskState, to: TaskState): boolean {
444
+ return TASK_TRANSITIONS[from].includes(to);
445
+ }
446
+
447
+ /** Phase-gate state machine (A1-1; 12 legal pairs); replay checks it like task transitions. `passed` is terminal. */
448
+ export const GATE_TRANSITIONS: Readonly<Record<GateState, readonly GateState[]>> = {
449
+ pending: ["suite-running", "awaiting-qa"],
450
+ "suite-running": ["awaiting-qa", "suite-failed"],
451
+ "suite-failed": ["pending", "suite-running"],
452
+ "awaiting-qa": ["qa-running", "passed", "pending"],
453
+ "qa-running": ["awaiting-qa", "pending", "passed"],
454
+ passed: [],
455
+ };
456
+
457
+ /** Why a gate changed; one per `gate-changed` event (A1-1). Owners per trigger: `GATE_TRIGGER_OWNERS`. */
458
+ export type GateTrigger =
459
+ | "phase-integrated" | "suite-passed" | "suite-culprit-found" | "culprit-reverted" | "suite-rerun"
460
+ | "qa-dispatched" | "qa-requeued" | "qa-cap" | "qa-next-round" | "qa-clean" | "no-open-qa" | "cap-accepted" | "cap-fix";
461
+
462
+ /** Key of a legal gate transition: `"<from>><to>"`. */
463
+ export type GateTransitionKey = `${GateState}>${GateState}`;
464
+
465
+ /** Triggers allowed per legal gate pair (A1-1): exactly the 12 keys of `GATE_TRANSITIONS`. */
466
+ export const GATE_TRANSITION_TRIGGERS: Readonly<Partial<Record<GateTransitionKey, readonly GateTrigger[]>>> = {
467
+ "pending>suite-running": ["phase-integrated"],
468
+ "pending>awaiting-qa": ["phase-integrated"],
469
+ "suite-running>awaiting-qa": ["suite-passed"],
470
+ "suite-running>suite-failed": ["suite-culprit-found"],
471
+ "suite-failed>pending": ["culprit-reverted"],
472
+ "suite-failed>suite-running": ["suite-rerun"],
473
+ "awaiting-qa>qa-running": ["qa-dispatched"],
474
+ "awaiting-qa>passed": ["no-open-qa", "cap-accepted"],
475
+ "awaiting-qa>pending": ["cap-fix"],
476
+ "qa-running>awaiting-qa": ["qa-requeued", "qa-cap"],
477
+ "qa-running>pending": ["qa-next-round"],
478
+ "qa-running>passed": ["qa-clean"],
479
+ };
480
+
481
+ /** Module that may journal a gate change: a task owner or `QL` (QaLoop). */
482
+ export type GateOwner = TransitionOwner | "QL";
483
+
484
+ /** Who writes each legal gate transition (A1-1). */
485
+ export const GATE_TRANSITION_OWNERS: Readonly<Partial<Record<GateTransitionKey, readonly GateOwner[]>>> = {
486
+ "pending>suite-running": ["Q"],
487
+ "pending>awaiting-qa": ["Q"],
488
+ "suite-running>awaiting-qa": ["Q"],
489
+ "suite-running>suite-failed": ["Q"],
490
+ "suite-failed>pending": ["Q"],
491
+ "suite-failed>suite-running": ["Q"],
492
+ "awaiting-qa>qa-running": ["Rt", "Rc"],
493
+ "awaiting-qa>passed": ["QL"],
494
+ "awaiting-qa>pending": ["QL"],
495
+ "qa-running>awaiting-qa": ["Rt", "P", "Q", "QL"],
496
+ "qa-running>pending": ["QL"],
497
+ "qa-running>passed": ["QL"],
498
+ };
499
+
500
+ /**
501
+ * Who may journal each trigger (A2, QA-1.4-29). Refines `GATE_TRANSITION_OWNERS`: for every legal pair, the union of the
502
+ * owners of its triggers equals the pair's owners. Only the pair `qa-running>awaiting-qa` splits: `qa-requeued` is written
503
+ * by `Rt`/`P`/`Q` (a task ending or being parked/requeued), `qa-cap` only by `QL`.
504
+ *
505
+ * Row 4b (A2, QA-1.4-24): for a `kind: "qa"` task, a launch with a task-class prep error journals `[TS], AS, TT ready->dispatched, AE(failed),
506
+ * AX(error), TT dispatched->failed, G1, G2` with G1 = `awaiting-qa>qa-running` (`qa-dispatched`, owner Rt) and G2 = `qa-running>awaiting-qa`
507
+ * (`qa-requeued`, owner Rt). Both gate events are written (never only one, never none) so each `from` equals the phase's gate at that point
508
+ * (`awaiting-qa`, then `qa-running`) and the batch ends where it started; the failed qa task then returns through the normal retry path.
509
+ */
510
+ export const GATE_TRIGGER_OWNERS: Readonly<Record<GateTrigger, readonly GateOwner[]>> = {
511
+ "phase-integrated": ["Q"],
512
+ "suite-passed": ["Q"],
513
+ "suite-culprit-found": ["Q"],
514
+ "culprit-reverted": ["Q"],
515
+ "suite-rerun": ["Q"],
516
+ "qa-dispatched": ["Rt", "Rc"],
517
+ "qa-requeued": ["Rt", "P", "Q"],
518
+ "qa-cap": ["QL"],
519
+ "qa-next-round": ["QL"],
520
+ "qa-clean": ["QL"],
521
+ "no-open-qa": ["QL"],
522
+ "cap-accepted": ["QL"],
523
+ "cap-fix": ["QL"],
524
+ };
525
+
526
+ /** True iff `a -> b` is a legal gate transition (§3.3). */
527
+ export function canGateTransition(a: GateState, b: GateState): boolean {
528
+ return GATE_TRANSITIONS[a].includes(b);
529
+ }
530
+
531
+ /** Plan status machine (§3.4); `completed` and `aborted` are terminal. */
532
+ export const LEDGER_STATUS_TRANSITIONS: Readonly<Record<LedgerStatus, readonly LedgerStatus[]>> = {
533
+ compiling: ["awaiting-residue", "awaiting-approval", "aborted"],
534
+ "awaiting-residue": ["awaiting-approval", "aborted"],
535
+ "awaiting-approval": ["running", "aborted"],
536
+ running: ["paused", "completed", "aborted"],
537
+ paused: ["running", "aborted"],
538
+ completed: [],
539
+ aborted: [],
540
+ };
541
+
542
+ /** True iff `a -> b` is a legal plan status transition (§3.4). */
543
+ export function canStatusTransition(a: LedgerStatus, b: LedgerStatus): boolean {
544
+ return LEDGER_STATUS_TRANSITIONS[a].includes(b);
545
+ }
546
+
547
+ /** Task states that survive a crash and so are journaled with an fsync (§6). */
548
+ export const DURABLE_TASK_STATES: readonly TaskState[] =
549
+ ["dispatched", "running", "completed", "integrating", "integrated", "reverted", "cancelled"];
550
+
551
+ /** Attempts that consume `maxAttempts`: `succeeded` and `failed` only (§4, R6, QA-0.1-20). */
552
+ export function countsTowardMaxAttempts(a: Attempt): boolean {
553
+ return a.outcome === "succeeded" || a.outcome === "failed";
554
+ }
555
+ /** Number of attempts of `t` that count toward `maxAttempts` (§4). */
556
+ export function countedAttempts(t: TaskNode): number {
557
+ return t.attempts.filter(countsTowardMaxAttempts).length;
558
+ }
559
+ /** True while `t` may start another counted attempt (§4). */
560
+ export function hasAttemptsLeft(t: TaskNode, maxAttempts: number): boolean {
561
+ return countedAttempts(t) < maxAttempts;
562
+ }
563
+ /** Circuit-breaker failure sample: a failed attempt, or a fail/unverifiable verdict (§4). */
564
+ export function isBreakerFailure(a: Attempt): boolean {
565
+ return a.outcome === "failed" || a.verdict === "fail" || a.verdict === "unverifiable";
566
+ }
567
+
568
+ // ---------------------------------------------------------------------------------------------------------------
569
+ // §6 ExecutorEvent
570
+ // ---------------------------------------------------------------------------------------------------------------
571
+
572
+ /** Why the orchestrator is woken with a synthetic message (D15 658-664). */
573
+ export type WakeReason = "inbox" | "phase-paused" | "plan-completed" | "manual-ready" | "stale-context";
574
+
575
+ /** Writer-lock holder (2.2). */
576
+ export interface LockHolder {
577
+ pid: number;
578
+ hostname: string;
579
+ sessionID: string;
580
+ startedAt: IsoTime;
581
+ heartbeatAt: IsoTime;
582
+ }
583
+
584
+ /** Appendix D metric rows carried by `metric` events. */
585
+ export type MetricPayload =
586
+ | { name: "idle-with-ready"; fromAt: IsoTime; toAt: IsoTime; ms: number; readyTaskIds: TaskId[]; free: number }
587
+ | { name: "wake"; reason: WakeReason; stateKey: string; result: "sent" | "debounced" | "duplicate" | "failed" }
588
+ | { name: "launch"; taskId: TaskId; attempt: number; agent: string; model: string; provider: string; heavy: boolean }
589
+ | {
590
+ name: "context-age"; taskId: TaskId; attempt: number; bootID: string; epoch: number; callID: string; capturedAt: IsoTime;
591
+ ageMs: number; // D14 guard 4
592
+ result: "confirmed" | "timeout" | "threw" | "superseded" | "task-error" | "hook-failed";
593
+ }
594
+ | {
595
+ name: "capacity"; provider: string; change: "decrease" | "increase" | "pause" | "resume" | "retry-stop";
596
+ from: number; to: number; until: IsoTime | null; errorType: string | null; status: number | null;
597
+ }
598
+ | { name: "counter"; key: string; value: number; labels: Record<string, string> }; // other Appendix D rows
599
+
600
+ /** `Omit` applied to each member of a union (plain `Omit` collapses a discriminated union). */
601
+ export type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
602
+
603
+ /**
604
+ * Batch framing (A1-2): `batch` is the `seq` of the batch's first event, `last` marks its final event. The first event of a file and any
605
+ * event after `last: true` has `batch === seq`; the others share the previous `batch`. A trailing batch without `last: true` is dropped at load.
606
+ */
607
+ type E<T extends string, P> = { seq: number; at: IsoTime; batch: number; last: boolean; type: T } & P;
608
+
609
+ /** One journal line; `seq` is strictly +1 per line (§6). */
610
+ export type ExecutorEvent =
611
+ | E<"ledger-init", { ledger: LedgerV1 }>
612
+ // pre-approval statuses only
613
+ | E<"draft-replaced", { draft: Pick<LedgerV1, "planDigest" | "sharedContext" | "waves" | "phases" | "tasks" | "edges"> }>
614
+ | E<"status-changed", { from: LedgerStatus; to: LedgerStatus; reason: string }>
615
+ | E<"plan-approved", { config: ExecutorConfig; by: string }>
616
+ | E<"orchestrator-bound", { sessionID: string; reason: "compile" | "adopt" }>
617
+ | E<"lock-takeover", { reason: string; previous: LockHolder | null; holder: LockHolder }>
618
+ // state pending, or done (doneBefore)
619
+ | E<"task-created", { task: TaskNode }>
620
+ | E<"edge-added", { edge: Edge }>
621
+ | E<"task-transition", { taskId: TaskId; from: TaskState; to: TaskState; trigger: TransitionTrigger; detail: string | null }>
622
+ | E<"attempt-started", { taskId: TaskId; attempt: Attempt }>
623
+ | E<"attempt-child", { taskId: TaskId; n: number; childSessionID: string }>
624
+ | E<"attempt-adopted", { taskId: TaskId; n: number; childSessionID: string }>
625
+ | E<"attempt-resumed", { taskId: TaskId; n: number; resumes: number }>
626
+ | E<"attempt-ended", { taskId: TaskId; n: number; outcome: AttemptOutcome; endedAt: IsoTime; detail: string | null }>
627
+ | E<"attempt-verdict", { taskId: TaskId; n: number; verdict: Verdict; ref: string | null }>
628
+ | E<"attempt-context", { taskId: TaskId; n: number; context: string }>
629
+ | E<"task-slot", { taskId: TaskId; slot: string | null; branch: string | null }>
630
+ | E<"task-integrated", { taskId: TaskId; from: string; to: string }>
631
+ | E<"integration-head", { head: string }>
632
+ | E<"task-footprint", { taskId: TaskId; footprint: Footprint }> // durable; monotone (A1-8), owner Rt, row 18b only
633
+ | E<"integration-step", {
634
+ edge: "start" | "end"; entry: IntegrationEntry; step: IntegrationStep;
635
+ result: IntegrationStepResult | null; detail: string | null; failingIds: string[];
636
+ /** True on the one end event that finishes the entry (A1-3). */
637
+ closes: boolean;
638
+ }>
639
+ | E<"gate-changed", { phaseId: PhaseId; from: GateState; to: GateState; trigger: GateTrigger; qaRound: number }>
640
+ | E<"phase-paused", { phaseId: PhaseId; paused: boolean; reason: string }>
641
+ | E<"phase-tagged", { phaseId: PhaseId; tag: string }>
642
+ | E<"inbox-added", { item: InboxItem }>
643
+ | E<"inbox-answered", { id: string; answer: string }>
644
+ | E<"wake", { reason: WakeReason; stateKey: string }>
645
+ | E<"metric", { metric: MetricPayload }>;
646
+
647
+ /** An event as callers submit it: the store assigns `seq`, `batch` and `last`, the Clock supplies `at` (§6, A1-2). */
648
+ export type ExecutorEventInput = DistributiveOmit<ExecutorEvent, "seq" | "at" | "batch" | "last">;
649
+
650
+ /** A batch computed against the ledger it applies to; runs synchronously inside the writer's serialization and must be pure (A1-2). */
651
+ export type BatchBuilder = (ledger: Readonly<LedgerV1>) => readonly ExecutorEventInput[];
652
+
653
+ /** False only for `metric` and for a `task-transition` into a non-durable state; true means fsync (§6, D8). */
654
+ export function isDurableEvent(e: ExecutorEventInput): boolean {
655
+ if (e.type === "metric") return false;
656
+ if (e.type === "task-transition") return DURABLE_TASK_STATES.includes(e.to);
657
+ return true;
658
+ }
659
+
660
+ /** Event types copied to the never-rotated `history.jsonl` (A1-3). */
661
+ export type HistoryEventType = "metric" | "integration-step" | "attempt-verdict" | "wake";
662
+ const HISTORY_EVENT_TYPES: readonly string[] = ["metric", "integration-step", "attempt-verdict", "wake"];
663
+
664
+ /** True for the four history-class event types (A1-3). */
665
+ export function isHistoryEvent(e: { type: string }): boolean {
666
+ return HISTORY_EVENT_TYPES.includes(e.type);
667
+ }
668
+
669
+ // ---------------------------------------------------------------------------------------------------------------
670
+ // §7 Constants, guards, launch header, findings
671
+ // ---------------------------------------------------------------------------------------------------------------
672
+
673
+ /** A launch not confirmed within this long is `lost` (D14 guard 1, D-f). */
674
+ export const LAUNCH_CONFIRM_TIMEOUT_MS = 30_000;
675
+ /** Wait for a terminal `session.execution.*` event after a runner throw. */
676
+ export const CHILD_END_GRACE_MS = 5_000;
677
+ /** Concurrent heavy-tier children per provider (3.1.3.a). */
678
+ export const HEAVY_CAP_PER_PROVIDER = 2;
679
+ /**
680
+ * Maximum budget resumes of the same attempt. QA-PDF21-2-18: derived from the guard's cumulative ceiling (the role budget ×
681
+ * {@link GUARD_CUMULATIVE_MULTIPLIER}), so every round the attempt may take — the first launch plus each resume — still has a
682
+ * full per-dispatch budget under that ceiling; one more resume would be refused at its first call.
683
+ */
684
+ export const BUDGET_RESUMES = GUARD_CUMULATIVE_MULTIPLIER - 1;
685
+ /** Trailer identifying a saved work-in-progress commit. */
686
+ export const WIP_TRAILER = "Omr-Wip";
687
+ /** Marker identifying an orchestrator shell session. */
688
+ export const ORCHESTRATOR_SHELL_RE = /\(orchestrator shell\)/i;
689
+
690
+ /** Remove only semicolon-delimited criteria clauses assigned to the orchestrator's shell. */
691
+ export function stripOrchestratorShell(criterion: string): { kept: string | null; dropped: boolean } {
692
+ const kept: string[] = [];
693
+ let dropped = false;
694
+ for (const clause of criterion.split(";")) {
695
+ if (ORCHESTRATOR_SHELL_RE.test(clause)) dropped = true;
696
+ else if (clause.trim() !== "") kept.push(clause.trim());
697
+ }
698
+ return { kept: kept.length === 0 ? null : kept.join("; "), dropped };
699
+ }
700
+
701
+ /** Codes of `ExecutorError` (§8). */
702
+ export type ExecutorErrorCode =
703
+ | "E_INVALID_INPUT" | "E_PLAN_STATE" | "E_NOT_OWNER" | "E_LEDGER_NOT_FOUND" | "E_EXISTS" | "E_SCHEMA_NEWER"
704
+ | "E_SCHEMA_INVALID" | "E_SEQ_GAP" | "E_ILLEGAL_TRANSITION" | "E_LOCK_HELD" | "E_LOCK_LOST" | "E_COMPILE"
705
+ | "E_CYCLE" | "E_RESIDUE" | "E_SLOT_UNAVAILABLE" | "E_SLOT_BROKEN" | "E_PROVISION" | "E_GIT" | "E_IDENTITY"
706
+ | "E_CAPACITY" | "E_NO_CONTEXT" | "E_LAUNCH_TASK" | "E_DISPOSED" | "E_STALE_BASE";
707
+
708
+ /** Error every executor interface method throws; not ledger data (§8). A failing `append` leaves memory and disk unchanged. */
709
+ export class ExecutorError extends Error {
710
+ readonly code: ExecutorErrorCode;
711
+ readonly detail: JsonValue;
712
+ constructor(code: ExecutorErrorCode, message: string, detail: JsonValue = null) {
713
+ super(message);
714
+ this.name = "ExecutorError";
715
+ this.code = code;
716
+ this.detail = detail;
717
+ }
718
+ }
719
+
720
+ type Rec = Record<string, unknown>;
721
+
722
+ function isRec(v: unknown): v is Rec {
723
+ return typeof v === "object" && v !== null && !Array.isArray(v);
724
+ }
725
+ function isStr(v: unknown): v is string {
726
+ return typeof v === "string";
727
+ }
728
+ function isNum(v: unknown): v is number {
729
+ return typeof v === "number" && Number.isFinite(v);
730
+ }
731
+ function isInt(v: unknown): v is number {
732
+ return typeof v === "number" && Number.isInteger(v);
733
+ }
734
+ function isBool(v: unknown): v is boolean {
735
+ return typeof v === "boolean";
736
+ }
737
+ function isStrArr(v: unknown): v is string[] {
738
+ return Array.isArray(v) && v.every(isStr);
739
+ }
740
+ function isOneOf<T extends string>(set: readonly T[], v: unknown): v is T {
741
+ return typeof v === "string" && (set as readonly string[]).includes(v);
742
+ }
743
+ function hasOwn(o: object, k: string): boolean {
744
+ return Object.prototype.hasOwnProperty.call(o, k);
745
+ }
746
+ const ISO_TIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
747
+ function isIso(v: unknown): v is IsoTime {
748
+ return typeof v === "string" && ISO_TIME_PATTERN.test(v) && Number.isFinite(Date.parse(v));
749
+ }
750
+ function isStrOrNull(v: unknown): v is string | null {
751
+ return v === null || isStr(v);
752
+ }
753
+ function inRange(v: unknown, r: readonly [number, number], integer: boolean): v is number {
754
+ if (typeof v !== "number" || !Number.isFinite(v) || (integer && !Number.isInteger(v))) return false;
755
+ return v >= r[0] && v <= r[1];
756
+ }
757
+ function isRepoPath(v: unknown): v is string {
758
+ if (!isStr(v) || v.length === 0 || v.includes("\\") || v.startsWith("/")) return false;
759
+ return v.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
760
+ }
761
+
762
+ /** The numeric `schema` of an unknown ledger value, or null; lets the store tell "newer" (E_SCHEMA_NEWER) from "invalid" (§7). */
763
+ export function ledgerSchemaOf(v: unknown): number | null {
764
+ if (!isRec(v)) return null;
765
+ const s = v.schema;
766
+ return typeof s === "number" && Number.isFinite(s) ? s : null;
767
+ }
768
+
769
+ function isRunCommandRefs(v: unknown): boolean {
770
+ return Array.isArray(v) && v.every((r) => isRec(r) && isStr(r.script) && isStrArr(r.args));
771
+ }
772
+
773
+ /** Types and enums of an `ExecutorConfig`, ignoring numeric ranges (those are `config-limits`). */
774
+ function isConfigShape(v: unknown): v is ExecutorConfig {
775
+ if (!isRec(v)) return false;
776
+ if (!isNum(v.maxParallel) || !isNum(v.batchMax) || !isNum(v.maxAttempts) || !isNum(v.qaMaxRounds)) return false;
777
+ if (!isStrOrNull(v.slotsDir)) return false;
778
+ if (v.approve !== "ask" && v.approve !== "auto") return false;
779
+ if (v.crossPhase !== "gate" && v.crossPhase !== "inferred") return false;
780
+ if (v.land !== "ff-when-clean" && v.land !== "manual") return false;
781
+ if (!(v.integrationChecks === "auto" || isRunCommandRefs(v.integrationChecks))) return false;
782
+ if (!(v.phaseSuite === "auto" || v.phaseSuite === "off" || isRunCommandRefs(v.phaseSuite))) return false;
783
+ if (!(v.provision === "auto" ||
784
+ (isRec(v.provision) && Object.values(v.provision).every((m) => Array.isArray(m) && m.every(isStrArr))))) return false;
785
+ if (!isStr(v.python)) return false;
786
+ if (!isNum(v.sharedContextChars) || !isNum(v.capacityCooldownMs) || !isNum(v.capacityPauseMs) || !isNum(v.wakeDebounceMs)) {
787
+ return false;
788
+ }
789
+ const cb = v.circuitBreaker;
790
+ return isRec(cb) && isNum(cb.failureRatio) && isNum(cb.minAttempts) && isNum(cb.consecutiveFailures);
791
+ }
792
+
793
+ /** True iff every numeric field of a shape-valid config is within `EXECUTOR_LIMITS` (integers where the field is a count). */
794
+ function configWithinLimits(c: ExecutorConfig): boolean {
795
+ const L = EXECUTOR_LIMITS;
796
+ return inRange(c.maxParallel, L.maxParallel, true) && inRange(c.batchMax, L.batchMax, true) &&
797
+ inRange(c.maxAttempts, L.maxAttempts, true) && inRange(c.qaMaxRounds, L.qaMaxRounds, true) &&
798
+ inRange(c.sharedContextChars, L.sharedContextChars, true) && inRange(c.capacityCooldownMs, L.capacityCooldownMs, true) &&
799
+ inRange(c.capacityPauseMs, L.capacityPauseMs, true) && inRange(c.wakeDebounceMs, L.wakeDebounceMs, true) &&
800
+ inRange(c.circuitBreaker.failureRatio, L.failureRatio, false) && inRange(c.circuitBreaker.minAttempts, L.minAttempts, true) &&
801
+ inRange(c.circuitBreaker.consecutiveFailures, L.consecutiveFailures, true);
802
+ }
803
+
804
+ function isFootprint(v: unknown): v is Footprint {
805
+ return isRec(v) && Array.isArray(v.writes) && v.writes.every(isRepoPath) && Array.isArray(v.reads) &&
806
+ v.reads.every(isRepoPath) && isOneOf(["explicit", "ownership", "inferred", "unknown"] as const, v.confidence) &&
807
+ Array.isArray(v.sources) &&
808
+ v.sources.every((s) => isOneOf(["path", "ownership", "writes-line", "llm", "learned"] as const, s));
809
+ }
810
+
811
+ function isAttempt(v: unknown): v is Attempt {
812
+ return isRec(v) && isInt(v.n) && v.n >= 1 && isStr(v.nonce) && NONCE_PATTERN.test(v.nonce) && isStrOrNull(v.callID) &&
813
+ isStrOrNull(v.childSessionID) && isIso(v.startedAt) && (v.endedAt === null || isIso(v.endedAt)) &&
814
+ (v.outcome === null || isOneOf(ATTEMPT_OUTCOMES, v.outcome)) &&
815
+ (v.verdict === null || isOneOf(VERDICTS, v.verdict)) && isStr(v.context);
816
+ }
817
+
818
+ /** Shape guard for an `attempt-resumed` journal event; replay checks the target, state and count increment. */
819
+ export function isAttemptResumedEvent(v: unknown): v is Extract<ExecutorEvent, { type: "attempt-resumed" }> {
820
+ return isRec(v) && v.type === "attempt-resumed" && isInt(v.seq) && v.seq >= 1 && isIso(v.at) &&
821
+ isInt(v.batch) && v.batch >= 1 && isBool(v.last) && isTaskId(v.taskId) &&
822
+ isInt(v.n) && v.n >= 1 && isInt(v.resumes) && v.resumes >= 1;
823
+ }
824
+
825
+ const SLOT_REQUIRED_STATES: readonly TaskState[] = ["dispatched", "running", "completed", "verifying", "verified", "integrating"];
826
+ const BRANCH_REQUIRED_STATES: readonly TaskState[] = ["verifying", "verified", "integrating"];
827
+
828
+ /**
829
+ * Task states that hold no slot (A1-7 `slot-forbidden`): the slot is released on entering them. QA-PDF21-3 amends A1-7 for
830
+ * `parked`: a park whose slot's work could not be saved keeps the slot on the task (never reset or released while that
831
+ * work is unsaved), so a parked task may hold a slot; every other park clears it as before.
832
+ */
833
+ const SLOT_FORBIDDEN_STATES: readonly TaskState[] =
834
+ ["pending", "blocked", "done", "cancelled", "integrated", "reverted"];
835
+
836
+ /** One violated invariant: a stable `code` and the JSON path `at` of the offending value (A1-7). */
837
+ export interface LedgerViolation {
838
+ code: string;
839
+ /** JSON path, e.g. `$.tasks.T1.slot`. */
840
+ at: string;
841
+ }
842
+
843
+ /** Types, enums, finite numbers and patterns of a task node; no cross-field invariants. */
844
+ function isTaskShape(v: unknown): v is TaskNode {
845
+ if (!isRec(v)) return false;
846
+ if (!isTaskId(v.id) || !isStr(v.title)) return false;
847
+ if (!isStrOrNull(v.phase) || !isOneOf(TASK_KINDS, v.kind) || !isStr(v.text) || !isStrArr(v.subtasks)) return false;
848
+ const r = v.route;
849
+ if (!isRec(r) || !isStr(r.line) || !isStr(r.role) || !(r.tier === null || isOneOf(["fast", "medium", "heavy"] as const, r.tier)) ||
850
+ !isBool(r.pin)) return false;
851
+ if (!isOneOf(["required", "deferred", "none"] as const, v.verify) || !isStrOrNull(v.acceptance)) return false;
852
+ if (!isFootprint(v.footprint)) return false;
853
+ const est = v.estimate;
854
+ if (!isRec(est) || !isNum(est.p50) || !isNum(est.p90) || est.p50 < 0 || est.p50 > est.p90 || !isStr(est.source)) return false;
855
+ if (!isOneOf(TASK_STATES, v.state) || !Array.isArray(v.attempts) || !v.attempts.every(isAttempt)) return false;
856
+ if (!isStrOrNull(v.slot) || !isStrOrNull(v.branch)) return false;
857
+ const integ = v.integrated;
858
+ return integ === null || (isRec(integ) && isStr(integ.from) && isStr(integ.to));
859
+ }
860
+
861
+ /** Cross-field invariants of a shape-valid task node, as violations at path `at` (A1-7). */
862
+ function taskInvariantViolations(t: TaskNode, at: string): LedgerViolation[] {
863
+ const out: LedgerViolation[] = [];
864
+ const add = (code: string, sub: string): void => { out.push({ code, at: `${at}${sub}` }); };
865
+ const attempts = t.attempts;
866
+ if (!attempts.every((a, i) => a.n === i + 1)) add("attempt-n", ".attempts");
867
+ const open = attempts.filter((a) => a.outcome === null).length;
868
+ const last = attempts[attempts.length - 1];
869
+ if (t.state === "dispatched" || t.state === "running") {
870
+ if (open !== 1 || last?.outcome !== null) add("open-attempt", ".attempts");
871
+ } else if (open !== 0) add("open-attempt", ".attempts");
872
+ if (SLOT_REQUIRED_STATES.includes(t.state) && t.slot === null) add("slot-required", ".slot");
873
+ if (SLOT_FORBIDDEN_STATES.includes(t.state) && t.slot !== null) add("slot-forbidden", ".slot");
874
+ if (BRANCH_REQUIRED_STATES.includes(t.state) && t.branch === null) add("branch-required", ".branch");
875
+ if (t.state === "integrated" && t.integrated === null) add("integrated-missing", ".integrated");
876
+ if (t.integrated !== null && !(GIT_ID_PATTERN.test(t.integrated.from) && GIT_ID_PATTERN.test(t.integrated.to))) {
877
+ add("git-id", ".integrated");
878
+ }
879
+ if ((t.kind === "manual" || t.kind === "preflight") && attempts.length > 0) add("manual-attempts", ".attempts");
880
+ attempts.forEach((a, i) => {
881
+ if ((a.outcome === null) !== (a.endedAt === null) || (a.endedAt !== null && Date.parse(a.endedAt) < Date.parse(a.startedAt))) {
882
+ add("attempt-ended-pair", `.attempts[${i}]`);
883
+ }
884
+ if (a.verdict !== null && a.outcome !== "succeeded") add("verdict-unsucceeded", `.attempts[${i}].verdict`);
885
+ });
886
+ if (new Set(attempts.map((a) => a.nonce)).size !== attempts.length) add("nonce-duplicate", ".attempts");
887
+ if (t.state === "running" && last !== undefined && last.childSessionID === null) add("running-without-child", ".attempts");
888
+ if (t.kind === "qa" && t.phase === null) add("qa-without-phase", ".phase");
889
+ return out;
890
+ }
891
+
892
+ /** Every violation of a task node at path `at`: `shape` alone when the shape is wrong, else the cross-field invariants. */
893
+ function taskViolations(v: unknown, at: string): LedgerViolation[] {
894
+ return isTaskShape(v) ? taskInvariantViolations(v, at) : [{ code: "shape", at }];
895
+ }
896
+
897
+ /**
898
+ * Guard for a task node (§7, A1-7): types, enums, finite numbers, patterns, plus the cross-field invariants
899
+ * (`attempt-n`, `open-attempt`, `slot-required`, `slot-forbidden`, `branch-required`, `integrated-missing`, `git-id`,
900
+ * `manual-attempts`, `attempt-ended-pair`, `verdict-unsucceeded`, `nonce-duplicate`, `running-without-child`,
901
+ * `qa-without-phase`). Unknown extra fields are accepted.
902
+ */
903
+ export function isTaskNode(v: unknown): v is TaskNode {
904
+ return taskViolations(v, "$").length === 0;
905
+ }
906
+
907
+ function isPhaseShape(v: unknown): v is PhaseRecord {
908
+ return isRec(v) && isStr(v.id) && isStr(v.title) && isStr(v.wave) && isStrArr(v.dependsOn) &&
909
+ isOneOf(GATE_STATES, v.gate) && isInt(v.qaRound) && isBool(v.paused) && isStrOrNull(v.tag);
910
+ }
911
+
912
+ function isInboxItem(v: unknown): v is InboxItem {
913
+ return isRec(v) && isStr(v.id) &&
914
+ isOneOf(["question", "failure", "usage-limit", "landing", "flaky", "qa-cap", "breaker"] as const, v.kind) &&
915
+ isOneOf(["info", "blocking", "critical"] as const, v.severity) && isStrOrNull(v.taskId) && isStr(v.text) &&
916
+ isStrArr(v.options) && isStrOrNull(v.answer) && isIso(v.createdAt);
917
+ }
918
+
919
+ const EDGE_KINDS = ["structural", "explicit", "graph", "contract", "conflict", "llm", "learned"] as const;
920
+ const CONFIDENCES = ["high", "medium", "low"] as const;
921
+
922
+ /** QA2/`qa-gate` checks over the tasks of one shape-valid ledger (A1-1, A1-7). */
923
+ function qaViolations(phases: readonly PhaseRecord[], tasks: Record<string, TaskNode>, status: LedgerStatus, out: LedgerViolation[]): void {
924
+ const all = Object.values(tasks);
925
+ phases.forEach((p, i) => {
926
+ const qa = all.filter((t) => t.kind === "qa" && t.phase === p.id);
927
+ const live = qa.filter((t) => t.state !== "done" && t.state !== "cancelled");
928
+ if (live.length > 1) out.push({ code: "qa-multiple-open", at: `$.phases[${i}]` });
929
+ if (status === "aborted") return;
930
+ const inFlight = qa.filter((t) => t.state === "dispatched" || t.state === "running");
931
+ if (inFlight.length > 0 && p.gate !== "qa-running") out.push({ code: "qa-gate", at: `$.phases[${i}].gate` });
932
+ if (p.gate === "qa-running") {
933
+ const settled = inFlight.length === 0 && qa.length > 0 && live.length === 0 && qa.some((t) => t.state === "done");
934
+ if (inFlight.length !== 1 && !settled) out.push({ code: "qa-gate", at: `$.phases[${i}].gate` });
935
+ }
936
+ });
937
+ }
938
+
939
+ /**
940
+ * Every violated invariant of a candidate ledger (A1-7), each with a stable `code` and the JSON path `at`; `[]` means a valid version-1 ledger.
941
+ * `shape` marks a wrong type, enum, pattern or non-finite number (checks that depend on that part are skipped). Codes: `shape`, `schema`,
942
+ * `config-limits`, `task-key`, `task-phase`, `phase-wave`, `edge-endpoint`, `seq`, the task codes of `isTaskNode`, `shared-context-length`,
943
+ * `shared-context-slot-path`, `shared-context-header`, `path-not-absolute`, `git-id`, `phase-id`, `phase-duplicate`, `wave-id`,
944
+ * `wave-duplicate`, `wave-membership`, `phase-depends`, `slots-dir-unresolved`, `inbox-id`, `inbox-duplicate`, `inbox-task`,
945
+ * `qa-multiple-open`, `qa-round`, `qa-gate`. A newer `schema` is a violation (use `ledgerSchemaOf` to tell). Unknown extra fields are accepted.
946
+ */
947
+ export function ledgerViolations(v: unknown): LedgerViolation[] {
948
+ const out: LedgerViolation[] = [];
949
+ const add = (code: string, at: string): void => { out.push({ code, at }); };
950
+ if (!isRec(v)) return [{ code: "shape", at: "$" }];
951
+ if (v.schema !== LEDGER_SCHEMA) add("schema", "$.schema");
952
+ if (v.launcher !== "A") add("shape", "$.launcher");
953
+ if (!isStr(v.planId) || !PLAN_ID_PATTERN.test(v.planId)) add("shape", "$.planId");
954
+ if (!isStr(v.planPath)) add("shape", "$.planPath");
955
+ else if (!ABSOLUTE_PATH_PATTERN.test(v.planPath)) add("path-not-absolute", "$.planPath");
956
+ if (!isStr(v.planDigest) || !/^[0-9a-f]{64}$/.test(v.planDigest)) add("shape", "$.planDigest");
957
+
958
+ const repo = v.repo;
959
+ if (!isRec(repo) || !isStr(repo.key) || !isStr(repo.toplevel) || !isStr(repo.baseBranch) || !isStr(repo.baseCommit)) {
960
+ add("shape", "$.repo");
961
+ } else {
962
+ if (!ABSOLUTE_PATH_PATTERN.test(repo.toplevel)) add("path-not-absolute", "$.repo.toplevel");
963
+ if (!GIT_ID_PATTERN.test(repo.baseCommit)) add("git-id", "$.repo.baseCommit");
964
+ }
965
+ const integ = v.integration;
966
+ if (!isRec(integ) || !isStr(integ.branch) || !isStr(integ.worktree) || !isStr(integ.head)) {
967
+ add("shape", "$.integration");
968
+ } else {
969
+ if (!ABSOLUTE_PATH_PATTERN.test(integ.worktree)) add("path-not-absolute", "$.integration.worktree");
970
+ if (!GIT_ID_PATTERN.test(integ.head)) add("git-id", "$.integration.head");
971
+ }
972
+ const status = isOneOf(LEDGER_STATUSES, v.status) ? v.status : null;
973
+ if (status === null) add("shape", "$.status");
974
+ const orch = v.orchestrator;
975
+ if (!isRec(orch) || !isStr(orch.sessionID) || !isIso(orch.boundAt)) add("shape", "$.orchestrator");
976
+ if (!isInt(v.seq)) add("shape", "$.seq");
977
+ else if (v.seq < 1) add("seq", "$.seq");
978
+
979
+ const config = isConfigShape(v.config) ? v.config : null;
980
+ if (config === null) add("shape", "$.config");
981
+ else {
982
+ if (!configWithinLimits(config)) add("config-limits", "$.config");
983
+ if (config.slotsDir !== null) {
984
+ if (!ABSOLUTE_PATH_PATTERN.test(config.slotsDir)) add("path-not-absolute", "$.config.slotsDir");
985
+ } else if (status === "running" || status === "paused" || status === "completed") add("slots-dir-unresolved", "$.config.slotsDir");
986
+ }
987
+ if (!isStr(v.sharedContext)) add("shape", "$.sharedContext");
988
+ else {
989
+ if (config !== null && v.sharedContext.length > config.sharedContextChars) add("shared-context-length", "$.sharedContext");
990
+ if (config !== null && config.slotsDir !== null && config.slotsDir.length > 0 && v.sharedContext.includes(config.slotsDir)) {
991
+ add("shared-context-slot-path", "$.sharedContext");
992
+ }
993
+ if (hasHeaderShapedLine(v.sharedContext)) add("shared-context-header", "$.sharedContext");
994
+ }
995
+
996
+ // waves
997
+ const waves: Array<{ id: string; phases: string[] }> = [];
998
+ if (!Array.isArray(v.waves)) add("shape", "$.waves");
999
+ else {
1000
+ v.waves.forEach((w: unknown, i) => {
1001
+ if (!isRec(w) || !isStr(w.id) || !isStrArr(w.phases)) { add("shape", `$.waves[${i}]`); return; }
1002
+ if (!WAVE_ID_PATTERN.test(w.id)) add("wave-id", `$.waves[${i}].id`);
1003
+ if (waves.some((o) => o.id === w.id)) add("wave-duplicate", `$.waves[${i}].id`);
1004
+ waves.push({ id: w.id, phases: w.phases });
1005
+ });
1006
+ }
1007
+ // phases
1008
+ const phases: PhaseRecord[] = [];
1009
+ const wavesOk = Array.isArray(v.waves) && waves.length === v.waves.length;
1010
+ if (!Array.isArray(v.phases)) add("shape", "$.phases");
1011
+ else {
1012
+ v.phases.forEach((p: unknown, i) => {
1013
+ if (!isPhaseShape(p)) { add("shape", `$.phases[${i}]`); return; }
1014
+ if (!PHASE_ID_PATTERN.test(p.id)) add("phase-id", `$.phases[${i}].id`);
1015
+ if (phases.some((o) => o.id === p.id)) add("phase-duplicate", `$.phases[${i}].id`);
1016
+ if (p.qaRound < 1 || p.qaRound > QA_ROUND_LIMIT) add("qa-round", `$.phases[${i}].qaRound`);
1017
+ phases.push(p);
1018
+ });
1019
+ }
1020
+ const phasesOk = Array.isArray(v.phases) && phases.length === v.phases.length;
1021
+ const phaseIds = new Set<string>(phases.map((p) => p.id));
1022
+ if (wavesOk) {
1023
+ const waveIds = new Set<string>(waves.map((w) => w.id));
1024
+ phases.forEach((p, i) => { if (!waveIds.has(p.wave)) add("phase-wave", `$.phases[${i}].wave`); });
1025
+ }
1026
+ phases.forEach((p, i) => {
1027
+ if (p.dependsOn.some((d) => d === p.id || !phaseIds.has(d))) add("phase-depends", `$.phases[${i}].dependsOn`);
1028
+ });
1029
+ if (wavesOk && phasesOk) {
1030
+ waves.forEach((w, i) => {
1031
+ if (w.phases.some((id) => phases.find((p) => p.id === id)?.wave !== w.id)) add("wave-membership", `$.waves[${i}].phases`);
1032
+ });
1033
+ phases.forEach((p, i) => {
1034
+ if (waves.filter((w) => w.phases.includes(p.id)).length !== 1) add("wave-membership", `$.phases[${i}].wave`);
1035
+ });
1036
+ }
1037
+
1038
+ // tasks
1039
+ // Null prototype: a `__proto__` key must stay a plain entry (QA-1.4-31).
1040
+ const tasks: Record<string, TaskNode> = Object.create(null);
1041
+ let tasksOk = false;
1042
+ if (!isRec(v.tasks)) add("shape", "$.tasks");
1043
+ else {
1044
+ tasksOk = true;
1045
+ for (const key of Object.keys(v.tasks)) {
1046
+ const t: unknown = v.tasks[key];
1047
+ const tv = taskViolations(t, `$.tasks.${key}`);
1048
+ out.push(...tv);
1049
+ if (tv.some((x) => x.code === "shape")) { tasksOk = false; continue; }
1050
+ if (!isTaskShape(t)) { tasksOk = false; continue; }
1051
+ tasks[key] = t;
1052
+ if (t.id !== key) add("task-key", `$.tasks.${key}`);
1053
+ if (t.phase !== null && !phaseIds.has(t.phase)) add("task-phase", `$.tasks.${key}.phase`);
1054
+ }
1055
+ }
1056
+ if (tasksOk && phasesOk && status !== null) qaViolations(phases, tasks, status, out);
1057
+
1058
+ // edges
1059
+ if (!Array.isArray(v.edges)) add("shape", "$.edges");
1060
+ else {
1061
+ v.edges.forEach((e: unknown, i) => {
1062
+ if (!isRec(e) || !isStr(e.from) || !isStr(e.to) || !isStr(e.evidence) || !isOneOf(EDGE_KINDS, e.kind) ||
1063
+ !isOneOf(CONFIDENCES, e.confidence)) { add("shape", `$.edges[${i}]`); return; }
1064
+ if (isRec(v.tasks)) {
1065
+ if (!hasOwn(v.tasks, e.to)) add("edge-endpoint", `$.edges[${i}].to`);
1066
+ if (e.from.startsWith("gate:")) {
1067
+ if (!phaseIds.has(e.from.slice("gate:".length))) add("edge-endpoint", `$.edges[${i}].from`);
1068
+ } else if (!hasOwn(v.tasks, e.from)) add("edge-endpoint", `$.edges[${i}].from`);
1069
+ }
1070
+ });
1071
+ }
1072
+
1073
+ // inbox
1074
+ if (!Array.isArray(v.inbox)) add("shape", "$.inbox");
1075
+ else {
1076
+ const ids = new Set<string>();
1077
+ const nums = new Set<string>();
1078
+ v.inbox.forEach((item: unknown, i) => {
1079
+ if (!isInboxItem(item)) { add("shape", `$.inbox[${i}]`); return; }
1080
+ const m = INBOX_ID_PATTERN.exec(item.id);
1081
+ if (m === null || m[1] !== INBOX_ID_PREFIX[item.kind]) add("inbox-id", `$.inbox[${i}].id`);
1082
+ const num = m?.[2] ?? "";
1083
+ if (ids.has(item.id) || (num !== "" && nums.has(num))) add("inbox-duplicate", `$.inbox[${i}].id`);
1084
+ ids.add(item.id);
1085
+ if (num !== "") nums.add(num);
1086
+ if (item.taskId !== null && isRec(v.tasks) && !hasOwn(v.tasks, item.taskId)) add("inbox-task", `$.inbox[${i}].taskId`);
1087
+ });
1088
+ }
1089
+ return out;
1090
+ }
1091
+
1092
+ /**
1093
+ * Guard for a version-1 ledger (§7, A1-7): true iff `ledgerViolations(v)` is empty. A newer `schema` returns false
1094
+ * (use `ledgerSchemaOf` to tell). Unknown extra fields are accepted.
1095
+ */
1096
+ export function isLedgerV1(v: unknown): v is LedgerV1 {
1097
+ return ledgerViolations(v).length === 0;
1098
+ }
1099
+
1100
+ /**
1101
+ * Prompt grammar (QA-0.1-21): `prompt = planContext "\n\n" headerLine "\n\n" taskBlock`,
1102
+ * `planContext = "PLAN CONTEXT\n" [EXECUTOR_READ_CAP_LINE "\n"] ledger.sharedContext` (the read-cap line for editing
1103
+ * tasks only, DF-2-9), `headerLine = header " nonce=" nonce`,
1104
+ * `header = "[plan " planId ":" taskId "#" attempt "]"` with attempt = `Attempt.n` (D-b). `taskBlock` belongs to 3.1.4.
1105
+ * The child's first-context fail-closed check (3.1.7.a) refuses every tool call of an unbound child whose prompt matches.
1106
+ * Consumers must import this pattern; never re-derive it (the memo's old task-id lookahead was wrong, QA-1.4-12).
1107
+ */
1108
+ export const LAUNCH_HEADER_PATTERN =
1109
+ /^\[plan ([a-z0-9][a-z0-9-]{2,40}):((?!\d+#)[A-Za-z0-9][A-Za-z0-9._-]{0,63})#([1-9][0-9]{0,3})\] nonce=([0-9a-f]{32})$/m;
1110
+
1111
+ /** The four fields a launch header carries (§7). */
1112
+ export interface LaunchHeaderFields {
1113
+ planId: string;
1114
+ taskId: string;
1115
+ attempt: number;
1116
+ nonce: string;
1117
+ }
1118
+
1119
+ /** Renders `[plan <planId>:<taskId>#<attempt>] nonce=<nonce>`; throws E_LAUNCH_TASK when the result would not match `LAUNCH_HEADER_PATTERN`. */
1120
+ export function formatLaunchHeader(p: LaunchHeaderFields): string {
1121
+ const line = `[plan ${p.planId}:${p.taskId}#${p.attempt}] nonce=${p.nonce}`;
1122
+ const m = LAUNCH_HEADER_PATTERN.exec(line);
1123
+ if (!Number.isInteger(p.attempt) || m === null || m[0] !== line) {
1124
+ throw new ExecutorError("E_LAUNCH_TASK", "launch header fields do not match the launch header grammar", {
1125
+ planId: p.planId, taskId: p.taskId, attempt: p.attempt, nonce: p.nonce,
1126
+ });
1127
+ }
1128
+ return line;
1129
+ }
1130
+
1131
+ /** True iff some line of `text` is shaped like a launch header (the multiline pattern). */
1132
+ function hasHeaderShapedLine(text: string): boolean {
1133
+ return LAUNCH_HEADER_PATTERN.test(text);
1134
+ }
1135
+
1136
+ /**
1137
+ * The executor's own read-cap line for an editing task (DF-2-9). The router honours the first read-cap token of a prompt,
1138
+ * so this line sits right after the `"PLAN CONTEXT"` line, before the shared context and the task text (both neutralized).
1139
+ */
1140
+ export const EXECUTOR_READ_CAP_LINE = "CAP:12";
1141
+
1142
+ /** The fixed opening of every launch prompt: `"PLAN CONTEXT\n"`, then the executor's read-cap line when `readCap`. */
1143
+ function launchOpening(readCap: boolean): string {
1144
+ return readCap ? `PLAN CONTEXT\n${EXECUTOR_READ_CAP_LINE}\n` : "PLAN CONTEXT\n";
1145
+ }
1146
+
1147
+ /**
1148
+ * Strict, at the fixed position (A1-7): the prompt starts with `"PLAN CONTEXT\n"`, optionally the executor's read-cap line
1149
+ * (`EXECUTOR_READ_CAP_LINE + "\n"`), then `sharedContext + "\n\n"`; the next line matches `LAUNCH_HEADER_PATTERN` in full and is
1150
+ * followed by `"\n\n"`. Anything else is null, including a `sharedContext` that itself has a header-shaped line. Recovery (C7)
1151
+ * uses this with `ledger.sharedContext`.
1152
+ */
1153
+ export function parseLaunchHeader(prompt: string, sharedContext: string): LaunchHeaderFields | null {
1154
+ if (hasHeaderShapedLine(sharedContext)) return null;
1155
+ // An editing task's prompt carries the executor's read-cap line; every other prompt goes straight to the shared context.
1156
+ const prefix = [launchOpening(true), launchOpening(false)].map(open => `${open}${sharedContext}\n\n`).find(p => prompt.startsWith(p));
1157
+ if (prefix === undefined) return null;
1158
+ const rest = prompt.slice(prefix.length);
1159
+ const end = rest.indexOf("\n\n");
1160
+ if (end < 0) return null;
1161
+ const line = rest.slice(0, end);
1162
+ const m = LAUNCH_HEADER_PATTERN.exec(line);
1163
+ if (m === null || m[0] !== line) return null;
1164
+ const [, planId, taskId, attempt, nonce] = m;
1165
+ if (planId === undefined || taskId === undefined || attempt === undefined || nonce === undefined) return null;
1166
+ return { planId, taskId, attempt: Number(attempt), nonce };
1167
+ }
1168
+
1169
+ /** Loose: any line matches. Only for the 3.1.7.a fail-closed check (over-matching fails closed). */
1170
+ export function looksLikePlanPrompt(prompt: string): boolean {
1171
+ return hasHeaderShapedLine(prompt);
1172
+ }
1173
+
1174
+ /**
1175
+ * §7 grammar: `"PLAN CONTEXT\n" + [EXECUTOR_READ_CAP_LINE "\n"] + sharedContext + "\n\n" + headerLine + "\n\n" + taskBlock`.
1176
+ * The read-cap line is present only when `readCap` (an editing task); it is then the prompt's first read-cap token (DF-2-9).
1177
+ * Throws E_LAUNCH_TASK when `sharedContext` has a header-shaped line, the header fields are invalid, or `taskBlock` does not start with "TASK".
1178
+ */
1179
+ export function formatLaunchPrompt(sharedContext: string, header: LaunchHeaderFields, taskBlock: string, readCap = false): string {
1180
+ if (hasHeaderShapedLine(sharedContext)) {
1181
+ throw new ExecutorError("E_LAUNCH_TASK", "shared context contains a launch-header-shaped line");
1182
+ }
1183
+ if (!taskBlock.startsWith("TASK")) {
1184
+ throw new ExecutorError("E_LAUNCH_TASK", 'task block must start with "TASK"');
1185
+ }
1186
+ return `${launchOpening(readCap)}${sharedContext}\n\n${formatLaunchHeader(header)}\n\n${taskBlock}`;
1187
+ }
1188
+
1189
+ export type FindingSeverity = "blocking" | "critical" | "major" | "minor" | "nit";
1190
+ export interface Finding {
1191
+ id: string;
1192
+ severity: FindingSeverity;
1193
+ /** Repo-relative, '/'-separated. */
1194
+ files: string[];
1195
+ problem: string;
1196
+ fix: string;
1197
+ }
1198
+ export interface FindingsReport {
1199
+ findings: Finding[];
1200
+ }
1201
+
1202
+ /**
1203
+ * JSON schema of the QA findings report (§7). Extraction rule (the instruction in 3.1.4 and `QaLoop.parse`):
1204
+ * the last ```json fenced block of the final answer, else the whole text.
1205
+ * Ids of QaLoop-created tasks are deterministic (idempotent recovery): fix `${phaseId}.FIX${round}-${k}`,
1206
+ * re-review `${phaseId}.QA${round + 1}`.
1207
+ */
1208
+ export const FINDINGS_FORMAT = {
1209
+ type: "object", additionalProperties: false, required: ["findings"],
1210
+ properties: {
1211
+ findings: {
1212
+ type: "array",
1213
+ items: {
1214
+ type: "object", additionalProperties: false, required: ["id", "severity", "files", "problem", "fix"],
1215
+ properties: {
1216
+ id: { type: "string", pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$" },
1217
+ severity: { enum: ["blocking", "critical", "major", "minor", "nit"] },
1218
+ files: { type: "array", items: { type: "string", minLength: 1 } },
1219
+ problem: { type: "string", minLength: 1 },
1220
+ fix: { type: "string" },
1221
+ },
1222
+ },
1223
+ },
1224
+ },
1225
+ } as const;
1226
+
1227
+ const FINDING_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
1228
+ const FINDING_KEYS: readonly string[] = ["id", "severity", "files", "problem", "fix"];
1229
+
1230
+ function isFinding(v: unknown): v is Finding {
1231
+ return isRec(v) && Object.keys(v).every((k) => FINDING_KEYS.includes(k)) && isStr(v.id) && FINDING_ID_PATTERN.test(v.id) &&
1232
+ isOneOf(["blocking", "critical", "major", "minor", "nit"] as const, v.severity) &&
1233
+ Array.isArray(v.files) && v.files.every((f) => isStr(f) && f.length > 0) &&
1234
+ isStr(v.problem) && v.problem.length > 0 && isStr(v.fix);
1235
+ }
1236
+
1237
+ /** True iff `v` validates against `FINDINGS_FORMAT` (additional properties rejected, as the schema says). */
1238
+ export function isFindingsReport(v: unknown): v is FindingsReport {
1239
+ return isRec(v) && Object.keys(v).every((k) => k === "findings") && Array.isArray(v.findings) && v.findings.every(isFinding);
1240
+ }
1241
+
1242
+ // ---- QA rounds (A1-1)
1243
+
1244
+ /** Highest QA round a phase can reach (A1-1). */
1245
+ export const QA_ROUND_LIMIT = 999;
1246
+ /** Highest fix-task index within one round (A1-1). */
1247
+ export const FIX_TASKS_PER_ROUND_LIMIT = 999;
1248
+ /** Prefix of the `Attempt.context` a qa attempt gets when its output does not parse (QA6). */
1249
+ export const QA_UNPARSABLE_CONTEXT_PREFIX = "QA OUTPUT UNPARSABLE: ";
1250
+ /** Answers a critical `qa-cap` item offers; `fix` is withheld at `QA_ROUND_LIMIT` (QA8). */
1251
+ export const QA_CAP_OPTIONS = ["accept", "fix"] as const;
1252
+ export type QaCapChoice = (typeof QA_CAP_OPTIONS)[number];
1253
+
1254
+ function isIntIn(v: number, lo: number, hi: number): boolean {
1255
+ return Number.isInteger(v) && v >= lo && v <= hi;
1256
+ }
1257
+
1258
+ /** Id of fix task `k` created from the findings of round `round`: `${phaseId}.FIX${round}-${k}`. Throws E_INVALID_INPUT outside the limits. */
1259
+ export function fixTaskId(phaseId: PhaseId, round: number, k: number): TaskId {
1260
+ if (!PHASE_ID_PATTERN.test(phaseId) || !isIntIn(round, 1, QA_ROUND_LIMIT) || !isIntIn(k, 1, FIX_TASKS_PER_ROUND_LIMIT)) {
1261
+ throw new ExecutorError("E_INVALID_INPUT", "invalid fix task id inputs", { phaseId, round, k });
1262
+ }
1263
+ return `${phaseId}.FIX${round}-${k}`;
1264
+ }
1265
+
1266
+ /** Id of the qa task of round `round` >= 2: `${phaseId}.QA${round}`. Throws E_INVALID_INPUT outside the limits. */
1267
+ export function reviewTaskId(phaseId: PhaseId, round: number): TaskId {
1268
+ if (!PHASE_ID_PATTERN.test(phaseId) || !isIntIn(round, 2, QA_ROUND_LIMIT)) {
1269
+ throw new ExecutorError("E_INVALID_INPUT", "invalid review task id inputs", { phaseId, round });
1270
+ }
1271
+ return `${phaseId}.QA${round}`;
1272
+ }
1273
+
1274
+ /** How many attempts of `t` ended with unparsable QA output: those whose context starts with `QA_UNPARSABLE_CONTEXT_PREFIX` (QA6). */
1275
+ export function qaUnparsableCount(t: TaskNode): number {
1276
+ return t.attempts.filter((a) => a.context.startsWith(QA_UNPARSABLE_CONTEXT_PREFIX)).length;
1277
+ }
1278
+
1279
+ /** The report stored in a qa attempt's context: `JSON.stringify({findings: [...]})` with the keys in schema order. */
1280
+ export function canonicalFindingsJson(r: FindingsReport): string {
1281
+ return JSON.stringify({
1282
+ findings: r.findings.map((f) => ({ id: f.id, severity: f.severity, files: f.files, problem: f.problem, fix: f.fix })),
1283
+ });
1284
+ }
1285
+
1286
+ // ---------------------------------------------------------------------------------------------------------------
1287
+ // §8 Provider errors (R3)
1288
+ // ---------------------------------------------------------------------------------------------------------------
1289
+
1290
+ /** A host error as the executor sees it. */
1291
+ export interface HostError {
1292
+ type: string;
1293
+ status: number | null;
1294
+ message: string;
1295
+ }
1296
+
1297
+ /**
1298
+ * Capacity class of a provider error (R3): the `type` decides (`provider.rate-limit` -> rate-limit, `provider.quota`
1299
+ * -> quota, `provider.internal` -> overload only with status 529; any other `provider.internal` is not capacity, QA-0.1-30);
1300
+ * any other type falls back to its status (429 -> rate-limit, 529 -> overload); else null.
1301
+ */
1302
+ export function classifyProviderError(e: Pick<HostError, "type" | "status">): "rate-limit" | "overload" | "quota" | null {
1303
+ switch (e.type) {
1304
+ case "provider.rate-limit": return "rate-limit";
1305
+ case "provider.quota": return "quota";
1306
+ default:
1307
+ // `provider.internal` is overload only with status 529; with another status it falls back to the status like any type.
1308
+ if (e.status === 429) return "rate-limit";
1309
+ if (e.status === 529) return "overload";
1310
+ return null;
1311
+ }
1312
+ }
1313
+
1314
+ /** Outcome of a child execution failure (R3): capacity when `classifyProviderError` says so, else `failed`. */
1315
+ export function executionFailureOutcome(e: HostError): "capacity" | "failed" {
1316
+ return classifyProviderError(e) === null ? "failed" : "capacity";
1317
+ }
1318
+
1319
+ /** `ExecutorConfig` with every writable property (and the nested circuit breaker) read-only (QA-1.4-15). */
1320
+ export type ReadonlyExecutorConfig = Readonly<Omit<ExecutorConfig, "circuitBreaker">> & {
1321
+ readonly circuitBreaker: Readonly<ExecutorConfig["circuitBreaker"]>;
1322
+ };
1323
+
1324
+ /** A fresh, mutable copy of the Appendix C defaults; edit this, never `EXECUTOR_DEFAULTS` (QA-1.4-15). */
1325
+ export function executorDefaults(): ExecutorConfig {
1326
+ return { ...EXECUTOR_DEFAULTS, circuitBreaker: { ...EXECUTOR_DEFAULTS.circuitBreaker } };
1327
+ }
1328
+
1329
+ /** Appendix C defaults (plan 4381-4399). Frozen and typed read-only: use `executorDefaults()` for a mutable copy. */
1330
+ export const EXECUTOR_DEFAULTS: ReadonlyExecutorConfig = Object.freeze({
1331
+ maxParallel: 4,
1332
+ slotsDir: null,
1333
+ approve: "ask",
1334
+ crossPhase: "gate",
1335
+ land: "ff-when-clean",
1336
+ batchMax: 4,
1337
+ maxAttempts: 3,
1338
+ qaMaxRounds: 3,
1339
+ integrationChecks: "auto",
1340
+ phaseSuite: "auto",
1341
+ provision: "auto",
1342
+ python: "auto",
1343
+ sharedContextChars: 12000,
1344
+ capacityCooldownMs: 120000,
1345
+ capacityPauseMs: 900000,
1346
+ wakeDebounceMs: 5000,
1347
+ circuitBreaker: Object.freeze({ failureRatio: 0.4, minAttempts: 5, consecutiveFailures: 3 }),
1348
+ });
1349
+
1350
+ // ---------------------------------------------------------------------------------------------------------------
1351
+ // §8 Interfaces. Every method throws `ExecutorError`.
1352
+ // ---------------------------------------------------------------------------------------------------------------
1353
+
1354
+ export type { ExpandInput } from "./expand";
1355
+
1356
+ // Type-only extension of the existing expansion input; expansion behaviour is unchanged.
1357
+ declare module "./expand" {
1358
+ interface ExpandInput {
1359
+ /** The previous attempt's work restored as uncommitted changes. */
1360
+ restored?: { attempt: number; files: number };
1361
+ }
1362
+ }
1363
+
1364
+ /** Ledger persistence (2.2): snapshot plus journal under one writer lock. */
1365
+ export interface LedgerStore {
1366
+ /** pre: no plan dir; isLedgerV1(draft) and `draft.seq === 1`; post: dir, snapshot, journal (ledger-init `{seq: 1, batch: 1, last: true}`), lock held.
1367
+ * err E_EXISTS, E_SCHEMA_INVALID (including any other draft seq) */
1368
+ create(draft: LedgerV1, holder: LockHolder): Promise<LedgerWriter>;
1369
+ /** Takes the writer lock. Load rules (A2, QA-1.4-25): batch framing applies to the main journal only: rule (2) a torn last line is dropped,
1370
+ * rule (3) a trailing incomplete batch (events before the `last: true` event) is dropped whole with one warning, and a batch that is
1371
+ * malformed anywhere else is E_SEQ_GAP. The history journal is checked for strictly increasing `seq` and a torn last line only (no batches).
1372
+ * err E_LEDGER_NOT_FOUND, E_LOCK_HELD (detail = holder), E_SCHEMA_NEWER, E_SEQ_GAP, E_ILLEGAL_TRANSITION (detail names the event) */
1373
+ open(planId: PlanId, holder: LockHolder): Promise<LedgerWriter>;
1374
+ /** Only when the lock is stale (dead pid on this host, or heartbeat > 60 s) or the caller is adopting; journals lock-takeover. err E_LOCK_HELD */
1375
+ takeover(planId: PlanId, holder: LockHolder, reason: string): Promise<LedgerWriter>;
1376
+ /** Lock-free consistent read (retries while snapshot seq != first journal seq). A torn last line is dropped with one warning, and so is a
1377
+ * trailing incomplete batch (rule (3), main journal only; A2, QA-1.4-25), so a reader never sees half a batch. */
1378
+ read(planId: PlanId): Promise<LedgerV1>;
1379
+ list(): Promise<Array<{ planId: PlanId; status: LedgerStatus; toplevel: string; orchestratorSessionID: string; seq: number }>>;
1380
+ /** snapshot = current ledger; events = every history event since seq 1 merged with every event of the current main journal, deduplicated
1381
+ * by `seq`, ascending (A1-3). No lock; torn last lines dropped. Only history-class events are guaranteed back to seq 1. */
1382
+ exportPlan(planId: PlanId): Promise<{ snapshot: LedgerV1; events: ExecutorEvent[] }>;
1383
+ /** pre: status completed|aborted; no live writer elsewhere. post: plan dir gone. Returns false when absent. err E_PLAN_STATE, E_LOCK_HELD */
1384
+ remove(planId: PlanId): Promise<boolean>;
1385
+ }
1386
+
1387
+ /** The one writer of a plan's ledger (D-e): validates, sequences and persists event batches. */
1388
+ export interface LedgerWriter {
1389
+ readonly planId: PlanId;
1390
+ readonly ledger: Readonly<LedgerV1>;
1391
+ /** One atomic batch. A builder runs synchronously inside the writer's serialization against the ledger the batch applies to and must be pure;
1392
+ * `[]` appends nothing and resolves with the current ledger. Validation per A1-2 (per-event preconditions in order; `ledgerViolations` at
1393
+ * batch end). Events share one `at`; `seq`, `batch` and `last` are assigned; all lines go in one appendText; fsync iff any event
1394
+ * isDurableEvent; then the history copy (A1-3). Resolves after the fsync.
1395
+ * err E_ILLEGAL_TRANSITION (nothing written; detail = {batchIndex, eventIndex|null, codes}), E_LOCK_LOST, I/O */
1396
+ append(batch: readonly ExecutorEventInput[] | BatchBuilder): Promise<Readonly<LedgerV1>>;
1397
+ /** Integration entries still open in the history journal (A1-3); updated on every append. */
1398
+ openIntegration(): readonly OpenIntegrationEntry[];
1399
+ /** Wake keys already written (A1-6): built from the history journal at `open`, updated on every append. Lets the `Waker` stay idempotent
1400
+ * across restarts without scanning the ledger. (QA-1.4-23) */
1401
+ wakeKeys(): ReadonlySet<string>;
1402
+ /** Also every 200 events, then rotates the journal. */
1403
+ snapshot(): Promise<void>;
1404
+ /** Snapshot, then release the lock; idempotent. */
1405
+ close(): Promise<void>;
1406
+ }
1407
+
1408
+ /** Counts and critical-path figures of a compiled plan (2.3). */
1409
+ export interface CompileSummary {
1410
+ tasks: number;
1411
+ phases: number;
1412
+ edges: number;
1413
+ workMs: number;
1414
+ criticalPathMs: number;
1415
+ width: number;
1416
+ expectedMakespanMs: number;
1417
+ manual: TaskId[];
1418
+ warnings: string[];
1419
+ }
1420
+
1421
+ /** Plan text -> draft ledger (2.3). */
1422
+ export interface PlanCompiler {
1423
+ /** Reads the plan (FileSystem) and worktrees (GitRunner). Never writes. post: draft.status is awaiting-residue iff residueRequest.
1424
+ * err E_COMPILE (line), E_CYCLE (minimal cycle), E_INVALID_INPUT (unknown phases/doneBefore) */
1425
+ compile(planPath: string, opts: {
1426
+ phases?: PhaseId[]; doneBefore?: PhaseId; config: ExecutorConfig; orchestratorSessionID: string; now: IsoTime;
1427
+ }): Promise<{ draft: LedgerV1; residueRequest?: { prompt: string; schema: JsonValue; taskIds: TaskId[] }; summary: CompileSummary }>;
1428
+ /** Monotone merge, then re-validation. err E_RESIDUE (precise) */
1429
+ mergeResidue(draft: LedgerV1, responseText: string): { draft: LedgerV1; summary: CompileSummary };
1430
+ /** For router_plan add-tasks. Returns the new nodes and edges plus `reopened` (ready tasks that must go ready->pending). err E_CYCLE, E_INVALID_INPUT */
1431
+ addTasks(ledger: LedgerV1, text: string): { tasks: TaskNode[]; edges: Edge[]; reopened: TaskId[] };
1432
+ /** Cycles, ids, paths, concurrency closure. */
1433
+ validate(ledger: LedgerV1): Array<{ code: string; message: string; taskIds: TaskId[] }>;
1434
+ }
1435
+
1436
+ /** A leased work slot (2.4). */
1437
+ export interface SlotLease {
1438
+ slot: string;
1439
+ path: string;
1440
+ planId: PlanId;
1441
+ owner: string;
1442
+ commit: string;
1443
+ }
1444
+
1445
+ /** A lease returned by one acquisition, with optional proof of that acquisition's completed reset. */
1446
+ export interface SlotAcquisition extends SlotLease {
1447
+ /** Full reset at this base: pointer/link checks, checkout/clean, HEAD/status verification and provisioning drift.
1448
+ * Absent for same-owner/recovery, create/recreate or otherwise unproven acquisitions. This is not a persistent
1449
+ * cleanliness guarantee: consume it immediately after acquire, and reset if the required base has changed. */
1450
+ readonly verifiedResetBase?: string;
1451
+ }
1452
+
1453
+ /** Pool of provisioned git worktrees (2.4). */
1454
+ export interface SlotPool {
1455
+ /** Never waits: a reset, provisioned slot leased to `owner`, or E_SLOT_UNAVAILABLE. Concurrent calls are claimed in call order; never double-leases.
1456
+ * A task that already holds a slot gets the same slot back. err E_SLOT_UNAVAILABLE, E_PROVISION, E_SLOT_BROKEN */
1457
+ acquire(planId: PlanId, owner: string, baseCommit: string): Promise<SlotAcquisition>;
1458
+ acquireSpecial(planId: PlanId, kind: "integration" | "ci"): Promise<SlotAcquisition>;
1459
+ /** Checkout detached + clean tracked; re-provision on manifest drift. */
1460
+ reset(slot: string, commit: string): Promise<void>;
1461
+ /** Persist a leased checkout's commit after the caller has cleaned and verified its HEAD. Does not reset it. */
1462
+ noteCommit(slot: string, commit: string): Promise<void>;
1463
+ /** Clean the checkout and report whether provisioning drift was detected. */
1464
+ cleanForChecks(slot: string): Promise<{ drifted: boolean }>;
1465
+ /** Idempotent. */
1466
+ release(slot: string): Promise<void>;
1467
+ /** Subscribe without opening the pool. Called only after a task slot's leased -> ready marker is durable.
1468
+ * Failed/unchanged releases and special slots do not notify. Returns an unsubscribe function. */
1469
+ onTaskSlotReleased?(listener: () => void): () => void;
1470
+ get(slot: string): Promise<SlotRecord | null>;
1471
+ list(planId?: PlanId): Promise<SlotRecord[]>;
1472
+ /** Removes only marked slots of completed/aborted plans, or unknown plans after 7 d; never follows links; reports unmarked dirs */
1473
+ gc(isFinished: (planId: PlanId) => Promise<boolean | null>, opts?: { savedSlots?: ReadonlySet<string> }): Promise<{ removed: string[]; reported: string[] }>;
1474
+ }
1475
+
1476
+ /** Called after the fsync of the corresponding journal batch. */
1477
+ export interface IntegrationListener {
1478
+ onIntegrated(taskId: TaskId): void;
1479
+ onConflict(taskId: TaskId): void;
1480
+ onFailed(taskId: TaskId): void;
1481
+ onReverted(taskId: TaskId): void;
1482
+ onGate(phaseId: PhaseId, gate: GateState): void;
1483
+ onInbox(item: InboxItem): void;
1484
+ }
1485
+
1486
+ /**
1487
+ * Serial rebase/check/fast-forward queue, phase suite and landing (3.2).
1488
+ * Leases (A2, QA-1.4-22): the queue releases a task's leases (`LeaseService.releaseTask`) in the same step that releases its slot
1489
+ * (A1-2.4), i.e. after the fsync of the batch that moves it to integrated, cancelled or blocked (never before).
1490
+ */
1491
+ export interface IntegrationQueue {
1492
+ /** pre: each id is verified with slot and branch. Idempotent (an id already queued or integrating is ignored).
1493
+ * Dequeue only while `status === "running"` and the task's phase is null or not paused (A1-8): a queued task of a paused phase is
1494
+ * skipped but keeps its position, and a batch takes only dequeueable tasks.
1495
+ * Dequeue journals verified->integrating (durable) before any git step. err E_PLAN_STATE, E_DISPOSED */
1496
+ enqueue(taskIds: readonly TaskId[]): void;
1497
+ /** Runs once per plan before the first dequeue, whatever the task states, in running and paused (A1-3); starts no new step except its reruns.
1498
+ * Step 0 reconciles the integration branch tip with `integration.head` (complete a fast-forward that landed, else halt). A halt writes `status-changed running->paused` only when the plan is
1499
+ * `running` (an already paused plan stays paused, no event) and always raises the inbox item (A2, QA-1.4-26);
1500
+ * step 1 handles each open history entry oldest first by kind (rollback and requeue, rerun the revert, rerun the suite, tag, land).
1501
+ * Idempotent. */
1502
+ resume(): Promise<ResumeReport>;
1503
+ /** Starts the phase suite when §3.3's precondition holds and the plan is running with the phase not paused; idempotent.
1504
+ * Batch rules (A2, QA-1.4-21): the gate change into `suite-running` (trigger `phase-integrated`, or `suite-rerun` from `suite-failed`) and the
1505
+ * suite's opening `integration-step` (ISS) are ONE Q batch; the suite's closing ISE and the gate change out of `suite-running`
1506
+ * (`suite-passed` / `suite-culprit-found`) are ONE batch (same for a `suite-rerun` suite). A crash therefore never leaves the gate in
1507
+ * `suite-running` with a half-written pair, except through rollback while paused (below).
1508
+ * On gate `suite-running` with NO open phase-suite entry in `openIntegration()`: "start the suite, no gate event" (journal the ISS only;
1509
+ * the gate already is `suite-running`, so no `gate-changed` is written). Recovery row: gate `suite-running`, no open entry -> `checkPhase`.
1510
+ * The runtime calls `checkPhase` for each phase whose gate is `suite-running` or whose precondition holds when a paused plan resumes
1511
+ * (`status-changed paused->running`), so no phase stays in `suite-running` forever. */
1512
+ checkPhase(phaseId: PhaseId): Promise<void>;
1513
+ /** ff-when-clean or manual; never force, never non-ff. */
1514
+ land(): Promise<{ landed: boolean; inbox: InboxItem | null }>;
1515
+ /** Stops dequeuing, rolls back the step in progress, journals one batch with the row-33 events (integrating->cancelled) and closes the other
1516
+ * open entries `rolled-back` (A1-8 abort order, step 2). */
1517
+ abort(): Promise<void>;
1518
+ queued(): readonly TaskId[];
1519
+ dispose(): Promise<void>;
1520
+ }
1521
+
1522
+ /** Registry taskRef of a plan task; unique per process (PLAN_ID and TASK_ID grammars exclude ':'). */
1523
+ export function leaseTaskRef(planId: PlanId, taskId: TaskId): string { return `${planId}:${taskId}`; }
1524
+ /** Registry holderID of a plan task's own lease holder (before and independent of any child session). */
1525
+ export function leaseHolderID(planId: PlanId, taskId: TaskId): string { return `plan:${planId}:${taskId}`; }
1526
+ export interface LeaseHolderInfo {
1527
+ /** null: not a plan task (an ad-hoc child session). */
1528
+ planId: PlanId | null;
1529
+ taskId: TaskId | null;
1530
+ /** Registry holderID: a child session id, or leaseHolderID(...). */
1531
+ holderID: string;
1532
+ }
1533
+ /**
1534
+ * Which plan task holds a path lease (2.1). `path` is repo-relative (Footprint rules). Write keys are per checkout
1535
+ * (DF-1.1-4): only plan-task (`until-integrated`) leases conflict across the worktrees of a repository, so the port behind
1536
+ * this view must answer with the registry's repository-wide query (`LeaseRegistry.planHolderOf`), which matches a plan
1537
+ * task's lease in any worktree of the repo; the logical key alone matches one checkout only.
1538
+ */
1539
+ export interface LeaseView { holder(path: string): LeaseHolderInfo | null; }
1540
+ /**
1541
+ * Per-plan lease seam over the ONE process-wide Phase 1.3 registry (A2/A3, QA-1.4-22/-32/-33).
1542
+ * Holder of every task lease: { holderID: leaseHolderID(planId, id), tree, isChild: true,
1543
+ * taskRef: leaseTaskRef(planId, id), scope: "until-integrated" }.
1544
+ * Child sessions join through the 2.1 guard with their own holderID, the same taskRef and scope, and tree = slot path;
1545
+ * they are re-entrant (same owner) and end with releaseTask. Never calls registry.restore.
1546
+ */
1547
+ export interface LeaseService extends LeaseView {
1548
+ readonly planId: PlanId;
1549
+ /** tree = the task's slot path (SlotLease.path). writes = footprint.writes.
1550
+ * [] -> { ok: true } with no registry call (never pass [] to acquireWrite: it is an unknown-target write).
1551
+ * Otherwise ONE acquireWrite(holder, writes): atomic all-or-nothing in the registry.
1552
+ * held | unknown-target -> "held" with the holder(s) the registry names (at least one; not necessarily all). */
1553
+ acquireTask(i: { taskId: TaskId; tree: string; writes: readonly string[] }):
1554
+ | { ok: true }
1555
+ | { ok: false; reason: "held"; holders: LeaseHolderInfo[] }
1556
+ | { ok: false; reason: "cap" | "invalid"; message: string };
1557
+ /** registry.releaseTask(leaseTaskRef(planId, taskId)); idempotent.
1558
+ * Called after the fsync of every batch that writes TS(null) for the task, by the module that wrote it (A1-2.4 release column):
1559
+ * Rt rows 6, 9, 14, 15qa, 18b, 20, 22, 24, 27, 29, 39 (abort included); Q rows 5, 13, 19, 30, 33; P rows 17, 36.
1560
+ * For a live child being cancelled, after its completion settles. */
1561
+ releaseTask(taskId: TaskId): void;
1562
+ /** At open/takeover, after the slots are resolved. For every task: releaseTask(id); then for each task with
1563
+ * slot !== null and writes non-empty: acquireTask({ taskId: id, tree, writes: footprint.writes }).
1564
+ * Touches no holder outside this plan's taskRefs. Returns the tasks whose leases could not be re-taken
1565
+ * (the runtime raises one inbox item per entry; it does not throw). */
1566
+ rebuild(tasks: ReadonlyArray<{ id: TaskId; slot: string | null; tree: string | null; footprint: Footprint }>):
1567
+ Array<{ taskId: TaskId; holders: LeaseHolderInfo[] }>;
1568
+ }
1569
+ export interface TaskRoute {
1570
+ agent: string;
1571
+ /** Resolved (role-range-clamped) tier, not the role's floor or the task's unvalidated request. */
1572
+ tier?: string;
1573
+ model: { providerID: string; modelID: string; variant: string | null };
1574
+ provider: string;
1575
+ heavy: boolean;
1576
+ }
1577
+ export interface CapacityView {
1578
+ routeOf(task: TaskNode): TaskRoute;
1579
+ free(provider: string, heavy: boolean): number;
1580
+ }
1581
+ export interface ScheduledTask {
1582
+ taskId: TaskId;
1583
+ route: TaskRoute;
1584
+ bottomLevelMs: number;
1585
+ }
1586
+
1587
+ /** Critical-path scheduler (3.1.2); pure, deterministic, never throws for a valid ledger. */
1588
+ export interface Scheduler {
1589
+ /** Tasks that are ready, not manual/preflight, not in inFlight, in an unpaused phase of a running plan, with every edge satisfied
1590
+ * (task source integrated|done; gate source passed), R16, no held predicted write (soft), within free capacity counted down greedily.
1591
+ * Order: bottom level desc, ties by plan order.
1592
+ * `leases.holder(path)` answering a holder whose `planId` is another plan or null is "not a plan task" under R6 -> lease-unresolvable. */
1593
+ readySet(ledger: LedgerV1, inFlight: ReadonlySet<TaskId>, leases: LeaseView, capacity: CapacityView): ScheduledTask[];
1594
+ /** pending->ready and blocked->ready candidates. */
1595
+ promotable(ledger: LedgerV1): { toReady: TaskId[]; unblock: TaskId[] };
1596
+ manualReady(ledger: LedgerV1): TaskId[];
1597
+ /** Returns the learned edge to append, or null if it exists or would make a cycle (then R6: lease-unresolvable) */
1598
+ addLearnedEdge(ledger: LedgerV1, holder: TaskId, blocked: TaskId, evidence: string): Edge | null;
1599
+ }
1600
+
1601
+ /** A provider signal as the capacity controller sees it (3.1.3). */
1602
+ export interface ProviderSignal {
1603
+ source: "retry-hook" | "retry-scheduled" | "step-failed" | "execution-failed";
1604
+ sessionID: string;
1605
+ stepKey: string;
1606
+ provider: string;
1607
+ error: HostError;
1608
+ at: IsoTime;
1609
+ }
1610
+
1611
+ /** Adaptive per-provider concurrency (3.1.3, D13 495-535). */
1612
+ export interface CapacityController {
1613
+ /** 1..maxParallel */
1614
+ limit(provider: string): number;
1615
+ canAcquire(provider: string, heavy: boolean): boolean;
1616
+ /** err E_CAPACITY. `opts.force` never throws E_CAPACITY (late-child adoption only, A1-5). */
1617
+ acquire(provider: string, heavy: boolean, taskId: TaskId, attempt: number, opts?: { force: true }): { id: string };
1618
+ /** Idempotent; growth only after a quiet cooldown. */
1619
+ release(token: { id: string }, result: "success" | "other"): void;
1620
+ /** Dedupe per stepKey. The first rate-limit/overload signal of a step halves the limit (floor 1) and holds it for cooldown; quota -> pause.
1621
+ * Returns the inbox input for the runtime to raise once per pause. */
1622
+ onSignal(s: ProviderSignal): {
1623
+ decreased: boolean; pausedUntil: IsoTime | null; inbox: Omit<InboxItem, "id" | "createdAt" | "answer"> | null;
1624
+ };
1625
+ /** True only when planChild and (provider paused or the step's first retry signal is older than capacityCooldownMs). */
1626
+ shouldStopRetry(i: { sessionID: string; stepKey: string; provider: string; planChild: boolean }): boolean;
1627
+ pausedUntil(provider: string): IsoTime | null;
1628
+ snapshot(): JsonValue;
1629
+ }
1630
+
1631
+ // ---- TaskLauncher (3.1.5; launcher A only, ADR D14 548-645)
1632
+
1633
+ /** Identity of one retained capture (A1-4): the process, the capture counter and the router call. */
1634
+ export interface ContextRef {
1635
+ /** 16 lowercase hex, random once per process, owned by `ChildRunner`. */
1636
+ bootID: string;
1637
+ epoch: number;
1638
+ callID: string;
1639
+ }
1640
+
1641
+ /** The newest router-tool capture of a session in this process (§9). */
1642
+ export interface RetainedContextInfo {
1643
+ sessionID: string;
1644
+ callID: string;
1645
+ messageID: string;
1646
+ agent: string;
1647
+ capturedAt: IsoTime;
1648
+ bootID: string;
1649
+ /** +1 per capture in this process. */
1650
+ epoch: number;
1651
+ }
1652
+
1653
+ /** Thrown (rejected) by `ChildRunner.run` when the pinned capture is no longer the current one (A1-4, rows L5/L3). */
1654
+ export class ContextSupersededError extends Error {
1655
+ readonly requested: ContextRef;
1656
+ readonly current: ContextRef | null;
1657
+ constructor(requested: ContextRef, current: ContextRef | null) {
1658
+ super("retained context superseded");
1659
+ this.name = "ContextSupersededError";
1660
+ this.requested = requested;
1661
+ this.current = current;
1662
+ }
1663
+ }
1664
+
1665
+ /** True for a `ContextSupersededError`, by name, so it survives realm and module boundaries (A1-4). */
1666
+ export function isContextSupersededError(e: unknown): e is ContextSupersededError {
1667
+ return typeof e === "object" && e !== null && (e as { name?: unknown }).name === "ContextSupersededError";
1668
+ }
1669
+
1670
+ /**
1671
+ * Launch gate (A1-6). `disposed` has no wake; every other non-ok reason has one. Keys:
1672
+ * `context-stale` -> `stale-context:<bootID>:<epoch>`; `no-context` (a capture existed in this process and is gone) ->
1673
+ * `no-context:<bootID>:<orchestratorSessionID>:<lastEpoch>`; `awaiting-first-router-call` (guard 6) ->
1674
+ * `await-router-call:<bootID>:<orchestratorSessionID>`. The runtime wakes iff not ok, `wake !== null` and there is work
1675
+ * waiting for a root context: the ready set computed as if the gate were ok is non-empty, or recovered work (a
1676
+ * re-verification or a recovered child's end) has not yet been admitted (also on a paused plan).
1677
+ */
1678
+ export type LaunchGate =
1679
+ | { ok: true; context: RetainedContextInfo; ageMs: number }
1680
+ | { ok: false; reason: "disposed"; wake: null }
1681
+ | {
1682
+ ok: false;
1683
+ reason: "no-context" | "awaiting-first-router-call" | "context-stale";
1684
+ wake: { reason: "stale-context"; stateKey: string };
1685
+ };
1686
+
1687
+ export interface LaunchRequest {
1688
+ planId: PlanId;
1689
+ taskId: TaskId;
1690
+ attempt: number;
1691
+ nonce: string;
1692
+ orchestratorSessionID: string;
1693
+ /**
1694
+ * Resume of the same attempt; no new child, confirmed on the first step. It opens a new guard round and read-cap round for the
1695
+ * child (`DispatchBookkeeping.beginResumeRound`, QA-PDF21-2-11), and may follow its own attempt's run whose completion settled
1696
+ * before that run's runner returned (QA-PDF21-2-17).
1697
+ */
1698
+ resume?: { childSessionID: string };
1699
+ /** The gated capture; `attempt-started.attempt.callID === context.callID` (A1-4). */
1700
+ context: ContextRef;
1701
+ route: TaskRoute;
1702
+ role: string;
1703
+ /** Route `needs`. */
1704
+ grant: string[];
1705
+ /**
1706
+ * QA-PDF21-2-20 (optional, additive): the route's `budget=` (`routeBudgetOf(expanded.routeLine)`), bound with the child as a
1707
+ * routed dispatch's binding carries it, so the guard raises the child's per-dispatch budget by it. Absent or null: none named.
1708
+ */
1709
+ routeBudget?: number | null;
1710
+ /** Slot path. */
1711
+ workRoot: string;
1712
+ /** §7 grammar; the header must match (planId, taskId, attempt, nonce). */
1713
+ prompt: string;
1714
+ }
1715
+
1716
+ export interface LaunchHooks {
1717
+ /** Late child. Pure decision, journals nothing: "adopt" iff this attempt is the latest, its outcome lost, the task ready and the plan not aborted. */
1718
+ onLateChild(childSessionID: string): Promise<"adopt" | "refuse">;
1719
+ /** The single journaling point for a created child (in time or adopted late), inside onCreated after RoleBindings.bind and before the
1720
+ * child is prompted. Rt appends with a builder: dispatched with this attempt open -> [AC, TT child-created]; ready with this attempt
1721
+ * latest and lost -> [AA, TT adopt, G1] + forced token; anything else -> throw (refuse). A throw makes the runner interrupt the child. */
1722
+ onChildCreated(childSessionID: string): Promise<void>;
1723
+ /**
1724
+ * pdf2-1 (a): a `completed` end keeps the child's role binding (the caller may resume the child for its budget) until
1725
+ * `TaskLauncher.releaseBinding` drops it or a resume of the same child under the same task and attempt takes it over.
1726
+ * Absent or false: every end evicts the binding when the completion settles.
1727
+ */
1728
+ holdCompletedBinding?: boolean;
1729
+ }
1730
+
1731
+ /** Why a launch was not confirmed (A1-5): "timeout" and "threw" mark the context stale; "task-error" is R1 (counts). */
1732
+ export type LaunchConfirmation =
1733
+ | { kind: "confirmed"; childSessionID: string; latencyMs: number }
1734
+ | { kind: "unconfirmed"; reason: "timeout" | "threw" | "superseded" | "task-error" | "hook-failed"; error: string | null };
1735
+
1736
+ export type CancelReason = "abort" | "blocked" | "superseded" | "dispose";
1737
+
1738
+ /**
1739
+ * How a child ended. `endedAt` is the launcher's wall-clock reading and may precede `Attempt.startedAt` (clock step, restart).
1740
+ * The runtime journals `attempt-ended.endedAt = max(end.endedAt, attempt.startedAt)` so the ledger invariant
1741
+ * `endedAt >= startedAt` (`attempt-time`) always holds (A2, QA-1.4-27); it never rewrites `startedAt`.
1742
+ */
1743
+ export type ChildEnd =
1744
+ | { kind: "completed"; childSessionID: string; text: string; endedAt: IsoTime }
1745
+ | { kind: "failed"; childSessionID: string; error: HostError; endedAt: IsoTime }
1746
+ | { kind: "capacity"; childSessionID: string; error: HostError; endedAt: IsoTime }
1747
+ | { kind: "interrupted"; childSessionID: string | null; reason: CancelReason; endedAt: IsoTime }
1748
+ | {
1749
+ kind: "lost"; childSessionID: string | null;
1750
+ reason: "unconfirmed" | "unrequested-interrupt" | "runner-error" | "restart" | "context-superseded" | "refused";
1751
+ endedAt: IsoTime;
1752
+ };
1753
+
1754
+ export interface LaunchHandle {
1755
+ taskId: TaskId;
1756
+ attempt: number;
1757
+ nonce: string;
1758
+ context: ContextRef;
1759
+ contextAgeMs: number;
1760
+ startedAt: IsoTime;
1761
+ /** Settles within LAUNCH_CONFIRM_TIMEOUT_MS (Clock). */
1762
+ confirmation: Promise<LaunchConfirmation>;
1763
+ /** Settles exactly once; never rejects. */
1764
+ completion: Promise<ChildEnd>;
1765
+ }
1766
+
1767
+ /** Starts and cancels plan children through the retained router-call context (3.1.5). */
1768
+ export interface TaskLauncher {
1769
+ /** Pure read of in-memory state. ok only with a capture from `orchestratorSessionID` taken in this process (guard 6) whose epoch is not stale. */
1770
+ gate(orchestratorSessionID: string): LaunchGate;
1771
+ /** pre: gate ok and `req.context` is the current capture of `orchestratorSessionID`; the task is dispatched with its open attempt fsynced; the capacity token and slot are held, and the task's leases were acquired by Rt (`LeaseService.acquireTask`) before the row-4 batch and are released if the append fails or the builder returns [].
1772
+ * Does: the decision row, recordDispatchStart and the D2 in-flight registration (DispatchBookkeeping); then ChildRunner.run with detached:true,
1773
+ * `context: req.context`, an executor-owned AbortController (combined with the plugin lifetime), explicit agent and model, cwd = workRoot.
1774
+ * Emits the context-age metric. The launcher never journals (Rt does, A1-5). markStale only for "timeout" and "threw". Classifies the end:
1775
+ * runner result -> completed; else the terminal session.execution.* event (waits <= CHILD_END_GRACE_MS): failed -> executionFailureOutcome;
1776
+ * interrupted -> `interrupted` if cancel() was called, else `lost` (guard 5); no event -> lost(runner-error). The fallback trigger (D2): a
1777
+ * terminal event before the runner settles resolves completion, with text from HostSessions.context (last assistant message).
1778
+ * err (synchronous, before any host call): E_NO_CONTEXT (gate not ok / context is not the current capture), E_LAUNCH_TASK (header or prompt
1779
+ * mismatch, unknown agent, bad workRoot), E_DISPOSED */
1780
+ launch(req: LaunchRequest, hooks: LaunchHooks): LaunchHandle;
1781
+ /** Requested interrupt: records the request, aborts the executor-owned signal, HostSessions.interrupt(child) if known. Idempotent. */
1782
+ cancel(taskId: TaskId, attempt: number, reason: CancelReason): Promise<void>;
1783
+ inFlight(): ReadonlyArray<{ taskId: TaskId; attempt: number; childSessionID: string | null; startedAt: IsoTime }>;
1784
+ /**
1785
+ * pdf2-1 (a): evicts the binding a `completed` end held (`LaunchHooks.holdCompletedBinding`) once the caller decided not
1786
+ * to resume `childSessionID`. A no-op when nothing is held for it (a resume took it over, or it was never held).
1787
+ */
1788
+ releaseBinding?(childSessionID: string): void;
1789
+ /** Aborts every owned signal; journals nothing (recovery closes those attempts as lost). */
1790
+ dispose(): Promise<void>;
1791
+ }
1792
+
1793
+ /**
1794
+ * Journals `wake` (durable), then HostSessions.synthetic({..., resume: true}); debounced by wakeDebounceMs;
1795
+ * never the same stateKey twice (D15 668-671).
1796
+ */
1797
+ export interface Waker {
1798
+ /* Rules (A1-6, QA-1.4-23):
1799
+ * - Dedupe source: the `stateKey` of every `wake` event of the plan, i.e. `LedgerWriter.wakeKeys()` (history at open + this writer since).
1800
+ * - A key is burned when its `wake` event is journaled (durable, before `synthetic`): the same key never wakes twice -> "duplicate".
1801
+ * - "debounced" (inside `wakeDebounceMs` of the last wake) journals nothing and burns nothing.
1802
+ * - "failed" (the `synthetic` call threw) burns the key. The caller may retry the same situation at most twice, each at least
1803
+ * `wakeDebounceMs` after the previous, with the keys `<key>#2` and `<key>#3`.
1804
+ * - `inbox:<id>` keys are plan-unique already. */
1805
+ wake(reason: WakeReason, stateKey: string): Promise<"sent" | "debounced" | "duplicate" | "failed">;
1806
+ }
1807
+
1808
+ /**
1809
+ * The executor's public surface, consumed by 4.1 (tool/command) and 5.1 (3.1.6).
1810
+ * Every action on a plan whose orchestrator is another live session -> E_NOT_OWNER. Wrong status -> E_PLAN_STATE.
1811
+ * Exemption (A1-8, QA-1.4-16): `status`, `ready`, `exportPlan` and `planLine` are read-only: never E_NOT_OWNER, any status
1812
+ * including completed/aborted; `status` uses its `sessionID` only to pick the plan when `planId` is null.
1813
+ */
1814
+ export interface ExecutorRuntime {
1815
+ compile(i: { path: string; phases?: PhaseId[]; doneBefore?: PhaseId; sessionID: string }):
1816
+ Promise<{ planId: PlanId; summary: CompileSummary; residuePrompt: string | null }>;
1817
+ residue(planId: PlanId, text: string, sessionID: string): Promise<CompileSummary>;
1818
+ /** awaiting-approval -> running; config snapshot; slotsDir resolved. */
1819
+ approve(planId: PlanId, sessionID: string): Promise<void>;
1820
+ /** The full board with Appendix D metrics. */
1821
+ status(planId: PlanId | null, sessionID: string): Promise<string>;
1822
+ ready(planId: PlanId): Promise<{ launchable: TaskId[]; manual: TaskId[] }>;
1823
+ addTasks(planId: PlanId, text: string, sessionID: string): Promise<{ added: TaskId[]; reopened: TaskId[] }>;
1824
+ answer(planId: PlanId, inboxId: string, text: string, sessionID: string): Promise<void>;
1825
+ /** manual/preflight in ready only; else E_INVALID_INPUT */
1826
+ done(planId: PlanId, taskId: TaskId, sessionID: string): Promise<void>;
1827
+ pause(planId: PlanId, sessionID: string): Promise<void>;
1828
+ resume(planId: PlanId, sessionID: string): Promise<void>;
1829
+ /** Order (A1-8): (1) in-memory latch (no launch, enqueue or promotion); (2) `await queue.abort()` (on a throw: log and continue);
1830
+ * (3) one Rt builder batch cancelling every task not in {done, cancelled, integrated, integrating}, then `status-changed -> aborted` last;
1831
+ * (4) after the fsync `launcher.cancel(t, n, "abort")` for every launch in flight, including unsettled lost ones. Terminal states, gates and inbox untouched. */
1832
+ abort(planId: PlanId, sessionID: string): Promise<void>;
1833
+ land(planId: PlanId, sessionID: string): Promise<void>;
1834
+ adopt(planId: PlanId, sessionID: string): Promise<void>;
1835
+ gc(): Promise<{ removed: string[]; reported: string[] }>;
1836
+ exportPlan(planId: PlanId): Promise<string>;
1837
+ /** completed/aborted only: gc, deleteRefs omr/<planId>/, LedgerStore.remove */
1838
+ purge(planId: PlanId, sessionID: string): Promise<void>;
1839
+ // Host feeds (3.1.7 wiring). Never throw into the host.
1840
+ /** Refresh after capture; lifts guard 6; re-evaluates the ready set. */
1841
+ onRouterToolCall(sessionID: string): void;
1842
+ onHostEvent(e: HostSessionEvent): void;
1843
+ /** stop only for plan children */
1844
+ onRetryHook(i: { sessionID: string; stepKey: string; error: HostError }): { stop: boolean };
1845
+ /** Also used by RecoveryService; ignores closed attempts. */
1846
+ onChildEnd(taskId: TaskId, attempt: number, end: ChildEnd): Promise<void>;
1847
+ /** The Appendix B plan line (+ the stale suffix, 4361-4362). */
1848
+ planLine(sessionID: string): string | null;
1849
+ start(): Promise<void>;
1850
+ dispose(): Promise<void>;
1851
+ }
1852
+
1853
+ /** What recovery decided for one task (4.2.4; the matrix is in the memo §8). */
1854
+ export interface ReconcileAction {
1855
+ taskId: TaskId;
1856
+ from: TaskState;
1857
+ evidence: "finished" | "alive" | "lost" | "none";
1858
+ action: "adopt" | "process-result" | "requeue-lost" | "reverify" | "re-enqueue" | "resume-integration" | "interrupt-orphan" | "none";
1859
+ }
1860
+
1861
+ /** Restart recovery and orchestrator adoption (4.2.4, D16 679-707). */
1862
+ export interface RecoveryService {
1863
+ /** Once per process; only ledgers in running|paused with repo.toplevel === this session's toplevel. Second call is a no-op. */
1864
+ recover(): Promise<Array<{ planId: PlanId; actions: ReconcileAction[] }>>;
1865
+ /** Takes over a stale lock and journals orchestrator-bound(adopt); the launch gate then waits for that session's first router call. err E_LOCK_HELD */
1866
+ adopt(planId: PlanId, sessionID: string): Promise<void>;
1867
+ }
1868
+
1869
+ /** Unattended-run policy: inbox, parking, answers, the circuit breaker (4.2.2). */
1870
+ export interface UnattendedPolicy {
1871
+ /** Dedupe: an open item with the same kind+taskId+text is returned instead. Journals inbox-added (durable); wakes ("inbox", "inbox:<id>") unless closed at creation. */
1872
+ raise(i: Omit<InboxItem, "id" | "createdAt" | "answer"> & { answer?: string }): Promise<InboxItem>;
1873
+ /** From running (escalate|ambiguity|qa-unparsable|budget-cap) or conflict|failed|reverted (exhausted). post: parked; transitive **pending** dependents
1874
+ * -> blocked (a dependent of an un-integrated task cannot be ready or in flight, R9/R10); one inbox item.
1875
+ * Leases are held exactly while `slot !== null` (A1-2.4): parking releases the slot and so calls `LeaseService.releaseTask` after the fsync of the park batch (P rows 17, 36); the answered
1876
+ * task re-acquires through `LeaseService.acquireTask` when it is launched again (A2, QA-1.4-22). */
1877
+ park(taskId: TaskId, cause: "escalate" | "ambiguity" | "qa-unparsable" | "exhausted" | "budget-cap", text: string): Promise<InboxItem>;
1878
+ /** pre: item open. post: inbox-answered; attempt-context on the latest attempt; parked -> ready. A critical `qa-cap` item goes to
1879
+ * `QaLoop.onCapAnswer` instead (the answer must be one of its options). err E_INVALID_INPUT */
1880
+ answer(inboxId: string, text: string): Promise<{ resumed: TaskId | null }>;
1881
+ /** blocked -> ready where every dependency is integrated|done. */
1882
+ unblock(): Promise<TaskId[]>;
1883
+ /** Feeds a counted attempt (§4). A trip pauses the phase, raises one critical breaker item and wakes once. */
1884
+ recordAttempt(phaseId: PhaseId, a: Attempt): Promise<{ tripped: boolean }>;
1885
+ }
1886
+
1887
+ /** QA rounds: parse findings, create fix and re-review tasks, close the gate (4.2.3). */
1888
+ export interface QaLoop {
1889
+ /** Pure; extraction rule in §7. */
1890
+ parse(text: string): { ok: true; report: FindingsReport } | { ok: false; error: string };
1891
+ /** pre: the qa task is done; gate qa-running. post: A1-1 gate table (passed | pending with fix and re-review tasks created and edges added, round+1
1892
+ * | cap reached -> qa-cap critical item and phase paused); deferred minor/nit findings recorded as closed info items. Fix tasks of one round have
1893
+ * disjoint writes. Idempotent: if the gate is no longer qa-running it writes nothing and returns the outcome derived from the ledger. */
1894
+ onQaResult(taskId: TaskId, report: FindingsReport): Promise<"passed" | "next-round" | "cap-reached">;
1895
+ /** A phase with no open qa task (outside done/cancelled) and no open critical qa-cap item naming one of its qa tasks -> passed; otherwise a no-op. */
1896
+ onAwaitingQa(phaseId: PhaseId): Promise<void>;
1897
+ /** Answer of a critical `qa-cap` item: `accept` (defer the remaining findings, awaiting-qa -> passed) or `fix` (awaiting-qa -> pending, round+1,
1898
+ * fix and re-review tasks). The trimmed, lowercased answer must equal an option, else E_INVALID_INPUT. */
1899
+ onCapAnswer(inboxId: string, choice: QaCapChoice): Promise<"passed" | "next-round">;
1900
+ }
1901
+
1902
+ // Adapters over existing modules (§8): in-process, not I/O; doubles stand in for them in tests.
1903
+
1904
+ /** The routing kernel as the executor sees it. */
1905
+ export interface RouteResolver {
1906
+ route(task: TaskNode): TaskRoute;
1907
+ }
1908
+ /** binding.ts: binds a child session to a role, grant and work root. */
1909
+ export interface RoleBindings {
1910
+ bind(i: { childSessionID: string; role: string; agent: string; workRoot: string; grant: string[] }): void;
1911
+ }
1912
+ /** Dispatch bookkeeping the launcher drives around a launch (D2): decision row, dispatch start, in-flight registry. */
1913
+ export interface DispatchBookkeeping {
1914
+ decisionRow(req: LaunchRequest): void;
1915
+ recordDispatchStart(req: LaunchRequest, startedAt: IsoTime): void;
1916
+ registerInFlight(taskId: TaskId, attempt: number, childSessionID: string | null): void;
1917
+ /**
1918
+ * `status` (optional, additive, QA-3.1-24): how the launch settled when the launcher knows it, so a consumer does not fall
1919
+ * back to a guess when the runner result settles before the child's own end event.
1920
+ */
1921
+ unregisterInFlight(taskId: TaskId, attempt: number, status?: ChildEnd["kind"]): void;
1922
+ /**
1923
+ * QA-PDF21-2-11 (optional, additive): a launch that resumes its child (`req.resume`) opens a NEW guard round and a new read-cap
1924
+ * round for that child session before the runner call, exactly as a routed resume does: the per-dispatch budget and the read
1925
+ * counter restart, the cumulative ceiling stays. `prompt`: the launch prompt, whose cap line (if any) sets the new round's cap.
1926
+ */
1927
+ beginResumeRound?(childSessionID: string, agent: string, prompt: string): void;
1928
+ }
1929
+ /**
1930
+ * QA-PDF21-2-11/-20: the plugin's guard state of an executor child, as the v2 adapter's bookkeeping drives it (index.ts hands
1931
+ * it over through `routerOnExecutorChildGuard`). `beginResumeRound`: a resume's new guard round and read-cap round (a routed
1932
+ * resume's `guardStore.beginDispatch` and `resumeRoleSession`). `applyCap`: a freshly bound child's read cap, parsed from its
1933
+ * launch prompt's cap line as a routed role dispatch's is.
1934
+ */
1935
+ export interface ExecutorChildGuardPort {
1936
+ beginResumeRound(childSessionID: string, agent: string, prompt: string): void;
1937
+ applyCap(childSessionID: string, agent: string, prompt: string): void;
1938
+ }
1939
+ /** Deterministic verification of a task in its slot. */
1940
+ export interface SlotVerifier {
1941
+ verify(task: TaskNode, slot: SlotLease, attempt: Attempt): Promise<{ verdict: Verdict; findings: string; ref: string }>;
1942
+ }
1943
+
1944
+ // ---------------------------------------------------------------------------------------------------------------
1945
+ // §9 Seams (no real I/O in unit tests)
1946
+ // ---------------------------------------------------------------------------------------------------------------
1947
+
1948
+ /** Time and entropy; `randomHex` is the only entropy source (nonce). */
1949
+ export interface Clock {
1950
+ now(): number;
1951
+ iso(ms?: number): IsoTime;
1952
+ setTimer(ms: number, fn: () => void): { readonly id: number };
1953
+ clearTimer(h: { readonly id: number }): void;
1954
+ randomHex(bytes: number): string;
1955
+ }
1956
+
1957
+ export interface ProcessResult {
1958
+ code: number | null;
1959
+ signal: string | null;
1960
+ stdout: string;
1961
+ stderr: string;
1962
+ truncated: boolean;
1963
+ durationMs: number;
1964
+ }
1965
+ export interface ProcOpts {
1966
+ /** Optional v2 diagnostics, forwarded to the lowest process boundary. */
1967
+ service?: import("./observations").ServiceExecution;
1968
+ cwd: string;
1969
+ timeoutMs: number;
1970
+ env?: Readonly<Record<string, string>>;
1971
+ stdin?: string;
1972
+ maxOutputBytes?: number;
1973
+ signal?: AbortSignal;
1974
+ }
1975
+ /** No shell; a non-zero exit is a result; throws only spawn/ETIMEDOUT/EOUTPUT. Preparation adapters preserve `service`. */
1976
+ export interface GitRunner {
1977
+ run(args: readonly string[], o: ProcOpts): Promise<ProcessResult>;
1978
+ }
1979
+ /** Never a shell. `pid`/`hostname`/`isAlive` serve lock staleness (2.2.2.e). */
1980
+ export interface Spawner {
1981
+ run(command: string, args: readonly string[], o: ProcOpts): Promise<ProcessResult>;
1982
+ readonly pid: number;
1983
+ readonly hostname: string;
1984
+ isAlive(pid: number): boolean;
1985
+ }
1986
+ export interface FsStat {
1987
+ kind: "file" | "dir" | "symlink" | "junction" | "other";
1988
+ size: number;
1989
+ mtimeMs: number;
1990
+ }
1991
+ /** Errors carry `.code` (ENOENT, EEXIST, EPERM, EBUSY...); the 2 s EPERM/EBUSY retry belongs to the caller. */
1992
+ export interface FileSystem {
1993
+ readText(p: string): Promise<string>;
1994
+ writeText(p: string, data: string, o?: { exclusive?: boolean; fsync?: boolean }): Promise<void>;
1995
+ appendText(p: string, data: string, o: { fsync: boolean }): Promise<void>;
1996
+ rename(a: string, b: string): Promise<void>;
1997
+ rm(p: string, o: { recursive: boolean }): Promise<void>;
1998
+ mkdir(p: string): Promise<void>;
1999
+ readdir(p: string): Promise<string[]>;
2000
+ lstat(p: string): Promise<FsStat | null>;
2001
+ realpath(p: string): Promise<string>;
2002
+ fsyncDir(p: string): Promise<void>;
2003
+ }
2004
+
2005
+ export interface HostSessionContext {
2006
+ messages: Array<{ role: "user" | "assistant" | "idle"; text: string | null; outcome: string | null }>;
2007
+ /** Stored history has an open tool call; absent means unknown and is treated as in flight. */
2008
+ toolInFlight?: boolean;
2009
+ }
2010
+ /**
2011
+ * QA-3.1-8: the v2 adapter owns the step key `<sessionID>:<k>` and sets the optional `stepKey` on every step/retry event it
2012
+ * forwards (`step.started`, `retry`, `step.failed`); a consumer prefers `e.stepKey` over its own count.
2013
+ */
2014
+ export type HostSessionEvent =
2015
+ | { type: "step.started"; sessionID: string; providerID: string; modelID: string; stepKey?: string; at: IsoTime }
2016
+ | { type: "retry"; sessionID: string; stepKey: string; source: "hook" | "scheduled"; error: HostError; at: IsoTime }
2017
+ | { type: "step.failed" | "execution.failed"; sessionID: string; error: HostError; stepKey?: string; at: IsoTime }
2018
+ /** QA-3.1-8: the host's `session.step.ended`; it closes the step `stepKey` names. */
2019
+ | { type: "step.ended"; sessionID: string; stepKey?: string; at: IsoTime }
2020
+ | { type: "execution.interrupted" | "execution.completed"; sessionID: string; at: IsoTime };
2021
+
2022
+ /** O6b/C7: context, interrupt, synthetic; `move` and `get` as used in v2-client.ts:129,198. */
2023
+ export interface HostSessions {
2024
+ get(sessionID: string): Promise<{ id: string; parentID: string | null } | null>;
2025
+ context(sessionID: string): Promise<HostSessionContext>;
2026
+ activity(sessionID: string): Promise<"active" | "inactive" | "unknown">;
2027
+ interrupt(sessionID: string): Promise<void>;
2028
+ synthetic(i: {
2029
+ sessionID: string; text: string; description: string; metadata: Record<string, JsonValue>; resume: true;
2030
+ }): Promise<void>;
2031
+ move(sessionID: string, directory: string): Promise<void>;
2032
+ onEvent(listener: (e: HostSessionEvent) => void): () => void;
2033
+ }
2034
+
2035
+ export interface ChildRunRequest {
2036
+ parentSessionID: string;
2037
+ /** Resume this child session instead of creating one (the runner honours it). */
2038
+ resumeSessionID?: string;
2039
+ prompt: string;
2040
+ agent: string;
2041
+ model: { providerID: string; modelID: string; variant: string | null };
2042
+ cwd: string;
2043
+ /** Executor-owned. */
2044
+ signal: AbortSignal;
2045
+ /** QA-0.1-25: the runner must NOT add the retained toolContext.signal and must NOT forward progress, even while that call is active. */
2046
+ detached: true;
2047
+ /**
2048
+ * The gated capture this run is pinned to (A1-4): `run()` uses exactly this capture; when
2049
+ * `retainedContext(parentSessionID)` is null or its (bootID, epoch, callID) differs, it rejects with
2050
+ * `ContextSupersededError` before any host call.
2051
+ */
2052
+ context: ContextRef;
2053
+ onCreated(childSessionID: string): Promise<void>;
2054
+ onConfirmed?(childSessionID: string): Promise<void>;
2055
+ }
2056
+ export interface ChildRunner {
2057
+ /** 16 lowercase hex, random once per process (A1-4). */
2058
+ readonly bootID: string;
2059
+ run(r: ChildRunRequest): Promise<{ sessionID: string; text: string }>;
2060
+ dispose(sessionID: string): Promise<void>;
2061
+ /** The newest router-tool capture of that session in this process. */
2062
+ retainedContext(sessionID: string): RetainedContextInfo | null;
2063
+ onContextCaptured(listener: (c: RetainedContextInfo) => void): () => void;
2064
+ }