@ordewell/core 0.10.5 → 0.10.6

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 (44) hide show
  1. package/dist/{IRunner-Crkt3tHD.d.ts → IFileSystem-C4_mpfze.d.ts} +97 -14
  2. package/dist/{IRunner-lMQIa5Wc.d.mts → IFileSystem-DUgeWWQN.d.mts} +97 -14
  3. package/dist/{ModeResolver-B4hhABNf.d.mts → ModeResolver-4qNjxcDs.d.mts} +1 -1
  4. package/dist/{ModeResolver-CUR5jCSU.d.ts → ModeResolver-DGK2rWHE.d.ts} +1 -1
  5. package/dist/{Task-D4QHjdGv.d.mts → Task-C0o4i3Nn.d.mts} +23 -4
  6. package/dist/{Task-D4QHjdGv.d.ts → Task-C0o4i3Nn.d.ts} +23 -4
  7. package/dist/{chunk-6LEA6WAM.mjs → chunk-DMG4ISUG.mjs} +923 -45
  8. package/dist/chunk-DMG4ISUG.mjs.map +1 -0
  9. package/dist/{chunk-RT4NQ2BZ.mjs → chunk-EEE2GBLG.mjs} +114 -27
  10. package/dist/chunk-EEE2GBLG.mjs.map +1 -0
  11. package/dist/chunk-H7QX32BH.mjs +647 -0
  12. package/dist/chunk-H7QX32BH.mjs.map +1 -0
  13. package/dist/{chunk-F3KIX7WR.mjs → chunk-LTHKFBKM.mjs} +4 -4
  14. package/dist/chunk-LTHKFBKM.mjs.map +1 -0
  15. package/dist/index.d.mts +278 -1701
  16. package/dist/index.d.ts +278 -1701
  17. package/dist/index.js +2729 -1903
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +2171 -1523
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/parsing.d.mts +2 -2
  22. package/dist/parsing.d.ts +2 -2
  23. package/dist/parsing.js +231 -75
  24. package/dist/parsing.js.map +1 -1
  25. package/dist/parsing.mjs +3 -3
  26. package/dist/plan-utils.d.mts +20 -4
  27. package/dist/plan-utils.d.ts +20 -4
  28. package/dist/plan-utils.js +255 -97
  29. package/dist/plan-utils.js.map +1 -1
  30. package/dist/plan-utils.mjs +33 -19
  31. package/dist/{plan-utils-wI8MuDBC.d.mts → runSettingsText-BgOmLxdw.d.mts} +1941 -108
  32. package/dist/{plan-utils-BVJCzNvm.d.ts → runSettingsText-BgXvajj2.d.ts} +1941 -108
  33. package/dist/testing.d.mts +2 -3
  34. package/dist/testing.d.ts +2 -3
  35. package/dist/testing.js.map +1 -1
  36. package/dist/testing.mjs +1 -1
  37. package/package.json +1 -1
  38. package/dist/IFileSystem-ClBdp59f.d.ts +0 -78
  39. package/dist/IFileSystem-Db34maxC.d.mts +0 -78
  40. package/dist/chunk-4QLFM73A.mjs +0 -1407
  41. package/dist/chunk-4QLFM73A.mjs.map +0 -1
  42. package/dist/chunk-6LEA6WAM.mjs.map +0 -1
  43. package/dist/chunk-F3KIX7WR.mjs.map +0 -1
  44. package/dist/chunk-RT4NQ2BZ.mjs.map +0 -1
@@ -17,6 +17,90 @@ function loadedSkillTokens(text, loaded) {
17
17
  return skillTokens(text).filter((t) => loaded.includes(t.name));
18
18
  }
19
19
 
20
+ // src/services/PlanTree.ts
21
+ function* walkPlan(tasks) {
22
+ function* walk(level, ancestors, parentLabel) {
23
+ for (const task of level) {
24
+ const label = parentLabel ? `${parentLabel}.${task.order}` : String(task.order);
25
+ yield { task, parent: ancestors.at(-1), ancestors, siblings: level, label };
26
+ yield* walk(task.subtasks ?? [], [...ancestors, task], label);
27
+ }
28
+ }
29
+ yield* walk(tasks, []);
30
+ }
31
+ function taskPlacement(tasks, id) {
32
+ for (const row of walkPlan(tasks)) if (row.task.id === id) return row;
33
+ return void 0;
34
+ }
35
+ function subtreeIds(tasks, id) {
36
+ const found = taskPlacement(tasks, id);
37
+ return new Set(found ? [...walkPlan([found.task])].map(({ task }) => task.id) : []);
38
+ }
39
+ function dependencyCandidates(tasks, taskId) {
40
+ if (!taskId) return [...tasks];
41
+ const found = taskPlacement(tasks, taskId);
42
+ return found ? found.siblings.filter((t) => t.order < found.task.order) : [];
43
+ }
44
+ function dependentsOf(tasks, taskId) {
45
+ const removed = subtreeIds(tasks, taskId);
46
+ return [...walkPlan(tasks)].map(({ task }) => task).filter((t) => !removed.has(t.id) && t.dependencies.some((id) => removed.has(id)));
47
+ }
48
+ function dependencyTargetErrors(tasks, taskId, dependencies) {
49
+ const found = taskPlacement(tasks, taskId);
50
+ if (!found) return ["Task not found"];
51
+ const descendants = subtreeIds(tasks, taskId);
52
+ const errors = [];
53
+ for (const dep of dependencies) {
54
+ if (dep === taskId) {
55
+ errors.push(`"${found.task.title}" cannot depend on itself`);
56
+ continue;
57
+ }
58
+ const target = taskPlacement(tasks, dep)?.task;
59
+ if (!target) {
60
+ errors.push(`Unknown dependency "${dep}"`);
61
+ continue;
62
+ }
63
+ if (found.ancestors.some((t) => t.id === dep) || descendants.has(dep)) {
64
+ errors.push(`"${found.task.title}" cannot depend on "${target.title}", its ancestor or descendant`);
65
+ }
66
+ }
67
+ return errors;
68
+ }
69
+ function findDependencyCycle(tasks) {
70
+ const byId = new Map([...walkPlan(tasks)].map(({ task }) => [task.id, task]));
71
+ const path = [];
72
+ const done = /* @__PURE__ */ new Set();
73
+ const visit = (id) => {
74
+ if (done.has(id)) return null;
75
+ const at = path.indexOf(id);
76
+ if (at >= 0) return path.slice(at);
77
+ path.push(id);
78
+ for (const dep of byId.get(id)?.dependencies ?? []) {
79
+ const hit = visit(dep);
80
+ if (hit) return hit;
81
+ }
82
+ path.pop();
83
+ done.add(id);
84
+ return null;
85
+ };
86
+ for (const id of byId.keys()) {
87
+ const hit = visit(id);
88
+ if (hit) return hit.map((key) => byId.get(key));
89
+ }
90
+ return null;
91
+ }
92
+ function canSetDependencies(tasks, taskId, dependencies) {
93
+ const [error] = dependencyTargetErrors(tasks, taskId, dependencies);
94
+ if (error) return { ok: false, error };
95
+ const replace = (level) => level.map((t) => ({
96
+ ...t,
97
+ dependencies: t.id === taskId ? dependencies : t.dependencies,
98
+ subtasks: replace(t.subtasks ?? [])
99
+ }));
100
+ const cycle = findDependencyCycle(replace(tasks));
101
+ return cycle ? { ok: false, error: `Dependency cycle detected: ${[...cycle, cycle[0]].map((t) => `"${t.title}"`).join(" \u2192 ")}` } : { ok: true };
102
+ }
103
+
20
104
  // src/services/TaskRefs.ts
