opencode-model-router 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  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
@@ -0,0 +1,1080 @@
1
+ import { createHash } from "node:crypto";
2
+ import { posix, win32 } from "node:path";
3
+
4
+ import type { RoleSpec } from "../../router/roles";
5
+ import { NEEDS, type RouteLine } from "../../routing/classify/types";
6
+ import type { AnnotatedPlan, PlanStep } from "../../routing/engine";
7
+ import type { DurationModel } from "../../routing/outcomes/durations";
8
+ import { neutralizeDirectives } from "../../verify/pending";
9
+ import { grantFor } from "../../routing/roles/policy";
10
+ import {
11
+ EXECUTOR_LIMITS,
12
+ ExecutorError,
13
+ LAUNCH_HEADER_PATTERN,
14
+ ORCHESTRATOR_SHELL_RE,
15
+ PLAN_ID_PATTERN,
16
+ ledgerViolations,
17
+ type CompileSummary,
18
+ type Edge,
19
+ type ExecutorConfig,
20
+ type JsonValue,
21
+ type LedgerV1,
22
+ type PhaseRecord,
23
+ type PlanCompiler,
24
+ type PlanId,
25
+ type TaskId,
26
+ type TaskNode,
27
+ type TaskState,
28
+ type Tier,
29
+ } from "../types";
30
+ import { Reach, buildEdges, conflictEdges, type EdgeTask } from "./edges";
31
+ import { formatSummary, planEstimate, taskEstimate } from "./estimate";
32
+ import {
33
+ UNKNOWN_WRITES,
34
+ extractFootprint,
35
+ loadRepoView,
36
+ repoViewFrom,
37
+ type OwnershipInput,
38
+ type RepoGit,
39
+ type RepoView,
40
+ type TaskFootprint,
41
+ } from "./footprint";
42
+ import { annotateUnrouted, parsePlan, type CompileIssue, type ParsedPhase, type ParsedPlan, type ParsedTask } from "./parse";
43
+ import {
44
+ mergeResidueInto,
45
+ parseResidue,
46
+ residueOverflow,
47
+ residueRequestOf,
48
+ validateResidue,
49
+ type ResidueCandidate,
50
+ } from "./residue";
51
+ import { isTopNode, validateLedger } from "./validate";
52
+
53
+ export { formatSummary };
54
+
55
+ // Plan compiler (memo 2.3.1 sections 1 and 9). No I/O except through `CompilerDeps`.
56
+
57
+ const ISO_MS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
58
+
59
+ function sha256Hex(text: string): string {
60
+ return createHash("sha256").update(text, "utf8").digest("hex");
61
+ }
62
+
63
+ function sha1Hex(text: string): string {
64
+ return createHash("sha1").update(text, "utf8").digest("hex");
65
+ }
66
+
67
+ function slug(s: string): string {
68
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
69
+ }
70
+
71
+ function baseName(p: string): string {
72
+ const seg = p.split(/[\\/]/).filter((x) => x !== "");
73
+ const last = seg[seg.length - 1] ?? "plan";
74
+ const dot = last.lastIndexOf(".");
75
+ return dot > 0 ? last.slice(0, dot) : last;
76
+ }
77
+
78
+ /** Slug of the plan file name (plus the selected phases); at most 41 chars, else cut to 34 plus `-` and 6 hex of its sha1. */
79
+ export function planIdOf(planPath: string, phases: readonly string[] | undefined, doneBefore?: string): PlanId {
80
+ let id = slug(baseName(planPath));
81
+ // QA-2.3-17: `--` cannot occur inside a slugged phase id, so ["1.1.2"] and ["1.1","2"] stay distinct; doneBefore is part of the id.
82
+ if (phases !== undefined && phases.length > 0) id = `${id}-${phases.map(slug).join("--")}`;
83
+ if (doneBefore !== undefined) id = `${id}-db-${slug(doneBefore)}`;
84
+ if (id === "") id = "plan";
85
+ if (id.length > 41) id = `${id.slice(0, 34).replace(/-+$/, "")}-${sha1Hex(id).slice(0, 6)}`;
86
+ if (!PLAN_ID_PATTERN.test(id)) id = `p-${sha1Hex(id).slice(0, 8)}`;
87
+ return id;
88
+ }
89
+
90
+ function isAbsolutePlanPath(p: string): boolean {
91
+ return /^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+|\/)/.test(p);
92
+ }
93
+
94
+ function inRangeOf(v: unknown, r: readonly [number, number], integer: boolean): boolean {
95
+ return typeof v === "number" && Number.isFinite(v) && (!integer || Number.isInteger(v)) && v >= r[0] && v <= r[1];
96
+ }
97
+
98
+ /** Shape plus `EXECUTOR_LIMITS` check of a config; the first problem as text, else null. */
99
+ function configProblem(c: ExecutorConfig): string | null {
100
+ const L = EXECUTOR_LIMITS;
101
+ const checks: Array<[string, unknown, readonly [number, number], boolean]> = [
102
+ ["maxParallel", c.maxParallel, L.maxParallel, true],
103
+ ["batchMax", c.batchMax, L.batchMax, true],
104
+ ["maxAttempts", c.maxAttempts, L.maxAttempts, true],
105
+ ["qaMaxRounds", c.qaMaxRounds, L.qaMaxRounds, true],
106
+ ["sharedContextChars", c.sharedContextChars, L.sharedContextChars, true],
107
+ ["capacityCooldownMs", c.capacityCooldownMs, L.capacityCooldownMs, true],
108
+ ["capacityPauseMs", c.capacityPauseMs, L.capacityPauseMs, true],
109
+ ["wakeDebounceMs", c.wakeDebounceMs, L.wakeDebounceMs, true],
110
+ ["circuitBreaker.failureRatio", c.circuitBreaker?.failureRatio, L.failureRatio, false],
111
+ ["circuitBreaker.minAttempts", c.circuitBreaker?.minAttempts, L.minAttempts, true],
112
+ ["circuitBreaker.consecutiveFailures", c.circuitBreaker?.consecutiveFailures, L.consecutiveFailures, true],
113
+ ];
114
+ for (const [name, v, r, integer] of checks) {
115
+ if (!inRangeOf(v, r, integer)) return `config.${name} must be ${integer ? "an integer" : "a number"} in ${r[0]}..${r[1]}`;
116
+ }
117
+ if (c.approve !== "ask" && c.approve !== "auto") return "config.approve must be ask or auto";
118
+ if (c.crossPhase !== "gate" && c.crossPhase !== "inferred") return "config.crossPhase must be gate or inferred";
119
+ if (c.land !== "ff-when-clean" && c.land !== "manual") return "config.land must be ff-when-clean or manual";
120
+ if (c.slotsDir !== null && typeof c.slotsDir !== "string") return "config.slotsDir must be a string or null";
121
+ if (typeof c.python !== "string") return "config.python must be a string";
122
+ // QA-2.3-17: the command-valued settings are checked here too, so a bad draft is rejected at the input.
123
+ if (!(c.integrationChecks === "auto" || isRunCommandRefs(c.integrationChecks))) {
124
+ return "config.integrationChecks must be \"auto\" or a list of {script, args}";
125
+ }
126
+ if (!(c.phaseSuite === "auto" || c.phaseSuite === "off" || isRunCommandRefs(c.phaseSuite))) {
127
+ return "config.phaseSuite must be \"auto\", \"off\" or a list of {script, args}";
128
+ }
129
+ const prov: unknown = c.provision;
130
+ const provOk = prov === "auto" || (typeof prov === "object" && prov !== null && !Array.isArray(prov)
131
+ && Object.values(prov).every((m: unknown) => Array.isArray(m) && m.every(isStringArray)));
132
+ if (!provOk) return "config.provision must be \"auto\" or a map of string[][]";
133
+ return null;
134
+ }
135
+
136
+ function isStringArray(v: unknown): boolean {
137
+ return Array.isArray(v) && v.every((s) => typeof s === "string");
138
+ }
139
+
140
+ function isRunCommandRefs(v: unknown): boolean {
141
+ return Array.isArray(v) && v.every((r: unknown) => {
142
+ if (typeof r !== "object" || r === null) return false;
143
+ const o = r as { script?: unknown; args?: unknown };
144
+ return typeof o.script === "string" && isStringArray(o.args);
145
+ });
146
+ }
147
+
148
+ /** Deep copy of a JSON-shaped config. */
149
+ function cloneConfig(c: ExecutorConfig): ExecutorConfig {
150
+ return JSON.parse(JSON.stringify(c)) as ExecutorConfig;
151
+ }
152
+
153
+ function checkInputs(
154
+ planPath: string,
155
+ opts: { config: ExecutorConfig; now: string; orchestratorSessionID: string },
156
+ ): ExecutorConfig {
157
+ if (typeof planPath !== "string" || !isAbsolutePlanPath(planPath)) {
158
+ throw new ExecutorError("E_INVALID_INPUT", "planPath must be an absolute path", { planPath });
159
+ }
160
+ if (typeof opts.now !== "string" || !ISO_MS_RE.test(opts.now) || !Number.isFinite(Date.parse(opts.now))) {
161
+ throw new ExecutorError("E_INVALID_INPUT", "now must be an ISO time with milliseconds", { now: String(opts.now) });
162
+ }
163
+ if (typeof opts.orchestratorSessionID !== "string" || opts.orchestratorSessionID === "") {
164
+ throw new ExecutorError("E_INVALID_INPUT", "orchestratorSessionID must be a non-empty string", null);
165
+ }
166
+ if (typeof opts.config !== "object" || opts.config === null) {
167
+ throw new ExecutorError("E_INVALID_INPUT", "config must be an object", null);
168
+ }
169
+ const problem = configProblem(opts.config);
170
+ if (problem !== null) throw new ExecutorError("E_INVALID_INPUT", problem, null);
171
+ return cloneConfig(opts.config);
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------------------------------------------
175
+ // Shared context (D2): paths -> <worktree>, headers removed, directives neutralised, cap at the last newline.
176
+
177
+ const HEADER_REPLACEMENT = "[header-shaped line removed]";
178
+
179
+ function escapeRe(s: string): string {
180
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
181
+ }
182
+
183
+ function rootRegex(root: string, ci: boolean): RegExp | null {
184
+ const parts = root.split(/[\\/]+/).filter((x) => x !== "");
185
+ if (parts.length === 0) return null;
186
+ const lead = /^[\\/]{2}/.test(root) ? "[\\\\/]{2}" : /^[\\/]/.test(root) ? "[\\\\/]" : "";
187
+ const body = parts.map(escapeRe).join("[\\\\/]+");
188
+ return new RegExp(`${lead}${body}(?![A-Za-z0-9_.-])[\\\\/]*`, ci ? "gi" : "g");
189
+ }
190
+
191
+ function cutAtNewline(text: string, cap: number): string {
192
+ if (text.length <= cap) return text;
193
+ const nl = text.lastIndexOf("\n", cap);
194
+ if (nl > 0) return text.slice(0, nl).replace(/\s+$/, "");
195
+ let end = cap;
196
+ const code = text.charCodeAt(end - 1);
197
+ if (code >= 0xd800 && code <= 0xdbff) end -= 1;
198
+ return text.slice(0, end);
199
+ }
200
+
201
+ function sharedContextOf(
202
+ raw: string,
203
+ roots: readonly string[],
204
+ ci: boolean,
205
+ cap: number,
206
+ warnings: CompileIssue[],
207
+ ): string {
208
+ let text = raw;
209
+ const ordered = [...new Set(roots)].sort((a, b) => b.length - a.length);
210
+ for (const root of ordered) {
211
+ const re = rootRegex(root, ci);
212
+ if (re !== null) text = text.replace(re, (m) => (/[\\/]$/.test(m) ? `<worktree>${m.includes("/") && !m.includes("\\") ? "/" : "\\"}` : "<worktree>"));
213
+ }
214
+ const headerRe = new RegExp(LAUNCH_HEADER_PATTERN.source, LAUNCH_HEADER_PATTERN.flags.replace(/[gy]/g, ""));
215
+ const lines = text.split(/\r\n|\n|\r/);
216
+ let removed = 0;
217
+ const kept = lines.map((l) => {
218
+ if (!headerRe.test(l)) return l;
219
+ removed += 1;
220
+ return HEADER_REPLACEMENT;
221
+ });
222
+ if (removed > 0) {
223
+ warnings.push({ code: "shared-context-header", line: 0, message: `${removed} header-shaped line(s) in the shared context were removed` });
224
+ }
225
+ text = neutralizeDirectives(kept.join("\n"));
226
+ const cut = cutAtNewline(text, cap);
227
+ if (cut.length < text.length) {
228
+ warnings.push({ code: "shared-context-truncated", line: 0, message: `shared context cut to ${cut.length} of ${text.length} chars` });
229
+ }
230
+ return cut;
231
+ }
232
+
233
+ // ---------------------------------------------------------------------------------------------------------------
234
+ // Edge-task helpers
235
+
236
+ const CONTRACT_TITLE_RE = /\b(?:contract|interface|types?|schema)\b/i;
237
+ const CONTRACT_VERB_RE = /\b(?:define|implement|create|add|write|extend|introduce|declare|export|update|modify|specify)\b/i;
238
+ const CONTRACT_FILE_RE = /(?:^|\/)(?:types\.ts|[^/]*\.d\.ts|schema[^/]*|contract[^/]*)$/i;
239
+
240
+ function isContractTask(title: string, writes: readonly string[]): boolean {
241
+ if (CONTRACT_TITLE_RE.test(title) && CONTRACT_VERB_RE.test(title)) return true;
242
+ // QA-2.3-32: a directory write also keeps its directory key (QA-2.3-16); that key (a prefix of another write) is not a file.
243
+ const dirs = new Set<string>();
244
+ for (const w of writes) {
245
+ for (let cut = w.lastIndexOf("/"); cut > 0; cut = w.lastIndexOf("/", cut - 1)) dirs.add(w.slice(0, cut).toLowerCase());
246
+ }
247
+ return writes.some((w) => !dirs.has(w.toLowerCase()) && CONTRACT_FILE_RE.test(w));
248
+ }
249
+
250
+ function formatIssue(i: CompileIssue): string {
251
+ return i.line > 0 ? `${i.code} L${i.line}: ${i.message}` : `${i.code}: ${i.message}`;
252
+ }
253
+
254
+ function edgeTaskOf(t: TaskNode, planIndex: number): EdgeTask {
255
+ const top = isTopNode(t);
256
+ return {
257
+ id: t.id,
258
+ phase: t.phase,
259
+ kind: t.kind,
260
+ planIndex,
261
+ writes: top ? UNKNOWN_WRITES : t.footprint.writes,
262
+ reads: t.footprint.reads,
263
+ confidence: t.footprint.confidence,
264
+ isContract: isContractTask(t.title, t.footprint.writes),
265
+ };
266
+ }
267
+
268
+ function gateRef(phase: string): string {
269
+ return `gate:${phase}`;
270
+ }
271
+
272
+ /** Phase gate dependencies derived from `gate:P -> task` edges (D7), in phase order. */
273
+ function dependsOnFrom(phases: readonly PhaseRecord[], tasks: Readonly<Record<string, TaskNode>>, edges: readonly Edge[]): void {
274
+ const deps = new Map<string, Set<string>>();
275
+ for (const e of edges) {
276
+ if (!e.from.startsWith("gate:")) continue;
277
+ const from = e.from.slice("gate:".length);
278
+ const to = tasks[e.to]?.phase ?? null;
279
+ if (to === null || to === from) continue;
280
+ const s = deps.get(to);
281
+ if (s === undefined) deps.set(to, new Set([from]));
282
+ else s.add(from);
283
+ }
284
+ const order = new Map(phases.map((p, i) => [p.id, i] as const));
285
+ for (const p of phases) {
286
+ const s = deps.get(p.id);
287
+ p.dependsOn = s === undefined ? [] : [...s].sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
288
+ }
289
+ }
290
+
291
+ function countPrior(tasks: readonly TaskNode[]): number {
292
+ return tasks.filter((t) => t.kind !== "manual" && t.kind !== "preflight" && t.estimate.source === "prior").length;
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------------------------------------------
296
+ // Dependencies
297
+
298
+ /** Everything the compiler touches outside memory; stubbed in tests. */
299
+ export interface CompilerDeps {
300
+ fs: {
301
+ readText(absPath: string): Promise<string>;
302
+ /** Optional seam (QA-2.3-17): the real path of the common git dir, used as `repo.key`. */
303
+ realpath?(absPath: string): Promise<string>;
304
+ };
305
+ git: RepoGit;
306
+ /**
307
+ * Optional seam (QA-2.3-3): the tracked files (repo-relative, '/'-separated) of the repository at `toplevel`, for
308
+ * `addTasks`, which is synchronous. When absent, `addTasks` uses the files recorded by the last `compile` of the same
309
+ * repository (`repo.key`) and, failing that, only the paths the ledger already knows.
310
+ */
311
+ listTrackedFiles?: (toplevel: string) => readonly string[];
312
+ durations: DurationModel;
313
+ /** Bound to `annotateSteps`. */
314
+ annotate: (steps: readonly PlanStep[]) => Promise<AnnotatedPlan>;
315
+ /** Selected role's resolved policy (including configured narrowing); stubbed in tests. */
316
+ roleOf: (route: RouteLine | null, tier: Tier | null) => RoleSpec;
317
+ /** `<defaultSlotsDir(toplevel, planId)>\integration` (O1). */
318
+ integrationWorktree: (planId: PlanId, repo: LedgerV1["repo"]) => string;
319
+ }
320
+
321
+ const SETTLED: ReadonlySet<TaskState> = new Set<TaskState>(["done", "cancelled", "integrated"]);
322
+
323
+ /**
324
+ * `PathOutcome` reasons for a spelling that leaves the repository (a write there is rejected by `addTasks`). A URL is not
325
+ * among them (QA-2.3-23): it is never a write target, so it is ignored like a read.
326
+ */
327
+ const OUTSIDE_REASONS: ReadonlySet<string> = new Set(["outside", "other-drive", "unc", "device", "escape"]);
328
+
329
+ function defaultCi(): boolean {
330
+ return process.platform === "win32";
331
+ }
332
+
333
+ function dirOf(p: string): string {
334
+ return /^(?:[A-Za-z]:|\\\\)/.test(p) ? win32.dirname(p) : posix.dirname(p);
335
+ }
336
+
337
+ function isTier(v: unknown): v is Tier {
338
+ return v === "fast" || v === "medium" || v === "heavy";
339
+ }
340
+
341
+ async function gitText(git: RepoGit, args: readonly string[], cwd: string): Promise<string> {
342
+ const r = await git.run(args, cwd);
343
+ if (r.code !== 0) throw new ExecutorError("E_GIT", `git ${args.join(" ")} failed (exit ${r.code})`, { args: [...args], code: r.code });
344
+ return r.stdout.trim();
345
+ }
346
+
347
+ async function readRepo(deps: CompilerDeps, toplevel: string): Promise<LedgerV1["repo"]> {
348
+ const git = deps.git;
349
+ const common = await gitText(git, ["rev-parse", "--path-format=absolute", "--git-common-dir"], toplevel);
350
+ const branch = await git.run(["symbolic-ref", "HEAD"], toplevel);
351
+ const branchRef = branch.stdout.trim();
352
+ if (branch.code !== 0 || !branchRef.startsWith("refs/heads/") || branchRef === "refs/heads/") {
353
+ throw new ExecutorError("E_INVALID_INPUT", "check out the base branch before compiling a plan (detached HEAD)", null);
354
+ }
355
+ const baseBranch = branchRef.slice("refs/heads/".length);
356
+ // Resolve the branch ref afresh on every compile, never the plan directory's HEAD or a cached base.
357
+ const baseCommit = await gitText(git, ["rev-parse", "--verify", `refs/heads/${baseBranch}^{commit}`], toplevel);
358
+ const abs = /^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(common) ? common : (/^[A-Za-z]:/.test(toplevel) ? win32.resolve(toplevel, common) : posix.resolve(toplevel, common));
359
+ // QA-2.3-17: the key is the real path of the common git dir, so two spellings of one repository get one key.
360
+ const key = deps.fs.realpath === undefined ? abs : await deps.fs.realpath(abs);
361
+ return { key, toplevel, baseBranch, baseCommit };
362
+ }
363
+
364
+ // ---------------------------------------------------------------------------------------------------------------
365
+ // Selection
366
+
367
+ interface Selection {
368
+ included: ParsedPhase[];
369
+ selected: ReadonlySet<string>;
370
+ earlier: ReadonlySet<string>;
371
+ }
372
+
373
+ function selectPhases(parsed: ParsedPlan, opts: { phases?: readonly string[]; doneBefore?: string }, warnings: CompileIssue[]): Selection {
374
+ const byId = new Map(parsed.phases.map((p) => [p.id, p] as const));
375
+ const order = new Map(parsed.phases.map((p, i) => [p.id, i] as const));
376
+ const selected = new Set<string>();
377
+ if (opts.phases === undefined) {
378
+ for (const p of parsed.phases) selected.add(p.id);
379
+ } else {
380
+ if (opts.phases.length === 0) throw new ExecutorError("E_INVALID_INPUT", "phases must not be empty", null);
381
+ for (const id of opts.phases) {
382
+ const p = byId.get(id);
383
+ if (p === undefined) throw new ExecutorError("E_INVALID_INPUT", `unknown phase ${id}`, { phase: id });
384
+ if (p.dogfood) throw new ExecutorError("E_INVALID_INPUT", `phase ${id} is a dogfood phase and cannot be selected`, { phase: id });
385
+ selected.add(id);
386
+ }
387
+ for (const p of parsed.phases) {
388
+ if (p.synthetic && p.id.endsWith(".post") && selected.has(p.id.slice(0, -".post".length))) selected.add(p.id);
389
+ }
390
+ }
391
+ const earlier = new Set<string>();
392
+ if (opts.doneBefore !== undefined) {
393
+ const at = order.get(opts.doneBefore);
394
+ if (at === undefined) throw new ExecutorError("E_INVALID_INPUT", `unknown doneBefore phase ${opts.doneBefore}`, { phase: opts.doneBefore });
395
+ for (const p of parsed.phases) if ((order.get(p.id) ?? 0) < at) earlier.add(p.id);
396
+ }
397
+ const included = parsed.phases.filter((p) => selected.has(p.id) || earlier.has(p.id));
398
+ const includedIds = new Set(included.map((p) => p.id));
399
+ for (const p of included) {
400
+ if (!selected.has(p.id)) continue;
401
+ for (const d of p.dependsOn) {
402
+ if (includedIds.has(d.id)) continue;
403
+ if (d.external && !byId.has(d.id)) {
404
+ // QA-2.3-10: an external (dogfood) dependency cannot be checked here; the caller must vouch for it with doneBefore.
405
+ if (opts.doneBefore === undefined) {
406
+ throw new ExecutorError(
407
+ "E_INVALID_INPUT",
408
+ `phase ${p.id} depends on ${d.id}, which is not in this plan; pass doneBefore to run without it`,
409
+ { phase: p.id, dependsOn: d.id },
410
+ );
411
+ }
412
+ warnings.push({ code: "depends-external-unknown", line: d.line, message: `phase ${p.id} depends on ${d.id}, which is not in this plan; ignored (doneBefore is set)` });
413
+ continue;
414
+ }
415
+ throw new ExecutorError(
416
+ "E_INVALID_INPUT",
417
+ `phase ${p.id} depends on ${d.id}, which is neither selected nor earlier than doneBefore`,
418
+ { phase: p.id, dependsOn: d.id },
419
+ );
420
+ }
421
+ }
422
+ // QA-2.3-25: the same dependency rule for graph edges: an edge from a phase (or a task of a phase) that is neither
423
+ // selected nor earlier than doneBefore into a selected phase would be dropped silently, so the run is refused.
424
+ if (opts.phases !== undefined) {
425
+ const taskPhase = new Map(parsed.tasks.map((t) => [t.id, t.phase] as const));
426
+ const waveById = new Map(parsed.waves.map((w) => [w.id, w] as const));
427
+ const phasesOf = (id: string): string[] => {
428
+ if (byId.has(id)) return [id];
429
+ const w = waveById.get(id);
430
+ if (w !== undefined) return [...w.phases];
431
+ const ph = taskPhase.get(id);
432
+ return ph === undefined || ph === null ? [] : [ph];
433
+ };
434
+ for (const g of parsed.graphs) {
435
+ for (const e of g.edges) {
436
+ const into = phasesOf(e.to).filter((id) => selected.has(id));
437
+ if (into.length === 0) continue;
438
+ const outside = phasesOf(e.from).find((id) => !includedIds.has(id) && byId.get(id)?.dogfood !== true);
439
+ if (outside === undefined) continue;
440
+ throw new ExecutorError(
441
+ "E_INVALID_INPUT",
442
+ `graph edge ${e.raw.trim()} (line ${e.line}) comes from phase ${outside}, which is neither selected nor earlier than doneBefore`,
443
+ { phase: into[0] ?? null, dependsOn: outside, line: e.line },
444
+ );
445
+ }
446
+ }
447
+ }
448
+ return { included, selected, earlier };
449
+ }
450
+
451
+ // ---------------------------------------------------------------------------------------------------------------
452
+ // Node assembly
453
+
454
+ function ownershipOf(parsed: ParsedPlan, phase: string | null): OwnershipInput[] {
455
+ if (phase === null) return [];
456
+ return parsed.ownership.filter((r) => r.owners.includes(phase)).map((r) => ({ path: r.path, owners: r.owners, line: r.line }));
457
+ }
458
+
459
+ function isRoutedWriter(t: ParsedTask, fp: TaskFootprint): boolean {
460
+ return t.kind !== "manual" && t.kind !== "preflight" && t.kind !== "qa"
461
+ && !t.writesLine?.none && fp.footprint.writes.length > 0;
462
+ }
463
+
464
+ /** Footprints outrank inferred intent, never an author's explicit route. Role maxima stay unchanged. */
465
+ function writerRouteOf(t: ParsedTask, fp: TaskFootprint): ParsedTask["route"] {
466
+ const route = t.route;
467
+ if (route === null || route.inferred !== true || !isRoutedWriter(t, fp)) return route;
468
+ const fields = route.fields;
469
+ if (fields === null) return route;
470
+ const readOnlyClass = fields.class === "search" || fields.class === "recon" || fields.class === "design" || fields.class === "review";
471
+ const cls = readOnlyClass || fields.class === undefined ? "implement" : fields.class;
472
+ const needs = NEEDS.filter((need) => need === "edit" || fields.needs?.includes(need));
473
+ // Only engine-generated lines reach here: canonical class/needs tokens, with every other field kept verbatim.
474
+ let line = route.line;
475
+ for (const [key, value] of [["class", cls], ["needs", needs.join(",")]]) {
476
+ const token = new RegExp(`(\\s)${key}=[^\\s\\]]+`);
477
+ line = token.test(line) ? line.replace(token, `$1${key}=${value}`) : line.replace(/\]$/, ` ${key}=${value}]`);
478
+ }
479
+ return { ...route, line, fields: { ...fields, class: cls, needs } };
480
+ }
481
+
482
+ function nodeOf(
483
+ deps: CompilerDeps,
484
+ t: ParsedTask,
485
+ phase: string | null,
486
+ fp: TaskFootprint,
487
+ state: TaskState,
488
+ warnings: CompileIssue[],
489
+ ): TaskNode {
490
+ const manual = t.kind === "manual" || t.kind === "preflight";
491
+ const reconciled = writerRouteOf(t, fp);
492
+ const fields = reconciled?.fields ?? null;
493
+ const tier: Tier | null = t.tierTag ?? (isTier(fields?.tier) ? fields.tier : null);
494
+ const spec = manual ? null : deps.roleOf(fields, tier);
495
+ const role = spec?.agent ?? "";
496
+ if (spec !== null && reconciled !== null && reconciled.inferred !== true && isRoutedWriter(t, fp)) {
497
+ // Launch binds a slot work root. Check the selected role's declared grant, not its maximum or prose-inferred needs.
498
+ const grant = grantFor(spec, { class: fields?.class ?? "other", risk: fields?.risk ?? "low", scope: fields?.scope ?? "single",
499
+ needs: fields?.needs ?? [], confidence: 1, source: "route-line" }, [], "<executor-slot>");
500
+ if (!grant.actions.has("edit")) {
501
+ throw new ExecutorError("E_COMPILE", `route-write-conflict (line ${t.span.line}): task ${t.id} declares writes but its explicit route is read-only (${role} has no edit grant); choose an edit-capable class and needs=edit`,
502
+ { code: "route-write-conflict", line: t.span.line, taskId: t.id });
503
+ }
504
+ }
505
+ const route: TaskNode["route"] = manual
506
+ ? { line: "", role: "", tier: null, pin: false }
507
+ : { line: reconciled?.line ?? "", role, tier, pin: fields?.pin ?? false };
508
+ let verify: TaskNode["verify"];
509
+ if (manual) verify = "none";
510
+ else if (t.verify !== null) verify = t.verify;
511
+ else if (t.kind === "qa") verify = "none";
512
+ else if (t.acceptance !== null || (fields?.detection !== undefined && fields.detection !== "none")) verify = "required";
513
+ else {
514
+ verify = "none";
515
+ warnings.push({ code: "unverified-task", line: t.span.line, message: `task ${t.id} has no acceptance block or detection; it will not be verified` });
516
+ }
517
+ return {
518
+ id: t.id,
519
+ title: t.title,
520
+ phase,
521
+ kind: t.kind,
522
+ text: t.text,
523
+ subtasks: [...t.subtasks],
524
+ route,
525
+ verify,
526
+ acceptance: t.acceptance,
527
+ footprint: fp.footprint,
528
+ estimate: taskEstimate(deps.durations, { kind: t.kind, state, role, tier, route: fields }),
529
+ state,
530
+ attempts: [],
531
+ slot: null,
532
+ branch: null,
533
+ integrated: null,
534
+ };
535
+ }
536
+
537
+ function footprintWarnings(t: ParsedTask, fp: TaskFootprint, out: CompileIssue[]): void {
538
+ for (const i of fp.ignored) {
539
+ out.push({ code: "path-ignored", line: i.line, message: `${t.id}: ${JSON.stringify(i.raw)} ignored (${i.reason})` });
540
+ }
541
+ for (const r of fp.foreignRoots) {
542
+ out.push({ code: "foreign-root", line: t.span.line, message: `${t.id}: paths under ${r} were mapped into this repository` });
543
+ }
544
+ if (fp.ownershipAssumed) {
545
+ out.push({
546
+ code: "ownership-assumed",
547
+ line: t.span.line,
548
+ message: `${t.id}: no write evidence; assumed to write everything its phase owns (confidence inferred)`,
549
+ });
550
+ }
551
+ }
552
+
553
+ function summaryOf(l: LedgerV1, warnings: readonly string[]): CompileSummary {
554
+ const tasks = Object.values(l.tasks);
555
+ return {
556
+ tasks: tasks.length,
557
+ phases: l.phases.length,
558
+ edges: l.edges.length,
559
+ ...planEstimate(l, l.config.maxParallel),
560
+ manual: tasks.filter((t) => t.kind === "manual" || t.kind === "preflight").map((t) => t.id),
561
+ warnings: [...warnings],
562
+ };
563
+ }
564
+
565
+ // ---------------------------------------------------------------------------------------------------------------
566
+ // Residue candidates
567
+
568
+ const UNRESOLVED_CODES: ReadonlySet<string> = new Set(["graph-node-unknown", "explicit-ref-unknown", "explicit-merged-first-unresolved"]);
569
+
570
+ function lexical(p: string): string {
571
+ return p.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
572
+ }
573
+
574
+ function residueCandidates(a: {
575
+ parsedTasks: ReadonlyMap<string, ParsedTask>;
576
+ nodes: readonly TaskNode[];
577
+ edges: readonly Edge[];
578
+ phases: readonly PhaseRecord[];
579
+ issues: readonly CompileIssue[];
580
+ parsed: ParsedPlan;
581
+ repo: RepoView;
582
+ }): ResidueCandidate[] {
583
+ const out: ResidueCandidate[] = [];
584
+ const byPhase = new Map<string, TaskNode[]>();
585
+ for (const n of a.nodes) {
586
+ if (n.phase === null || (n.kind !== "task" && n.kind !== "tests" && n.kind !== "fix")) continue;
587
+ const l = byPhase.get(n.phase);
588
+ if (l === undefined) byPhase.set(n.phase, [n]);
589
+ else l.push(n);
590
+ }
591
+ // 1. consecutive hash-id steps (unannotated plans)
592
+ for (const list of byPhase.values()) {
593
+ for (let i = 1; i < list.length; i += 1) {
594
+ const u = list[i - 1] as TaskNode;
595
+ const v = list[i] as TaskNode;
596
+ if (a.parsedTasks.get(u.id)?.idSource === "hash" && a.parsedTasks.get(v.id)?.idSource === "hash") {
597
+ out.push({ from: u.id, to: v.id, why: "consecutive steps without ids; the order between them is not stated" });
598
+ }
599
+ }
600
+ }
601
+ // 2. unresolved phrase / graph references
602
+ for (const i of a.issues) {
603
+ if (UNRESOLVED_CODES.has(i.code)) out.push({ from: "?", to: "?", why: formatIssue(i) });
604
+ }
605
+ // 3. ownership rows that no task of an owner phase mentions
606
+ for (const row of a.parsed.ownership) {
607
+ const p = lexical(row.path);
608
+ for (const owner of row.owners) {
609
+ if (!a.phases.some((ph) => ph.id === owner)) continue;
610
+ const mine = a.nodes.filter((n) => n.phase === owner);
611
+ const mentioned = mine.some((n) => [...n.footprint.writes, ...n.footprint.reads].some((x) => x === p || x.startsWith(`${p}/`) || p.startsWith(`${x}/`)));
612
+ if (!mentioned) out.push({ from: owner, to: p, why: `ownership-unmatched L${row.line}: no task of ${owner} mentions ${p}` });
613
+ }
614
+ }
615
+ // 4. concurrent same-phase pairs where v mentions u's id or a file u creates, without a Reads line
616
+ const ids = a.nodes.map((n) => n.id);
617
+ const phaseOf = new Map(a.nodes.map((n) => [n.id, n.phase] as const));
618
+ const reach = new Reach(ids, (id) => phaseOf.get(id) ?? null, a.phases.map((p) => p.id));
619
+ for (const e of a.edges) {
620
+ if (phaseOf.has(e.to) && (phaseOf.has(e.from) || e.from.startsWith("gate:"))) {
621
+ if (e.from.startsWith("gate:") && !a.phases.some((p) => `gate:${p.id}` === e.from)) continue;
622
+ reach.add(e.from, e.to);
623
+ }
624
+ }
625
+ for (const list of byPhase.values()) {
626
+ for (let j = 1; j < list.length; j += 1) {
627
+ const v = list[j] as TaskNode;
628
+ const pv = a.parsedTasks.get(v.id);
629
+ if (pv === undefined) continue;
630
+ for (let i = 0; i < j; i += 1) {
631
+ const u = list[i] as TaskNode;
632
+ if (!reach.concurrent(u.id, v.id)) continue;
633
+ const mentionsId = pv.body.includes(u.id);
634
+ const created = u.footprint.writes.filter((w) => !a.repo.files.has(w) && !a.repo.dirs.has(w));
635
+ const mentionsFile = pv.readsLine === null && created.some((w) => pv.body.includes(w));
636
+ if (mentionsId || mentionsFile) {
637
+ out.push({ from: u.id, to: v.id, why: mentionsId ? `${v.id} mentions ${u.id} but no order is stated` : `${v.id} mentions a file ${u.id} creates` });
638
+ }
639
+ }
640
+ }
641
+ }
642
+ return out;
643
+ }
644
+
645
+ // ---------------------------------------------------------------------------------------------------------------
646
+ // Compiler
647
+
648
+ function draftInvalid(errors: ReadonlyArray<{ code: string; message: string; taskIds: readonly string[] }>, extra: readonly string[]): ExecutorError {
649
+ const detail: JsonValue = {
650
+ code: "draft-invalid",
651
+ line: 0,
652
+ violations: errors.map((e) => ({ code: e.code, message: e.message, taskIds: [...e.taskIds] })),
653
+ ledger: [...extra],
654
+ };
655
+ const first = errors[0];
656
+ return new ExecutorError("E_COMPILE", `compiled draft is invalid: ${first === undefined ? (extra[0] ?? "unknown") : `${first.code}: ${first.message}`}`, detail);
657
+ }
658
+
659
+ /** QA-2.3-22: warnings that make `addTasks` refuse a fragment (a reference it cannot resolve would be lost silently). */
660
+ const FAIL_CLOSED_CODES: ReadonlySet<string> = new Set(["explicit-ref-unknown", "graph-node-unknown", "depends-unknown"]);
661
+
662
+ /**
663
+ * QA-2.3-2: `parsePlan` keeps a phrase or graph reference only when it names a node of the same text, so a fragment's
664
+ * `before 1.1.2` to a ledger task would be dropped. The fragment is parsed a second time with one stub item per ledger
665
+ * task appended (after a blank line, so the fragment's own items are untouched); only the phrases and graph blocks of
666
+ * that second parse are used, the tasks, phases and ownership stay those of the fragment alone.
667
+ */
668
+ function fragmentWithLedgerRefs(frag: ParsedPlan, text: string, ledger: LedgerV1): ParsedPlan {
669
+ const ids = Object.keys(ledger.tasks).filter((id) => /^(?:T|P)?\d+(?:\.(?:\d+|[A-Z]{1,4}))+[a-z]?$/.test(id));
670
+ if (ids.length === 0) return frag;
671
+ const stubbed = `${text.replace(/\s+$/, "")}\n\n**Tasks**\n${ids.map((id) => `- **${id}** (ledger task)`).join("\n")}\n`;
672
+ const withStubs = parsePlan(stubbed);
673
+ const own = new Set(frag.tasks.map((t) => t.id));
674
+ const fromLedger = (id: string): boolean => !own.has(id) && ids.includes(id);
675
+ return {
676
+ ...frag,
677
+ phrases: withStubs.phrases.filter((p) => !fromLedger(p.subject.id)),
678
+ graphs: withStubs.graphs,
679
+ warnings: [
680
+ ...frag.warnings.filter((w) => !FAIL_CLOSED_CODES.has(w.code)),
681
+ ...withStubs.warnings.filter((w) => FAIL_CLOSED_CODES.has(w.code)),
682
+ ],
683
+ };
684
+ }
685
+
686
+ export function createPlanCompiler(deps: CompilerDeps): PlanCompiler {
687
+ // Per-instance state (QA-2.3-13, QA-2.3-3), keyed by `repo.key`: the case flag (`core.ignorecase`) and the tracked files
688
+ // read by `compile`. `mergeResidue`, `addTasks` and `validate` use them; a repository this instance never compiled
689
+ // (a ledger resumed in a new process) falls back to the platform default and to the paths the ledger knows.
690
+ const ciByRepo = new Map<string, boolean>();
691
+ const filesByRepo = new Map<string, readonly string[]>();
692
+ const ciFor = (repo: LedgerV1["repo"]): boolean => ciByRepo.get(repo.key) ?? defaultCi();
693
+
694
+ async function compile(
695
+ planPath: string,
696
+ opts: { phases?: string[]; doneBefore?: string; config: ExecutorConfig; orchestratorSessionID: string; now: string },
697
+ ): Promise<{ draft: LedgerV1; residueRequest?: { prompt: string; schema: JsonValue; taskIds: TaskId[] }; summary: CompileSummary }> {
698
+ const config = checkInputs(planPath, opts);
699
+ const text = await deps.fs.readText(planPath);
700
+ const planDigest = sha256Hex(text);
701
+ const cwd = dirOf(planPath);
702
+ const view = await loadRepoView(deps.git, cwd);
703
+ const ci = view.caseInsensitive;
704
+ await deps.durations.load();
705
+
706
+ const issues: CompileIssue[] = [];
707
+ const parsed = await annotateUnrouted(parsePlan(text), deps.annotate);
708
+ issues.push(...parsed.warnings);
709
+ text.split(/\r\n|\n|\r/).forEach((line, i) => {
710
+ const criteria = /^[ \t]*criteria[ \t]*:(.*)$/i.exec(line)?.[1];
711
+ if (criteria === undefined) return;
712
+ const clauses = criteria.split(";").map((clause) => clause.trim()).filter((clause) => clause !== "");
713
+ if (clauses.some((clause) => ORCHESTRATOR_SHELL_RE.test(clause)) && clauses.some((clause) => !ORCHESTRATOR_SHELL_RE.test(clause))) {
714
+ issues.push({ code: "orchestrator-shell-mixed", line: i + 1, message: "only the marked clause is skipped" });
715
+ }
716
+ });
717
+
718
+ const sel = selectPhases(parsed, opts, issues);
719
+ const includedIds = new Set(sel.included.map((p) => p.id));
720
+ const wholePlan = opts.phases === undefined;
721
+ const universe = parsed.tasks.filter((t) => (t.phase === null ? wholePlan : includedIds.has(t.phase)));
722
+ const pp: ParsedPlan = {
723
+ ...parsed,
724
+ phases: sel.included,
725
+ waves: parsed.waves.map((w) => ({ ...w, phases: w.phases.filter((id) => includedIds.has(id)) })).filter((w) => w.phases.length > 0),
726
+ tasks: universe,
727
+ };
728
+
729
+ // footprints in plan order, then edges
730
+ const created = new Set<string>();
731
+ const fps = new Map<string, TaskFootprint>();
732
+ const edgeTasks: EdgeTask[] = [];
733
+ universe.forEach((t, i) => {
734
+ const fp = extractFootprint(t, ownershipOf(parsed, t.phase), view, created);
735
+ fps.set(t.id, fp);
736
+ footprintWarnings(t, fp, issues);
737
+ const top = fp.editing && fp.footprint.confidence === "unknown";
738
+ edgeTasks.push({
739
+ id: t.id,
740
+ phase: t.phase,
741
+ kind: t.kind,
742
+ planIndex: i,
743
+ writes: top ? UNKNOWN_WRITES : fp.footprint.writes,
744
+ reads: fp.footprint.reads,
745
+ confidence: fp.footprint.confidence,
746
+ isContract: isContractTask(t.title, fp.footprint.writes),
747
+ });
748
+ });
749
+ // QA-2.3-10 / QA-2.3-21: a prose reference to a phase, wave or task of the plan that is outside this run is not an
750
+ // unresolved reference; it gets its own warning and does not feed the residue.
751
+ const planNodes = new Set([...parsed.phases.map((p) => p.id), ...parsed.waves.map((w) => w.id), ...parsed.tasks.map((t) => t.id)]);
752
+ const runNodes = new Set([...includedIds, ...pp.waves.map((w) => w.id), ...universe.map((t) => t.id)]);
753
+ const built = buildEdges(pp, edgeTasks, { crossPhase: config.crossPhase, ci, planNodes });
754
+ for (const w of built.warnings) {
755
+ const ref = w.code === "explicit-ref-unknown" ? /^unknown (?:reference|subject) (\S+?):/.exec(w.message)?.[1] : undefined;
756
+ if (ref !== undefined && planNodes.has(ref) && !runNodes.has(ref)) {
757
+ issues.push({ code: "ref-outside-run", line: w.line, message: `${ref} is not part of this run: ${w.message}` });
758
+ } else issues.push(w);
759
+ }
760
+
761
+ // doneBefore projection
762
+ const materialized = new Set(universe.filter((t) => t.phase === null || sel.selected.has(t.phase)).map((t) => t.id));
763
+ const phaseOfTask = new Map(universe.map((t) => [t.id, t.phase] as const));
764
+ const edges: Edge[] = [];
765
+ const seen = new Set<string>();
766
+ for (const e of built.edges) {
767
+ let from: string = e.from;
768
+ let evidence = e.evidence;
769
+ // buildEdges only knows the included phases, so every `gate:` source is part of this run.
770
+ if (!from.startsWith("gate:") && !materialized.has(from)) {
771
+ const ph = phaseOfTask.get(from) ?? null;
772
+ if (ph === null || !includedIds.has(ph)) continue;
773
+ from = `gate:${ph}`;
774
+ evidence = `via ${from}; ${evidence}`;
775
+ }
776
+ if (!materialized.has(e.to)) continue;
777
+ const key = `${from}>${e.to}`;
778
+ if (seen.has(key)) continue;
779
+ seen.add(key);
780
+ edges.push({ from, to: e.to, kind: e.kind, confidence: e.confidence, evidence });
781
+ }
782
+
783
+ // tasks
784
+ const tasks: Record<string, TaskNode> = {};
785
+ const parsedById = new Map<string, ParsedTask>();
786
+ for (const t of universe) {
787
+ if (!materialized.has(t.id)) continue;
788
+ parsedById.set(t.id, t);
789
+ const state: TaskState = t.phase !== null && sel.earlier.has(t.phase) ? "done" : "pending";
790
+ tasks[t.id] = nodeOf(deps, t, t.phase, fps.get(t.id) as TaskFootprint, state, issues);
791
+ }
792
+ const nodes = Object.values(tasks);
793
+ const qaCount = new Map<string, number>();
794
+ for (const n of nodes) if (n.kind === "qa" && n.phase !== null) qaCount.set(n.phase, (qaCount.get(n.phase) ?? 0) + 1);
795
+
796
+ // phases and waves
797
+ const phases: PhaseRecord[] = sel.included.map((p) => ({
798
+ id: p.id,
799
+ title: p.title,
800
+ wave: p.wave,
801
+ dependsOn: [],
802
+ gate: sel.earlier.has(p.id) ? "passed" : "pending",
803
+ qaRound: 1,
804
+ paused: false,
805
+ tag: null,
806
+ }));
807
+ dependsOnFrom(phases, tasks, edges);
808
+ const waves: LedgerV1["waves"] = [];
809
+ for (const w of pp.waves) {
810
+ const ids = phases.filter((p) => p.wave === w.id).map((p) => p.id);
811
+ if (ids.length > 0) waves.push({ id: w.id, phases: ids });
812
+ }
813
+ for (const p of phases) {
814
+ if (!waves.some((w) => w.id === p.wave)) waves.push({ id: p.wave, phases: phases.filter((q) => q.wave === p.wave).map((q) => q.id) });
815
+ }
816
+
817
+ const planId = planIdOf(planPath, opts.phases, opts.doneBefore);
818
+ const repo = await readRepo(deps, view.toplevel);
819
+ // QA-2.3-13 / QA-2.3-3: remember the case flag and the tracked files of this repository for the later calls.
820
+ ciByRepo.set(repo.key, ci);
821
+ filesByRepo.set(repo.key, [...view.files]);
822
+ const roots = [view.toplevel, ...view.worktrees];
823
+ const sharedContext = sharedContextOf(parsed.sharedContextRaw, roots, ci, config.sharedContextChars, issues);
824
+
825
+ const draft: LedgerV1 = {
826
+ schema: 1,
827
+ planId,
828
+ planPath,
829
+ planDigest,
830
+ repo,
831
+ integration: { branch: `omr/${planId}/integration`, worktree: deps.integrationWorktree(planId, repo), head: repo.baseCommit },
832
+ launcher: "A",
833
+ status: "awaiting-approval",
834
+ orchestrator: { sessionID: opts.orchestratorSessionID, boundAt: opts.now },
835
+ config,
836
+ sharedContext,
837
+ waves,
838
+ phases,
839
+ tasks,
840
+ edges,
841
+ inbox: [],
842
+ seq: 1,
843
+ };
844
+
845
+ // self-check: both validators must pass (bug guard)
846
+ const errors = validateLedger(draft, { ci });
847
+ const lv = ledgerViolations(draft);
848
+ if (errors.length > 0 || lv.length > 0 || draft.seq !== 1) {
849
+ throw draftInvalid(errors, lv.map((v) => `${v.code} at ${v.at}`));
850
+ }
851
+
852
+ // residue
853
+ const overflow = residueOverflow(draft);
854
+ if (overflow > 0) issues.push({ code: "residue-capped", line: 0, message: `${overflow} editing task(s) over the residue cap keep their write set unrefined (unknown ones stay top; ownership-assumed ones keep the paths their phase owns)` });
855
+ const candidates = residueCandidates({ parsedTasks: parsedById, nodes, edges, phases, issues, parsed: pp, repo: view });
856
+ const residueRequest = residueRequestOf(draft, candidates);
857
+ if (residueRequest !== undefined) draft.status = "awaiting-residue";
858
+
859
+ if (nodes.length > 0 && countPrior(nodes) * 2 > nodes.filter((n) => n.kind !== "manual" && n.kind !== "preflight").length) {
860
+ issues.push({ code: "estimate-prior", line: 0, message: "most estimates come from the 8-minute prior (no timing history)" });
861
+ }
862
+ const summary = summaryOf(draft, issues.map(formatIssue));
863
+ return residueRequest === undefined ? { draft, summary } : { draft, residueRequest, summary };
864
+ }
865
+
866
+ function mergeResidue(draft: LedgerV1, responseText: string): { draft: LedgerV1; summary: CompileSummary } {
867
+ const ci = ciFor(draft.repo);
868
+ const checked = validateResidue(draft, parseResidue(responseText), { ci });
869
+ if (!checked.ok) {
870
+ throw new ExecutorError("E_RESIDUE", `residue rejected (${checked.code} at ${checked.at})`, { code: checked.code, at: checked.at, detail: checked.detail });
871
+ }
872
+ const merged = mergeResidueInto(draft, checked.value, { ci });
873
+ const rest = merged.edges.filter((e) => e.kind !== "conflict");
874
+ const all = Object.values(merged.tasks);
875
+ const phaseOf = new Map(all.map((t) => [t.id, t.phase] as const));
876
+ const reach = new Reach(all.map((t) => t.id), (id) => phaseOf.get(id) ?? null, merged.phases.map((p) => p.id));
877
+ for (const e of rest) {
878
+ if (phaseOf.has(e.to) && (phaseOf.has(e.from) || merged.phases.some((p) => `gate:${p.id}` === e.from))) reach.add(e.from, e.to);
879
+ }
880
+ const live = all.map((t, i) => edgeTaskOf(t, i)).filter((t) => !SETTLED.has(merged.tasks[t.id]?.state ?? "pending"));
881
+ const conflicts = conflictEdges(live, reach, ci);
882
+ const next: LedgerV1 = { ...merged, edges: [...rest, ...conflicts], status: "awaiting-approval" };
883
+ const errors = validateLedger(next, { ci });
884
+ const lv = ledgerViolations(next);
885
+ if (errors.length > 0 || lv.length > 0) {
886
+ throw new ExecutorError("E_RESIDUE", "the merged residue leaves an invalid plan", {
887
+ code: "residue-invalid",
888
+ violations: errors.map((e) => ({ code: e.code, message: e.message, taskIds: [...e.taskIds] })),
889
+ ledger: lv.map((v) => `${v.code} at ${v.at}`),
890
+ });
891
+ }
892
+ return { draft: next, summary: summaryOf(next, []) };
893
+ }
894
+
895
+ /**
896
+ * The contract allows only E_CYCLE and E_INVALID_INPUT: a parse failure (E_COMPILE) becomes E_INVALID_INPUT.
897
+ * QA-2.3-22: a reference the fragment cannot resolve (`explicit-ref-unknown`, `graph-node-unknown`, `depends-unknown`)
898
+ * fails closed with E_INVALID_INPUT; every other warning is dropped, because the contract returns no warnings.
899
+ */
900
+ function addTasks(ledger: LedgerV1, text: string): { tasks: TaskNode[]; edges: Edge[]; reopened: TaskId[] } {
901
+ try {
902
+ return addTasksChecked(ledger, text);
903
+ } catch (e) {
904
+ if (e instanceof ExecutorError && e.code === "E_COMPILE") {
905
+ throw new ExecutorError("E_INVALID_INPUT", e.message, e.detail ?? null);
906
+ }
907
+ throw e;
908
+ }
909
+ }
910
+
911
+ function addTasksChecked(ledger: LedgerV1, text: string): { tasks: TaskNode[]; edges: Edge[]; reopened: TaskId[] } {
912
+ const frag = fragmentWithLedgerRefs(parsePlan(text), text, ledger);
913
+ if (frag.tasks.length === 0) throw new ExecutorError("E_INVALID_INPUT", "the fragment contains no tasks", null);
914
+ const ci = ciFor(ledger.repo);
915
+ const phaseIds = new Set(ledger.phases.map((p) => p.id));
916
+ const taken = new Set(Object.keys(ledger.tasks).map((k) => k.toLowerCase()));
917
+
918
+ // repo view: the tracked files (seam, else the files recorded at compile); only when neither exists, the paths the
919
+ // ledger already knows (this method is synchronous, so no git here)
920
+ const tracked = deps.listTrackedFiles?.(ledger.repo.toplevel) ?? filesByRepo.get(ledger.repo.key);
921
+ const known = new Set<string>(tracked ?? []);
922
+ if (tracked === undefined) {
923
+ for (const t of Object.values(ledger.tasks)) for (const p of [...t.footprint.writes, ...t.footprint.reads]) known.add(p);
924
+ }
925
+ const view = repoViewFrom({
926
+ toplevel: ledger.repo.toplevel,
927
+ worktrees: [ledger.repo.toplevel, ledger.integration.worktree],
928
+ files: [...known],
929
+ caseInsensitive: ci,
930
+ });
931
+
932
+ const created = new Set<string>();
933
+ const issues: CompileIssue[] = [];
934
+ const base = Object.keys(ledger.tasks).length;
935
+ const newNodes: TaskNode[] = [];
936
+ const edgeTasks: EdgeTask[] = [];
937
+ frag.tasks.forEach((t, i) => {
938
+ const folded = t.id.toLowerCase();
939
+ if (taken.has(folded)) throw new ExecutorError("E_INVALID_INPUT", `task id ${t.id} already exists in the ledger`, { taskId: t.id });
940
+ taken.add(folded);
941
+ const prefix = t.id.includes(".") ? t.id.slice(0, t.id.lastIndexOf(".")) : null;
942
+ const phase = t.phase !== null && phaseIds.has(t.phase) ? t.phase : prefix !== null && phaseIds.has(prefix) ? prefix : null;
943
+ if (phase === null) throw new ExecutorError("E_INVALID_INPUT", `task ${t.id} belongs to no phase of the ledger`, { taskId: t.id, phase: t.phase });
944
+ // QA-2.3-3: a phase whose gate has passed is closed; a task added there would never be waited for.
945
+ if (ledger.phases.find((p) => p.id === phase)?.gate === "passed") {
946
+ throw new ExecutorError("E_INVALID_INPUT", `phase ${phase} has already passed its gate; task ${t.id} cannot be added to it`, { taskId: t.id, phase });
947
+ }
948
+ // QA-2.3-33: the phase's QA reviews every task of the phase, so it must still be able to wait for a new one.
949
+ const phaseQa = Object.values(ledger.tasks).find((x) => x.phase === phase && x.id.toLowerCase() === `${phase}.qa`.toLowerCase());
950
+ if (phaseQa !== undefined && phaseQa.state !== "pending" && phaseQa.state !== "ready") {
951
+ throw new ExecutorError("E_INVALID_INPUT", `the phase's QA has already started (${phaseQa.id} is ${phaseQa.state}); add task ${t.id} to a later phase`, { taskId: t.id, phase, qa: phaseQa.id });
952
+ }
953
+ const fp = extractFootprint(t, ownershipOf(frag, t.phase), view, created);
954
+ // QA-2.3-2: a write path that leaves the repository is rejected here, not silently dropped.
955
+ const outside = fp.ignored.find((x) => x.write === true && OUTSIDE_REASONS.has(x.reason));
956
+ if (outside !== undefined) {
957
+ throw new ExecutorError("E_INVALID_INPUT", `task ${t.id} writes ${JSON.stringify(outside.raw)}, which is outside the repository (${outside.reason})`, { taskId: t.id, path: outside.raw, reason: outside.reason });
958
+ }
959
+ footprintWarnings(t, fp, issues);
960
+ const node = nodeOf(deps, t, phase, fp, "pending", issues);
961
+ newNodes.push(node);
962
+ edgeTasks.push({ ...edgeTaskOf(node, base + i), writes: fp.editing && fp.footprint.confidence === "unknown" ? UNKNOWN_WRITES : fp.footprint.writes });
963
+ });
964
+ const newIds = new Set(newNodes.map((n) => n.id));
965
+
966
+ // QA-2.3-2: references of the fragment resolve against the ledger and the fragment together. The ledger's tasks
967
+ // and phases are passed to the edge passes (earlier in plan order) so `before X`, `Depends on:` and graph blocks can
968
+ // name them; only the edges that involve a new task are kept.
969
+ const existing = Object.values(ledger.tasks);
970
+ const fragPhaseIds = new Set(frag.phases.map((p) => p.id));
971
+ // QA-2.3-19: the phase view comes from the ledger (`dependsOn`, `waves`), so a new task gets the gate edges of its phase.
972
+ const ledgerDeps = (id: string): Array<{ id: string; external: boolean; line: number }> =>
973
+ (ledger.phases.find((q) => q.id === id)?.dependsOn ?? []).map((d) => ({ id: d, external: false, line: 0 }));
974
+ const fragView: ParsedPlan = {
975
+ ...frag,
976
+ phases: [
977
+ ...ledger.phases.filter((p) => !fragPhaseIds.has(p.id)).map((p): ParsedPhase => ({
978
+ id: p.id, title: p.title, wave: p.wave, span: { line: 0, endLine: 0 }, dogfood: false, synthetic: false,
979
+ dependsOn: ledgerDeps(p.id), order: null, fixTemplate: null, intro: "", newTests: null,
980
+ })),
981
+ ...frag.phases.map((p): ParsedPhase => (phaseIds.has(p.id) ? { ...p, dependsOn: [...ledgerDeps(p.id), ...p.dependsOn.filter((d) => !ledger.phases.some((q) => q.id === p.id && q.dependsOn.includes(d.id)))] } : p)),
982
+ ],
983
+ // the fragment's own wave headings are not used: its tasks must belong to phases of the ledger
984
+ waves: ledger.waves.map((w, i) => ({ id: w.id, title: "", line: i + 1, phases: [...w.phases] })),
985
+ };
986
+ const built = buildEdges(fragView, [...existing.map((t, i) => edgeTaskOf(t, i)), ...edgeTasks], { crossPhase: ledger.config.crossPhase, ci });
987
+ // QA-2.3-22: a reference the fragment cannot resolve fails closed instead of being dropped silently.
988
+ const unresolved = [...frag.warnings, ...built.warnings].find((w) => FAIL_CLOSED_CODES.has(w.code));
989
+ if (unresolved !== undefined) {
990
+ throw new ExecutorError("E_INVALID_INPUT", `the fragment has an unresolved reference: ${formatIssue(unresolved)}`, { code: unresolved.code, line: unresolved.line });
991
+ }
992
+ const newEdges: Edge[] = [];
993
+ const seen = new Set(ledger.edges.map((e) => `${e.from}>${e.to}`));
994
+ const push = (e: Edge): void => {
995
+ const key = `${e.from}>${e.to}`;
996
+ if (seen.has(key)) return;
997
+ seen.add(key);
998
+ newEdges.push(e);
999
+ };
1000
+ for (const e of built.edges) {
1001
+ if (e.from.startsWith("gate:") && !phaseIds.has(e.from.slice("gate:".length))) {
1002
+ throw new ExecutorError("E_INVALID_INPUT", `edge ${e.from} -> ${e.to} names a phase that is not in the ledger`, { from: e.from, to: e.to });
1003
+ }
1004
+ const fromNew = newIds.has(e.from);
1005
+ const toNew = newIds.has(e.to);
1006
+ if (!fromNew && !toNew) continue;
1007
+ if (e.kind === "structural") {
1008
+ // QA-2.3-19: existing -> new (pre-flight, gates, earlier stages) and new -> existing while that task can still wait.
1009
+ if (!toNew) {
1010
+ const state = ledger.tasks[e.to]?.state;
1011
+ if (state !== "pending" && state !== "ready") {
1012
+ // QA-2.3-33: the target is past ready (e.g. `<phase>.TESTS` done); the new task is linked to the target's
1013
+ // successors instead, transitively, until a task that can still wait (as D3 contracts a virtual item).
1014
+ if (fromNew) {
1015
+ const visited = new Set<string>([e.to]);
1016
+ const queue: string[] = [e.to];
1017
+ for (const cur of queue) {
1018
+ for (const s of ledger.edges) {
1019
+ if (s.kind !== "structural" || s.from !== cur || visited.has(s.to)) continue;
1020
+ visited.add(s.to);
1021
+ const sState = ledger.tasks[s.to]?.state;
1022
+ if (sState === "pending" || sState === "ready") push({ ...e, to: s.to });
1023
+ else if (ledger.tasks[s.to] !== undefined) queue.push(s.to);
1024
+ }
1025
+ }
1026
+ }
1027
+ continue;
1028
+ }
1029
+ }
1030
+ }
1031
+ // conflicts and contracts are recomputed below with the whole ledger's reach; keep the new-to-new ones only
1032
+ if ((e.kind === "conflict" || e.kind === "contract") && !(fromNew && toNew)) continue;
1033
+ if (fromNew && !toNew) {
1034
+ const state = ledger.tasks[e.to]?.state;
1035
+ if (state !== "pending" && state !== "ready") {
1036
+ throw new ExecutorError("E_INVALID_INPUT", `edge ${e.from} -> ${e.to}: ${e.to} is ${state ?? "unknown"} and cannot wait for a new task`, { from: e.from, to: e.to });
1037
+ }
1038
+ }
1039
+ push(e);
1040
+ }
1041
+
1042
+ // conflicts against the live tasks of the ledger (existing tasks come first in plan order)
1043
+ const allTasks = [...Object.values(ledger.tasks), ...newNodes];
1044
+ const phaseOf = new Map(allTasks.map((t) => [t.id, t.phase] as const));
1045
+ const reach = new Reach(allTasks.map((t) => t.id), (id) => phaseOf.get(id) ?? null, ledger.phases.map((p) => p.id));
1046
+ for (const e of [...ledger.edges, ...newEdges]) {
1047
+ const fromKnown = e.from.startsWith("gate:") ? phaseIds.has(e.from.slice("gate:".length)) : phaseOf.has(e.from);
1048
+ if (phaseOf.has(e.to) && fromKnown) reach.add(e.from, e.to);
1049
+ }
1050
+ const live = [
1051
+ ...Object.values(ledger.tasks).filter((t) => !SETTLED.has(t.state)).map((t, i) => edgeTaskOf(t, i)),
1052
+ ...edgeTasks,
1053
+ ];
1054
+ for (const e of conflictEdges(live, reach, ci)) if (newIds.has(e.to)) push(e);
1055
+
1056
+ // the extended ledger must stay acyclic and closed for every new task
1057
+ const trialTasks: Record<string, TaskNode> = { ...ledger.tasks };
1058
+ for (const n of newNodes) trialTasks[n.id] = n;
1059
+ const trial: LedgerV1 = { ...ledger, tasks: trialTasks, edges: [...ledger.edges, ...newEdges] };
1060
+ const problems = validateLedger(trial, { ci }).filter((e) => e.code === "cycle" || e.taskIds.some((id) => newIds.has(id)));
1061
+ const cycle = problems.find((e) => e.code === "cycle");
1062
+ if (cycle !== undefined) throw new ExecutorError("E_CYCLE", cycle.message, { cycle: [...cycle.taskIds], evidence: [] });
1063
+ if (problems.length > 0) {
1064
+ throw new ExecutorError("E_INVALID_INPUT", `added tasks are invalid: ${problems[0]?.message ?? ""}`, {
1065
+ violations: problems.map((e) => ({ code: e.code, message: e.message, taskIds: [...e.taskIds] })),
1066
+ });
1067
+ }
1068
+
1069
+ const reopened: TaskId[] = [];
1070
+ for (const e of newEdges) {
1071
+ const target = ledger.tasks[e.to];
1072
+ if (target === undefined || target.state !== "ready" || reopened.includes(e.to)) continue;
1073
+ // every reopen candidate comes from a new task (still pending), so a ready target always has to wait for it
1074
+ reopened.push(e.to);
1075
+ }
1076
+ return { tasks: newNodes, edges: newEdges, reopened };
1077
+ }
1078
+
1079
+ return { compile, mergeResidue, addTasks, validate: (ledger) => validateLedger(ledger, { ci: ciFor(ledger.repo) }) };
1080
+ }