@ordewell/core 0.10.12 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/AUTHORS.md +37 -0
  2. package/NOTICE +71 -0
  3. package/README.md +1 -1
  4. package/dist/{IFileSystem-1PqRCjhu.d.mts → IRunner-B5l9PCTv.d.ts} +926 -102
  5. package/dist/{IFileSystem-lTRL_G9Z.d.ts → IRunner-DBgDx_Mr.d.mts} +926 -102
  6. package/dist/{ModeResolver-CoJAJD-f.d.ts → ModeResolver-BDAgouuE.d.mts} +9 -2
  7. package/dist/{ModeResolver-6TQXVsde.d.mts → ModeResolver-DyXeZ9ib.d.ts} +9 -2
  8. package/dist/{Task-CfBM0wkV.d.mts → Task-BL4Idm9r.d.mts} +656 -26
  9. package/dist/{Task-CfBM0wkV.d.ts → Task-BL4Idm9r.d.ts} +656 -26
  10. package/dist/{chunk-ESKK5I4F.mjs → chunk-4QXOWEGC.mjs} +1888 -334
  11. package/dist/chunk-4QXOWEGC.mjs.map +1 -0
  12. package/dist/{chunk-KWS3VEER.mjs → chunk-MYXMIVWA.mjs} +6 -6
  13. package/dist/chunk-MYXMIVWA.mjs.map +1 -0
  14. package/dist/{chunk-PFH7WFIB.mjs → chunk-QTZ5XTBY.mjs} +228 -15
  15. package/dist/chunk-QTZ5XTBY.mjs.map +1 -0
  16. package/dist/{chunk-24EL4Z2W.mjs → chunk-YAFNYNFX.mjs} +342 -36
  17. package/dist/chunk-YAFNYNFX.mjs.map +1 -0
  18. package/dist/index.d.mts +1488 -769
  19. package/dist/index.d.ts +1488 -769
  20. package/dist/index.js +32003 -20350
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +29380 -19553
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/parsing.d.mts +2 -2
  25. package/dist/parsing.d.ts +2 -2
  26. package/dist/parsing.js +232 -25
  27. package/dist/parsing.js.map +1 -1
  28. package/dist/parsing.mjs +3 -3
  29. package/dist/plan-utils.d.mts +4 -4
  30. package/dist/plan-utils.d.ts +4 -4
  31. package/dist/plan-utils.js +1156 -96
  32. package/dist/plan-utils.js.map +1 -1
  33. package/dist/plan-utils.mjs +144 -8
  34. package/dist/{runSettingsText-Jb_efnI4.d.mts → runSettingsText-BKwWs052.d.mts} +2882 -621
  35. package/dist/{runSettingsText-C5uv2axI.d.ts → runSettingsText-CAXiTpsj.d.ts} +2882 -621
  36. package/dist/testing.d.mts +10 -4
  37. package/dist/testing.d.ts +10 -4
  38. package/dist/testing.js +30 -7
  39. package/dist/testing.js.map +1 -1
  40. package/dist/testing.mjs +26 -7
  41. package/dist/testing.mjs.map +1 -1
  42. package/package.json +7 -3
  43. package/skills/diagnose/SKILL.md +52 -0
  44. package/skills/explore/SKILL.md +65 -0
  45. package/dist/chunk-24EL4Z2W.mjs.map +0 -1
  46. package/dist/chunk-ESKK5I4F.mjs.map +0 -1
  47. package/dist/chunk-KWS3VEER.mjs.map +0 -1
  48. package/dist/chunk-NJGID6BG.mjs +0 -115
  49. package/dist/chunk-NJGID6BG.mjs.map +0 -1
  50. package/dist/chunk-PFH7WFIB.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/conversation/skillTokens.ts","../src/services/PlanTree.ts","../src/services/repoPath.ts","../src/services/isolationRecord.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","/**\n * The path of the repo in a workspace that is itself the repository. Kept in\n * its own module, with no imports, so a browser surface can word a merge\n * result without pulling in the isolation record's `path` dependency.\n */\nexport const SELF_REPO = '.';\n","import * as path from 'path';\nimport type {\n IsolationHandoff,\n IsolationLandedTask,\n IsolationRemoval,\n IsolationRepo,\n IsolationRun,\n IsolationTaskRecord,\n IsolationTaskStatus,\n IsolationView,\n PlanIsolation,\n PreservedWork,\n RepoGroupLayout,\n TaskIsolation,\n} from '../interfaces/IWorktreeIsolation';\nimport { SELF_REPO } from './repoPath';\n\nexport { SELF_REPO };\n\nexport function integrationBranchFor(runId: string): string {\n return `ordewell/${runId}/integration`;\n}\n\nexport function repoRootOf(workspaceRoot: string, repoPath: string): string {\n return path.join(workspaceRoot, repoPath);\n}\n\n/** A removal that kept nothing back. */\nexport function noRemoval(): IsolationRemoval {\n return { preserved: [], refused: [] };\n}\n\n/**\n * A `prepare` that failed after it had already replaced the last attempt of\n * the task: that attempt's unlanded work was kept on `preserved` first, and no\n * record names it any more, so whoever tells the user about the failure has to\n * tell them where it went. Reads as the failure it wraps.\n */\nexport class PrepareFailedError extends Error {\n constructor(readonly failure: unknown, readonly preserved: PreservedWork[]) {\n super(failure instanceof Error ? failure.message : String(failure));\n this.name = failure instanceof Error ? failure.name : 'Error';\n this.cause = failure;\n }\n}\n\n/** Add what `from` kept back to `into`. */\nexport function absorbRemoval(into: IsolationRemoval, from: IsolationRemoval): IsolationRemoval {\n into.preserved.push(...from.preserved);\n into.refused.push(...from.refused);\n return into;\n}\n\n/** The group a run isolates, as the planner is told it. */\nexport function layoutOf(run: IsolationRun): RepoGroupLayout {\n return { repos: run.repos.map((r) => r.path), shared: [...run.shared] };\n}\n\nconst ISOLATION_STATE: Record<IsolationTaskStatus, Exclude<TaskIsolation['state'], 'none'>> = {\n active: 'active',\n merged: 'integrated',\n conflict: 'conflict',\n repairing: 'repairing',\n kept: 'kept',\n failed: 'kept',\n};\n\n/** Whether a saved record's status is one this build knows; a newer daemon may have written one it does not. */\nconst isKnownStatus = (status: string): status is IsolationTaskStatus =>\n Object.prototype.hasOwnProperty.call(ISOLATION_STATE, status);\n\n/** Paths of the repos a task brought commits to. */\nexport function changedReposOf(record: IsolationTaskRecord): string[] {\n return Object.entries(record.repos).filter(([, r]) => r.changed).map(([repoPath]) => repoPath);\n}\n\n/**\n * `repairLimit` is `conflictRepairAttempts` as it stands now, which is what the\n * next repair will be held to. Without one — a saved plan never carries server\n * config — the repair attempt is left out and a live status update fills it in.\n */\nexport function taskIsolationOf(record: IsolationTaskRecord, repairLimit?: number): TaskIsolation {\n return {\n state: ISOLATION_STATE[record.status],\n branch: record.branch,\n worktree: record.workspace,\n repos: changedReposOf(record),\n ...(record.conflictRepo ? { conflictRepo: record.conflictRepo } : {}),\n ...(record.conflictFiles?.length ? { conflictFiles: record.conflictFiles } : {}),\n ...(record.repairs && repairLimit !== undefined ? { repair: { attempt: record.repairs, limit: repairLimit } } : {}),\n ...(record.repairedFiles?.length ? { repairedFiles: record.repairedFiles } : {}),\n };\n}\n\n/**\n * What a run hands over: each repo's integration branch and base, and what\n * landed, in plan order. Work the user has merged already, at a merge gate\n * (ADR-0020), is not handed over again.\n */\nexport function handoffOf(run: IsolationRun): IsolationHandoff {\n const merged = Object.values(run.tasks)\n .filter((r) => r.status === 'merged' && !r.inHead)\n .sort((a, b) => a.order - b.order);\n const entry = (r: IsolationTaskRecord): IsolationLandedTask => ({\n taskId: r.taskId, order: r.order, title: r.title,\n ...(r.repairedFiles?.length ? { repairedFiles: r.repairedFiles } : {}),\n });\n return {\n repos: run.repos.map((repo) => ({\n path: repo.path,\n integrationBranch: repo.integrationBranch,\n baseRef: repo.baseRef,\n ...(repo.baseBranch ? { baseBranch: repo.baseBranch } : {}),\n ...(repo.startedDetached ? { startedDetached: true as const } : {}),\n landed: merged.filter((r) => r.repos[repo.path]?.changed).map(entry),\n })),\n landed: merged.map(entry),\n };\n}\n\n/** A task record as ADR-0013 persisted it, for one repository. */\nexport interface Adr0013TaskRecord {\n taskId: string;\n order: number;\n title: string;\n branch: string;\n worktree: string;\n status: IsolationTaskStatus;\n linked: string[];\n}\n\n/** A run as ADR-0013 persisted it (0.4.23): one repository, its refs on the run itself. */\nexport interface Adr0013IsolationRun {\n id: string;\n workspaceRoot: string;\n baseRef: string;\n baseBranch?: string;\n integrationBranch: string;\n tasks: Record<string, Adr0013TaskRecord>;\n}\n\nexport interface Adr0013PlanIsolation {\n run: Adr0013IsolationRun;\n resolvers: Record<string, string>;\n}\n\nfunction isAdr0013(run: IsolationRun | Adr0013IsolationRun): run is Adr0013IsolationRun {\n return 'integrationBranch' in run && typeof run.integrationBranch === 'string';\n}\n\nfunction fromAdr0013Task(r: Adr0013TaskRecord): IsolationTaskRecord {\n return {\n taskId: r.taskId,\n order: r.order,\n title: r.title,\n branch: r.branch,\n workspace: r.worktree,\n status: r.status,\n // A merged task's branch was merged into the one repo there was; what it\n // changed was never recorded, and landing is what `changed` stands for.\n repos: { [SELF_REPO]: { worktree: r.worktree, linked: r.linked ?? [], ...(r.status === 'merged' ? { changed: true } : {}) } },\n ...(r.status === 'conflict' ? { conflictRepo: SELF_REPO } : {}),\n };\n}\n\n/**\n * A persisted plan isolation in today's shape. A run saved in the ADR-0013\n * format — recognised by its own `integrationBranch` — becomes a group of one\n * at `.`, keeping its branches, so a session saved by 0.4.23 resumes and hands\n * off exactly as it would have.\n */\nexport function migratePlanIsolation(state: PlanIsolation | Adr0013PlanIsolation): PlanIsolation {\n const { run, resolvers } = state;\n if (!isAdr0013(run)) return { run, resolvers: resolvers ?? {} };\n const repo: IsolationRepo = {\n path: SELF_REPO,\n root: repoRootOf(run.workspaceRoot, SELF_REPO),\n baseRef: run.baseRef,\n ...(run.baseBranch ? { baseBranch: run.baseBranch } : {}),\n integrationBranch: run.integrationBranch,\n };\n const tasks = Object.fromEntries(Object.entries(run.tasks ?? {}).map(([id, r]) => [id, fromAdr0013Task(r)]));\n return { run: { id: run.id, workspaceRoot: run.workspaceRoot, repos: [repo], shared: [], sharedRepos: [], tasks }, resolvers: resolvers ?? {} };\n}\n\n/** Bring a loaded plan's isolation record, if any, to today's shape in place. */\nexport function migratePlanStateIsolation(plan: { isolation?: PlanIsolation | Adr0013PlanIsolation }): void {\n if (plan.isolation?.run) plan.isolation = migratePlanIsolation(plan.isolation);\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isArray = (value: unknown): value is readonly unknown[] => Array.isArray(value);\n\n/**\n * Whether a payload carries a run this module can read. The check tells today's\n * record from an ADR-0013 one and stops at the fields both shapes need; the\n * record's own fields are trusted from there, as `stateStore` trusts the JSON it\n * loaded. An older daemon still sends the ADR-0013 shape, so the migration runs\n * on the way in rather than being assumed.\n */\nfunction carriesIsolation(plan: unknown): plan is { isolation: PlanIsolation | Adr0013PlanIsolation } {\n if (!isRecord(plan) || !isRecord(plan.isolation)) return false;\n const { run } = plan.isolation;\n if (!isRecord(run) || !isRecord(run.tasks)) return false;\n if (isArray(run.repos)) {\n return run.repos.some((repo) => isRecord(repo)\n && typeof repo.path === 'string'\n && typeof repo.integrationBranch === 'string'\n && typeof repo.baseRef === 'string');\n }\n return typeof run.integrationBranch === 'string' && typeof run.baseRef === 'string';\n}\n\n/**\n * What a persisted plan says about its isolated run, as a surface shows it: the\n * handoff and each task's mark. `null` when the payload carries no record — a\n * planner reply, or a plan that never isolated — which says nothing either way.\n *\n * This is the one reading of a saved record outside the daemon: the migration\n * from the ADR-0013 shape happens here, so no surface grows its own parser.\n * `repairLimit` is server config a saved plan never carries; without it the\n * repair attempt is left for a live status update to fill in.\n */\nexport function isolationViewOfPlan(plan: unknown, repairLimit?: number): IsolationView | null {\n if (!carriesIsolation(plan)) return null;\n const { run } = migratePlanIsolation(plan.isolation);\n const tasks: Record<string, TaskIsolation> = {};\n for (const [taskId, record] of Object.entries(run.tasks)) {\n // A status this build does not know is its own mark-less task, not a crash:\n // a newer daemon may have written one.\n if (!isKnownStatus(record.status)) continue;\n tasks[taskId] = taskIsolationOf(record, repairLimit);\n }\n return { tasks, handoff: handoffOf(run) };\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, ReportedWindow, UsageRecord, UsageTotals } from './Usage';\nimport type { ExecutionRecord, ScriptConsent, SupervisorLevel } from './Execution';\nimport type { SkillSource } from '../services/SkillsService';\nimport type { SupervisionMemorySnapshot } from '../services/LoopGuards';\nimport type { SupervisorSnapshot } from '../services/Supervisor';\nimport type { TaskLoop } from './Loop';\nimport type { HandoffDigest } from './Handoff';\nimport { SKILL_NAME_PATTERN } from '../conversation/skillTokens';\nimport { subtreeIds, walkPlan } from '../services/PlanTree';\nimport { migratePlanStateIsolation } from '../services/isolationRecord';\n\nexport interface UserStep {\n order: number;\n instruction: string;\n completed: boolean;\n}\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.\n * `script_exit` is a script task's exit status, its one evidence (ADR-0035).\n */\nexport interface VerificationCheck {\n name: 'exit_code' | 'completion_marker' | 'task_complete' | 'manual' | 'script_exit';\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 * What the attempt's evidence said of the work: the status the runner's\n * `task_complete` call reported, or a script's exit read the same way —\n * `done` on exit 0, `failed` on a non-zero exit, a signal or its time limit,\n * `blocked` when it could not start. A loop starts a round only on `failed`\n * (ADR-0045 L2). Absent when nothing reported: a runner that exited without\n * the call, Mark complete, a stopped script, a verdict saved before it was kept.\n */\n reported?: 'done' | 'failed' | 'blocked';\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\n/** `script` is an ops task whose body Ordewell runs with no model (ADR-0035). */\nexport type TaskType = 'ai' | 'user' | 'script';\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 * Drop what a build before the per-message research budget was removed wrote\n * for it (ADR-0037): the budget, its two run settings, its per-turn flag, and\n * the report wait a task carried. The persisted types no longer name these,\n * so a reopened session would otherwise spread them onto the wire and write\n * them back; they are deleted by key, never widened into the types.\n */\nexport function dropRetiredPlanFields(plan: LegacyPlanState): void {\n const raw = plan as unknown as Record<string, unknown>;\n delete raw.researchBudget;\n const settings = plan.runSettings as unknown as Record<string, unknown> | undefined;\n if (settings) {\n delete settings.researchMaxParallel;\n delete settings.researchMaxPerMessage;\n }\n for (const turn of plan.pendingTurns ?? []) delete (turn as unknown as Record<string, unknown>).budgetStarted;\n for (const task of flattenTasks(plan.tasks)) delete (task as unknown as Record<string, unknown>).researchWait;\n}\n\n/**\n * Move a mid-run edit an older build queued for its next batch boundary into\n * the pending turns: it was never answered, so it waits like any other.\n */\nfunction carryOverQueuedEdits(plan: LegacyPlanState): void {\n const queued = plan.queuedMessages ?? [];\n delete plan.queuedMessages;\n if (queued.length === 0) return;\n const carried = queued.map(({ id, text, timestamp, skills }): PendingPlanTurn => ({ id, source: 'user', text, timestamp, ...(skills ? { skills } : {}) }));\n plan.pendingTurns = [...(plan.pendingTurns ?? []), ...carried];\n}\n\n/**\n * Bring a loaded plan to the shape this build reads, in place: every plan-shape\n * migration lives here, so each can be tested from an old shape without a whole\n * Session, as {@link migrateLoadedTasks} does for tasks.\n *\n * `adopting` is false when a Session reloads the plan it already holds: the\n * live run's task pauses are fresher than the save, so they stay.\n */\nexport function migrateLoadedPlan(plan: LegacyPlanState, { adopting = true }: { adopting?: boolean } = {}): void {\n // Saved before approval had its own record: the status said it, and\n // executing a plan approved every task it held. Read once, here, and never\n // again — a surface rewrites the status for display.\n plan.approved ??= plan.status !== 'draft' && plan.status !== 'rejected';\n if (!plan.approvedTasks && plan.approved) {\n plan.approvedTasks = flattenTasks(plan.tasks).map((t) => t.id);\n }\n // A saved reset time belonged to a run that is gone; loading is not consent\n // to spend tokens (ADR-0044).\n if (adopting) {\n for (const task of flattenTasks(plan.tasks)) delete task.resumeAt;\n }\n migratePlanStateIsolation(plan);\n // Older builds copied the since-removed transport setting onto the plan.\n // Every plan now runs structured (ADR-0018), so the copy is not carried on.\n delete (plan as { runnerTransport?: unknown }).runnerTransport;\n // Run settings are the user's now (ADR-0030); an older plan's own copies\n // are not read, and go with this save.\n for (const key of ['supervisorLevel', 'mergeAtGatesAutomatically', 'supervisorRetryLimit', 'wakeUpReadBudget']) {\n delete (plan as unknown as Record<string, unknown>)[key];\n }\n // The per-message research budget is gone (ADR-0037); a plan saved before\n // its removal is read once and written back without its keys.\n dropRetiredPlanFields(plan);\n carryOverQueuedEdits(plan);\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 /**\n * The latest attempt's handoff, as the plan keeps it (ADR-0047): its\n * summary, first findings and artifacts. The whole handoff, report and all,\n * is in that attempt's log. Absent when the attempt handed none over, and\n * on a plan saved before handoffs, which reads `outputSummary` instead.\n */\n handoff?: HandoffDigest;\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. A script task is one by nature and\n * stores none (see {@link runsAsOps}).\n */\n ops?: boolean;\n /** A top-level read-only AI task whose report returns to the planner (ADR-0037 R1). */\n research?: boolean;\n /** A retry still owes research's report under its original authority (ADR-0037 R3). */\n researchOrigin?: TaskReportTo;\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 /**\n * An attempt of it has started, so its chat exists from then on: kept after\n * a failure, a cancel, a skip or a completion, and restored with the plan.\n * Set by the attempt's own start — never by a status or a manual mark.\n */\n attempted?: true;\n attemptUsage?: AttemptUsage[];\n /**\n * A script task's body (ADR-0035), exactly one of these two: argument\n * vectors run in order with no shell, stopping at the first that fails, or\n * one script run by the research shell's interpreter.\n */\n commands?: string[][];\n script?: string;\n /** A script task's time limit; absent means ten minutes (`DEFAULT_SCRIPT_TIMEOUT_MS`). */\n timeoutMs?: number;\n /** Set on a loop's check (ADR-0045): the tasks that fix what it finds, and how many times it may run. */\n loop?: TaskLoop;\n /**\n * The round of a loop's check's latest run, or the one it is running;\n * absent is round 1. Execution state, saved so a reload resumes mid-round,\n * and started over by a retry of the check (ADR-0045 L5, L7).\n */\n loopRound?: number;\n /**\n * A planner turn waits for this task's result (ADR-0037, R2): set when the\n * tool that started it answered before it ended, or when research lands.\n * Cleared once its end is reported, in a turn acting for whoever started it (R3).\n */\n reportTo?: TaskReportTo;\n}\n\n/**\n * Who started a task whose result is owed to the planner (ADR-0037, R3): a\n * planner turn in the user's conversation, or the supervisor, at its level\n * then, with script consent (ADR-0035) or the research profile (ADR-0037 R4).\n */\nexport type TaskReportTo = ({ consent: ScriptConsent; research?: never } | { research: true; consent?: never }) & (\n | { actor: 'planner-turn' }\n | { actor: 'supervisor'; level: SupervisorLevel }\n);\n\n/** Whose authority a turn opened without the user acts with (ADR-0037, R3): the user's turn, or the supervisor's. */\nexport type TurnAuthority = 'user' | 'supervisor';\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`. 'compaction' is one phase of the planner's own compaction\n // (`compaction`); a subagent's never is one.\n type:\n | 'thinking' | 'tool_call' | 'tool_result' | 'plan_token' | 'interrupted' | 'liveness'\n | 'text_delta' | 'text_retracted' | 'usage' | 'subagent_started' | 'subagent_finished' | 'compaction';\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 compaction?: PlannerCompaction;\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. Gemini's is its `inputTokenLimit`:\n * the prompt alone, the reply limited by `maxOutputTokens` apart from it.\n */\n contextWindow?: number;\n /** The longest reply the catalog says the model is served with, when it says. */\n maxOutputTokens?: 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 * compaction appended, which stands in for the earlier messages in the\n * planner's context while the transcript keeps them (see `checkpoint`). '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 * Set on a 'compaction' entry that is a checkpoint of the planner's context\n * (ADR-0002). A 'compaction' entry without one is a legacy summary when it\n * stands first — it replaced what it condensed — and a marker drawn but\n * never replayed anywhere else.\n */\n checkpoint?: ContextCheckpoint;\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 * Where a compaction cut the planner's context (ADR-0002): its summary stands\n * for every transcript entry before `keptFrom`, and the entries from there on\n * replay verbatim. Entries are only appended, or inserted at a held turn's\n * position, which no checkpoint's cut passes, so the index never moves.\n */\nexport interface ContextCheckpoint {\n /** Stable across saves, forks and the wire, so a surface can tell this checkpoint from another with the same text. */\n id: string;\n /** An index into the whole transcript, at or before the checkpoint entry itself. */\n keptFrom: number;\n trigger: 'manual' | 'auto';\n}\n\n/**\n * How a planner compaction ended. `condensed`: a summary stands in for the\n * older context (a checkpoint was written, or a harness planner reported its\n * own compaction done). `pruned`: older recoverable tool output was dropped\n * from the live context alone. `unchanged`: nothing needed doing. `paused`:\n * the context could not be brought to fit, so the planner waits.\n */\nexport type PlannerCompactionOutcome = 'condensed' | 'pruned' | 'unchanged' | 'stopped' | 'failed' | 'paused';\n\n/**\n * One planner compaction's lifecycle as it was observed (ADR-0017): both\n * phases share `id`, which is the checkpoint's id when one is written. Only\n * Ordewell's own compaction announces a start; a harness planner's native one\n * is reported when it is over, and nothing invents the start it never sent.\n * Sizes are only ever what a backend reported.\n */\nexport type PlannerCompaction =\n | { phase: 'started'; id: string; origin: 'ordewell'; trigger: ContextCheckpoint['trigger']; at: string }\n | {\n phase: 'ended';\n id: string;\n origin: 'ordewell' | 'native';\n trigger: ContextCheckpoint['trigger'];\n outcome: PlannerCompactionOutcome;\n at: string;\n preTokens?: number;\n postTokens?: number;\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 * A supervisor input carrying a report the planner asked for (ADR-0037, R2),\n * which opens a turn at every supervisor level: `user` for a task started in\n * the user's turn, which the turn then acts as (R3).\n */\n report?: TurnAuthority;\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\n/**\n * The planner paused on its context (ADR-0002): an API planner's call could\n * not be brought inside its model's window, so the turn ended with nothing\n * landed and the planner waits for the user's Retry compaction. What it\n * keeps is bounded: the inputs stay in `pendingTurns`, and only the calls\n * that changed something are listed, never the live context itself.\n */\nexport interface PlannerContextPause {\n /** The model the call did not fit. */\n model: string;\n at: string;\n /** What the user is told: why it paused, and what Retry compaction does. */\n reason: string;\n /** The pending inputs the paused turn took: a retry answers these, and what arrived since waits for the turn after it. */\n inputs: string[];\n /**\n * The calls the paused turn made that changed something or reached out,\n * each with the head of what it returned (`effectLedger`). It is never\n * replayed to the planner as a note: it is what lets a retry see that a\n * turn which ran effects cannot start again from the transcript, and what\n * the refusal lists for the user.\n */\n done?: string[];\n /** More such calls ran than `done` keeps: the refusal could not list all of them, and a retry without the live context stays refused. */\n doneTruncated?: true;\n}\n\nexport interface LegacyPlanState {\n /** Research profiles the planner approved as they landed: lifting one withdraws its approval (ADR-0037 R4). */\n researchApprovals?: string[];\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 /**\n * The id of the plan's last isolated run, which closed with everything it\n * landed merged into the user's branch; absent once a later run decides how\n * it executes. With no run record left, it is what tells a Merge all asked\n * for after that run from one in a plan that never isolated (ADR-0029).\n */\n mergedRun?: string;\n /** Kept so a reopened session shows the same token line (#49). */\n plannerUsage?: PlannerUsage;\n /** The windows reported over the session, so a reopened one knows each model's from its first call. */\n contextWindows?: ReportedWindow[];\n /** The planner hit its usage limit and the inputs its turn took wait to be sent again; absent otherwise. */\n plannerResend?: PlannerResendState;\n /** The planner's context could not fit its model's window: its turn's inputs wait for Retry compaction; absent otherwise. */\n plannerContextPause?: PlannerContextPause;\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 const type = overrides.type ?? 'ai';\n return {\n id: overrides.id ?? uuidv4(),\n order: overrides.order ?? 0,\n title: overrides.title ?? '',\n description: overrides.description ?? '',\n type,\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.handoff ? { handoff: structuredClone(overrides.handoff) } : {}),\n ...(overrides.attempted ? { attempted: true as const } : {}),\n ...(overrides.attemptUsage ? { attemptUsage: structuredClone(overrides.attemptUsage) } : {}),\n assignedModel: overrides.assignedModel,\n assignedRunner: overrides.assignedRunner ?? DEFAULT_RUNNERS[0],\n // A script task runs in no mode (ADR-0035): one given it would read as a mode it runs in.\n taskMode: overrides.taskMode ?? (type === 'script' ? undefined : '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 ...(overrides.commands !== undefined ? { commands: overrides.commands.map((argv) => [...argv]) } : {}),\n ...(overrides.script !== undefined ? { script: overrides.script } : {}),\n ...(overrides.timeoutMs !== undefined ? { timeoutMs: overrides.timeoutMs } : {}),\n ...(overrides.loop ? { loop: { body: [...overrides.loop.body], maxRounds: overrides.loop.maxRounds } } : {}),\n ...(overrides.loopRound !== undefined ? { loopRound: overrides.loopRound } : {}),\n ...(overrides.research !== undefined ? { research: overrides.research } : {}),\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 * Whether a task runs as an ops task (ADR-0020): an AI task marked so, or a\n * script task, which is one by nature and never marked (ADR-0035).\n */\nexport function runsAsOps(task: Pick<Task, 'ops' | 'type'>): boolean {\n return task.type === 'script' || opsFlag(task.ops, task.type) === true;\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\n/**\n * A removed task leaves every dependency on it, and every loop's body it was\n * in (ADR-0045 L8): a loop it leaves with no body is no loop. Whether its\n * removal may go ahead at all — a loop's check may not be removed — is the\n * caller's to say.\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 const pruned: Task = {\n ...t,\n dependencies: t.dependencies.filter((depId) => !removed.has(depId)),\n subtasks: prune(t.subtasks),\n };\n if (!t.loop?.body.some((id) => removed.has(id))) return pruned;\n const body = t.loop.body.filter((id) => !removed.has(id));\n if (body.length > 0) return { ...pruned, loop: { ...t.loop, body } };\n delete pruned.loop;\n delete pruned.loopRound;\n return pruned;\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 waiting on the user with its attempt still live: the runner sits at a checkpoint or for input. */\nexport function waitsMidAttempt(task: Pick<Task, 'status' | 'awaitingReason'>): boolean {\n return task.status === 'awaiting_user' && (task.awaitingReason === 'checkpoint' || task.awaitingReason === 'input');\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 or script task\n * not started yet, in a plan they approved, outside their approval record —\n * the planner added it since, or changed a script's body. It starts once they\n * start it or execute the plan. In a plan they never approved nothing is\n * 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 !== 'user'\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. A failed task the rewrite\n * turns into a script task or out of one is kept as it was: what ran, and\n * where, is fixed once it has run (ADR-0020, ADR-0035).\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 if (prior?.status === 'failed' && (prior.type === 'script') !== (t.type === 'script')) return { ...prior };\n return {\n ...t,\n status: prior?.status ?? 'pending',\n skipReason: prior?.skipReason,\n verdict: prior?.verdict,\n outputSummary: prior?.outputSummary,\n handoff: prior?.handoff,\n runnerSessionId: prior?.runnerSessionId,\n runnerSessionOwner: prior?.runnerSessionOwner,\n carriedFrom: prior?.carriedFrom,\n attemptSkills: prior?.attemptSkills,\n attempted: prior?.attempted,\n attemptUsage: prior?.attemptUsage,\n loopRound: prior?.loopRound,\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 reportTo: prior?.reportTo,\n researchOrigin: prior?.researchOrigin,\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;AACh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