21
105
  function taskOrderLabel(task, parent) {
22
106
  return parent ? `${parent.label ?? parent.order}.${task.order}` : String(task.order);
@@ -27,16 +111,8 @@ function taskRef(task, parent) {
27
111
  function titledTaskRef(task, parent) {
28
112
  return `${taskRef(task, parent)} ${task.title}`;
29
113
  }
30
- function* depthFirst(tasks, parent, parentLabel) {
31
- for (const task of tasks) {
32
- const label = taskOrderLabel(task, parent ? { order: parent.order, label: parentLabel } : void 0);
33
- yield { task, parent, label };
34
- yield* depthFirst(task.subtasks ?? [], task, label);
35
- }
36
- }
37
114
  function findTaskRef(tasks, id) {
38
- for (const match of depthFirst(tasks)) if (match.task.id === id) return match;
39
- return void 0;
115
+ return taskPlacement(tasks, id);
40
116
  }
41
117
  function taskRefOf(tasks, id) {
42
118
  const found = findTaskRef(tasks, id);
@@ -49,7 +125,7 @@ function titledTaskRefOf(tasks, id) {
49
125
  function resolveTaskRef(tasks, ref) {
50
126
  const s = String(ref).trim();
51
127
  if (!s) return void 0;
52
- for (const { task } of depthFirst(tasks)) if (task.id === s) return task;
128
+ for (const { task } of walkPlan(tasks)) if (task.id === s) return task;
53
129
  const label = s.startsWith("#") ? s.slice(1) : s;
54
130
  if (/^\d+(\.\d+)*$/.test(label)) {
55
131
  let level = tasks;
@@ -60,9 +136,16 @@ function resolveTaskRef(tasks, ref) {
60
136
  }
61
137
  return found;
62
138
  }
63
- for (const { task } of depthFirst(tasks)) if (task.title === s) return task;
139
+ for (const { task } of walkPlan(tasks)) if (task.title === s) return task;
64
140
  return void 0;
65
141
  }
142
+ function resolveUserTaskRef(tasks, ref) {
143
+ const found = resolveTaskRef(tasks, ref);
144
+ if (found) return found;
145
+ const prefix = String(ref).trim();
146
+ const matches = prefix ? [...walkPlan(tasks)].filter(({ task }) => task.id.startsWith(prefix)) : [];
147
+ return matches.length === 1 ? matches[0].task : void 0;
148
+ }
66
149
 
67
150
  // src/models/Task.ts
68
151
  import { v4 as uuidv4 } from "uuid";
@@ -147,7 +230,7 @@ function migratePlanState(raw) {
147
230
  finalized: true
148
231
  }));
149
232
  const pendingTasks = raw.tasks.filter(
150
- (t) => t.status !== "completed" && t.status !== "failed" && t.status !== "blocked"
233
+ (t) => t.status !== "completed" && t.status !== "failed"
151
234
  );
152
235
  return {
153
236
  phase: "executing",
@@ -226,7 +309,7 @@ function createEmptyPlan() {
226
309
  };
227
310
  }
228
311
  function flattenTasks(tasks) {
229
- return tasks.flatMap((t) => [t, ...flattenTasks(t.subtasks ?? [])]);
312
+ return [...walkPlan(tasks)].map(({ task }) => task);
230
313
  }
231
314
  function rejoinPlanTree(pending, log) {
232
315
  const latest = /* @__PURE__ */ new Map();
@@ -246,14 +329,7 @@ function rejoinPlanTree(pending, log) {
246
329
  return [...latest.values()].filter((task) => !nested.has(task.id)).map(rebuild).sort((a, b) => a.order - b.order);
247
330
  }
248
331
  function flattenTasksWithParents(tasks) {
249
- const rows = [];
250
- const walk = (t, parent, parentLabel) => {
251
- const label = taskOrderLabel(t, parent ? { order: parent.order, label: parentLabel } : void 0);
252
- rows.push({ task: t, parent, label, ref: `#${label}` });
253
- for (const sub of t.subtasks ?? []) walk(sub, t, label);
254
- };
255
- for (const t of tasks) walk(t, null);
256
- return rows;
332
+ return [...walkPlan(tasks)].map(({ task, parent, label }) => ({ task, parent: parent ?? null, label, ref: `#${label}` }));
257
333
  }
258
334
  function addTaskToPlan(tasks, partial) {
259
335
  const maxOrder = tasks.reduce((max, t) => Math.max(max, t.order), 0);
@@ -265,12 +341,13 @@ function addTaskToPlan(tasks, partial) {
265
341
  return renumberTasks([...tasks, newTask]);
266
342
  }
267
343
  function removeTaskFromPlan(tasks, taskId) {
268
- const result = tasks.filter((t) => t.id !== taskId).map((t) => ({
344
+ const removed = subtreeIds(tasks, taskId);
345
+ const prune = (level) => level.filter((t) => !removed.has(t.id)).map((t) => ({
269
346
  ...t,
270
- dependencies: t.dependencies.filter((depId) => depId !== taskId),
271
- subtasks: removeTaskFromPlan(t.subtasks, taskId)
347
+ dependencies: t.dependencies.filter((depId) => !removed.has(depId)),
348
+ subtasks: prune(t.subtasks)
272
349
  }));
273
- return renumberTasks(result);
350
+ return renumberTasks(prune(tasks));
274
351
  }
275
352
  function updateTaskInPlan(tasks, taskId, changes) {
276
353
  return renumberTasks(
@@ -300,7 +377,7 @@ function approvalRecordOf(plan) {
300
377
  };
301
378
  }
302
379
  function waitsForApproval(task, record) {
303
- return record.approved === true && task.type === "ai" && (task.status === "pending" || task.status === "approved" || task.status === "blocked") && !(record.approvedTasks ?? []).includes(task.id);
380
+ return record.approved === true && task.type === "ai" && (task.status === "pending" || task.status === "approved") && !(record.approvedTasks ?? []).includes(task.id);
304
381
  }
305
382
  function stampOrigin(before, after, bySupervisor) {
306
383
  const prior = new Map(flattenTasks([...before]).map((t) => [t.id, t]));
@@ -330,6 +407,7 @@ function keepExecutionState(current, rewrite) {
330
407
  return {
331
408
  ...t,
332
409
  status: prior?.status ?? "pending",
410
+ skipReason: prior?.skipReason,
333
411
  verdict: prior?.verdict,
334
412
  outputSummary: prior?.outputSummary,
335
413
  runnerSessionId: prior?.runnerSessionId,
@@ -357,12 +435,21 @@ function keepExecutionState(current, rewrite) {
357
435
  export {
358
436
  skillTokens,
359
437
  loadedSkillTokens,
438
+ walkPlan,
439
+ taskPlacement,
440
+ subtreeIds,
441
+ dependencyCandidates,
442
+ dependentsOf,
443
+ dependencyTargetErrors,
444
+ findDependencyCycle,
445
+ canSetDependencies,
360
446
  taskOrderLabel,
361
447
  taskRef,
362
448
  titledTaskRef,
363
449
  taskRefOf,
364
450
  titledTaskRefOf,
365
451
  resolveTaskRef,
452
+ resolveUserTaskRef,
366
453
  isAwaitingReason,
367
454
  migrateLoadedTasks,
368
455
  isUserMessage,
@@ -389,4 +476,4 @@ export {
389
476
  stampOrigin,
390
477
  keepExecutionState
391
478
  };
392
- //# sourceMappingURL=chunk-RT4NQ2BZ.mjs.map
479
+ //# sourceMappingURL=chunk-EEE2GBLG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/conversation/skillTokens.ts","../src/services/PlanTree.ts","../src/services/TaskRefs.ts","../src/models/Task.ts"],"sourcesContent":["/** A name a skill can have, lower-cased: the one pattern for a `/name` token and for a skill folder. */\nexport const SKILL_NAME_PATTERN = '[a-z0-9][a-z0-9_-]*';\n\n/**\n * A `/skill-name` token anywhere in a message: whitespace (or string start)\n * before it, a skill name in any case, optional trailing punctuation that\n * isn't part of the name, then whitespace (or string end). The punctuation\n * group is what lets \"/grilling,\" name \"grilling\".\n */\nconst SKILL_TOKEN = new RegExp(`(^|\\\\s)\\\\/(${SKILL_NAME_PATTERN})([,.!?;:]*)(?=\\\\s|$)`, 'gi');\n\n/** Where a skill name is invoked: `start` is its `/`, `end` is just past the name, before any punctuation. */\nexport interface SkillToken {\n name: string;\n start: number;\n end: number;\n}\n\n/**\n * The first `/name` token for each name in `text`, names lower-cased. Only\n * the first counts because a skill loads once per message however often it is\n * named, so a later repeat is plain text.\n */\nexport function skillTokens(text: string): SkillToken[] {\n const tokens: SkillToken[] = [];\n const seen = new Set<string>();\n for (const match of text.matchAll(SKILL_TOKEN)) {\n const name = match[2].toLowerCase();\n if (seen.has(name)) continue;\n seen.add(name);\n const start = match.index + match[1].length;\n tokens.push({ name, start, end: start + 1 + match[2].length });\n }\n return tokens;\n}\n\n/** The tokens in a sent message that loaded one of `loaded` — what a surface highlights in the user's bubble. */\nexport function loadedSkillTokens(text: string, loaded: readonly string[]): SkillToken[] {\n return skillTokens(text).filter((t) => loaded.includes(t.name));\n}\n","/** Plan placement and dependency rules, shared with browser-bundled surfaces. */\nexport interface TreeTask<T> {\n id: string;\n order: number;\n title: string;\n subtasks?: readonly T[];\n}\n\nexport interface DependencyTask<T> extends TreeTask<T> {\n dependencies: readonly string[];\n}\n\nexport interface TaskPlacement<T> {\n task: T;\n parent?: T;\n ancestors: readonly T[];\n siblings: readonly T[];\n label: string;\n}\n\nexport function* walkPlan<T extends TreeTask<T>>(tasks: readonly T[]): Generator<TaskPlacement<T>> {\n function* walk(level: readonly T[], ancestors: readonly T[], parentLabel?: string): Generator<TaskPlacement<T>> {\n for (const task of level) {\n const label = parentLabel ? `${parentLabel}.${task.order}` : String(task.order);\n yield { task, parent: ancestors.at(-1), ancestors, siblings: level, label };\n yield* walk(task.subtasks ?? [], [...ancestors, task], label);\n }\n }\n yield* walk(tasks, []);\n}\n\nexport function taskPlacement<T extends TreeTask<T>>(tasks: readonly T[], id: string): TaskPlacement<T> | undefined {\n for (const row of walkPlan(tasks)) if (row.task.id === id) return row;\n return undefined;\n}\n\n/** Includes the root: deletion has to detach every edge into the removed tree. */\nexport function subtreeIds<T extends TreeTask<T>>(tasks: readonly T[], id: string): Set<string> {\n const found = taskPlacement(tasks, id);\n return new Set(found ? [...walkPlan([found.task])].map(({ task }) => task.id) : []);\n}\n\n/** Pickers offer earlier siblings; API validity is independent of display order. */\nexport function dependencyCandidates<T extends TreeTask<T>>(tasks: readonly T[], taskId?: string): T[] {\n if (!taskId) return [...tasks];\n const found = taskPlacement(tasks, taskId);\n return found ? found.siblings.filter((t) => t.order < found.task.order) : [];\n}\n\n/** The surviving tasks whose dependency lists a subtree removal will change. */\nexport function dependentsOf<T extends DependencyTask<T>>(tasks: readonly T[], taskId: string): T[] {\n const removed = subtreeIds(tasks, taskId);\n return [...walkPlan(tasks)].map(({ task }) => task)\n .filter((t) => !removed.has(t.id) && t.dependencies.some((id) => removed.has(id)));\n}\n\nexport interface DependencyCheck { ok: boolean; error?: string }\n\n/** Target restrictions, separate from cycles so a planner batch can check its final graph. */\nexport function dependencyTargetErrors<T extends TreeTask<T>>(\n tasks: readonly T[], taskId: string, dependencies: readonly string[],\n): string[] {\n const found = taskPlacement(tasks, taskId);\n if (!found) return ['Task not found'];\n const descendants = subtreeIds(tasks, taskId);\n const errors: string[] = [];\n for (const dep of dependencies) {\n if (dep === taskId) { errors.push(`\"${found.task.title}\" cannot depend on itself`); continue; }\n const target = taskPlacement(tasks, dep)?.task;\n if (!target) { errors.push(`Unknown dependency \"${dep}\"`); continue; }\n if (found.ancestors.some((t) => t.id === dep) || descendants.has(dep)) {\n errors.push(`\"${found.task.title}\" cannot depend on \"${target.title}\", its ancestor or descendant`);\n }\n }\n return errors;\n}\n\n/** The tasks on one dependency cycle, in dependency order, or null. */\nexport function findDependencyCycle<T extends DependencyTask<T>>(tasks: readonly T[]): T[] | null {\n const byId = new Map([...walkPlan(tasks)].map(({ task }) => [task.id, task]));\n const path: string[] = [];\n const done = new Set<string>();\n const visit = (id: string): string[] | null => {\n if (done.has(id)) return null;\n const at = path.indexOf(id);\n if (at >= 0) return path.slice(at);\n path.push(id);\n for (const dep of byId.get(id)?.dependencies ?? []) {\n const hit = visit(dep);\n if (hit) return hit;\n }\n path.pop();\n done.add(id);\n return null;\n };\n for (const id of byId.keys()) {\n const hit = visit(id);\n if (hit) return hit.map((key) => byId.get(key)!);\n }\n return null;\n}\n\nexport function canSetDependencies<T extends DependencyTask<T>>(\n tasks: readonly T[], taskId: string, dependencies: readonly string[],\n): DependencyCheck {\n const [error] = dependencyTargetErrors(tasks, taskId, dependencies);\n if (error) return { ok: false, error };\n const replace = (level: readonly T[]): T[] => level.map((t) => ({\n ...t,\n dependencies: t.id === taskId ? dependencies : t.dependencies,\n subtasks: replace(t.subtasks ?? []),\n }));\n const cycle = findDependencyCycle(replace(tasks));\n return cycle\n ? { ok: false, error: `Dependency cycle detected: ${[...cycle, cycle[0]].map((t) => `\"${t.title}\"`).join(' → ')}` }\n : { ok: true };\n}\n","import { taskPlacement, walkPlan, type TreeTask } from './PlanTree';\n\n/**\n * Task references: the one grammar for naming a task in a plan, both ways.\n * A label is rendered from a task's order under its parent (\"2\", \"2.1\"), and\n * a reference written by anyone — the planner, a tool call, a command — is\n * resolved back against the plan tree. Pure so a\n * browser-bundled surface can use it through `@ordewell/core/plan-utils`.\n */\n\n/** The shape a reference resolves over: the plan's task tree, or a surface's projection of it. */\nexport type RefTask<T> = TreeTask<T>;\n\n/**\n * The parent a label extends. A label is the full path (\"3.2.1\"), so a parent\n * below the top level carries the label it was itself reached by; without one\n * the parent's order stands for it, which is right for a top-level parent.\n */\nexport interface RefParent {\n order: number;\n label?: string;\n}\n\n/** Dotted path label for a task, e.g. \"2.1\" for the first subtask of task 2, \"2.1.3\" one level down. */\nexport function taskOrderLabel(task: { order: number }, parent?: RefParent): string {\n return parent ? `${parent.label ?? parent.order}.${task.order}` : String(task.order);\n}\n\n/** How a surface refers to a task in prose: \"#2\", or \"#2.1\" for a subtask. */\nexport function taskRef(task: { order: number }, parent?: RefParent): string {\n return `#${taskOrderLabel(task, parent)}`;\n}\n\n/** A task named in full, as a confirmation or a picker title does: \"#2 Deploy\". */\nexport function titledTaskRef(task: { order: number; title: string }, parent?: RefParent): string {\n return `${taskRef(task, parent)} ${task.title}`;\n}\n\n/** A task found in a plan tree, with its parent and the full path label its reference extends. */\nexport interface RefTaskMatch<T> {\n task: T;\n parent?: T;\n label: string;\n}\n\n/** The task a plan tree holds, by id, with its parent; undefined when the tree holds none. */\nexport function findTaskRef<T extends RefTask<T>>(tasks: readonly T[], id: string): RefTaskMatch<T> | undefined {\n return taskPlacement(tasks, id);\n}\n\n/**\n * The reference {@link taskRef} renders for the task a plan tree holds, by id\n * — its full path, dotted, for a subtask. Undefined when the tree holds no such task.\n */\nexport function taskRefOf<T extends RefTask<T>>(tasks: readonly T[], id: string): string | undefined {\n const found = findTaskRef(tasks, id);\n return found && `#${found.label}`;\n}\n\n/**\n * The reference and title {@link titledTaskRef} renders for the task a plan\n * tree holds, by id — its full path, dotted, for a subtask. Undefined when the\n * tree holds no such task.\n */\nexport function titledTaskRefOf<T extends RefTask<T>>(tasks: readonly T[], id: string): string | undefined {\n const found = findTaskRef(tasks, id);\n return found && `#${found.label} ${found.task.title}`;\n}\n\n/**\n * Resolve a written reference to a task at any depth: an id, then an order\n * label with or without \"#\" (\"#2\", \"2\", \"#2.1\"), then an exact title.\n *\n * An order label is read against the tree, never a flattened list: subtask\n * orders restart at 1 under each parent, so \"#2\" always means top-level task 2\n * and a subtask is reachable only by its dotted path (\"#2.1\", \"#2.1.3\").\n */\nexport function resolveTaskRef<T extends RefTask<T>>(tasks: readonly T[], ref: string | number): T | undefined {\n const s = String(ref).trim();\n if (!s) return undefined;\n for (const { task } of walkPlan(tasks)) if (task.id === s) return task;\n const label = s.startsWith('#') ? s.slice(1) : s;\n if (/^\\d+(\\.\\d+)*$/.test(label)) {\n let level: readonly T[] | undefined = tasks;\n let found: T | undefined;\n for (const order of label.split('.').map(Number)) {\n found = level?.find((t) => t.order === order);\n level = found?.subtasks;\n }\n return found;\n }\n for (const { task } of walkPlan(tasks)) if (task.title === s) return task;\n return undefined;\n}\n\n/**\n * A reference as the user types one: {@link resolveTaskRef}, then a unique\n * prefix of a task's id at any depth. Only the user's: a model's reference\n * that names no task is refused, never matched to the one task a fragment of\n * it happens to fit.\n */\nexport function resolveUserTaskRef<T extends RefTask<T>>(tasks: readonly T[], ref: string | number): T | undefined {\n const found = resolveTaskRef(tasks, ref);\n if (found) return found;\n const prefix = String(ref).trim();\n const matches = prefix ? [...walkPlan(tasks)].filter(({ task }) => task.id.startsWith(prefix)) : [];\n return matches.length === 1 ? matches[0].task : undefined;\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport type { PlanIsolation } from '../interfaces/IWorktreeIsolation';\nimport type { AttemptUsage, PlannerUsage, UsageRecord, UsageTotals } from './Usage';\nimport type { ExecutionRecord, SupervisorLevel } from './Execution';\nimport type { SkillSource } from '../services/SkillsService';\nimport type { SupervisionMemorySnapshot } from '../services/LoopGuards';\nimport type { SupervisorSnapshot } from '../services/Supervisor';\nimport { SKILL_NAME_PATTERN } from '../conversation/skillTokens';\nimport { subtreeIds, walkPlan } from '../services/PlanTree';\n\nexport interface UserStep {\n order: number;\n instruction: string;\n completed: boolean;\n}\n\n/** One deterministic signal gathered while verifying a completed task. `completion_marker` is only in verdicts saved before completion was reported through `task_complete` alone. */\nexport interface VerificationCheck {\n name: 'exit_code' | 'completion_marker' | 'task_complete' | 'manual';\n passed: boolean;\n /** A check that did not apply. Skipped checks don't affect the verdict. */\n skipped: boolean;\n detail: string;\n}\n\n/** Evidence-based verdict for a completed task. Single end-to-end outcome produced by verification. */\nexport interface Verdict {\n outcome: 'pass' | 'fail';\n reason: string;\n checks: VerificationCheck[];\n decidedAt: string;\n}\n\nexport interface TaskOutputSummary {\n reviewReason: string;\n /** The `task_complete` summary, the task's report; absent when the attempt ended without one, and from sessions saved before it was kept. */\n report?: string;\n /** Empty when there is a report: the turn's final text is the report itself. */\n logTail: string;\n capturedAt: string;\n}\n\nexport type TaskType = 'ai' | 'user';\n/**\n * `skipped` is terminal and verdict-less: the task will not be waited for, and\n * nothing it did lands. Its dependents go ahead without it once the work it\n * waited on is done. There is no stored `blocked`: a task is blocked when a\n * failed dependency says so (ADR-0034), and a file that kept the old status\n * loads as pending.\n */\nexport type TaskStatus = 'pending' | 'approved' | 'in_progress' | 'completed' | 'failed' | 'awaiting_user' | 'skipped';\nexport type TaskMode = string;\n\n/**\n * Why an `awaiting_user` task waits (ADR-0018, W1): a structured turn that\n * ended without a `task_complete` call, a checkpoint question, work that did not\n * land, an ops task that changed tracked files (ADR-0020), or its runner's\n * usage limit. Saved, so no surface has to guess it from whether an attempt\n * is live.\n */\nexport type AwaitingReason = 'input' | 'checkpoint' | 'conflict' | 'files-changed' | 'usage-limit';\n\nexport function isAwaitingReason(value: unknown): value is AwaitingReason {\n return value === 'input' || value === 'checkpoint' || value === 'conflict' || value === 'files-changed' || value === 'usage-limit';\n}\n\nexport interface TaskModelAssignment {\n modelId: string;\n modelLabel: string;\n thinkingEffort?: string;\n /**\n * All variant ids the model offered when this assignment was made. Carried\n * on the assignment because runners need it at spawn time (opencode's TUI\n * only honors an assigned variant when the others are config-disabled) and\n * the discovery catalog isn't available there.\n */\n availableVariants?: string[];\n}\n\nexport type RunnerId = string;\n\n/**\n * Bring loaded tasks to the structured-only shape, in place. A task saved\n * while the terminal transport existed may say it ran there, and why; neither\n * means anything now, and such a task left no session to continue. Its\n * completion marker id went with the text markers: completion is reported\n * only through `task_complete`.\n */\nexport function migrateLoadedTasks(tasks: readonly Task[]): void {\n for (const task of tasks) {\n if (typeof task.runnerSessionId !== 'string') delete task.runnerSessionId;\n if (typeof task.carriedFrom !== 'string') delete task.carriedFrom;\n if (typeof task.runnerSessionOwner !== 'string') delete task.runnerSessionOwner;\n const legacy = task as Task & { transport?: { kind?: unknown; nativeSessionId?: unknown } };\n if (!task.runnerSessionId && legacy.transport?.kind === 'structured' && typeof legacy.transport.nativeSessionId === 'string') {\n task.runnerSessionId = legacy.transport.nativeSessionId;\n }\n delete legacy.transport;\n delete (task as { completionMarker?: unknown }).completionMarker;\n // The effort once had a second home on the task; the spawn reads only the model's.\n const effort = (task as { thinkingEffort?: unknown }).thinkingEffort;\n if (typeof effort === 'string' && task.assignedModel && !task.assignedModel.thinkingEffort) task.assignedModel.thinkingEffort = effort;\n delete (task as { thinkingEffort?: unknown }).thinkingEffort;\n migrateLoadedTasks(task.subtasks ?? []);\n }\n}\n\n/**\n * A task skill as one attempt received it: read from the task's own worktree\n * (or global) at spawn, kept so the user can see what the runner was told\n * even after the skill's file changes.\n */\nexport interface TaskSkillSnapshot {\n name: string;\n source: SkillSource;\n path: string;\n content: string;\n}\n\n/** A task skill as a surface is told of it: the body stays in the task's log file and the session. */\nexport type TaskSkillNotice = Omit<TaskSkillSnapshot, 'content'>;\n\nexport interface Task {\n id: string;\n order: number;\n title: string;\n description: string;\n type: TaskType;\n status: TaskStatus;\n dependencies: string[];\n prompt?: string;\n userSteps?: UserStep[];\n subtasks: Task[];\n verdict?: Verdict;\n outputSummary?: TaskOutputSummary;\n assignedModel?: TaskModelAssignment;\n assignedRunner: RunnerId;\n taskMode?: TaskMode;\n autonomy?: 'AFK' | 'HITL';\n sliceType?: 'HITL' | 'AFK';\n userStoriesCovered?: string[];\n /** The runner's saved session for a later continue; cleared when a fresh attempt starts. */\n runnerSessionId?: string;\n /**\n * The runner that session belongs to: a session cannot cross runners, so\n * Continue is offered only while the task is still assigned to it. Absent\n * on a plan saved before it was recorded; the last attempt's runner stands\n * in (see `sessionOwner`).\n */\n runnerSessionOwner?: RunnerId;\n /** Set only while `status` is `awaiting_user`, and not always then — a pause saved by an older build has none. */\n awaitingReason?: AwaitingReason;\n /**\n * When a task paused on its runner's usage limit is resumed on its own (ISO\n * time): the reset the runner announced, plus a short margin. Absent when no\n * reset time could be read or the user cancelled the resume — the task then\n * waits for a manual retry. Set only with `awaitingReason` `usage-limit`.\n */\n resumeAt?: string;\n /**\n * The runner a task paused on its usage limit was moved off (ADR-0018, U1):\n * its next attempt is a carry-over, a fresh session that starts from that\n * attempt's files. Cleared once that attempt runs, and by a retry.\n */\n carriedFrom?: RunnerId;\n /** Why the task was skipped, as whoever skipped it put it; set only while `status` is `skipped`, and not always then. */\n skipReason?: string;\n /**\n * An ops task (ADR-0020): it changes no repository files, runs at the\n * workspace root rather than in a worktree, and waits for the change tasks\n * it depends on to be merged into the user's branch. Top-level AI tasks\n * only; absent means a change task.\n */\n ops?: boolean;\n /**\n * The dependencies, by title, whose work was not merged into the user's\n * branch when the user force-started this task past its merge gate\n * (ADR-0020). Cleared when the task is retried.\n */\n forcedPastGate?: string[];\n /**\n * Task skills (`applies-to: task`) attached by name. Their bodies are put in\n * the runner's prompt at spawn, resolved where the task runs — a subtask's\n * are its own, never its parent's. Absent means none.\n */\n skills?: string[];\n /** The skills the latest attempt was given, as read when it spawned. */\n attemptSkills?: TaskSkillSnapshot[];\n /**\n * Who put the task in the plan, when it was not the user's own planning:\n * `supervisor` for a task an Act supervisor added during a run, which\n * counts as approved to run (ADR-0029). Set by the session, never by an op.\n */\n addedBy?: 'supervisor';\n attemptUsage?: AttemptUsage[];\n}\n\nexport interface DiscoveredMode {\n id: string;\n label: string;\n description: string;\n}\n\nexport type ResearchToolType =\n | 'read_file' | 'read_files' | 'glob' | 'grep' | 'find_symbol' | 'list_dir'\n | 'bash' | 'fetch' | 'web_search' | 'spawn_research_agent'\n | 'task_query' | 'task_output' | 'task_diff'\n /**\n * A tool belonging to a harness planner's own toolbox (ADR-0009) that has no\n * Ordewell equivalent — Edit, WebFetch, TodoWrite, whatever a coding agent\n * ships next. The real name travels in `toolLabel` rather than being\n * relabelled as a tool it is not; the union stays closed so the\n * exhaustiveness checks in every surface's icon/label switch survive.\n */\n | 'agent_tool';\n\n/**\n * What happened when a research tool call ran, for honest per-surface\n * rendering. The broadcast seam carries this on every `research_step_done` so\n * surfaces do not have to pattern-match refusal text to tell a refused `rm`\n * from a successful `rm` — the old render path flipped a `✓` for both.\n */\nexport type ResearchStepOutcome = 'success' | 'failure' | 'refused' | 'denied' | 'not_executed';\n\nexport interface ResearchStep {\n id: string;\n tool: ResearchToolType;\n /** The tool's own name when it came from a harness planner — always set for `agent_tool`. */\n toolLabel?: string;\n args: string;\n result: string;\n success: boolean;\n outcome: ResearchStepOutcome;\n /** The model's tool_call id, so a surface can match `tool_result` to the\n * pending `tool_call` it announced — robust under parallel same-tool rounds. */\n toolCallId?: string;\n /** The research subagent that ran the call, so a reload regroups it under that subagent. */\n subagentId?: string;\n timestamp: string;\n thinkingText?: string;\n}\n\nexport interface UserPromptEntry {\n id: string;\n type: 'user_prompt' | 'system';\n content: string;\n timestamp: string;\n}\n\nexport type SubagentOutcome = 'done' | 'failed' | 'stopped';\n\n/**\n * One subagent's whole run, logged when it finishes: what it was asked, how it\n * ended and what it reported. Its steps stay separate entries carrying the same\n * `subagentId`, so an older reader that knows only steps still shows them.\n */\nexport interface SubagentLogEntry {\n id: string;\n type: 'subagent';\n subagentId: string;\n brief: string;\n model?: string;\n outcome: SubagentOutcome;\n digest: string;\n usage?: UsageTotals;\n timestamp: string;\n}\n\nexport type ResearchLogEntry = ResearchStep | UserPromptEntry | SubagentLogEntry;\n\nexport interface ResearchProgress {\n // 'liveness' carries no content: a raw-line signal from the harness process\n // (ADR-0009) that reaches a surface even when a turn is producing nothing\n // visible — a subagent's filtered chatter, most often — so an idle watchdog\n // downstream doesn't mistake \"nothing to show\" for \"nothing happening\".\n //\n // The turn-scoped kinds below carry one planner turn's stream (#47); see the\n // matching SessionMessage variants for the invariants each one keeps.\n // 'text_delta' is reply text as the model streams it (`text`, `segmentId`),\n // an envelope included: the turn's owner routes each segment to prose or to\n // the plan display, so no backend has to tell them apart. 'text_retracted'\n // takes back an attempt's text: `segmentId`'s, or when absent everything the\n // backend call that sends it has streamed.\n // 'usage' reports one model call (`record`). 'subagent_started' carries\n // `brief` and `model`; 'subagent_finished' carries `outcome`, `digest` and\n // `usage`.\n type:\n | 'thinking' | 'tool_call' | 'tool_result' | 'plan_token' | 'interrupted' | 'liveness'\n | 'text_delta' | 'text_retracted' | 'usage' | 'subagent_started' | 'subagent_finished';\n /** Minted by whoever runs the turn and passed through untouched; absent outside a turn. */\n turnId?: string;\n /** One continuous run of model text — text before a tool call is its own segment. */\n segmentId?: string;\n text?: string;\n tool?: string;\n /** Harness planners (ADR-0009): the agent's own name for a tool Ordewell has no member for. */\n toolLabel?: string;\n toolArgs?: string;\n toolResult?: string;\n planToken?: string;\n step?: ResearchStep;\n /** The model's tool_call id, threaded on tool_call and tool_result so a\n * surface can match the result to its pending call — robust under parallel\n * same-tool rounds where LIFO-by-name matching mislabels summaries. */\n toolCallId?: string;\n /** Present when this event originates from (or reports on) one spawned research subagent (issue #34). */\n subagentId?: string;\n record?: UsageRecord;\n brief?: string;\n model?: string;\n outcome?: SubagentOutcome;\n digest?: string;\n usage?: UsageTotals;\n}\n\nexport interface ThinkingBlock {\n id: string;\n text: string;\n}\n\nexport interface StreamThinkingEvent {\n type: 'thinking';\n block: ThinkingBlock;\n}\n\nexport interface StreamStepEvent {\n type: 'step';\n step: ResearchStep;\n}\n\nexport type StreamEvent = StreamThinkingEvent | StreamStepEvent;\n\nexport interface DiscoveredModel {\n modelId: string;\n modelLabel: string;\n runnerProvider?: string;\n /**\n * Human-facing provider name as the runner itself reports it (e.g.\n * \"OpenCode Zen\" for `runnerProvider: 'opencode'`). Populated from the\n * runner's own provider catalog when available; when absent the UI derives a\n * label from `runnerProvider` by title-casing.\n */\n runnerProviderLabel?: string;\n /**\n * The runner whose catalog listed this model. Stamped once, at the single\n * `ModelDiscovery.discover` choke point, so a flat cross-runner list can\n * still say where each entry came from — `runnerProvider` alone cannot:\n * OpenCode reports most of its catalog as `openrouter`, which names the\n * serving backend, not the agent Ordewell would spawn.\n */\n runnerId?: string;\n /** The runner's display name (`OpenCode`), from its manifest. */\n runnerLabel?: string;\n variants: { id: string; label: string }[];\n /**\n * The model's context window when the runner or catalog reports it (#49).\n * Read by the planner-model lookup so context fill can be shown; absent when\n * unknown rather than defaulted to zero.\n */\n contextWindow?: number;\n}\n\nexport type PlanStatus = 'draft' | 'approved' | 'rejected' | 'running' | 'completed';\n\n/**\n * One entry of the planner's persisted dialogue (ADR-0002). The single source\n * of truth for both UI redisplay and conversational context. Tool-call results\n * are NOT stored here — they live in the AI service's tool-use history;\n * `researchLog` remains the persisted tool trace for the UI.\n */\nexport interface ConversationMessage {\n role: 'user' | 'assistant';\n content: string;\n timestamp: string;\n /**\n * Timeline marker: 'plan_generated' records the point in the dialogue where\n * the plan was committed (the UI anchors the plan card there on restore);\n * 'system' is a host-injected notice; 'compaction' is the summary a\n * user-triggered compaction left in place of the earlier messages — always\n * the transcript's first entry. 'skill_load' is a skill loaded into the\n * conversation, its snapshot in `skill`; one the user invoked follows the\n * message that named it. 'execution' is a call at the command seam\n * (ADR-0029), its record in `execution`. 'wake_up' is the digest a wake-up\n * gave the supervisor (role 'user': the model was told it), and\n * 'supervisor' what the supervisor said in a wake-up turn (ADR-0029).\n * 'error' is a planner turn that ended on the planner's usage limit, drawn\n * as a failure and never replayed to the planner: it is not the planner's\n * answer, and its inputs are sent again (see {@link PlannerResendState}).\n * Absent for ordinary chat turns, so sessions saved before markers existed\n * degrade gracefully.\n */\n kind?: 'plan_generated' | 'system' | 'compaction' | 'skill_load' | 'execution' | 'wake_up' | 'supervisor' | 'error';\n actor?: 'Ordewell setting';\n /** Present exactly when `kind` is 'skill_load'. */\n skill?: SkillLoad;\n /** Present exactly when `kind` is 'execution'. */\n execution?: ExecutionRecord;\n /** A user's message that was force sent, stopping the turn before it (ADR-0023). */\n forced?: true;\n /**\n * What a reply showed, run by run, where each began (ADR-0017 A1). Beside\n * `content`, which stays the reply as the planner is told it. Absent on\n * entries saved before runs were kept, which reload as one message.\n */\n runs?: ReplyRun[];\n}\n\n/**\n * One run of a planner reply's text: the segment it streamed under, its\n * settled text, and when it began. A run that never streamed (a message the\n * conversation wrote in the planner's place) has a segment no stream used.\n */\nexport interface ReplyRun {\n segmentId: string;\n text: string;\n /** ISO timestamp. */\n startedAt: string;\n}\n\n/**\n * A skill's SKILL.md as it was when loaded into a planner conversation. A\n * snapshot rather than a reference: a resumed, forked or rewound conversation\n * replays the body the planner originally saw, even after the file changed or\n * was deleted.\n */\nexport interface SkillLoad {\n invokedBy: 'user' | 'planner';\n name: string;\n source: SkillSource;\n /** The SKILL.md that won, home-abbreviated (`~/...`): which copy loaded is what a reader needs from it. */\n path: string;\n content: string;\n /**\n * Set when the user named a task skill: it is not loaded into the planner's\n * context, which is only told to attach it to the tasks it fits. `content`\n * is empty; the description is what the planner's directive quotes.\n */\n attaches?: { description: string };\n}\n\n/** A skill load as a surface announces it — the body stays with the transcript. */\nexport type SkillLoadNotice = Omit<SkillLoad, 'content'>;\n\n/** A message the user sent, as opposed to a skill load their message caused or a wake-up digest. */\nexport function isUserMessage(entry: Pick<ConversationMessage, 'role' | 'kind'>): boolean {\n return entry.role === 'user' && entry.kind !== 'skill_load' && entry.kind !== 'wake_up';\n}\n\n/** A follow-up an older build queued behind a run's batch boundary; read only to carry it over as a {@link PendingPlanTurn}. */\nexport interface QueuedMessage {\n id: string;\n text: string;\n timestamp: string;\n skills?: SkillLoad[];\n}\n\n/** Who a planner turn answers (ADR-0029): the user's message, or a wake-up batch the supervisor is given. */\nexport type PlanTurnSource = 'user' | 'supervisor';\n\n/**\n * A planner turn's input not yet answered by a turn that ended. It leaves the\n * plan with the change its turn made, in the same save, so a reload replays\n * exactly the inputs no turn answered — once. A supervisor's input is a\n * wake-up batch not yet delivered (ADR-0029): it stays until a turn lands\n * with it, whatever turns fail meanwhile.\n */\nexport interface PendingPlanTurn {\n id: string;\n source: PlanTurnSource;\n /** The user's message, or a wake-up batch's digest. */\n text: string;\n timestamp: string;\n /** What its `/name` tokens loaded when it was sent, so a replay sends the same skills. */\n skills?: SkillLoad[];\n /** Force sent: it waits ahead of every input not forced, and its turn is its own (ADR-0023, F2). */\n forced?: true;\n}\n\n/**\n * The run's own copy of the user's run settings (ADR-0030): taken when the\n * user starts it, changed at once by a change made in this session, and\n * lowered by a tripped guard or a failed supervisor.\n */\nexport interface RunSettings {\n mergeAtGatesAutomatically: boolean;\n /** Absent on a run started before supervisor levels existed: Off. */\n supervisorLevel?: SupervisorLevel;\n /** Absent on a run started before ADR-0030: the user's setting. */\n supervisorRetryLimit?: number;\n /** Absent on a run started before ADR-0030: the user's setting. */\n wakeUpReadBudget?: number;\n /** Why the supervisor stopped for the rest of this run, which carries on as Off; absent while it watches. */\n unsupervised?: string;\n}\n\n/**\n * What supervision remembers across a daemon restart (ADR-0029): the loop\n * guards' memory and the wake-up state not yet delivered with a turn.\n */\nexport interface SupervisionSnapshot {\n /** Retries, failed-attempt shapes, the supervisor's edits and what the user was told. */\n guards?: SupervisionMemorySnapshot;\n /** The events inside their debounce window and the wake-up rate's timestamps. */\n wake?: SupervisorSnapshot;\n}\n\n/**\n * What waits on the planner's usage limit. With `at`, the inputs no turn\n * answered are sent again then, on their own; without it — the reset could\n * not be read, the resend hit the limit again, or it was cancelled — they go\n * with the next input: the user's message, or a wake-up.\n */\nexport interface PlannerResendState {\n /** The runner whose account hit the limit; a planner on another one is not held by it. */\n runner?: RunnerId;\n at?: string;\n}\n\nexport interface LegacyPlanState {\n runSettings?: RunSettings;\n /** What supervision remembers across a daemon restart (ADR-0029); absent on plans saved before it existed. */\n supervision?: SupervisionSnapshot;\n tasks: Task[];\n generatedAt: string;\n status: PlanStatus;\n runners: RunnerId[];\n lastUpdated: string;\n researchLog?: ResearchLogEntry[];\n /** The planner dialogue — user messages and assistant messages, in order (ADR-0002). */\n conversationHistory?: ConversationMessage[];\n /** Full markdown PRD once written by the planner (PRD mode), also saved to .scratch/<slug>/PRD.md. */\n prdMarkdown?: string;\n /** Planner turn inputs no turn has answered yet (ADR-0029); a reload replays them. */\n pendingTurns?: PendingPlanTurn[];\n /** Written by builds that queued mid-run edits; a load moves it into {@link pendingTurns}. */\n queuedMessages?: QueuedMessage[];\n /**\n * The plan's isolation run (ADR-0013), written from the orchestrator at\n * persist time and read back only when a saved plan is adopted. It names\n * branches and worktrees that belong to this plan alone: a fork of the plan\n * must leave it behind rather than share it.\n */\n isolation?: PlanIsolation;\n /** Kept so a reopened session shows the same token line (#49). */\n plannerUsage?: PlannerUsage;\n /** The planner hit its usage limit and the inputs its turn took wait to be sent again; absent otherwise. */\n plannerResend?: PlannerResendState;\n /**\n * The tasks the user approved to run: every task when they executed the\n * plan, and each one they started or retried themselves since. A command\n * from anyone else starts only these (ADR-0029); a task the planner added\n * after the approval waits for the user's. Only tasks still in the plan: a\n * task that leaves takes its approval with it.\n */\n approvedTasks?: string[];\n /**\n * The user approved the plan to run: Execute plan, signing off a review, or\n * autorun's start (ADR-0029, ADR-0030). Kept apart from {@link status},\n * which surfaces rewrite for display; a user's start of one task approves\n * that task, not the plan.\n */\n approved?: boolean;\n}\n\nexport interface Message {\n id: string;\n role: 'user' | 'planner' | 'system';\n content: string;\n timestamp: number;\n}\n\nexport interface TaskSnapshot extends Task {\n completedAt: number;\n verdict?: Verdict;\n retryCount: number;\n finalized: boolean;\n}\n\n/** The plan a surface reads whole carries the approval record, so it can tell which tasks wait for the user (ADR-0035). */\nexport type PlanState = (\n | {\n phase: 'planning';\n history: Message[];\n message: string;\n pendingTasks: Task[];\n }\n | {\n phase: 'executing';\n history: Message[];\n message: string;\n executionLog: TaskSnapshot[];\n pendingTasks: Task[];\n goal: string;\n runners: string[];\n status: PlanStatus;\n }\n) & ApprovalRecord;\n\nfunction hasPhase(raw: unknown): raw is PlanState {\n return typeof raw === 'object' && raw !== null && 'phase' in raw;\n}\n\nfunction hasTasks(raw: unknown): raw is LegacyPlanState {\n return typeof raw === 'object' && raw !== null && 'tasks' in raw && Array.isArray((raw as Record<string, unknown>).tasks);\n}\n\nfunction logEntryToMessage(entry: ResearchLogEntry): Message {\n const timestamp = new Date(entry.timestamp).getTime();\n if (!('type' in entry)) {\n return { id: entry.id, role: 'system', content: JSON.stringify({ tool: entry.tool, args: entry.args, result: entry.result }), timestamp };\n }\n if (entry.type === 'subagent') {\n const { subagentId, brief, outcome, digest } = entry;\n return { id: entry.id, role: 'system', content: JSON.stringify({ subagentId, brief, outcome, digest }), timestamp };\n }\n return { id: entry.id, role: entry.type === 'user_prompt' ? 'user' : 'system', content: entry.content, timestamp };\n}\n\nfunction migrateHistory(raw: LegacyPlanState): Message[] {\n const messages: Message[] = [];\n\n if (raw.researchLog) {\n messages.push(...raw.researchLog.map(logEntryToMessage));\n }\n\n if (raw.queuedMessages) {\n for (const qm of raw.queuedMessages) {\n messages.push({\n id: qm.id,\n role: 'system',\n content: qm.text,\n timestamp: new Date(qm.timestamp).getTime(),\n });\n }\n }\n\n return messages;\n}\n\nexport function migratePlanState(raw: unknown): PlanState {\n if (hasPhase(raw)) return raw;\n\n if (!hasTasks(raw)) {\n return {\n phase: 'planning',\n history: [],\n message: '',\n pendingTasks: [],\n };\n }\n\n const hasExecution = raw.tasks.some(\n (t) => t.status === 'completed' || t.status === 'failed',\n );\n\n const messages = migrateHistory(raw);\n const record = approvalRecordOf(raw);\n\n if (hasExecution) {\n const executionLog: TaskSnapshot[] = raw.tasks\n .filter((t) => t.status === 'completed' || t.status === 'failed')\n .map((t) => ({\n ...t,\n completedAt: new Date(raw.lastUpdated).getTime(),\n verdict: t.verdict,\n retryCount: 0,\n finalized: true,\n }));\n\n const pendingTasks = raw.tasks.filter(\n (t) => t.status !== 'completed' && t.status !== 'failed',\n );\n\n return {\n phase: 'executing',\n history: messages,\n message: '',\n executionLog,\n pendingTasks,\n goal: '',\n runners: raw.runners,\n status: raw.status,\n ...record,\n };\n }\n\n return {\n phase: 'planning',\n history: messages,\n message: '',\n pendingTasks: raw.tasks,\n ...record,\n };\n}\n\nexport { taskOrderLabel, taskRef, taskRefOf, titledTaskRef, titledTaskRefOf, resolveTaskRef, resolveUserTaskRef } from '../services/TaskRefs';\n\nexport function createTask(overrides: Partial<Task> = {}): Task {\n const skills = skillNames(overrides.skills);\n return {\n id: overrides.id ?? uuidv4(),\n order: overrides.order ?? 0,\n title: overrides.title ?? '',\n description: overrides.description ?? '',\n type: overrides.type ?? 'ai',\n status: overrides.status ?? 'pending',\n dependencies: overrides.dependencies ?? [],\n prompt: overrides.prompt,\n userSteps: overrides.userSteps,\n subtasks: overrides.subtasks ?? [],\n verdict: overrides.verdict,\n outputSummary: overrides.outputSummary,\n ...(overrides.attemptUsage ? { attemptUsage: structuredClone(overrides.attemptUsage) } : {}),\n assignedModel: overrides.assignedModel,\n assignedRunner: overrides.assignedRunner ?? DEFAULT_RUNNERS[0],\n taskMode: overrides.taskMode ?? 'build',\n autonomy: overrides.autonomy,\n sliceType: overrides.sliceType,\n userStoriesCovered: overrides.userStoriesCovered,\n ...(opsFlag(overrides.ops, overrides.type) ? { ops: true } : {}),\n ...(skills ? { skills } : {}),\n ...(overrides.addedBy === 'supervisor' ? { addedBy: 'supervisor' as const } : {}),\n };\n}\n\n/**\n * A name a skill can have, lower-cased as `/name` is. Anything else — a path\n * separator, `..` — is joined into a path and could only reach outside the\n * skill dirs.\n */\nconst SKILL_NAME = new RegExp(`^${SKILL_NAME_PATTERN}$`);\n\nexport function isSkillName(name: string): boolean {\n return SKILL_NAME.test(name);\n}\n\n/**\n * The `skills` field as a task stores it, however it arrived: the planner's\n * JSON is untyped. Names are trimmed, lower-cased and deduplicated, and one\n * no skill could have is dropped; none at all is stored absent, so a plan\n * without skills reads exactly as it did before them.\n */\nexport function skillNames(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const names = [...new Set(value.filter((v): v is string => typeof v === 'string').map((v) => v.trim().toLowerCase()).filter(isSkillName))];\n return names.length > 0 ? names : undefined;\n}\n\n/**\n * The skills of a task a merge or a split makes from others: what the edit\n * chose when it named any, none when it chose an explicit `[]`, else what the\n * tasks it came from had — a malformed value is not a request to drop them.\n */\nexport function inheritedSkills(chosen: unknown, inherited: readonly string[] | undefined): string[] | undefined {\n if (Array.isArray(chosen) && chosen.length === 0) return undefined;\n return skillNames(chosen) ?? skillNames(inherited);\n}\n\n/**\n * The `ops` flag as a task stores it (ADR-0020), however it arrived. Only a\n * literal `true` on an AI task marks an ops task: the planner's JSON is\n * untyped, and a quoted \"true\" read as ops would move a task out of its\n * worktree. Anything else is a change task, stored absent so saved plans need\n * no migration. Whether the task may be ops at all — a subtask may not — is\n * for whoever knows where it sits: the planner intake refuses it (`checkPlanInvariants`).\n */\nexport function opsFlag(value: unknown, type: Task['type'] = 'ai'): true | undefined {\n return value === true && type === 'ai' ? true : undefined;\n}\n\n/**\n * The flag of a task a merge or a split makes from others: what the edit\n * chose, else ops only when every task it came from was. A merge that takes\n * in a change edits files, so it is a change; a split part runs where its\n * task did.\n */\nexport function inheritedOps(from: readonly Pick<Task, 'ops'>[], chosen?: boolean): boolean {\n return chosen ?? from.every((t) => opsFlag(t.ops) === true);\n}\n\n/**\n * The runner set a plan has until one is chosen. The one runner named outside\n * its declaration on purpose: a default is a product choice that no manifest\n * or connector implies.\n */\nexport const DEFAULT_RUNNERS: readonly RunnerId[] = ['claude-code'];\n\nexport function createEmptyPlan(): LegacyPlanState {\n return {\n tasks: [],\n generatedAt: new Date().toISOString(),\n status: 'draft',\n runners: [...DEFAULT_RUNNERS],\n lastUpdated: new Date().toISOString(),\n };\n}\n\nexport function flattenTasks(tasks: readonly Task[]): Task[] {\n return [...walkPlan(tasks)].map(({ task }) => task);\n}\n\n/**\n * A phase-tagged plan rejoined into its tree. The execution log is flat — a\n * finished subtask is logged on its own as well as inside its parent — and in\n * the order tasks finished, so read as a list it puts subtasks at the top level\n * under orders that clash with real top-level tasks. A task's own entry is the\n * latest word on it: its parent's copy was taken when the parent last changed.\n */\nexport function rejoinPlanTree<T extends { id: string; order: number; subtasks?: T[] }>(pending: readonly T[], log: readonly T[]): T[] {\n const latest = new Map<string, T>();\n for (const task of [...pending, ...log]) latest.set(task.id, task);\n const nested = new Set<string>();\n const markNested = (task: T): void => {\n for (const sub of task.subtasks ?? []) {\n nested.add(sub.id);\n markNested(sub);\n }\n };\n for (const task of latest.values()) markNested(task);\n const rebuild = (task: T): T => {\n const own = latest.get(task.id) ?? task;\n return own.subtasks?.length ? { ...own, subtasks: own.subtasks.map(rebuild) } : own;\n };\n return [...latest.values()].filter((task) => !nested.has(task.id)).map(rebuild).sort((a, b) => a.order - b.order);\n}\n\n/**\n * A flattened task with the parent it hangs under, null for a top-level task,\n * and the path label and reference (`#2.1.3`) `TaskRefs` renders for it.\n */\nexport interface TaskWithParent {\n task: Task;\n parent: Task | null;\n label: string;\n ref: string;\n}\n\nexport function flattenTasksWithParents(tasks: readonly Task[]): TaskWithParent[] {\n return [...walkPlan(tasks)].map(({ task, parent, label }) => ({ task, parent: parent ?? null, label, ref: `#${label}` }));\n}\n\nexport function addTaskToPlan(tasks: readonly Task[], partial: Partial<Task>): Task[] {\n const maxOrder = tasks.reduce((max, t) => Math.max(max, t.order), 0);\n const newTask = createTask({\n ...partial,\n order: partial.order ?? maxOrder + 1,\n status: 'pending',\n });\n return renumberTasks([...tasks, newTask]);\n}\n\nexport function removeTaskFromPlan(tasks: readonly Task[], taskId: string): Task[] {\n const removed = subtreeIds(tasks, taskId);\n const prune = (level: readonly Task[]): Task[] => level\n .filter((t) => !removed.has(t.id))\n .map((t) => ({\n ...t,\n dependencies: t.dependencies.filter((depId) => !removed.has(depId)),\n subtasks: prune(t.subtasks),\n }));\n return renumberTasks(prune(tasks));\n}\n\nexport function updateTaskInPlan(tasks: readonly Task[], taskId: string, changes: Partial<Task>): Task[] {\n return renumberTasks(\n tasks.map((t) => {\n if (t.id === taskId) return { ...t, ...changes, id: t.id };\n return { ...t, subtasks: updateTaskInPlan(t.subtasks, taskId, changes) };\n })\n );\n}\n\nexport function renumberTasks(tasks: readonly Task[]): Task[] {\n return tasks.map((t, i) => ({\n ...t,\n order: i + 1,\n subtasks: renumberTasks(t.subtasks),\n }));\n}\n\n/** A task paused on its runner's usage limit, whether it resumes on its own or waits for the user (#84). */\nexport function pausedOnLimit(task: Readonly<Task>): boolean {\n return task.status === 'awaiting_user' && task.awaitingReason === 'usage-limit';\n}\n\n/** A task paused on a usage limit that resumes on its own when the limit resets (#84). */\nexport function waitsForReset(task: Readonly<Task>): boolean {\n return pausedOnLimit(task) && !!task.resumeAt;\n}\n\n/** The user's approval record, as a plan carries it (ADR-0029). */\nexport type ApprovalRecord = Pick<LegacyPlanState, 'approved' | 'approvedTasks'>;\n\n/** A copy of the plan's approval record, for a plan read whole; a field the plan lacks stays absent. */\nexport function approvalRecordOf(plan: ApprovalRecord): ApprovalRecord {\n return {\n ...(plan.approved !== undefined ? { approved: plan.approved } : {}),\n ...(plan.approvedTasks ? { approvedTasks: [...plan.approvedTasks] } : {}),\n };\n}\n\n/**\n * A task the scheduler leaves for the user (ADR-0035): an AI task not started\n * yet, in a plan they approved, outside their approval record — the planner\n * added it since. It starts once they start it or execute the plan. In a plan\n * they never approved nothing is theirs yet, so nothing is singled out.\n */\nexport function waitsForApproval(task: Pick<Task, 'id' | 'type' | 'status'>, record: ApprovalRecord): boolean {\n return record.approved === true\n && task.type === 'ai'\n && (task.status === 'pending' || task.status === 'approved')\n && !(record.approvedTasks ?? []).includes(task.id);\n}\n\n/**\n * Who put each task of an adopted list in the plan. A task the plan already\n * had keeps its origin, whatever the planner wrote; a new one is the\n * supervisor's when `bySupervisor`, and nobody's in particular otherwise, so\n * no planner can mark its own task as the supervisor's. `added` lists the new\n * tasks, subtasks included.\n */\nexport function stampOrigin(before: readonly Task[], after: readonly Task[], bySupervisor: boolean): { tasks: Task[]; added: string[] } {\n const prior = new Map(flattenTasks([...before]).map((t) => [t.id, t]));\n const added: string[] = [];\n const stamp = (tasks: readonly Task[]): Task[] => tasks.map((t) => {\n const was = prior.get(t.id);\n const origin = was ? was.addedBy : bySupervisor ? 'supervisor' : undefined;\n if (!was) added.push(t.id);\n const stamped: Task = { ...t, subtasks: stamp(t.subtasks ?? []) };\n if (origin) stamped.addedBy = origin;\n else delete stamped.addedBy;\n return stamped;\n });\n return { tasks: stamp(after), added };\n}\n\n/** Done, running, or held for the user: execution state only a runner or the user can change. */\nconst SETTLED_STATUSES: ReadonlySet<TaskStatus> = new Set<TaskStatus>(['completed', 'in_progress', 'awaiting_user']);\n\nfunction holdsSettledWork(task: Task): boolean {\n return SETTLED_STATUSES.has(task.status) || (task.subtasks ?? []).some(holdsSettledWork);\n}\n\n/**\n * Lay a planner-written task list over the plan it rewrites without letting it\n * change execution state. A planner restates tasks; it never witnessed one run,\n * so the status it writes is not evidence. A settled task is kept exactly as\n * it stands wherever the rewrite names it, and put back beside its old\n * neighbour where the rewrite leaves it out. Every other task keeps the status\n * it had; a task the rewrite adds starts pending.\n */\nexport function keepExecutionState(current: readonly Task[], rewrite: Task[]): Task[] {\n const existing = new Map(flattenTasks(current).map((t) => [t.id, t]));\n const named = new Set(flattenTasks(rewrite).map((t) => t.id));\n\n const overlay = (tasks: Task[], was: readonly Task[]): Task[] => {\n const result = tasks.map((t): Task => {\n const prior = existing.get(t.id);\n if (prior && SETTLED_STATUSES.has(prior.status)) return { ...prior };\n return {\n ...t,\n status: prior?.status ?? 'pending',\n skipReason: prior?.skipReason,\n verdict: prior?.verdict,\n outputSummary: prior?.outputSummary,\n runnerSessionId: prior?.runnerSessionId,\n runnerSessionOwner: prior?.runnerSessionOwner,\n carriedFrom: prior?.carriedFrom,\n attemptSkills: prior?.attemptSkills,\n attemptUsage: prior?.attemptUsage,\n // Where a task that has run ran is fixed, like its runner session (ADR-0020).\n ...(prior?.status === 'failed' ? { ops: prior.ops } : {}),\n forcedPastGate: prior?.forcedPastGate,\n subtasks: overlay(t.subtasks ?? [], prior?.subtasks ?? []),\n };\n });\n was.forEach((left, i) => {\n if (named.has(left.id) || !holdsSettledWork(left)) return;\n const neighbour = was.slice(0, i).reverse().find((t) => result.some((r) => r.id === t.id));\n const at = neighbour ? result.findIndex((r) => r.id === neighbour.id) + 1 : 0;\n result.splice(at, 0, { ...left });\n });\n return result;\n };\n\n return renumberTasks(overlay(rewrite, current));\n}\n"],"mappings":";AACO,IAAM,qBAAqB;AAQlC,IAAM,cAAc,IAAI,OAAO,cAAc,kBAAkB,yBAAyB,IAAI;AAcrF,SAAS,YAAY,MAA4B;AACtD,QAAM,SAAuB,CAAC;AAC9B,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,SAAS,KAAK,SAAS,WAAW,GAAG;AAC9C,UAAM,OAAO,MAAM,CAAC,EAAE,YAAY;AAClC,QAAI,KAAK,IAAI,IAAI,EAAG;AACpB,SAAK,IAAI,IAAI;AACb,UAAM,QAAQ,MAAM,QAAQ,MAAM,CAAC,EAAE;AACrC,WAAO,KAAK,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,EAAE,OAAO,CAAC;AAAA,EAC/D;AACA,SAAO;AACT;AAGO,SAAS,kBAAkB,MAAc,QAAyC;AACvF,SAAO,YAAY,IAAI,EAAE,OAAO,CAAC,MAAM,OAAO,SAAS,EAAE,IAAI,CAAC;AAChE;;;ACnBO,UAAU,SAAgC,OAAkD;AACjG,YAAU,KAAK,OAAqB,WAAyB,aAAmD;AAC9G,eAAW,QAAQ,OAAO;AACxB,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