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,551 @@
1
+ /**
2
+ * Phase 3.1.4: task expansion (the launch prompt of one plan task attempt).
3
+ *
4
+ * Design memo: docs/qa/critical-path-execution/phase-3.1.md M36 and §8 "expand.ts (3.1.4)".
5
+ * Pure except optional diagnostic logging and `loadExpansionEnv`, which reads the worktree list and
6
+ * `core.longpaths` through the `GitRunner` seam.
7
+ * The route line is re-serialized from whitelisted tokens; plan text never reaches it.
8
+ */
9
+ import * as path from "node:path";
10
+ import { DETECTIONS, NEEDS, RISKS, SCOPES, TASK_CLASSES } from "../routing/classify/types";
11
+ import { ROUTE_BUDGET_MAX } from "../routing/classify/route-line";
12
+ import { neutralizeDirectives } from "../verify/pending";
13
+ import { slotEnvFor } from "./slots/env";
14
+ import {
15
+ ABSOLUTE_PATH_PATTERN,
16
+ ExecutorError,
17
+ FINDINGS_FORMAT,
18
+ formatLaunchPrompt,
19
+ stripOrchestratorShell,
20
+ type GitRunner,
21
+ type LedgerV1,
22
+ type SlotLease,
23
+ type TaskId,
24
+ type TaskNode,
25
+ } from "./types";
26
+
27
+ /** What the expansion needs from git (M36): the repository's worktree paths and whether `core.longpaths` is on. */
28
+ export interface ExpansionEnv {
29
+ worktrees: readonly string[];
30
+ longPaths: boolean;
31
+ }
32
+
33
+ /**
34
+ * Prefix sets of one expansion (M36). `mappable` prefixes are rewritten to `slot`; any other absolute path under an
35
+ * `inRepo` prefix is unmappable and fails. Both are sorted longest first.
36
+ */
37
+ export interface PathMap {
38
+ mappable: readonly string[];
39
+ inRepo: readonly string[];
40
+ slot: string;
41
+ longPaths: boolean;
42
+ }
43
+
44
+ /** Input of `expandTask`: one attempt `attempt` of `taskId`, with its durable nonce, its slot and the git environment. */
45
+ export interface ExpandInput {
46
+ ledger: Readonly<LedgerV1>;
47
+ taskId: TaskId;
48
+ attempt: number;
49
+ nonce: string;
50
+ slot: SlotLease;
51
+ env: ExpansionEnv;
52
+ /** The previous attempt's work restored as uncommitted changes. */
53
+ restored?: { attempt: number; files: number };
54
+ /** Best-effort diagnostic for ignored route budgets; defaults to a console warning. */
55
+ log?(message: string, detail?: unknown): void;
56
+ }
57
+
58
+ /** The expansion: the full launch prompt, the re-serialized route line and the slot-relative check inputs. */
59
+ export interface ExpandedTask {
60
+ prompt: string;
61
+ routeLine: string;
62
+ /**
63
+ * QA-PDF21-2-20 (optional, additive): the route line's `budget=` (`routeBudgetOf(routeLine)`), the launch request's
64
+ * `routeBudget`; null when the line names none.
65
+ */
66
+ routeBudget?: number | null;
67
+ acceptance: string | null;
68
+ verify: string | null;
69
+ workRoot: string;
70
+ }
71
+
72
+ /**
73
+ * QA-PDF21-2-20: the `budget=` of a re-serialized route line (`renderRouteLine`: whitelisted tokens, an in-range budget only),
74
+ * or null when it names none. The launch request carries it into the plan child's binding, as a routed dispatch's binding.
75
+ */
76
+ export function routeBudgetOf(routeLine: string): number | null {
77
+ const m = /^\[route [^\]\r\n]*?\bbudget=(\d+)\]$/.exec(routeLine.trim());
78
+ const n = m?.[1] === undefined ? 0 : Number(m[1]);
79
+ return Number.isInteger(n) && n >= 1 && n <= ROUTE_BUDGET_MAX ? n : null;
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------------------------------------------
83
+ // Absolute path prefixes (M36 "Prefixes" and "Matching")
84
+ // ---------------------------------------------------------------------------------------------------------------
85
+
86
+ /** Windows `MAX_PATH`: a longer path needs `core.longpaths` in the slot (M36). */
87
+ export const MAX_PATH_CHARS = 260;
88
+
89
+ const DRIVE_OR_UNC = /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/;
90
+
91
+ /** A drive or UNC path: matched through `path.win32` and case-insensitively on every OS. */
92
+ function isWindowsPath(p: string): boolean {
93
+ return DRIVE_OR_UNC.test(p);
94
+ }
95
+
96
+ /** Characters that end a path token in prose (none of them can be part of a Windows file name segment). */
97
+ const PATH_TERMINATORS = new Set([..." \t\r\n\f\v\"'`<>|*?:;,()[]{}"]);
98
+ /** Characters that end a token only when followed by a terminator or the end of the text (sentence punctuation). */
99
+ const TRAILING_PUNCTUATION = new Set([".", ","]);
100
+
101
+ function isSeparator(c: string | undefined): boolean {
102
+ return c === "\\" || c === "/";
103
+ }
104
+
105
+ function isTerminator(c: string | undefined): boolean {
106
+ return c === undefined || PATH_TERMINATORS.has(c);
107
+ }
108
+
109
+ /** True iff a prefix ending at `end` (exclusive) ends at a segment boundary of `text`. */
110
+ function atSegmentBoundary(text: string, end: number): boolean {
111
+ const c = text[end];
112
+ if (c === undefined || isSeparator(c) || isTerminator(c)) return true;
113
+ return TRAILING_PUNCTUATION.has(c) && isTerminator(text[end + 1]);
114
+ }
115
+
116
+ /** True iff a path may start at `start`: not inside a word or another path. */
117
+ function atPathStart(text: string, start: number): boolean {
118
+ if (start === 0) return true;
119
+ const c = text[start - 1];
120
+ return c !== undefined && !/[A-Za-z0-9._~$%\\/-]/.test(c);
121
+ }
122
+
123
+ /** The end (exclusive) of the path token that starts at `start`, without trailing sentence punctuation. */
124
+ function tokenEnd(text: string, start: number): number {
125
+ let end = start;
126
+ while (end < text.length && !isTerminator(text[end])) end++;
127
+ while (end > start && TRAILING_PUNCTUATION.has(text[end - 1] ?? "")) end--;
128
+ return end;
129
+ }
130
+
131
+ /**
132
+ * The canonical form of a prefix: drive/UNC through `path.win32.normalize` (backslashes), POSIX through
133
+ * `path.posix.normalize`; no trailing separator except at a root. Null for a relative or empty path.
134
+ */
135
+ export function normalizePrefix(p: string): string | null {
136
+ const s = p.trim();
137
+ if (s === "" || !ABSOLUTE_PATH_PATTERN.test(s)) return null;
138
+ if (isWindowsPath(s)) {
139
+ const n = path.win32.normalize(s);
140
+ const root = path.win32.parse(n).root;
141
+ return n.length > root.length ? n.replace(/[\\/]+$/, "") : n;
142
+ }
143
+ const n = path.posix.normalize(s);
144
+ return n.length > 1 ? n.replace(/\/+$/, "") : n;
145
+ }
146
+
147
+ /** Normalized, de-duplicated (case-insensitively for drive/UNC), longest first, ties in code-unit order. */
148
+ function prefixList(paths: Iterable<string>): string[] {
149
+ const out = new Map<string, string>();
150
+ for (const p of paths) {
151
+ const n = normalizePrefix(p);
152
+ if (n === null) continue;
153
+ const key = isWindowsPath(n) ? n.toLowerCase() : n;
154
+ if (!out.has(key)) out.set(key, n);
155
+ }
156
+ return [...out.values()].sort((a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0));
157
+ }
158
+
159
+ function foldWin(c: string): string {
160
+ return c === "/" ? "\\" : c.toLowerCase();
161
+ }
162
+
163
+ /** True iff `prefix` (normalized) occurs in `text` at `start`, segment-bounded at its end. */
164
+ function prefixAt(text: string, start: number, prefix: string): boolean {
165
+ if (start + prefix.length > text.length) return false;
166
+ if (isWindowsPath(prefix)) {
167
+ for (let k = 0; k < prefix.length; k++) {
168
+ if (foldWin(text[start + k] ?? "") !== foldWin(prefix[k] ?? "")) return false;
169
+ }
170
+ } else if (text.startsWith(prefix, start) === false) {
171
+ return false;
172
+ }
173
+ // A root prefix (`C:\`, `/`) already ends at a separator.
174
+ return isSeparator(prefix[prefix.length - 1]) || atSegmentBoundary(text, start + prefix.length);
175
+ }
176
+
177
+ /** Throws the one error this module raises (M36): the expansion of this attempt cannot be launched. */
178
+ function fail(message: string, detail: Record<string, string | number | boolean | null> = {}): never {
179
+ throw new ExecutorError("E_LAUNCH_TASK", message, detail);
180
+ }
181
+
182
+ /** The longest prefix of `prefixes` (already longest first) at `start`, or null. */
183
+ function matchPrefix(text: string, start: number, prefixes: readonly string[]): string | null {
184
+ for (const p of prefixes) if (prefixAt(text, start, p)) return p;
185
+ return null;
186
+ }
187
+
188
+ /**
189
+ * Rewrites every absolute path under a `mappable` prefix to the same path under `map.slot` (M36). The prefix matches
190
+ * at a segment boundary only, through `path.win32` and case-insensitively for drive/UNC paths on every OS,
191
+ * case-sensitively for POSIX paths; the rest of the path is kept byte for byte. Any other path under an `inRepo`
192
+ * prefix is unmappable. A rewritten drive/UNC path longer than `MAX_PATH_CHARS` needs `map.longPaths`.
193
+ * Throws ExecutorError E_LAUNCH_TASK on an unmappable or too long path.
194
+ */
195
+ export function rewriteAbsolutePaths(text: string, map: PathMap): string {
196
+ const mappable = prefixList(map.mappable);
197
+ const inRepo = prefixList([...map.inRepo, ...map.mappable]);
198
+ const winSlot = isWindowsPath(map.slot);
199
+ let out = "";
200
+ let i = 0;
201
+ while (i < text.length) {
202
+ const c = text[i] ?? "";
203
+ const candidate = (isSeparator(c) || /[A-Za-z]/.test(c)) && atPathStart(text, i);
204
+ const hit = candidate ? matchPrefix(text, i, mappable) : null;
205
+ if (hit !== null) {
206
+ const end = tokenEnd(text, i + hit.length);
207
+ const sep = isSeparator(hit[hit.length - 1]) ? text[i + hit.length - 1] ?? "" : "";
208
+ const rewritten = `${map.slot}${sep}${text.slice(i + hit.length, end)}`;
209
+ if (winSlot && !map.longPaths && rewritten.length > MAX_PATH_CHARS) {
210
+ fail(`path longer than ${MAX_PATH_CHARS} characters in the slot and core.longpaths is off`, {
211
+ path: rewritten, length: rewritten.length,
212
+ });
213
+ }
214
+ out += rewritten;
215
+ i = end;
216
+ continue;
217
+ }
218
+ if (candidate && matchPrefix(text, i, inRepo) !== null) {
219
+ const inRepoHit = matchPrefix(text, i, inRepo) ?? "";
220
+ fail("absolute path in the repository cannot be mapped into the slot", {
221
+ path: text.slice(i, tokenEnd(text, i + inRepoHit.length)),
222
+ });
223
+ }
224
+ out += c;
225
+ i++;
226
+ }
227
+ return out;
228
+ }
229
+
230
+ // ---------------------------------------------------------------------------------------------------------------
231
+ // Git environment (the only I/O of this module, through the GitRunner seam)
232
+ // ---------------------------------------------------------------------------------------------------------------
233
+
234
+ function gitFailure(args: readonly string[], cwd: string, detail: string): never {
235
+ throw new ExecutorError("E_GIT", `git ${args.join(" ")} failed`, { cwd, detail });
236
+ }
237
+
238
+ /**
239
+ * Reads `git worktree list --porcelain` in `toplevel` (every listed path, in git's order, drive/UNC paths in
240
+ * `path.win32` form) and `core.longpaths` as the slot sees it. A missing `core.longpaths` is false.
241
+ * Throws ExecutorError E_GIT when git fails or exits non-zero (exit 1 of `git config --get` means "unset").
242
+ */
243
+ export async function loadExpansionEnv(
244
+ git: GitRunner,
245
+ i: { toplevel: string; slotPath: string; timeoutMs: number },
246
+ ): Promise<ExpansionEnv> {
247
+ const listArgs = ["worktree", "list", "--porcelain"] as const;
248
+ const list = await git.run(listArgs, { cwd: i.toplevel, timeoutMs: i.timeoutMs });
249
+ if (list.code !== 0) gitFailure(listArgs, i.toplevel, list.stderr.trim() || `exit ${String(list.code)}`);
250
+ const worktrees: string[] = [];
251
+ for (const raw of list.stdout.split("\n")) {
252
+ const line = raw.replace(/\r$/, "");
253
+ if (!line.startsWith("worktree ")) continue;
254
+ const p = line.slice("worktree ".length);
255
+ const n = normalizePrefix(p);
256
+ if (n !== null) worktrees.push(n);
257
+ }
258
+ const configArgs = ["config", "--bool", "--get", "core.longpaths"] as const;
259
+ const config = await git.run(configArgs, { cwd: i.slotPath, timeoutMs: i.timeoutMs });
260
+ if (config.code !== 0 && config.code !== 1) {
261
+ gitFailure(configArgs, i.slotPath, config.stderr.trim() || `exit ${String(config.code)}`);
262
+ }
263
+ return { worktrees, longPaths: config.code === 0 && config.stdout.trim() === "true" };
264
+ }
265
+
266
+ // ---------------------------------------------------------------------------------------------------------------
267
+ // Route line (M36 "Route line"): re-serialized from whitelisted tokens, never concatenated from plan text
268
+ // ---------------------------------------------------------------------------------------------------------------
269
+
270
+ /** `root="D:\my dir"`: the reference grammar's only way to carry whitespace in a value (extracted before tokenising). */
271
+ const QUOTED_ROOT_RE = /\broot\s*=\s*"([^"]*)"/i;
272
+ /** `needs=shell, edit`: whitespace after a needs comma is not a separator (as in the reference grammar). */
273
+ const NEEDS_LIST_RE = /(\bneeds=[a-z_]*)((?:\s*,\s*[a-z_]+(?![a-z_]|\s*=))+)/gi;
274
+
275
+ const ROUTE_CLASSES: readonly string[] = TASK_CLASSES;
276
+ const ROUTE_RISKS: readonly string[] = RISKS;
277
+ const ROUTE_SCOPES: readonly string[] = SCOPES;
278
+ const ROUTE_NEEDS: readonly string[] = NEEDS;
279
+ const ROUTE_DS: readonly string[] = DETECTIONS;
280
+ const ROUTE_TIERS: readonly string[] = ["fast", "medium", "heavy"];
281
+ /** A token value: lowercase letters, digits and `_` only (no whitespace, `]`, `[`, `"`, newline or separator). */
282
+ const TOKEN_VALUE_RE = /^[a-z0-9_]+$/;
283
+ /** The whole route line, brackets included: no nested bracket and no line break inside. */
284
+ const ROUTE_LINE_SHAPE_RE = /^\[route(?:[ \t]+([^[\]\r\n]*))?\]$/i;
285
+ /**
286
+ * A slot path usable as `root=`: drive-absolute or POSIX, no brackets, quotes, commas, semicolons, `..`, NUL, control
287
+ * characters or line breaks (U+2028/U+2029 included, QA-3.1-28). Plain spaces are allowed: such a path is sent quoted
288
+ * (`root="D:\my dir"`, QUOTED_ROOT_RE).
289
+ */
290
+ const ROOT_VALUE_RE = /^(?:[A-Za-z]:[\\/]|\/(?![\\/]))[^\x00-\x1f\x7f\u2028\u2029[\]",;]*$/;
291
+ /** Whitespace (only plain spaces get past ROOT_VALUE_RE) in a slot path: the value is quoted. */
292
+ const ROOT_NEEDS_QUOTES_RE = /\s/;
293
+
294
+ function routeFail(reason: string, detail: Record<string, string | number | boolean | null> = {}): never {
295
+ return fail(`route line cannot be rendered: ${reason}`, detail);
296
+ }
297
+
298
+ function isMemberOf(values: readonly string[], v: string): boolean {
299
+ return values.includes(v);
300
+ }
301
+
302
+ /** The whitelisted fields of the task's own route line (the plan's `[route ...]`), never its raw text. */
303
+ interface RouteFields {
304
+ cls: string | null;
305
+ risk: string | null;
306
+ scope: string | null;
307
+ needs: string[];
308
+ d: string | null;
309
+ tier: string | null;
310
+ pin: boolean | null;
311
+ budget: number | null;
312
+ }
313
+
314
+ function parseRouteFields(line: string, kind: TaskNode["kind"], log?: ExpandInput["log"]): RouteFields {
315
+ const f: RouteFields = { cls: null, risk: null, scope: null, needs: [], d: null, tier: null, pin: null, budget: null };
316
+ const trimmed = line.trim();
317
+ if (trimmed === "") return f;
318
+ // Earlier QA ledgers stored bare fix-route bodies. This compatibility case still uses the same strict parser.
319
+ const legacyFix = !trimmed.startsWith("[")
320
+ && (kind === "fix" || trimmed.startsWith("class=implement d=deterministic tier=medium pin"));
321
+ const shape = ROUTE_LINE_SHAPE_RE.exec(legacyFix ? `[route ${trimmed}]` : trimmed);
322
+ if (shape === null) routeFail("the task's route line is not one well-formed [route ...] line", { line: trimmed.slice(0, 80) });
323
+ const body = (shape[1] ?? "")
324
+ .replace(QUOTED_ROOT_RE, " ")
325
+ .replace(/\s*=\s*/g, "=")
326
+ .replace(NEEDS_LIST_RE, (_whole: string, head: string, tail: string) => head + tail.replace(/\s+/g, ""));
327
+ const seen = new Set<string>();
328
+ for (const token of body.split(/\s+/).filter((t) => t !== "")) {
329
+ const eq = token.indexOf("=");
330
+ const key = (eq === -1 ? token : token.slice(0, eq)).toLowerCase();
331
+ const raw = eq === -1 ? null : token.slice(eq + 1).toLowerCase();
332
+ if (seen.has(key)) routeFail(`duplicate field ${key}`);
333
+ seen.add(key);
334
+ if (key === "root") continue; // replaced by the slot
335
+ if (key === "pin") {
336
+ if (raw === null || raw === "true" || raw === "yes" || raw === "1") f.pin = true;
337
+ else if (raw === "false" || raw === "no" || raw === "0") f.pin = false;
338
+ else routeFail("value of pin is outside its token pattern", { value: raw.slice(0, 40) });
339
+ continue;
340
+ }
341
+ if (key === "budget") {
342
+ const n = raw !== null && /^\d+$/.test(raw) ? Number(raw) : 0;
343
+ if (n >= 1 && n <= ROUTE_BUDGET_MAX) f.budget = n;
344
+ else {
345
+ try {
346
+ log?.("route expansion ignored invalid or out-of-range budget", { value: raw?.slice(0, 40) ?? null });
347
+ } catch { /* logging never fails expansion */ }
348
+ }
349
+ continue;
350
+ }
351
+ if (raw === null || (key !== "needs" && !TOKEN_VALUE_RE.test(raw))) {
352
+ routeFail(`value of ${key} is outside its token pattern`, { key });
353
+ }
354
+ const value = raw ?? "";
355
+ switch (key) {
356
+ case "class": if (!isMemberOf(ROUTE_CLASSES, value)) routeFail("unknown class", { value: value.slice(0, 40) }); f.cls = value; break;
357
+ case "risk": if (!isMemberOf(ROUTE_RISKS, value)) routeFail("unknown risk", { value: value.slice(0, 40) }); f.risk = value; break;
358
+ case "scope": if (!isMemberOf(ROUTE_SCOPES, value)) routeFail("unknown scope", { value: value.slice(0, 40) }); f.scope = value; break;
359
+ case "d": if (!isMemberOf(ROUTE_DS, value)) routeFail("unknown d", { value: value.slice(0, 40) }); f.d = value; break;
360
+ case "tier": if (!isMemberOf(ROUTE_TIERS, value)) routeFail("unknown tier", { value: value.slice(0, 40) }); f.tier = value; break;
361
+ case "needs":
362
+ for (const n of value.split(",")) {
363
+ if (!isMemberOf(ROUTE_NEEDS, n)) routeFail("unknown need", { value: n.slice(0, 40) });
364
+ if (!f.needs.includes(n)) f.needs.push(n);
365
+ }
366
+ break;
367
+ default: routeFail(`unknown field ${key.slice(0, 40)}`);
368
+ }
369
+ }
370
+ return f;
371
+ }
372
+
373
+ /**
374
+ * The route line sent with the attempt (M36): re-serialized from the whitelisted tokens class, risk, scope, needs, d,
375
+ * `root=<slotPath>` (quoted when the path holds a space), tier, pin and budget. `task.route.tier` and `task.route.pin` (`[tier:X]` gives `tier=X pin`) win over the
376
+ * line's own `tier=`/`pin`. A value outside its token pattern, or holding whitespace, `]` or a line break, fails with
377
+ * E_LAUNCH_TASK, except invalid/out-of-range budgets, which are ignored as by the route compiler. The plan text
378
+ * (title, text, subtasks) is never read here.
379
+ */
380
+ export function renderRouteLine(task: TaskNode, slotPath: string, log: ExpandInput["log"] = console.warn): string {
381
+ if (!ROOT_VALUE_RE.test(slotPath) || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(slotPath)) {
382
+ routeFail("the slot path is not a usable root= value", { slotPath: slotPath.slice(0, 120) });
383
+ }
384
+ const f = parseRouteFields(task.route.line, task.kind, log);
385
+ const tier = task.route.tier ?? f.tier;
386
+ if (tier !== null && !isMemberOf(ROUTE_TIERS, tier)) routeFail("unknown tier", { value: String(tier).slice(0, 40) });
387
+ const pin = task.route.pin || f.pin === true;
388
+ const parts: string[] = [];
389
+ if (f.cls !== null) parts.push(`class=${f.cls}`);
390
+ if (f.risk !== null) parts.push(`risk=${f.risk}`);
391
+ if (f.scope !== null) parts.push(`scope=${f.scope}`);
392
+ const needs = ROUTE_NEEDS.filter((n) => f.needs.includes(n));
393
+ if (needs.length > 0) parts.push(`needs=${needs.join(",")}`);
394
+ if (f.d !== null) parts.push(`d=${f.d}`);
395
+ parts.push(ROOT_NEEDS_QUOTES_RE.test(slotPath) ? `root="${slotPath}"` : `root=${slotPath}`);
396
+ if (tier !== null) parts.push(`tier=${tier}`);
397
+ if (pin) parts.push("pin");
398
+ if (f.budget !== null) parts.push(`budget=${f.budget}`);
399
+ return `[route ${parts.join(" ")}]`;
400
+ }
401
+
402
+ // ---------------------------------------------------------------------------------------------------------------
403
+ // Task block (M36 "taskBlock order")
404
+ // ---------------------------------------------------------------------------------------------------------------
405
+
406
+ /** The three plan rules of 3.1.4, verbatim (M36 item 7). */
407
+ export const MUST_NOT_DO_RULES: readonly string[] = [
408
+ "no AI attribution in code, comments or docs",
409
+ "never run git",
410
+ "write only the `Writes:` paths",
411
+ ];
412
+
413
+ /** The qa instruction (M36 item 8): one json fenced block matching `FINDINGS_FORMAT`, the last block of the answer. */
414
+ export const FINDINGS_INSTRUCTION =
415
+ "End your final answer with exactly one ```json fenced block whose content matches this JSON schema:\n" +
416
+ JSON.stringify(FINDINGS_FORMAT);
417
+
418
+ /** Formatting rule of M36: line breaks become `\n` and trailing spaces/tabs are removed; nothing else changes. */
419
+ function tidy(text: string): string {
420
+ return text.replace(/\r\n?/g, "\n").split("\n").map((l) => l.replace(/[ \t]+$/, "")).join("\n");
421
+ }
422
+
423
+ /** `ENVIRONMENT` entries of the slot (M36 item 4): `slotEnvFor` entries sorted by key, then the PATH prefix, then unset names. */
424
+ function environmentLines(slot: SlotLease): string[] {
425
+ const out = [`Working directory: ${slot.path}`, `Base commit: ${slot.commit}`];
426
+ const env = slotEnvFor(slot.path);
427
+ if (env === null) return out;
428
+ for (const key of Object.keys(env.set).sort()) out.push(`${key}=${env.set[key] ?? ""}`);
429
+ for (const dir of env.prependPath) out.push(`PATH prepend: ${dir}`);
430
+ for (const name of [...env.unset].sort()) out.push(`unset: ${name}`);
431
+ return out;
432
+ }
433
+
434
+ /**
435
+ * The task block of one attempt (M36 "taskBlock order"). Plan text (title, text, subtasks, acceptance criteria) has
436
+ * every in-repo absolute path rewritten through `map` first. `\n` only, no trailing spaces.
437
+ */
438
+ export function renderTaskBlock(
439
+ ledger: Readonly<LedgerV1>, task: TaskNode, slot: SlotLease, map: PathMap, restored?: ExpandInput["restored"],
440
+ ): string {
441
+ void ledger;
442
+ const rw = (s: string): string => rewriteAbsolutePaths(s, map);
443
+ let skipped = false;
444
+ const childText = (text: string): string => text.split(/\r\n|\n|\r/).flatMap((line) => {
445
+ const m = /^(\s*criteria\s*:\s*)(.*)$/i.exec(line);
446
+ if (m === null) return [line];
447
+ const { kept, dropped } = stripOrchestratorShell(m[2] ?? "");
448
+ skipped ||= dropped;
449
+ if (!dropped) return [line];
450
+ return kept === null ? [] : [`${m[1]}${kept}`];
451
+ }).join("\n");
452
+ const out: string[] = [];
453
+ out.push(`TASK ${task.id}: ${rw(task.title)}`);
454
+ const text = childText(task.text);
455
+ if (text.trim() !== "") out.push(rw(text));
456
+ if (restored !== undefined) {
457
+ // QA-PDF21-2 nit: a seeded salvage commit has no attempt of its own (attempt 0): it is named as salvaged work.
458
+ const origin = restored.attempt === 0
459
+ ? `Previous work (salvaged, ${restored.files} files)`
460
+ : `Your previous attempt's work (attempt ${restored.attempt}, ${restored.files} files)`;
461
+ out.push("", `${origin} is already in your work root as uncommitted changes. Continue it; do not start over.`);
462
+ }
463
+ const subtasks = task.subtasks.map(childText).filter((s) => s.trim() !== "");
464
+ if (subtasks.length > 0) {
465
+ out.push("", "SUBTASKS");
466
+ subtasks.forEach((s, i) => out.push(`${i + 1}. ${rw(s)}`));
467
+ }
468
+ const list = (paths: readonly string[]): string => (paths.length === 0 ? "(none)" : paths.join(", "));
469
+ out.push("", `Writes: ${list(task.footprint.writes)}`, `Reads: ${list(task.footprint.reads)}`);
470
+ out.push("", "ENVIRONMENT", ...environmentLines(slot));
471
+ if (task.acceptance !== null) {
472
+ const { criteria, skipped: skippedAcceptance } = acceptanceCriteria(rw(task.acceptance));
473
+ skipped ||= skippedAcceptance;
474
+ if (criteria.length > 0) out.push("", "ACCEPTANCE", ...criteria.map((c) => `- ${c}`));
475
+ }
476
+ if (skipped) out.push("", "Checks marked (orchestrator shell) are run by the orchestrator after you return; do not run or request them.");
477
+ const latest = task.attempts[task.attempts.length - 1];
478
+ if (latest !== undefined && latest.context.trim() !== "") out.push("", "ATTEMPT CONTEXT", rw(latest.context));
479
+ out.push("", "MUST NOT DO", ...MUST_NOT_DO_RULES.map((r) => `- ${r}`));
480
+ if (task.kind === "qa") out.push("", "FINDINGS FORMAT", FINDINGS_INSTRUCTION);
481
+ return tidy(out.join("\n"));
482
+ }
483
+
484
+ /** The `criteria:` lines of an `[acceptance]` block as plain sentences (the machine checks are not shown to the child). */
485
+ function acceptanceCriteria(block: string): { criteria: string[]; skipped: boolean } {
486
+ const out: string[] = [];
487
+ let skipped = false;
488
+ for (const raw of block.split(/\r\n|\n|\r/)) {
489
+ const m = /^\s*criteria\s*:\s*(.+?)\s*$/i.exec(raw);
490
+ if (m?.[1] === undefined) continue;
491
+ const { kept, dropped } = stripOrchestratorShell(m[1]);
492
+ skipped ||= dropped;
493
+ if (kept !== null) out.push(kept);
494
+ }
495
+ return { criteria: out, skipped };
496
+ }
497
+
498
+ /** The prefix maps of one expansion (M36 "Prefixes"). */
499
+ function buildPathMap(ledger: Readonly<LedgerV1>, task: TaskNode, slot: SlotLease, env: ExpansionEnv): PathMap {
500
+ const own = declaredRoot(task.route.line);
501
+ const mappable = prefixList([...env.worktrees, ...(own === null ? [] : [own])]);
502
+ const planRoots: string[] = [];
503
+ for (const t of Object.values(ledger.tasks)) {
504
+ const r = declaredRoot(t.route.line);
505
+ if (r !== null) planRoots.push(r);
506
+ }
507
+ const inRepo = prefixList([...mappable, ledger.repo.toplevel, ...planRoots]);
508
+ return { mappable, inRepo, slot: slot.path, longPaths: env.longPaths };
509
+ }
510
+
511
+ /** The `root=` of a route line (quoted or bare), or null. Only used to build prefix sets; never re-emitted. */
512
+ function declaredRoot(line: string): string | null {
513
+ const q = QUOTED_ROOT_RE.exec(line);
514
+ if (q?.[1] !== undefined) return q[1];
515
+ const m = /\broot\s*=\s*([^\s\]]+)/i.exec(line);
516
+ return m?.[1] === undefined ? null : m[1].replace(/[,;]+$/, "");
517
+ }
518
+
519
+ /**
520
+ * Expands attempt `attempt` of `taskId` (M36). Deterministic: the same input gives the same bytes; a different attempt
521
+ * gives a different header line. The one input outside `ExpandInput` is the ENVIRONMENT block, which reads the
522
+ * process-wide slot registry through `slotEnvFor(slot.path)` (it resolves real paths): the bytes are stable for a given
523
+ * slot registration, and change if the slot's environment registration does. Throws ExecutorError E_LAUNCH_TASK for an unknown task, an unmappable or too long path, or a
524
+ * route line that cannot be re-serialized.
525
+ */
526
+ export function expandTask(i: ExpandInput): ExpandedTask {
527
+ const task = Object.prototype.hasOwnProperty.call(i.ledger.tasks, i.taskId) ? i.ledger.tasks[i.taskId] : undefined;
528
+ if (task === undefined) fail("task is not in the ledger", { taskId: i.taskId });
529
+ const map = buildPathMap(i.ledger, task, i.slot, i.env);
530
+ const routeLine = renderRouteLine(task, i.slot.path, i.log);
531
+ const taskBlock = renderTaskBlock(i.ledger, task, i.slot, map, i.restored);
532
+ // TaskNode carries no parsed CAP, and a cap written in the plan is neutralized with the rest of the task text. An editing
533
+ // task gets the executor's own read-cap line right after "PLAN CONTEXT", before the shared context and the task text, so
534
+ // it is the first read-cap token the router sees (the first one wins, DF-2-9).
535
+ const prompt = formatLaunchPrompt(
536
+ i.ledger.sharedContext, // The fixed launch/recovery prefix must match the ledger byte for byte.
537
+ { planId: i.ledger.planId, taskId: i.taskId, attempt: i.attempt, nonce: i.nonce },
538
+ neutralizeDirectives(taskBlock),
539
+ parseRouteFields(routeLine, task.kind).needs.includes("edit"),
540
+ );
541
+ return {
542
+ prompt,
543
+ routeLine,
544
+ routeBudget: routeBudgetOf(routeLine),
545
+ acceptance: task.acceptance === null ? null : rewriteAbsolutePaths(task.acceptance, map),
546
+ verify: task.verify === "none" ? null : task.verify,
547
+ workRoot: i.slot.path,
548
+ };
549
+ }
550
+
551
+ export type { LedgerV1, TaskId, TaskNode };