@ordewell/core 0.13.2 → 0.13.3
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.
- package/dist/{ModeResolver-BmG9O08A.d.ts → ModeResolver-CXGnEhbN.d.ts} +1 -1
- package/dist/{ModeResolver-CNKcOksr.d.mts → ModeResolver-DqpwKbfJ.d.mts} +1 -1
- package/dist/{Task-CH1z4L3h.d.mts → Task-TFPWtKoz.d.mts} +2 -0
- package/dist/{Task-CH1z4L3h.d.ts → Task-TFPWtKoz.d.ts} +2 -0
- package/dist/{chunk-7ACNW5CD.mjs → chunk-4OARA73Z.mjs} +2 -2
- package/dist/{chunk-3P5UIXTR.mjs → chunk-5ETS2NIB.mjs} +13 -3
- package/dist/{chunk-3P5UIXTR.mjs.map → chunk-5ETS2NIB.mjs.map} +1 -1
- package/dist/{chunk-I436RXQT.mjs → chunk-62MSJNOG.mjs} +3 -3
- package/dist/{chunk-I436RXQT.mjs.map → chunk-62MSJNOG.mjs.map} +1 -1
- package/dist/{chunk-MGMQKUIJ.mjs → chunk-DFRDXOEG.mjs} +15 -5
- package/dist/chunk-DFRDXOEG.mjs.map +1 -0
- package/dist/{chunk-O52PN7P2.mjs → chunk-FOGPFLRO.mjs} +4 -4
- package/dist/chunk-FOGPFLRO.mjs.map +1 -0
- package/dist/daemon-client.js +14 -4
- package/dist/daemon-client.js.map +1 -1
- package/dist/daemon-client.mjs +1 -1
- package/dist/{eventStore-ClHaWY9b.d.mts → eventStore-D9Kv5dTu.d.mts} +27 -2
- package/dist/{eventStore-s1fpKwFe.d.ts → eventStore-DeuZxnKm.d.ts} +27 -2
- package/dist/index.d.mts +21 -12
- package/dist/index.d.ts +21 -12
- package/dist/index.js +1487 -1362
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1104 -1002
- package/dist/index.mjs.map +1 -1
- package/dist/{maxParallel-fSAdLIMh.d.mts → maxParallel-CSTmqKeu.d.mts} +44 -8
- package/dist/{maxParallel-DXvhdlD5.d.ts → maxParallel-Ds9VI1KO.d.ts} +44 -8
- package/dist/parsing.d.mts +2 -2
- package/dist/parsing.d.ts +2 -2
- package/dist/parsing.js +1 -1
- package/dist/parsing.js.map +1 -1
- package/dist/parsing.mjs +3 -3
- package/dist/plan-utils.d.mts +4 -4
- package/dist/plan-utils.d.ts +4 -4
- package/dist/plan-utils.js.map +1 -1
- package/dist/plan-utils.mjs +3 -3
- package/dist/testing.d.mts +4 -2
- package/dist/testing.d.ts +4 -2
- package/dist/testing.js +2 -0
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +3 -1
- package/dist/testing.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-MGMQKUIJ.mjs.map +0 -1
- package/dist/chunk-O52PN7P2.mjs.map +0 -1
- /package/dist/{chunk-7ACNW5CD.mjs.map → chunk-4OARA73Z.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/conversation/skillTokens.ts","../src/services/PlanTree.ts","../src/services/repoPath.ts","../src/services/LandingLedger.ts","../src/services/isolationRecord.ts","../src/models/Usage.ts","../src/models/TaskKind.ts","../src/models/Task.ts","../src/models/SkipOrigin.ts","../src/models/TaskExecution.ts","../src/services/PlanGraph.ts","../src/services/TaskRefs.ts","../src/services/RunningLong.ts","../src/services/VerdictEngine.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 type { IsolationRun, IsolationTaskRecord, LandedTask } from '../interfaces/IWorktreeIsolation';\nimport type { Task } from '../models/Task';\n\n/*\n * The landing ledger (ADR-0054): what an isolated run keeps of who landed what\n * across every attempt, after a record has gone too. That is\n * `IsolationRun.landings`, `carried`, `landedTasks`, `landedOn`,\n * `keepsEveryLanding` and `reverted`, with each record's `landedTip` for a run\n * saved before `landings` were kept. Every read and write of those goes through\n * here and none of it asks git: GitWorktreeIsolation hands it what a merge made,\n * and FakeWorktreeIsolation hands it the same facts, so both keep one set of rules.\n */\n\n/** What a run starts with: every merge kept from the first, and the record of what merges carried, empty until one does. */\nexport const freshLedger = (): Pick<IsolationRun, 'keepsEveryLanding' | 'carried'> => ({ keepsEveryLanding: true, carried: {} });\n\n/** Every run started now holds {@link IsolationRun.carried}, empty or not, so one without it was saved by a build that kept no such record. */\nexport const startedOlder = (run: IsolationRun): boolean => run.carried === undefined;\n\n/** Whether a revert was committed on the run: its branch holds commits no record names, so it carries on with no record left. */\nexport const hasReverted = (run: IsolationRun): boolean => run.reverted === true;\n\n/** What a task landed as: its record while it has one, else what the ledger kept once a retry dropped it. */\nexport function landedTaskOf(run: IsolationRun | null | undefined, taskId: string): LandedTask | undefined {\n return run?.tasks[taskId] ?? run?.landedTasks?.[taskId];\n}\n\n/** What to call a task in a refusal: the id stands in once nothing names it. */\nexport const landedTitleOf = (run: IsolationRun, taskId: string): string => landedTaskOf(run, taskId)?.title ?? taskId;\n\n/** The merges that landed a task in a repo, oldest first; a run saved before they were kept has only the record's latest. */\nexport function landingsOf(run: IsolationRun, taskId: string, repoPath: string): string[] {\n const latest = run.tasks[taskId]?.repos[repoPath]?.landedTip;\n return run.landings?.[taskId]?.[repoPath] ?? (latest ? [latest] : []);\n}\n\n/** Every kept merge in a repo, by the task it landed. */\nexport function landingsIn(run: IsolationRun, repoPath: string): Array<{ taskId: string; merge: string }> {\n return Object.entries(run.landings ?? {}).flatMap(([taskId, byRepo]) => (byRepo[repoPath] ?? []).map((merge) => ({ taskId, merge })));\n}\n\n/** Whether anything ever landed in a repo, by the ledger or a record's tip. */\nexport function hasLandingIn(run: IsolationRun, repoPath: string): boolean {\n if (Object.values(run.landings ?? {}).some((byRepo) => (byRepo[repoPath]?.length ?? 0) > 0)) return true;\n return Object.values(run.tasks).some((record) => record.repos[repoPath]?.landedTip !== undefined);\n}\n\n/** The repos the ledger holds a task's merges in. */\nexport const landedReposOf = (run: IsolationRun, taskId: string): string[] => Object.keys(run.landings?.[taskId] ?? {});\n\n/** Whether another task's merge carried a task's work, in one repo or any. */\nexport function isCarried(run: IsolationRun | null | undefined, taskId: string, repoPath?: string): boolean {\n const tips = run?.carried?.[taskId];\n return repoPath === undefined ? tips !== undefined : tips?.[repoPath] !== undefined;\n}\n\n/** Every carried tip in a repo, by the task whose work it is. */\nexport function carriedTipsIn(run: IsolationRun, repoPath: string): Array<{ taskId: string; tip: string }> {\n return Object.entries(run.carried ?? {}).flatMap(([taskId, repos]) => (repos[repoPath] ?? []).map((tip) => ({ taskId, tip })));\n}\n\n/** Whether a task has work on the integration branch in a repo: a later attempt's record says nothing of the merges before it. */\nexport function landedIn(run: IsolationRun, taskId: string, repoPath: string): boolean {\n const record = run.tasks[taskId];\n return landingsOf(run, taskId, repoPath).length > 0 || isCarried(run, taskId, repoPath) || (record?.status === 'merged' && record.repos[repoPath]?.changed === true);\n}\n\n/** Whether a landed record's work is in a repo, for what its handoff and Merge all name there. */\nexport function mergedIn(run: IsolationRun, record: IsolationTaskRecord, repoPath: string): boolean {\n return !!record.repos[repoPath]?.changed || run.landings?.[record.taskId]?.[repoPath] !== undefined;\n}\n\n/**\n * Whether a task has work of its own on the integration branch, this attempt's\n * or an earlier one's. A retry, a failed spawn or a continue that conflicted\n * leaves a record that is not `merged`, or none, over merges still on the branch.\n */\nexport function landedWork(run: IsolationRun | null, taskId: string): boolean {\n const record = run?.tasks[taskId];\n return run?.landings?.[taskId] !== undefined || isCarried(run, taskId) || (record?.status === 'merged' && Object.values(record.repos).some((r) => r.changed));\n}\n\n/** Whether a task of a run that did not keep its merges from the start can have landed in an attempt no record speaks for: nothing says it did not. */\nexport function mayHaveLanded(run: IsolationRun | null, task: Readonly<Task>): boolean {\n const record = run?.tasks[task.id];\n return !run?.keepsEveryLanding && !landedWork(run, task.id) && task.type === 'ai' && !task.ops && !record?.readOnly && (task.attempted === true || record !== undefined);\n}\n\n/** A task that landed and left the plan with no record of what it depended on, or of what to call it: whether it stands on the work nothing can say. */\nexport function unreadLanding(run: IsolationRun | null, planned: ReadonlySet<string>): string | undefined {\n if (!run) return undefined;\n const landed = [...Object.keys(run.landings ?? {}), ...Object.keys(run.carried ?? {}), ...Object.keys(run.tasks)].filter((id) => !planned.has(id) && landedWork(run, id));\n const unread = landed.find((id) => !run.landedOn?.[id] || !landedTaskOf(run, id));\n return unread === undefined ? undefined : landedTitleOf(run, unread);\n}\n\n/**\n * The title of another task recorded as landed by the same merge. No landing\n * makes one for two tasks: a run saved when a landing recorded the branch's tip\n * whether or not it had moved can say so, and reverting that merge would take\n * the work of whichever task really made it (ADR-0054).\n */\nexport function alsoLandedBy(run: IsolationRun, repoPath: string, taskId: string, merge: string): string | undefined {\n const ids = new Set([...Object.keys(run.tasks), ...Object.keys(run.landings ?? {})]);\n const other = [...ids].find((id) => id !== taskId && landingsOf(run, id, repoPath).includes(merge));\n return other === undefined ? undefined : landedTitleOf(run, other);\n}\n\n/**\n * Landed work a revert can undo (ADR-0054): a merge of its own in every repo it\n * changed, none of it in the user's branch yet, and nothing of it carried in by\n * a resolver. A task at work again keeps its mark off, and a revert would refuse\n * it. A run with no `carried` record, or none given, offers nothing: every\n * revert of such a run is refused.\n */\nexport function marksRevertible(record: IsolationTaskRecord, run?: Pick<IsolationRun, 'landings' | 'carried'>): boolean {\n if (record.inHead || record.status === 'active' || record.status === 'repairing' || !run?.carried || run.carried[record.taskId]) return false;\n const landings = run.landings?.[record.taskId];\n const changed = record.status === 'merged' ? Object.entries(record.repos).filter(([, r]) => r.changed).map(([repoPath]) => repoPath) : [];\n return (changed.length > 0 || landings !== undefined) && changed.every((repo) => record.repos[repo].landedTip || landings?.[repo]);\n}\n\n/** The tasks with merges on the branch and no record left, a retry having dropped it, that a revert can still take. */\nexport function recordlessRevertible(run: IsolationRun): string[] {\n return Object.keys(run.landings ?? {}).filter((taskId) => run.carried && !run.carried[taskId]);\n}\n\n/** What a task depends on in the plan, a check counting on its body as it does at a merge gate (ADR-0045 L9). */\nconst dependenciesOf = (task: Readonly<Task>): string[] => [...task.dependencies, ...task.loop?.body ?? []];\n\n/** What a task depends on, directly or not, for {@link keepLandedOn} to keep as it is cut and as it lands. */\nexport function landedOnOf(taskId: string, tasks: readonly Readonly<Task>[]): string[] {\n const found = new Set<string>();\n const queue = [taskId];\n for (let id = queue.shift(); id !== undefined; id = queue.shift()) {\n const task = tasks.find((t) => t.id === id);\n for (const dependency of task ? dependenciesOf(task) : []) {\n if (found.has(dependency)) continue;\n found.add(dependency);\n queue.push(dependency);\n }\n }\n return [...found];\n}\n\n/** Everything that depends on the task, directly or not, by the plan or by what the ledger kept: the plan lets go of a task that leaves it, and of what stood on it through that task. */\nexport function dependentsOf(tasks: readonly Readonly<Task>[], run: IsolationRun | null, taskId: string): Set<string> {\n const edges = new Map(tasks.map((t) => [t.id, dependenciesOf(t)]));\n for (const [id, landedOn] of Object.entries(run?.landedOn ?? {})) edges.set(id, [...edges.get(id) ?? [], ...landedOn]);\n const found = new Set<string>([taskId]);\n const queue = [taskId];\n for (let id = queue.shift(); id !== undefined; id = queue.shift()) {\n for (const [other, dependencies] of edges) {\n if (found.has(other) || !dependencies.includes(id)) continue;\n found.add(other);\n queue.push(other);\n }\n }\n found.delete(taskId);\n return found;\n}\n\n/** The tasks a revert of this one stands to change the ground of, landed or not: no start of one may be claimed while it runs. */\nexport function revertReach(taskId: string, tasks: readonly Readonly<Task>[], run: IsolationRun | null): ReadonlySet<string> {\n return new Set([taskId, ...dependentsOf(tasks, run, taskId)]);\n}\n\nconst landedTask = ({ taskId, order, title, commit }: LandedTask): LandedTask => ({ taskId, order, title, ...(commit ? { commit } : {}) });\n\n/** A task's merges, by repo, as its landing went through: each repo's tip on the record and kept in the ledger once, newest last. */\nexport function recordLanding(run: IsolationRun, record: IsolationTaskRecord, tips: readonly (readonly [repoPath: string, merge: string])[]): void {\n for (const [repoPath, tip] of tips) {\n const entry = record.repos[repoPath];\n if (entry) entry.landedTip = tip;\n ((run.landings ??= {})[record.taskId] ??= {})[repoPath] = [...landingsOf(run, record.taskId, repoPath).filter((merge) => merge !== tip), tip];\n (run.landedTasks ??= {})[record.taskId] = landedTask(record);\n }\n}\n\n/**\n * Tips of tasks yet to land that a landing's merges brought in. A run that\n * started without the record never gets one: it would miss what landed before\n * it, and its absence is what refuses a revert (ADR-0054).\n */\nexport function recordCarried(run: IsolationRun, carried: readonly { record: LandedTask; repoPath: string; tip: string }[]): void {\n if (!run.carried) return;\n for (const { record, repoPath, tip } of carried) {\n const tips = (run.carried[record.taskId] ??= {});\n tips[repoPath] = [...tips[repoPath] ?? [], tip];\n (run.landedTasks ??= {})[record.taskId] = landedTask(record);\n }\n}\n\n/** What a task depends on, added to what it ever did: a plan edit takes a link off while its worktree stays cut from the work (ADR-0054). */\nexport function keepLandedOn(run: IsolationRun, taskId: string, dependsOn: readonly string[]): void {\n (run.landedOn ??= {})[taskId] = [...new Set([...run.landedOn?.[taskId] ?? [], ...dependsOn])];\n}\n\n/**\n * The tasks a revert took back, all in one step with no await between: a\n * landed record goes; a later attempt's that never landed stays, `kept`, for\n * the worktree only it names, its conflict over and nothing to repair or land;\n * the ledger lets go of each; and the run is marked as reverted.\n */\nexport function forgetReverted(run: IsolationRun, taskIds: readonly string[]): void {\n for (const taskId of taskIds) {\n const record = run.tasks[taskId];\n if (record?.status === 'merged') delete run.tasks[taskId];\n else if (record?.status === 'conflict') {\n record.status = 'kept';\n delete record.repairBase;\n delete record.conflictRepo;\n delete record.conflictFiles;\n }\n delete run.landings?.[taskId];\n delete run.landedTasks?.[taskId];\n delete run.landedOn?.[taskId];\n }\n run.reverted = true;\n}\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';\nimport { marksRevertible, mergedIn, recordlessRevertible } from './LandingLedger';\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, run?: Pick<IsolationRun, 'landings' | 'carried'>): 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 ...(marksRevertible(record, run) ? { revertible: true as const } : {}),\n };\n}\n\n/**\n * Every task's mark in a run. A task with merges on the branch and no record\n * left, a retry having dropped it, has no state to show and can still be\n * reverted. A status this build does not know is its own mark-less task, not a\n * crash: a newer daemon may have written one.\n */\nexport function taskIsolationsOf(run: IsolationRun, repairLimit?: number): Record<string, TaskIsolation> {\n const tasks: Record<string, TaskIsolation> = {};\n for (const taskId of recordlessRevertible(run)) tasks[taskId] = { state: 'none', revertible: true };\n for (const [taskId, record] of Object.entries(run.tasks)) {\n if (isKnownStatus(record.status)) tasks[taskId] = taskIsolationOf(record, repairLimit, run);\n }\n return tasks;\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) => mergedIn(run, r, repo.path)).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 return { tasks: taskIsolationsOf(run, repairLimit), handoff: handoffOf(run) };\n}\n","/** How the runner says this session is paid for; absent means it has not said. */\nexport interface SessionBilling {\n type: 'subscription' | 'api-key';\n plan?: string;\n}\n\nexport interface CostProvenance {\n kind: 'estimate' | 'billed' | 'unknown';\n billing: SessionBilling['type'] | 'unknown' | 'mixed';\n basis?: 'list' | 'managed';\n}\n\n/**\n * What one model call consumed, as its provider or runner reported it. Shared\n * by the planner's usage line (#49) and per-attempt task usage (#26): a record\n * says nothing about who asked for the call, so either can hold a list of them.\n *\n * Every measure is optional because backends report different subsets. An\n * absent field means \"not reported\" — never zero — so a total can tell the two\n * apart.\n */\nexport interface UsageRecord {\n /** The provider or runner id that reported the call — `openai`, `claude-code`, … */\n source: string;\n model?: string;\n /** A session breakdown can name a model without identifying the current context. */\n aggregate?: true;\n /**\n * What a call outside the agent's own turns was for — OpenCode's `title`,\n * `compaction` or `generate` calls, which it bills but does not put in a\n * step. A model's totals keep them apart, so a bill that includes them can\n * be read against the turns.\n */\n purpose?: string;\n inputTokens?: number;\n outputTokens?: number;\n /** The share of `inputTokens` served from the provider's prompt cache. */\n cachedInputTokens?: number;\n /**\n * Filled only from a provider's or runner's own report, never from a price\n * table kept in Ordewell: prices go stale, and a subscription runner has no\n * per-token price at all. No report means no cost, not a guessed one.\n */\n reportedCost?: { amount: number; currency: string; kind?: 'estimate' | 'billed'; basis?: 'list' | 'managed' };\n sessionBilling?: SessionBilling;\n /**\n * The model's context window: as the runner or provider reported it, or,\n * when it reported none, from that runner's or provider's own model listing\n * (`ContextWindowFill`). Never from a table kept in Ordewell.\n */\n contextWindow?: number;\n /**\n * What the main model's context holds once this call is done, counted the\n * way its runner's own UI counts it, so the meter reads what the user would\n * see there. Runners differ, and no sum of the measures above can tell.\n * A measure of the meter only: no total adds it. Absent, the meter reads the\n * prompt.\n */\n contextTokens?: number;\n /**\n * The runner reset the main model's context outside a call — a compaction,\n * or a `/clear`: no call, so the record measures nothing but `contextTokens`,\n * the size it reported the context left at, if it did. It may name the model\n * the new context belongs to; a record that names none is about whichever\n * runs now.\n */\n compacted?: true;\n /** Set when a subagent made the call; its usage still counts toward the total. */\n subagentId?: string;\n}\n\n/** A model's window as its reporter stated it: what a plan saves of its session's windows (`SessionWindows`). */\nexport interface ReportedWindow {\n source: string;\n model: string;\n contextWindow: number;\n}\n\n/**\n * A running sum of {@link UsageRecord}s. A measure stays absent until some\n * record reports it. Cost is kept per currency: two runners may bill in\n * different ones, and there is no honest exchange rate to fold them together.\n */\nexport interface UsageTotals {\n inputTokens?: number;\n outputTokens?: number;\n cachedInputTokens?: number;\n reportedCost?: Record<string, number>;\n costProvenance?: Record<string, CostProvenance>;\n}\n\n/**\n * The input side of a call whose provider reports its prompt in parts — the\n * uncached tail, with cache reads and cache writes beside it rather than inside\n * it (Anthropic, and OpenCode after it). The prompt the model saw is all three;\n * only the reads were served from cache, since a write is billed as fresh\n * input. A part left unreported adds nothing, and with no part reported there\n * is no measure at all.\n */\nexport function partedPromptUsage(parts: { uncached?: number; cacheRead?: number; cacheWrite?: number }): Pick<UsageRecord, 'inputTokens' | 'cachedInputTokens'> {\n const reported = [parts.uncached, parts.cacheRead, parts.cacheWrite].filter((n): n is number => n !== undefined);\n return {\n ...(reported.length > 0 ? { inputTokens: reported.reduce((a, b) => a + b, 0) } : {}),\n ...(parts.cacheRead !== undefined ? { cachedInputTokens: parts.cacheRead } : {}),\n };\n}\n\nconst TOKEN_FIELDS = ['inputTokens', 'outputTokens', 'cachedInputTokens'] as const;\n\n/**\n * What a budget counts (ADR-0056 M5), of a record or of totals alike: the same\n * tokens a total holds, input and output. `cachedInputTokens` is a share of the\n * input, so cache reads count, once.\n */\nexport function spentTokens({ inputTokens, outputTokens }: Pick<UsageTotals, 'inputTokens' | 'outputTokens'>): number {\n return (inputTokens ?? 0) + (outputTokens ?? 0);\n}\n\nexport function addUsage(totals: UsageTotals, record: UsageRecord): UsageTotals {\n const next: UsageTotals = { ...totals };\n for (const field of TOKEN_FIELDS) {\n const reported = record[field];\n if (reported !== undefined) next[field] = (totals[field] ?? 0) + reported;\n }\n if (record.reportedCost) {\n const { amount, currency } = record.reportedCost;\n const provenance: CostProvenance | undefined = record.reportedCost.kind || record.sessionBilling ? {\n kind: record.reportedCost.kind ?? 'unknown', billing: record.sessionBilling?.type ?? 'unknown',\n ...(record.reportedCost.basis ? { basis: record.reportedCost.basis } : {}),\n } : undefined;\n addCost(next, currency, amount, provenance);\n }\n return next;\n}\n\nfunction addCost(totals: UsageTotals, currency: string, amount: number, provenance?: CostProvenance): void {\n const hadCost = totals.reportedCost?.[currency] !== undefined;\n const previous = totals.costProvenance?.[currency];\n totals.reportedCost = { ...totals.reportedCost, [currency]: (totals.reportedCost?.[currency] ?? 0) + amount };\n if (!previous && !provenance) return;\n const unknown: CostProvenance = { kind: 'unknown', billing: 'unknown' };\n const a = previous ?? unknown;\n const b = provenance ?? unknown;\n const merged: CostProvenance = !hadCost ? b : {\n kind: a.kind === 'estimate' || b.kind === 'estimate' ? 'estimate' : a.kind === 'billed' && b.kind === 'billed' ? 'billed' : 'unknown',\n billing: a.billing === b.billing ? a.billing : 'mixed',\n ...(a.basis && a.basis === b.basis ? { basis: a.basis } : {}),\n };\n totals.costProvenance = { ...totals.costProvenance, [currency]: merged };\n}\n\n/**\n * What the planner has consumed over a session (#49). `totals` includes every\n * `bySubagent` entry. `lastPromptTokens` and `contextWindow` track the\n * planner's own calls only — a subagent runs its own model, whose window says\n * nothing about the planner's. `lastPromptTokens` is the context the last call\n * left (its `contextTokens`, else its prompt), under the name saved sessions\n * already hold it by.\n */\nexport interface PlannerUsage {\n sessionBilling?: SessionBilling;\n totals: UsageTotals;\n bySubagent?: Record<string, UsageTotals>;\n byModel?: ModelUsage[];\n source?: string;\n model?: string;\n lastPromptTokens?: number;\n contextWindow?: number;\n}\n\nexport function addPlannerUsage(usage: PlannerUsage, record: UsageRecord): PlannerUsage {\n // The size before a compaction is gone, so the meter shows the size after\n // or none until the next call — never the old one, which reads as full. The\n // record may name the model the new context now belongs to: that is a switch\n // of its own, and the old model's window does not measure it.\n if (record.compacted) {\n // A subagent's compaction says nothing about the main model, and a\n // breakdown measures no prompt of its own.\n if (record.subagentId || record.aggregate) return usage;\n const next: PlannerUsage = { ...usage };\n if (record.source !== undefined) next.source = record.source;\n if (record.model !== undefined) {\n if (record.source !== usage.source || record.model !== usage.model) delete next.contextWindow;\n next.model = record.model;\n }\n if (record.contextTokens !== undefined) next.lastPromptTokens = record.contextTokens;\n else delete next.lastPromptTokens;\n if (record.contextWindow !== undefined) next.contextWindow = record.contextWindow > 0 ? record.contextWindow : undefined;\n return next;\n }\n if (record.sessionBilling && !record.reportedCost && record.inputTokens === undefined && record.outputTokens === undefined && record.cachedInputTokens === undefined && record.contextWindow === undefined) {\n // The fact belongs to the source that stated it: kept with no source, it\n // would be lent to whichever backend reports a cost next.\n return record.subagentId ? usage : { ...usage, sessionBilling: record.sessionBilling, source: record.source };\n }\n record = { ...record, sessionBilling: record.sessionBilling ?? (usage.source === undefined || record.source === usage.source ? usage.sessionBilling : undefined) };\n const next: PlannerUsage = { ...usage, ...(!record.subagentId && record.sessionBilling ? { sessionBilling: record.sessionBilling } : {}), totals: addUsage(usage.totals, record), byModel: addModelUsage(usage.byModel ?? [], record) };\n if (record.subagentId) {\n next.bySubagent = { ...usage.bySubagent, [record.subagentId]: addUsage(usage.bySubagent?.[record.subagentId] ?? {}, record) };\n return next;\n }\n // A session breakdown names a model without measuring any call's prompt, so\n // it never moves the meter. It still comes from a source, though: a billing\n // fact belonging to another backend does not outlive it.\n if (record.aggregate) {\n if (record.source !== usage.source && !record.sessionBilling) delete next.sessionBilling;\n return next;\n }\n if (record.source !== usage.source || record.model !== usage.model) {\n delete next.lastPromptTokens;\n delete next.contextWindow;\n }\n if (record.source !== usage.source && !record.sessionBilling) delete next.sessionBilling;\n next.source = record.source;\n next.model = record.model;\n const used = record.contextTokens ?? record.inputTokens;\n if (used !== undefined) next.lastPromptTokens = used;\n // A reported window of 0 means \"not known\", not \"no room\": keep it out so the\n // meter shows no share rather than one against a guessed zero.\n if (record.contextWindow !== undefined) next.contextWindow = record.contextWindow > 0 ? record.contextWindow : undefined;\n return next;\n}\n\n/** Whether any measure was reported: a usage line of nothing but blanks says nothing. */\nexport function isMeasured(totals: UsageTotals): boolean {\n return totals.inputTokens !== undefined || totals.outputTokens !== undefined || totals.cachedInputTokens !== undefined\n || Object.keys(totals.reportedCost ?? {}).length > 0;\n}\n\n/**\n * The main model's context: what its last call left in it, against its window\n * when that is known. A window of 0 is not known.\n */\nexport interface ContextFill {\n usedTokens: number;\n windowTokens?: number;\n /**\n * Why an API planner's automatic compaction (ADR-0002) is not running for\n * its model, as it stood when the meter was sent: the settings file turns it\n * off, or no catalog states the model's window. Absent while it runs, and on\n * a harness planner, whose agent compacts its own context.\n */\n autoCompaction?: { off: 'settings' } | { off: 'unknown_window'; model: string };\n}\n\n/** What the usage line draws of a ledger — live from its broadcast, or reloaded from the saved one. */\nexport interface UsageLine {\n sessionBilling?: SessionBilling;\n byModel?: ModelUsage[];\n model?: string;\n totals: UsageTotals;\n bySubagent?: Record<string, UsageTotals>;\n contextFill?: ContextFill;\n}\n\nexport function usageLine(usage: PlannerUsage): UsageLine {\n const contextFill = plannerContextFill(usage);\n return {\n totals: usage.totals,\n ...(usage.sessionBilling ? { sessionBilling: usage.sessionBilling } : {}),\n ...(usage.byModel ? { byModel: usage.byModel } : {}),\n ...(usage.model ? { model: usage.model } : {}),\n ...(usage.bySubagent ? { bySubagent: usage.bySubagent } : {}),\n ...(contextFill ? { contextFill } : {}),\n };\n}\n\n/**\n * The main model's context as its last call left it, or undefined before one\n * was measured and after a compaction that reported no size. `usedTokens` is\n * what that call stated as its context, else its prompt total, cached tokens\n * included: a cached token still occupies the window, so subtracting the\n * cached share would understate how full the context is. The window rides\n * along only when known; a window of 0 is treated as unknown — never guessed.\n */\nexport function plannerContextFill(usage: PlannerUsage): ContextFill | undefined {\n if (usage.lastPromptTokens === undefined) return undefined;\n return { usedTokens: usage.lastPromptTokens, ...(usage.contextWindow !== undefined && usage.contextWindow > 0 ? { windowTokens: usage.contextWindow } : {}) };\n}\n\nexport interface ModelUsage {\n source: string;\n model?: string;\n /** Set on the row of calls made outside the agent's own turns ({@link UsageRecord.purpose}). */\n purpose?: string;\n totals: UsageTotals;\n}\n\nexport function addModelUsage(models: readonly ModelUsage[], record: UsageRecord): ModelUsage[] {\n const index = models.findIndex((m) => m.source === record.source && m.model === record.model && m.purpose === record.purpose);\n if (index < 0) return [...models, { source: record.source, ...(record.model ? { model: record.model } : {}), ...(record.purpose ? { purpose: record.purpose } : {}), totals: addUsage({}, record) }];\n return models.map((m, i) => i === index ? { ...m, totals: addUsage(m.totals, record) } : m);\n}\n\n/**\n * What Ordewell has counted of a runner's own session that reports its cost\n * as a running total: that total and each model's share, in USD, as of its\n * last report. A resume of that session counts its first report's growth\n * over this; with no count kept for it, that report only sets the baseline.\n */\nexport interface RunnerSessionCost {\n sessionId: string;\n usd: number;\n modelUsd: Record<string, number>;\n}\n\nexport interface AttemptUsage extends PlannerUsage {\n attempt: number;\n runner: string;\n /** The runner session this attempt ran in, as its runner reported it: what a later Continue of it resumes. */\n sessionId?: string;\n startedAt: string;\n endedAt?: string;\n wallTimeMs: number;\n /**\n * Of its wall time, what it spent running: a wait on a person (input, a\n * checkpoint, an approval) left out (ADR-0018 W1). Absent on an attempt\n * saved before it was kept, and on one that never had a clock.\n */\n runningMs?: number;\n /** What was counted of its runner session's running cost as it ended: a continue of that session counts on from it. */\n runnerSessionCost?: RunnerSessionCost;\n}\n\nexport function startAttemptUsage(attempt: number, runner: string, startedAt: string): AttemptUsage {\n return { attempt, runner, startedAt, wallTimeMs: 0, totals: {}, byModel: [] };\n}\n\n/** What its runner reports as it winds down after the attempt ended is added without moving its end. */\nexport function addAttemptUsage(usage: AttemptUsage, record: UsageRecord, now: string): AttemptUsage {\n const folded = addPlannerUsage(usage, record);\n return { ...usage, ...folded, lastPromptTokens: folded.lastPromptTokens, contextWindow: folded.contextWindow, wallTimeMs: Math.max(0, Date.parse(usage.endedAt ?? now) - Date.parse(usage.startedAt)) };\n}\n\n/** An attempt ends once; ended again once its runner wound down, it only takes the count that runner ended on. */\nexport function endAttemptUsage(usage: AttemptUsage, now: string, runnerSessionCost?: RunnerSessionCost, sessionId?: string, runningMs?: number): AttemptUsage {\n const endedAt = usage.endedAt ?? now;\n return {\n ...usage,\n endedAt,\n wallTimeMs: Math.max(0, Date.parse(endedAt) - Date.parse(usage.startedAt)),\n ...(usage.runningMs === undefined && runningMs !== undefined ? { runningMs } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(runnerSessionCost ? { runnerSessionCost } : {}),\n };\n}\n\n/** The count a continue of `sessionId` starts from: the one its latest attempt in that session ended with. */\nexport function countedSessionCost(attempts: readonly AttemptUsage[] | undefined, sessionId: string): RunnerSessionCost | undefined {\n return [...attempts ?? []].reverse().find((usage) => usage.runnerSessionCost?.sessionId === sessionId)?.runnerSessionCost;\n}\n\n/**\n * The model a continue's session last ran on and the window it was measured\n * against: the latest earlier attempt of that same runner session that\n * reported one. An attempt that measured nothing is skipped — a continuation\n * does not undo what its session was last measured against — and a window is\n * never borrowed from another session: a fresh attempt starts one.\n */\nexport function resumedSessionWindow(attempts: readonly AttemptUsage[] | undefined, runner: string, attempt: number, sessionId: string): Pick<PlannerUsage, 'source' | 'model' | 'contextWindow'> | undefined {\n const last = [...attempts ?? []].reverse().find((usage) => usage.attempt !== attempt && usage.runner === runner && usage.sessionId === sessionId && usage.contextWindow !== undefined);\n return last ? { source: last.source, model: last.model, contextWindow: last.contextWindow } : undefined;\n}\n\nexport interface PlanUsage {\n totals: UsageTotals;\n byModel: ModelUsage[];\n wallTimeMs: number;\n attempts: number;\n}\n\nexport function addUsageTotals(totals: UsageTotals, addition: UsageTotals): UsageTotals {\n const next = addUsage(totals, { source: '', inputTokens: addition.inputTokens, outputTokens: addition.outputTokens, cachedInputTokens: addition.cachedInputTokens });\n for (const [currency, amount] of Object.entries(addition.reportedCost ?? {})) addCost(next, currency, amount, addition.costProvenance?.[currency]);\n return next;\n}\n\ninterface UsageTask { type?: string; attemptUsage?: readonly AttemptUsage[]; subtasks?: readonly UsageTask[] }\n\nexport function planUsage(tasks: readonly UsageTask[]): PlanUsage {\n const result: PlanUsage = { totals: {}, byModel: [], wallTimeMs: 0, attempts: 0 };\n for (const task of tasks) {\n const child = planUsage(task.subtasks ?? []);\n result.totals = addUsageTotals(result.totals, child.totals);\n result.wallTimeMs += child.wallTimeMs;\n result.attempts += child.attempts;\n const models = [...child.byModel];\n for (const usage of task.attemptUsage ?? []) {\n result.totals = addUsageTotals(result.totals, usage.totals);\n result.wallTimeMs += usage.wallTimeMs;\n result.attempts++;\n models.push(...usage.byModel ?? []);\n }\n for (const model of models) {\n const existing = result.byModel.find((m) => m.source === model.source && m.model === model.model && m.purpose === model.purpose);\n if (existing) existing.totals = addUsageTotals(existing.totals, model.totals);\n else result.byModel.push({ ...model, totals: addUsageTotals({}, model.totals) });\n }\n }\n return result;\n}\n\n/**\n * What one task spent across every attempt and every model it ran on, so a\n * stop, a model change and a continue never makes the earlier spend vanish. The\n * context meter is the exception: it reads the latest attempt, because only the\n * current model's window says how full the next prompt is.\n */\nexport interface TaskUsageSummary {\n totals: UsageTotals;\n attempts: number;\n contextFill?: ContextFill;\n}\n\nexport function taskUsageSummary(task: Pick<UsageTask, 'attemptUsage' | 'type'>): TaskUsageSummary {\n const attempts = task.attemptUsage ?? [];\n const latest = attempts.at(-1);\n // A delegated task's usage is its whole subtree's (ADR-0055 D20): no one session's context, so it has no meter.\n const contextFill = latest && task.type !== 'delegated' ? plannerContextFill(latest) : undefined;\n return {\n totals: attempts.reduce((sum, attempt) => addUsageTotals(sum, attempt.totals), {} as UsageTotals),\n attempts: attempts.length,\n ...(contextFill ? { contextFill } : {}),\n };\n}\n\n// ── The text surfaces draw ───────────────────────────────────────────────────\n// Surfaces draw the main model's context and the money its runner reported,\n// never a token count, and word them here so none can disagree (ADR-0017 U1).\n\n/** `950`, `1.5k`, `61k`, `261k`, `1.2M`. */\nexport function formatTokenCount(n: number): string {\n if (n < 1000) return String(n);\n if (n < 10_000) return `${(n / 1000).toFixed(1).replace(/\\.0$/, '')}k`;\n if (n < 999_500) return `${Math.round(n / 1000)}k`;\n return `${(n / 1_000_000).toFixed(1).replace(/\\.0$/, '')}M`;\n}\n\n/** Two decimals from 1 up and up to four below it: a call can cost a fraction of a cent, a session several dollars. */\nexport function formatCost(currency: string, amount: number): string {\n const value = amount >= 1 ? amount.toFixed(2) : (([whole, frac = '']) => `${whole}.${frac.padEnd(2, '0')}`)(amount.toFixed(4).replace(/0+$/, '').split('.'));\n return currency.toLowerCase() === 'usd' ? `$${value}` : `${value} ${currency.toUpperCase()}`;\n}\n\n/** `ctx 61k (6%)`, `ctx 61k` while the window is unknown, nothing before a call was measured; `· no auto-compact` when automatic compaction is not running. */\nexport function contextMeterText(fill: ContextFill | undefined): string | null {\n if (!fill) return null;\n const used = `ctx ${formatTokenCount(fill.usedTokens)}`;\n const share = fill.windowTokens ? fill.usedTokens / fill.windowTokens * 100 : undefined;\n const meter = share === undefined ? used : `${used} (${share < 1 ? '<1' : Math.round(share)}%)`;\n return fill.autoCompaction ? `${meter} · no auto-compact` : meter;\n}\n\n/** Exact counts for the meter's hover, and why automatic compaction is not running, where it is not. */\nexport function contextMeterTitle(fill: ContextFill): string {\n const used = fill.usedTokens.toLocaleString('en-US');\n const counts = fill.windowTokens ? `${used} of ${fill.windowTokens.toLocaleString('en-US')} tokens` : `${used} tokens`;\n const off = fill.autoCompaction;\n if (!off) return counts;\n const why = off.off === 'settings'\n ? 'Automatic compaction is off in the settings file'\n : off.model\n ? `Automatic compaction is off: no catalog Ordewell holds states ${off.model}'s window`\n : 'Automatic compaction is off: no planner model is selected';\n return `${counts}. ${why}; /compact still condenses the conversation.`;\n}\n\n/** USD first, then the others by code, so a sum reads the same whichever attempt reported first. */\nfunction costParts(totals: UsageTotals): string[] {\n const rank = (currency: string): string => (currency.toLowerCase() === 'usd' ? '' : currency.toUpperCase());\n return Object.entries(totals.reportedCost ?? {}).sort(([a], [b]) => rank(a).localeCompare(rank(b))).map(([currency, amount]) => {\n const provenance = totals.costProvenance?.[currency];\n const equivalent = provenance?.billing === 'subscription';\n return `${provenance?.kind === 'estimate' || equivalent ? '≈' : ''}${formatCost(currency, amount)}${equivalent ? ' API-equivalent' : ''}`;\n });\n}\n\n/** The cost per currency as reported, joined by ` · `; null when none was reported. */\nexport function costText(totals: UsageTotals): string | null {\n const parts = costParts(totals);\n return parts.length > 0 ? parts.join(' · ') : null;\n}\n\n/** The meter, then the cost, joined by ` · `; null when neither is known. */\nexport function usageText(usage: { totals: UsageTotals; contextFill?: ContextFill }): string | null {\n const parts = [contextMeterText(usage.contextFill), costText(usage.totals)].filter((p): p is string => p !== null);\n return parts.length > 0 ? parts.join(' · ') : null;\n}\n\n/** Each runner/model's reported cost for the cost's hover, leaving out models with none. */\nexport function modelCostTitle(byModel: readonly ModelUsage[]): string | undefined {\n const lines = byModel.flatMap((m) => {\n const cost = costParts(m.totals);\n const descriptions = [...new Set(Object.values(m.totals.costProvenance ?? {}).map((p) => {\n const source = m.source === 'claude-code' ? 'Claude Code' : m.source === 'opencode' ? 'OpenCode' : m.source === 'openrouter' ? 'OpenRouter' : m.source;\n const basis = p.basis === 'list' ? ' at list price' : p.basis === 'managed' ? ' at managed price' : '';\n const kind = p.kind === 'estimate' ? `${source}'s estimate${basis}` : p.kind === 'billed' ? `Amount billed by ${source}` : 'Reported cost';\n return `${kind}${p.billing === 'subscription' ? '; not billed on a subscription' : ''}`;\n }))];\n return cost.length > 0 ? [`${m.source} / ${m.model ?? 'unattributed'}${m.purpose ? ` (${m.purpose})` : ''}: ${cost.join(' · ')}${descriptions.length ? ` — ${descriptions.join('; ')}` : ''}`] : [];\n });\n return lines.length > 0 ? lines.join('\\n') : undefined;\n}\n\n/** Each subagent's reported cost for the subagent count's hover, or that it reported none. */\nexport function subagentCostTitle(bySubagent: Readonly<Record<string, UsageTotals>>): string {\n return Object.entries(bySubagent)\n .map(([id, totals]) => `${id}: ${costParts(totals).join(' · ') || 'reported no cost'}`)\n .join('\\n');\n}\n\nfunction runnersOf(tasks: readonly UsageTask[]): AttemptUsage[] {\n return tasks.flatMap((task) => [...task.attemptUsage ?? [], ...runnersOf(task.subtasks ?? [])]);\n}\n\n/**\n * `Tasks total: $3.20 · codex reports no cost`: the cost over every attempt,\n * then the runners none of whose attempts reported one — codex reports no\n * price, and a price table is not Ordewell's to keep (ADR-0017 U1). A runner is\n * named only once an attempt of it has ended having reported usage: Claude\n * Code states a cost only on a turn's last line, so a first attempt still in\n * its turn has not said yet, and one that never ran said nothing. A total has\n * no meter: each task's own model holds its own window.\n */\nexport function tasksTotalText(tasks: readonly UsageTask[]): string | null {\n const attempts = runnersOf(tasks);\n if (attempts.length === 0) return null;\n const costed = (a: AttemptUsage): boolean => Object.keys(a.totals.reportedCost ?? {}).length > 0;\n const costless = [...new Set(attempts.filter((a) => a.endedAt !== undefined && isMeasured(a.totals)).map((a) => a.runner))]\n .filter((runner) => !attempts.some((a) => a.runner === runner && costed(a)));\n const note = costless.length === 0 ? [] : [`${costless.length === 1 ? costless[0] : `${costless.slice(0, -1).join(', ')} and ${costless.at(-1)}`} ${costless.length === 1 ? 'reports' : 'report'} no cost`];\n const parts = [...costParts(planUsage(tasks).totals), ...note];\n return parts.length > 0 ? `Tasks total: ${parts.join(' · ')}` : null;\n}\n","import type { Task, TaskType } from './Task';\n\ntype Field = keyof Task | 'thinkingEffort';\n\ninterface KindRules {\n forbidden: readonly Field[];\n plannerEditForbidden: readonly Field[];\n leaving: readonly (keyof Task)[];\n entering: readonly (keyof Task)[];\n topLevelOnly: boolean;\n mayHaveSubtasks: boolean;\n runsInMode: boolean;\n hasRunner: boolean;\n mayBeOps: boolean;\n mayBeResearch: boolean;\n}\n\nconst PLANNER_EDIT_FIELDS = ['readOnly', 'thinkingEffort'] as const;\n\nconst AI_ASSIGNMENT = ['assignedModel', 'taskMode', 'autonomy', 'ops'] as const;\n\n// ADR-0035 and ADR-0055 D1: a script's body and a child's goal are not runner prompts.\nexport const TASK_KINDS = {\n ai: { forbidden: [], plannerEditForbidden: [], leaving: ['research'], entering: ['userSteps'], topLevelOnly: false, mayHaveSubtasks: true, runsInMode: true, hasRunner: true, mayBeOps: true, mayBeResearch: true },\n user: { forbidden: [], plannerEditForbidden: [], leaving: [], entering: AI_ASSIGNMENT, topLevelOnly: false, mayHaveSubtasks: true, runsInMode: false, hasRunner: false, mayBeOps: false, mayBeResearch: false },\n script: {\n forbidden: ['assignedRunner', 'assignedModel', 'thinkingEffort', 'taskMode', 'readOnly', 'prompt', 'skills', 'userSteps', 'ops', 'subtasks'],\n plannerEditForbidden: PLANNER_EDIT_FIELDS,\n leaving: ['commands', 'script', 'timeoutMs'], entering: [...AI_ASSIGNMENT, 'prompt', 'skills', 'userSteps'],\n topLevelOnly: true, mayHaveSubtasks: false, runsInMode: false, hasRunner: false, mayBeOps: false, mayBeResearch: false,\n },\n delegated: {\n forbidden: ['prompt', 'taskMode', 'skills', 'userSteps', 'ops', 'commands', 'script', 'timeoutMs', 'research'],\n plannerEditForbidden: PLANNER_EDIT_FIELDS,\n leaving: [], entering: [],\n topLevelOnly: true, mayHaveSubtasks: false, runsInMode: false, hasRunner: true, mayBeOps: false, mayBeResearch: false,\n },\n} as const satisfies Record<TaskType, KindRules>;\n\nexport function forbiddenFields(kind: TaskType, boundary: 'task' | 'plannerEdit' = 'task'): readonly Field[] {\n return boundary === 'plannerEdit' ? TASK_KINDS[kind].plannerEditForbidden : TASK_KINDS[kind].forbidden;\n}\n\n/**\n * The forbidden fields a task or an edit holds, less those `ignored` (a\n * stored default, the read-only script exception). A `null` is a value it\n * holds, so it is refused as any other.\n */\nexport function presentForbiddenFields(kind: TaskType, fields: object, ignored: readonly Field[] = []): Field[] {\n return held(forbiddenFields(kind), fields, ignored, false);\n}\n\n/** The forbidden fields the planner's JSON wrote, where a `null` is how it leaves a field out. */\nexport function writtenForbiddenFields(kind: TaskType, raw: object, boundary: 'task' | 'plannerEdit' = 'task'): Field[] {\n return held(forbiddenFields(kind, boundary), raw, [], true);\n}\n\nfunction held(forbidden: readonly Field[], fields: object, ignored: readonly Field[], nullLeavesOut: boolean): Field[] {\n const raw = fields as Partial<Record<Field, unknown>>;\n return forbidden.filter((field) => {\n const value = raw[field];\n return !ignored.includes(field) && value !== undefined && !(nullLeavesOut && value === null) && value !== false\n && !(Array.isArray(value) && value.length === 0);\n });\n}\n\n/** Delegated tasks cannot flip: a child goal cannot become another kind of work (ADR-0055 D1). */\nexport function flipClears(from: TaskType, to: TaskType): (keyof Task)[] {\n if (from === to || from === 'delegated' || to === 'delegated') return [];\n return [...new Set<keyof Task>([...TASK_KINDS[from].leaving, ...TASK_KINDS[to].entering])];\n}\n\n/** Whether `value` names a kind: an edit's or a new task's `type` reaches core unchecked from the HTTP and MCP routes. */\nexport function isTaskType(value: unknown): value is TaskType {\n return typeof value === 'string' && Object.hasOwn(TASK_KINDS, value);\n}\n\n/** Why a `type` that names no kind is refused, after the task it was written for. */\nexport function unknownTypeRefusal(value: unknown): string {\n const kinds = taskKinds(false).map((kind) => `\"${kind}\"`);\n return `has \"type\" ${JSON.stringify(value)}, which is no kind of task: use ${kinds.slice(0, -1).join(', ')} or ${kinds.at(-1)}`;\n}\n\n/** Delegation changes the planner's vocabulary only when the session grants it (ADR-0055 D1). */\nexport function taskKinds(delegates: boolean): [TaskType, ...TaskType[]] {\n return (Object.keys(TASK_KINDS) as TaskType[]).filter((kind) => delegates || kind !== 'delegated') as [TaskType, ...TaskType[]];\n}\n","import { isTaskType, TASK_KINDS } from './TaskKind';\nimport { v4 as uuidv4 } from 'uuid';\nimport type { PlanIsolation } from '../interfaces/IWorktreeIsolation';\nimport type { AttemptUsage, PlannerUsage, ReportedWindow, RunnerSessionCost, 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 { legacySkipOrigin, type SkipOrigin } from './SkipOrigin';\nimport type { HandoffDigest } from './Handoff';\nimport type { DelegatedBudget, TaskScope } from './Delegation';\nimport { executionStateOf } from './TaskExecution';\nimport type { Grant } from '../services/Mandate';\nimport { SKILL_NAME_PATTERN } from '../conversation/skillTokens';\nimport { walkPlan } from '../services/PlanTree';\nimport { remove } from '../services/PlanGraph';\nimport { migratePlanStateIsolation } from '../services/isolationRecord';\nimport { interruptedVerdict } from '../services/VerdictEngine';\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' | 'protected_paths';\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, an attempt the host died in, a\n * 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/**\n * `script` is an ops task whose body Ordewell runs with no model (ADR-0035);\n * `delegated` holds a goal, and its attempt is a child plan (ADR-0055).\n */\nexport type TaskType = 'ai' | 'user' | 'script' | 'delegated';\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 because it conflicts (`conflict`) or because git refused to commit or\n * merge it for some other reason, such as no author identity (`landing-failed`),\n * an ops task that changed tracked files (ADR-0020), or its runner's usage\n * limit. Saved, so no surface has to guess it from whether an attempt is live.\n */\nexport type AwaitingReason = 'input' | 'checkpoint' | 'question-lost' | 'conflict' | 'landing-failed' | 'files-changed' | 'usage-limit';\n\nexport function isAwaitingReason(value: unknown): value is AwaitingReason {\n return value === 'input' || value === 'checkpoint' || value === 'question-lost' || value === 'conflict' || value === 'landing-failed' || 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 // A loop's own skip was told from a person's by its text; it now says so itself (ADR-0045 L7).\n const origin = legacySkipOrigin(task);\n if (origin) task.skipOrigin = origin;\n migrateLoadedTasks(task.subtasks ?? []);\n }\n}\n\n/**\n * Nothing is running when a plan comes off disk, so a task saved in progress\n * lost its attempt with the host that ran it. It is failed, in place, so the\n * inbox lists it and what depends on it waits (ADR-0053). Its attempts and\n * logs are left as they are. A delegated task parked at its subplanner's\n * question is no failure: it says the question is lost, and its child waits\n * to be continued (ADR-0055 D17).\n */\nexport function failInterruptedTasks(tasks: readonly Task[], now: string): void {\n for (const task of flattenTasks(tasks)) {\n if (task.type === 'delegated' && task.awaitingReason === 'checkpoint') task.awaitingReason = 'question-lost';\n if (task.status !== 'in_progress') continue;\n task.status = 'failed';\n task.verdict = interruptedVerdict(now);\n }\n}\n\n/**\n * A task an edit made manual has nothing to retry, and is the user's to do: one\n * failed, or waiting on the user with no runner to hear an answer, waits as a\n * manual task does (ADR-0053). A runner still at a question keeps it, and the\n * answer is still its to read, until it ends or the plan comes off disk.\n */\nexport function releaseMadeManual(tasks: readonly Task[], live: (taskId: string) => boolean = () => false): void {\n for (const task of flattenTasks(tasks)) {\n if (task.type !== 'user' || live(task.id) || (task.status !== 'failed' && task.status !== 'awaiting_user')) continue;\n task.status = 'pending';\n delete task.awaitingReason;\n delete task.resumeAt;\n }\n}\n\n/**\n * Nothing claims a repair when a plan comes off disk: what owed it went with\n * the host that saved it. So a task saved not started whose landing conflicted\n * is a conflict waiting on the user, in place, and the inbox lists it; the\n * next Execute still repairs it (ADR-0015, ADR-0053).\n */\nexport function settleOwedRepairs(plan: LegacyPlanState): void {\n const records = plan.isolation?.run.tasks;\n if (!records) return;\n for (const task of flattenTasks(plan.tasks)) {\n if ((task.status !== 'pending' && task.status !== 'approved') || records[task.id]?.status !== 'conflict') continue;\n task.status = 'awaiting_user';\n task.awaitingReason = 'conflict';\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 // An older direct edit could store a type no kind owns, or clear it, and\n // the kind table has no rules to read for one: it becomes \"ai\", as a type\n // the planner writes that no kind owns does.\n for (const task of flattenTasks(plan.tasks)) {\n if (!isTaskType(task.type)) task.type = 'ai';\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 /**\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 * The question a delegated task's subplanner is parked on (ADR-0056 M8). The\n * live one is held in memory by what answers it, so this copy is only what a\n * restart can still say was lost (ADR-0055 D17). Goes with the wait.\n */\n parkedQuestion?: string;\n /**\n * How many waits have ended since its latest attempt started, or since the\n * task was written if none has: an attempt can wait many times, and this\n * tells one wait from the next in an escalation's id (ADR-0053). Saved with\n * the plan, so the id holds across a reload. Absent counts as none.\n */\n waitsEnded?: number;\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 or a rearm.\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 * Who skipped it, set with `skipReason` and only while `status` is `skipped`.\n * A plan saved before this field has it only on a loop's own skips, which\n * loading gives it from their text ({@link migrateLoadedTasks}); any other\n * skip of such a plan has none, and reads as not the loop's.\n */\n skipOrigin?: SkipOrigin;\n /**\n * The user reverted its landed work (ADR-0054): saved with the plan, so the\n * hold that keeps it from running again outlives this process. Set only\n * while it waits as the revert left it: its next start clears it.\n */\n reverted?: true;\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 or re-armed.\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 /** What a delegated task's child plan must achieve, in place of a prompt (ADR-0055 D1). */\n goal?: string;\n /** A delegated task's budget (ADR-0056 M5). */\n budget?: DelegatedBudget;\n /** What a delegated task asks for past the floor; absent asks for nothing (ADR-0056 M2). */\n grants?: Grant[];\n /** The paths a delegated task's child may not change, what its check runs among them (ADR-0055 D7). */\n protectedPaths?: string[];\n /** What a delegated task declares it works on (ADR-0057 R6). */\n scope?: TaskScope;\n /**\n * On a delegated task, it answers a question and lands nothing (ADR-0055 D1).\n * On a script task, it runs sealed in a throwaway worktree, past no gate (D8).\n * A read-only AI task says so by its mode (ADR-0031) and stores none.\n */\n readOnly?: boolean;\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 | { actor: 'subplanner'; depth: number }\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 /** How many decision record entries the checkpoint's seed restates (ADR-0067); absent when it restated none. */\n record?: number;\n}\n\n/** What a decision record entry holds (ADR-0067): a choice, the user's own limit, a dropped option, or something still to settle. */\nexport const DECISION_RECORD_KINDS = ['decision', 'constraint', 'rejected', 'question'] as const;\nexport type DecisionRecordKind = typeof DECISION_RECORD_KINDS[number];\n\n/**\n * One entry in the planner's decision record (ADR-0067). The record is only\n * appended to: an entry that no longer stands is superseded by a later one\n * naming it, so the record as it was at any transcript point is a prefix.\n */\nexport interface DecisionRecordEntry {\n /** The kind's letter and its count within the kind: D1, C2, R1, Q3. */\n id: string;\n kind: DecisionRecordKind;\n /** A constraint's is the user's words, verbatim. */\n text: string;\n /** Why a decision was taken or an option rejected. */\n why?: string;\n /** The id of the entry this one replaces; a decision superseding a question answers it. */\n supersedes?: string;\n /** The transcript index of the user message whose turn recorded it, so a rewind before it drops it. */\n at: number;\n timestamp: string;\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/**\n * The timestamp of the planner's latest reply when it answers wake-ups alone\n * (ADR-0029): no message of the user's came with them or since, and no wake-up\n * is still unanswered. Host notices, calls at the seam, skill loads,\n * compactions and failed turns are no reply and no input, so they are passed over.\n */\nexport function wakeUpReply(history: readonly ConversationMessage[]): string | undefined {\n let reply: ConversationMessage | undefined;\n let woke = false;\n for (let i = history.length - 1; i >= 0; i--) {\n const entry = history[i];\n if (isUserMessage(entry)) return undefined;\n if (entry.kind === 'wake_up') {\n if (!reply) return undefined;\n woke = true;\n } else if (entry.role === 'assistant' && (entry.kind === undefined || entry.kind === 'supervisor' || entry.kind === 'plan_generated')) {\n // A turn may say something and commit a plan: past its inputs is the turn before.\n if (woke) break;\n reply ??= entry;\n }\n }\n return woke ? reply?.timestamp : undefined;\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 * The tasks a supervisor input is wholly about, absent when any of it is about\n * the run. While the user has stopped all of them it opens no turn (ADR-0029).\n */\n tasks?: string[];\n /** It goes with the next turn and opens none (ADR-0057 R6). */\n rides?: true;\n /** Who a message comes from where the conversation cannot tell (ADR-0055 D20): it stands or falls with its message, and a turn says it once. */\n aside?: string;\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 * A planner tool's change in the paused turn landed its inputs with it:\n * the transcript holds them already, and they wait only for a retry to\n * answer. A retry writes none of them again, and a Stop drops every one,\n * wake-ups included, since the planner has been told them.\n */\n landed?: true;\n}\n\n/**\n * A harness planner's own session, as far as a later process needs it: a hint,\n * taken up only under the runner, model, effort and folder it was opened with.\n * The transcript stays authoritative (ADR-0009 T4).\n */\nexport interface PlannerNativeSession {\n runner: string;\n sessionId: string;\n cwd: string;\n model?: string;\n effort?: string;\n /** What was counted of its running cost, so taking it up counts nothing twice (ADR-0056 M10). */\n cost?: RunnerSessionCost;\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 /** The subplanner's native session, for a Continue to take up (ADR-0055 D17): `heard` is how much of the Model context it holds. Absent on a root plan. */\n plannerSession?: PlannerNativeSession & { heard: number };\n /** What the planner recorded as decided, required, rejected and open, resent like the plan and seeding every checkpoint (ADR-0067). */\n decisionRecord?: DecisionRecordEntry[];\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 // Keep the legacy manual-task default in saved rows, though a manual task runs in no mode.\n taskMode: overrides.taskMode ?? (TASK_KINDS[type].runsInMode || type === 'user' ? 'build' : undefined),\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.goal !== undefined ? { goal: overrides.goal } : {}),\n ...(overrides.budget !== undefined ? { budget: { ...overrides.budget } } : {}),\n ...(overrides.grants !== undefined ? { grants: [...overrides.grants] } : {}),\n ...(overrides.protectedPaths !== undefined ? { protectedPaths: [...overrides.protectedPaths] } : {}),\n ...(overrides.scope !== undefined ? { scope: structuredClone(overrides.scope) } : {}),\n ...(overrides.readOnly ? { readOnly: true as const } : {}),\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), unless it\n * is read-only: that one runs sealed in a throwaway worktree (ADR-0055 D8).\n */\nexport function runsAsOps(task: Pick<Task, 'ops' | 'type' | 'readOnly'>): boolean {\n return (task.type === 'script' && !task.readOnly) || 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/** A task out of the plan, with every edge into it: `PlanGraph.remove` owns the rewrite, as it does for merge and split. */\nexport function removeTaskFromPlan(tasks: readonly Task[], taskId: string): Task[] {\n return remove(tasks, taskId);\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\n/** Whether {@link keepExecutionState} keeps this task exactly as it stands, whatever a rewrite says of it. */\nexport function isSettledTask(task: Pick<Task, 'status'>): boolean {\n return SETTLED_STATUSES.has(task.status);\n}\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 ...executionStateOf(prior),\n status: prior?.status ?? 'pending',\n // Where a task that has run ran is fixed, like its runner session (ADR-0020).\n ...(prior?.status === 'failed' ? { ops: prior.ops } : {}),\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","/**\n * Who ended a task as skipped (ADR-0045 L7). Stored beside the reason, never\n * read off its words: a person's or a supervisor's reason may say anything,\n * the loop's own texts may be reworded, and neither may change who skipped.\n *\n * - `loop`: a loop closed and the body that had not run was not waited for.\n * A new set of rounds undoes these.\n * - `user`, `supervisor`: a person, or a supervisor at Act, skipped it. A loop\n * whose body holds one has stopped, and stays so.\n * - `resolver`: its conflict ended some other way (ADR-0015).\n */\nexport type SkipOrigin = 'loop' | 'user' | 'supervisor' | 'resolver';\n\n/** Why a loop's body that did not run ends skipped once its loop is over (ADR-0045 L6). */\nexport const LOOP_PASSED = 'not needed: its check passed';\nexport const LOOP_OUT_OF_ROUNDS = 'not run: the loop ran out of rounds';\nexport const LOOP_CHECK_MARKED_COMPLETE = 'not needed: its check was marked complete';\nexport const LOOP_CHECK_SKIPPED = 'not needed: its check was skipped';\n\n/**\n * The texts a build before skip origins saved for a loop's own skips. Read\n * only to give such a plan the origin it lacks as it loads; they stay as they\n * were written even if the loop's wording changes, so no later build can read\n * a plan saved by this one wrongly.\n */\nconst LEGACY_LOOP_SKIP_REASONS: ReadonlySet<string> = new Set([\n 'not needed: its check passed',\n 'not run: the loop ran out of rounds',\n 'not needed: its check was marked complete',\n 'not needed: its check was skipped',\n]);\n\n/** The origin a task saved before skip origins was skipped by, which only a loop's own text gives away; undefined for any other. */\nexport function legacySkipOrigin(task: { status: string; skipReason?: string; skipOrigin?: SkipOrigin }): SkipOrigin | undefined {\n if (task.skipOrigin) return task.skipOrigin;\n return task.status === 'skipped' && LEGACY_LOOP_SKIP_REASONS.has(task.skipReason ?? '') ? 'loop' : undefined;\n}\n\n/** Whether a skipped body task has stopped its loop: anyone's skip but the loop's own does (ADR-0045 L7). */\nexport function stopsLoop(body: { status: string; skipOrigin?: SkipOrigin }): boolean {\n return body.status === 'skipped' && body.skipOrigin !== 'loop';\n}\n","import type { Task } from './Task';\n\n/*\n * Which of a task's fields are the plan's and which are its execution state,\n * and what a fresh attempt clears, stated once. A planner's rewrite keeps the\n * execution state it never witnessed (`keepExecutionState`); a retry and a\n * rearm clear the same attempt either way, but where they differ, below.\n *\n * - `plan`: what the plan says to run. The planner writes it.\n * - `execution`: the task's record of having run, which outlives an attempt:\n * a fresh attempt keeps it, and only a runner, the session or the user\n * changes it.\n * - `attempt`: the latest attempt's outcome, or what it waits on. Execution\n * state too, cleared by a fresh attempt.\n */\nexport type TaskFieldKind = 'plan' | 'execution' | 'attempt';\n\n/** Every key of `Task`, classified: a field added to `Task` without a kind here fails typecheck. */\nexport const TASK_FIELDS = {\n id: 'plan',\n order: 'plan',\n title: 'plan',\n description: 'plan',\n type: 'plan',\n status: 'attempt',\n dependencies: 'plan',\n prompt: 'plan',\n userSteps: 'plan',\n subtasks: 'plan',\n verdict: 'attempt',\n outputSummary: 'attempt',\n handoff: 'attempt',\n assignedModel: 'plan',\n assignedRunner: 'plan',\n taskMode: 'plan',\n autonomy: 'plan',\n sliceType: 'plan',\n userStoriesCovered: 'plan',\n // Cleared when an attempt spawns fresh, not when one is asked for: until then Continue may still offer it.\n runnerSessionId: 'execution',\n runnerSessionOwner: 'execution',\n awaitingReason: 'attempt',\n parkedQuestion: 'attempt',\n // Moved by status changes and cleared at an attempt's start (ADR-0053), so a fresh attempt asked for leaves it.\n waitsEnded: 'execution',\n resumeAt: 'attempt',\n carriedFrom: 'attempt',\n skipReason: 'attempt',\n skipOrigin: 'attempt',\n reverted: 'attempt',\n // A plan field, but where a failed task ran is fixed once it has run (ADR-0020): see `keepExecutionState`.\n ops: 'plan',\n research: 'plan',\n // A retry still owes research's report under its original authority (ADR-0037 R3).\n researchOrigin: 'execution',\n forcedPastGate: 'attempt',\n skills: 'plan',\n attemptSkills: 'execution',\n // Set by the session, never by an op (ADR-0029): the planner cannot write it.\n addedBy: 'execution',\n attempted: 'execution',\n attemptUsage: 'execution',\n commands: 'plan',\n script: 'plan',\n timeoutMs: 'plan',\n goal: 'plan',\n budget: 'plan',\n grants: 'plan',\n protectedPaths: 'plan',\n scope: 'plan',\n readOnly: 'plan',\n loop: 'plan',\n loopRound: 'attempt',\n reportTo: 'execution',\n} as const satisfies Record<keyof Task, TaskFieldKind>;\n\ntype FieldsOf<K extends TaskFieldKind> = { [F in keyof typeof TASK_FIELDS]: (typeof TASK_FIELDS)[F] extends K ? F : never }[keyof typeof TASK_FIELDS];\n\nexport type ExecutionField = FieldsOf<'execution' | 'attempt'>;\nexport type AttemptField = FieldsOf<'attempt'>;\n\nconst fieldsOf = <F extends keyof Task>(kinds: readonly TaskFieldKind[]): readonly F[] =>\n (Object.keys(TASK_FIELDS) as (keyof typeof TASK_FIELDS)[]).filter((f) => kinds.includes(TASK_FIELDS[f])) as F[];\n\n/** Every field that is execution state: what a planner's rewrite of the task never changes. */\nexport const EXECUTION_FIELDS: readonly ExecutionField[] = fieldsOf<ExecutionField>(['execution', 'attempt']);\n\n/** What a fresh attempt clears; `status` is set to pending instead. */\nexport const ATTEMPT_FIELDS: readonly AttemptField[] = fieldsOf<AttemptField>(['attempt']);\n\nexport interface FreshAttemptOptions {\n /**\n * A resume after a usage limit goes on with the attempt the limit cut\n * short, so a loop's check stays in its round; any other fresh attempt\n * starts the rounds over (ADR-0045 L7).\n */\n sameRound?: boolean;\n /**\n * The planner's `rearm`, a plan edit rather than a start. It keeps\n * `reverted`: a revert's hold is the user's to release, by a retry or a\n * force start (ADR-0054), and the saved mark is what keeps that hold past a\n * restart, so clearing it here would let the planner's edit lift the hold at\n * the next load.\n */\n rearm?: boolean;\n}\n\n/**\n * The changes that make a task a fresh attempt, from nothing it earned:\n * pending, with every attempt field cleared (`undefined`), and its record of\n * having run kept. Spread over the task, or written into it.\n */\nexport function freshAttempt(opts: FreshAttemptOptions = {}): Partial<Task> {\n const changes: Partial<Record<keyof Task, unknown>> = {};\n for (const field of ATTEMPT_FIELDS) {\n if (field === 'loopRound' && opts.sameRound) continue;\n if (field === 'reverted' && opts.rearm) continue;\n changes[field] = undefined;\n }\n changes.status = 'pending';\n return changes as Partial<Task>;\n}\n\n/** The task's execution state, every field named whether it holds a value or not, to lay over a rewrite of it. */\nexport function executionStateOf(task: Readonly<Task> | undefined): Partial<Task> {\n const state: Partial<Record<keyof Task, unknown>> = {};\n for (const field of EXECUTION_FIELDS) state[field] = task?.[field];\n return state as Partial<Task>;\n}\n","import { renumberTasks, waitsMidAttempt, type Task } from '../models/Task';\nimport { subtreeIds } from './PlanTree';\n\n/**\n * What the plan's edges become when tasks leave it or are swapped for others,\n * and the order that keeps them. `PlanTree`'s rules say which edges may\n * exist; this is the one place that rewrites them, so removal, merge and split\n * cannot disagree about a subtask that depended on the task going away. Every\n * rewrite reaches a dependency list at any depth, and a list comes out with\n * each id once.\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 remove(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\n/**\n * Swap `ids` for `newTasks`, which take the slot of the first of them, and\n * point everything that depended on any of `ids` at `tailId` — the new task\n * that stands for what they did — wherever it sits in the tree, so a task that\n * depended on both of two merged tasks depends on the merged one once. The new\n * tasks state their own dependencies and are not rewired. An edge into a\n * subtask the swap drops is left as it is: it dangles, and the plan's\n * invariants refuse it, as they do any unknown id. A loop's check and body are\n * not touched, because a task in either cannot be swapped (`loopReshapeRefusal`).\n */\nexport function replace(tasks: readonly Task[], ids: Iterable<string>, newTasks: readonly Task[], tailId: string): Task[] {\n const gone = new Set(ids);\n let placed = false;\n const rewire = (level: readonly Task[]): Task[] => {\n const out: Task[] = [];\n for (const t of level) {\n if (gone.has(t.id)) {\n if (!placed) { out.push(...newTasks); placed = true; }\n continue;\n }\n out.push({\n ...t,\n dependencies: [...new Set(t.dependencies.map((d) => (gone.has(d) ? tailId : d)))],\n subtasks: rewire(t.subtasks),\n });\n }\n return out;\n };\n const result = rewire(tasks);\n if (!placed) result.push(...newTasks);\n return renumberTasks(result);\n}\n\n/** A task the repair may not reposition: execution has already reached it. */\nfunction isPinned(t: Task): boolean {\n return t.status === 'in_progress' || waitsMidAttempt(t) || t.status === 'completed';\n}\n\n/**\n * Reorder one list of siblings so every dependency comes before its\n * dependents, moving as little as possible: pinned tasks keep the exact slot\n * they are in, and each free slot goes to the earliest-listed movable task\n * whose dependencies are already placed — so tasks the graph does not\n * constrain keep their relative order. A dependency outside the list (a task\n * of another level) constrains nothing here. Assumes an acyclic graph (the\n * caller checks first). `moves` says what moved, as `\"B\" #2→#1, \"A\" #1→#3`, or\n * is null when nothing did.\n */\nexport function repairOrder(tasks: Task[]): { tasks: Task[]; moves: string | null } | { error: string } {\n const byId = new Map(tasks.map((t) => [t.id, t]));\n const placed = new Set<string>();\n const movable = tasks.filter((t) => !isPinned(t));\n const result: Task[] = [];\n const blockerOf = (t: Task): Task | undefined => {\n const id = t.dependencies.find((d) => byId.has(d) && !placed.has(d));\n return id ? byId.get(id) : undefined;\n };\n const place = (t: Task) => { result.push(t); placed.add(t.id); };\n\n for (const occupant of tasks) {\n if (isPinned(occupant)) {\n const blocker = blockerOf(occupant);\n if (blocker) return { error: pinnedRefusal(blocker, occupant, 'before') };\n place(occupant);\n continue;\n }\n const next = movable.findIndex((t) => !blockerOf(t));\n if (next < 0) {\n // Nothing is schedulable and the graph is acyclic, so every movable task\n // left waits — directly or through others — on a pinned task further down\n // that would have to come up to free this slot.\n const [stuck, pin] = trailToPin(movable[0], blockerOf);\n return { error: pinnedRefusal(stuck, pin, 'after') };\n }\n place(movable.splice(next, 1)[0]);\n }\n return { tasks: result, moves: describeMoves(tasks, result) };\n}\n\n/** Walk the waiting-on chain from `task` down to the pinned task holding it up. */\nfunction trailToPin(task: Task, blockerOf: (t: Task) => Task | undefined): [Task, Task] {\n let at = task;\n for (;;) {\n const blocker = blockerOf(at);\n if (!blocker || isPinned(blocker)) return [at, blocker ?? at];\n at = blocker;\n }\n}\n\nfunction describeMoves(before: Task[], after: Task[]): string | null {\n const wasAt = new Map(before.map((t, i) => [t.id, i + 1]));\n const moved = after\n .map((t, i) => ({ t, from: wasAt.get(t.id)!, to: i + 1 }))\n .filter((m) => m.from !== m.to);\n return moved.length ? moved.map((m) => `\"${m.t.title}\" #${m.from}→#${m.to}`).join(', ') : null;\n}\n\nfunction pinnedRefusal(other: Task, pin: Task, side: 'before' | 'after'): string {\n const word = pin.status === 'completed' ? 'completed' : 'running';\n return `\"${other.title}\" would have to run ${side} \"${pin.title}\", which is ${word} and cannot be moved`;\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/** {@link taskRefOf} for a whole plan tree at once: each task's reference, by id. */\nexport function taskRefsOf<T extends RefTask<T>>(tasks: readonly T[]): Map<string, string> {\n const refs = new Map<string, string>();\n for (const { task, label } of walkPlan(tasks)) if (!refs.has(task.id)) refs.set(task.id, `#${label}`);\n return refs;\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 { flattenTasks, type Task } from '../models/Task';\nimport { addPlannerUsage, type PlannerUsage, type UsageRecord } from '../models/Usage';\n\n/**\n * An attempt that has run this long is worth a look whatever its plan's\n * history: below it, a task that runs long is still within what a single\n * brief often takes.\n */\nexport const RUNNING_LONG_FLOOR_MS = 30 * 60_000;\n/** How many times the longest passed AI task's running time an attempt may run before it is flagged. */\nexport const RUNNING_LONG_FACTOR = 3;\n\n/** How long an attempt may run before it is flagged, and the passed task that set it, when one did. */\nexport interface RunningLongThreshold {\n ms: number;\n basis?: RunningLongBasis;\n}\n\n/** The AI task that passed in the longest running time, which the threshold is a multiple of. */\nexport interface RunningLongBasis {\n taskId: string;\n runningMs: number;\n}\n\n/**\n * The larger of the floor and {@link RUNNING_LONG_FACTOR} times the longest\n * running time an AI task of this plan passed in, read from the attempt that\n * passed it. A script task has its own `timeoutMs`, and a failed attempt says\n * nothing of how long the work takes, so neither counts. Its waits on a person\n * are left out, as the live clock leaves them out: a task that waited overnight\n * says nothing of how long the work takes either. An attempt saved before its\n * running time was kept has only its wall time.\n */\nexport function runningLongThreshold(tasks: readonly Task[]): RunningLongThreshold {\n let basis: RunningLongBasis | undefined;\n for (const task of flattenTasks(tasks)) {\n if (task.type !== 'ai' || task.status !== 'completed') continue;\n const attempts = task.attemptUsage ?? [];\n const last = attempts[attempts.length - 1];\n if (!last?.endedAt) continue;\n const runningMs = last.runningMs ?? last.wallTimeMs;\n if (!basis || runningMs > basis.runningMs) basis = { taskId: task.id, runningMs };\n }\n const scaled = basis ? basis.runningMs * RUNNING_LONG_FACTOR : 0;\n return basis && scaled > RUNNING_LONG_FLOOR_MS ? { ms: scaled, basis } : { ms: RUNNING_LONG_FLOOR_MS };\n}\n\n/**\n * What a running-long flag says of the attempt (ADR-0018 W1): advisory, it\n * stops and fails nothing.\n */\nexport interface RunningLongFacts {\n /** Its running time passed the threshold, or its runner's session compacted on its own. */\n reason: 'duration' | 'compaction';\n /** Time the attempt has spent running, waits on a person left out. */\n elapsedMs: number;\n /** The running time this flag was due at: the threshold, doubled for each duration flag before it. */\n thresholdMs: number;\n basis?: RunningLongBasis;\n /** What the main model's context holds now, from the last usage record or compaction. */\n contextTokens?: number;\n contextWindow?: number;\n /** The most the context has held this attempt: the saved usage keeps only the last. */\n peakContextTokens?: number;\n /** Automatic compactions of the attempt's own runner session so far. */\n compactions: number;\n}\n\n/** A flag as the supervisor and the surfaces read it: the facts, of the attempt they were counted for. */\nexport type RunningLongEvent = RunningLongFacts & { attempt: number };\n\n/** The longest delay a timer keeps: Node fires a longer one at once. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\n/**\n * One attempt's running time, and the flags it raises. Time counts only while\n * the attempt runs: {@link hold} while it waits on a person (input, a\n * checkpoint, an approval), {@link run} once it goes on. Each duration flag\n * doubles the running time the next needs, as a quiet task's flag does.\n */\nexport class RunningLongClock {\n private accrued = 0;\n private since: number | null = null;\n private timer: NodeJS.Timeout | null = null;\n private flags = 0;\n private compactions = 0;\n /** The main model's context as the usage meter keeps it, by the same rules: a compaction or a model change clears it. */\n private meter: PlannerUsage = { totals: {} };\n private peak?: number;\n private stopped = false;\n\n constructor(\n private readonly threshold: () => RunningLongThreshold,\n private readonly flag: (facts: RunningLongFacts) => void,\n ) {}\n\n run(): void {\n if (this.stopped || this.since !== null) return;\n this.since = Date.now();\n this.arm();\n }\n\n hold(): void {\n if (this.since === null) return;\n this.accrued = this.runningMs();\n this.since = null;\n this.disarm();\n }\n\n stop(): void {\n this.hold();\n this.stopped = true;\n }\n\n usage(record: UsageRecord): void {\n // A subagent's context is not the attempt's, and an aggregate names no current context.\n if (this.stopped || record.subagentId || record.aggregate) return;\n const before = this.meter;\n this.meter = addPlannerUsage(this.meter, record);\n // A peak is measured against one model's window: another model's does not carry over.\n if (before.model !== this.meter.model || before.source !== this.meter.source) this.peak = undefined;\n this.measure();\n }\n\n /** A compaction of the attempt's own session: only one the runner did by itself says the context ran out. */\n compaction(trigger: 'manual' | 'auto', postTokens?: number): void {\n if (this.stopped) return;\n // The size before it is gone: with no size after, the context is unknown until the next call measures it.\n this.meter = { ...this.meter, lastPromptTokens: postTokens };\n this.measure();\n if (trigger !== 'auto') return;\n this.compactions += 1;\n this.flag(this.facts('compaction', this.due()));\n }\n\n private measure(): void {\n const tokens = this.meter.lastPromptTokens;\n if (tokens !== undefined) this.peak = Math.max(this.peak ?? 0, tokens);\n }\n\n /** Time spent running so far, waits on a person left out. */\n runningMs(): number {\n return this.accrued + (this.since === null ? 0 : Date.now() - this.since);\n }\n\n private due(): number {\n return this.threshold().ms * 2 ** this.flags;\n }\n\n private arm(): void {\n this.disarm();\n // A flag further off than a timer holds wakes early, and ripe() arms again.\n this.timer = setTimeout(() => this.ripe(), Math.min(MAX_TIMER_MS, Math.max(0, this.due() - this.runningMs())));\n }\n\n private disarm(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n\n /** Read again when the timer fires: a task that passed in the meantime may have raised the threshold. */\n private ripe(): void {\n this.timer = null;\n const due = this.due();\n if (this.runningMs() < due) {\n this.arm();\n return;\n }\n this.flags += 1;\n this.flag(this.facts('duration', due));\n if (!this.stopped && this.since !== null) this.arm();\n }\n\n private facts(reason: RunningLongFacts['reason'], thresholdMs: number): RunningLongFacts {\n const { basis } = this.threshold();\n return {\n reason,\n elapsedMs: this.runningMs(),\n thresholdMs,\n ...(basis ? { basis } : {}),\n ...(this.meter.lastPromptTokens !== undefined ? { contextTokens: this.meter.lastPromptTokens } : {}),\n ...(this.meter.contextWindow !== undefined ? { contextWindow: this.meter.contextWindow } : {}),\n ...(this.peak !== undefined ? { peakContextTokens: this.peak } : {}),\n compactions: this.compactions,\n };\n }\n}\n","import type { Task, Verdict, VerificationCheck } from '../models/Task';\nimport type { IRunnerSession, ScriptExit, ScriptFullOutput, ScriptStatus } from '../interfaces/IRunner';\nimport type { CheckpointAnswer, TaskCompleteArgs } from './mcp/tools';\nimport { RUNNING_LONG_FLOOR_MS, RunningLongClock, type RunningLongFacts, type RunningLongThreshold } from './RunningLong';\n\nexport type VerdictListener = (taskId: string, verdict: Verdict) => void;\nexport type CheckpointListener = (taskId: string, summary: string) => void;\n/** A tool-raised checkpoint whose call went away while its attempt lives on, so nothing is left to answer it. */\nexport type CheckpointWithdrawnListener = (taskId: string) => void;\n/** Fires on every idleSince transition (null→timestamp on silence, timestamp→null on resume/teardown). */\nexport type IdleListener = (taskId: string, idleSince: string | null) => void;\n/** A running AI attempt ran long or compacted on its own (ADR-0018 W1): advisory, it settles nothing. */\nexport type RunningLongListener = (taskId: string, facts: RunningLongFacts) => void;\n\nexport interface VerdictEngineOptions {\n /** How long an attempt may run before it is flagged, read again as tasks pass; the floor alone when absent. */\n runningLongThreshold?: () => RunningLongThreshold;\n}\n\n/**\n * No output for this long, with no tool call in flight, marks a running task\n * idle (advisory, UI-only). Long model turns and slow builds routinely go\n * quiet for minutes, so a shorter window flagged healthy tasks as Stalled. A run that ends with a build plus\n * the full test suite can print nothing for more than 5 minutes, which flagged\n * healthy tasks quiet and woke the supervisor for nothing, hence 10.\n */\nexport const IDLE_TIMEOUT_MS = 10 * 60_000;\n\n\nexport class VerdictEngine {\n private pendingVerdicts = new Map<string, Verdict>();\n private sessions = new Map<string, IRunnerSession>();\n private listeners: VerdictListener[] = [];\n private checkpointListeners: CheckpointListener[] = [];\n private withdrawnListeners: CheckpointWithdrawnListener[] = [];\n /** The open `checkpoint` tool call per task (ADR-0022, V5): settling it is how an answer reaches the runner. */\n private toolCheckpoints = new Map<string, (answer: CheckpointAnswer) => void>();\n /** The question a task's checkpoint asks, whole, for as long as it waits. */\n private checkpointQuestions = new Map<string, string>();\n private idleListeners: IdleListener[] = [];\n /**\n * Per-task generation. Replaced on every watch(), clear() and verdict.\n * Stale callbacks (from a prior session whose generation doesn't match\n * the current one) bail out instead of delivering a verdict for the\n * wrong session.\n */\n private generations = new Map<string, number>();\n /**\n * Generations come from one counter that {@link reset} never rewinds: a\n * per-task count restarted at 1 after a reset, and the next watch handed a\n * session that outlived the reset the same generation as its successor.\n */\n private lastGeneration = 0;\n private idleTimers = new Map<string, NodeJS.Timeout>();\n private idleSince = new Map<string, string | null>();\n /** Tasks waiting on the user, whose silence is expected rather than a sign of a stuck runner. */\n private idlePaused = new Set<string>();\n /**\n * Open tool approvals per structured task. They arrive mid-turn and leave the\n * status alone (ADR-0018, W1), but a task waiting on one is waiting on the\n * user, so it is not idle either.\n */\n private openApprovals = new Map<string, Set<string>>();\n /**\n * Tool calls per structured task with no result yet. A runner waiting on a\n * command it started (a long test suite, a bench run) prints nothing until it\n * returns; it is waiting, not stalled, so it is not idle either. A runner with\n * no call in flight and no output still is.\n */\n private openCalls = new Map<string, Set<string>>();\n /**\n * How often the current attempt has been flagged idle. Each flag doubles the\n * silence the next one needs: a long review that prints a line now and then\n * was flagged again after every line, and each flag woke the planner.\n */\n private idleFlags = new Map<string, number>();\n /** The running time of each AI task's current attempt (ADR-0018 W1). */\n private clocks = new Map<string, RunningLongClock>();\n /** The running time an attempt's clock stopped at, until the task's next attempt starts. */\n private ran = new Map<string, number>();\n private runningLongListeners: RunningLongListener[] = [];\n private readonly runningLongThreshold: () => RunningLongThreshold;\n\n constructor(options: VerdictEngineOptions = {}) {\n this.runningLongThreshold = options.runningLongThreshold ?? (() => ({ ms: RUNNING_LONG_FLOOR_MS }));\n }\n\n onVerdict(listener: VerdictListener): void {\n this.listeners.push(listener);\n }\n\n onCheckpoint(listener: CheckpointListener): void {\n this.checkpointListeners.push(listener);\n }\n\n onCheckpointWithdrawn(listener: CheckpointWithdrawnListener): void {\n this.withdrawnListeners.push(listener);\n }\n\n onIdleChange(listener: IdleListener): void {\n this.idleListeners.push(listener);\n }\n\n onRunningLong(listener: RunningLongListener): void {\n this.runningLongListeners.push(listener);\n }\n\n /** Advisory silence timestamp for a task, or null if it isn't idle. */\n getIdleSince(taskId: string): string | null {\n return this.idleSince.get(taskId) ?? null;\n }\n\n /**\n * Stop watching a task's silence while it waits on the user (ADR-0018, W1).\n * Watching resumes when its next turn starts, or when a checkpoint is answered.\n */\n pauseIdle(taskId: string): void {\n this.idlePaused.add(taskId);\n this.clearIdle(taskId);\n this.syncClock(taskId);\n }\n\n private resumeIdle(taskId: string): void {\n const gen = this.generations.get(taskId);\n if (!this.idlePaused.delete(taskId) || gen === undefined) return;\n this.syncClock(taskId);\n this.touchIdle(taskId, gen);\n }\n\n /**\n * An attempt's running time stops while it waits on a person, for input, a\n * checkpoint or an approval, and goes on when it does. A tool call in flight\n * is the runner working, so it counts.\n */\n private syncClock(taskId: string): void {\n const clock = this.clocks.get(taskId);\n if (!clock) return;\n if (this.idlePaused.has(taskId) || this.openApprovals.get(taskId)?.size) clock.hold();\n else clock.run();\n }\n\n private stopClock(taskId: string): void {\n const clock = this.clocks.get(taskId);\n if (!clock) return;\n clock.stop();\n this.ran.set(taskId, clock.runningMs());\n this.clocks.delete(taskId);\n }\n\n /**\n * The current or last attempt's running time, waits on a person left out:\n * what a later task's running-long threshold is a multiple of (ADR-0018 W1).\n * Undefined for a task with no clock.\n */\n runningMs(taskId: string): number | undefined {\n return this.clocks.get(taskId)?.runningMs() ?? this.ran.get(taskId);\n }\n\n /** Restart the silence timer on fresh output; broadcasts the null transition if it was idle. */\n private touchIdle(taskId: string, gen: number): void {\n if (this.idlePaused.has(taskId) || this.openApprovals.get(taskId)?.size || this.openCalls.get(taskId)?.size) return;\n const existing = this.idleTimers.get(taskId);\n if (existing) clearTimeout(existing);\n if (this.idleSince.get(taskId)) {\n this.idleSince.set(taskId, null);\n for (const l of this.idleListeners) l(taskId, null);\n }\n this.idleTimers.set(taskId, setTimeout(() => {\n if (this.generations.get(taskId) !== gen) return;\n const now = new Date().toISOString();\n this.idleFlags.set(taskId, (this.idleFlags.get(taskId) ?? 0) + 1);\n this.idleSince.set(taskId, now);\n for (const l of this.idleListeners) l(taskId, now);\n }, IDLE_TIMEOUT_MS * 2 ** (this.idleFlags.get(taskId) ?? 0)));\n }\n\n /** Tear down idle tracking for a task; broadcasts the null transition if it was idle. */\n private clearIdle(taskId: string): void {\n const timer = this.idleTimers.get(taskId);\n if (timer) clearTimeout(timer);\n this.idleTimers.delete(taskId);\n const wasIdle = this.idleSince.get(taskId);\n this.idleSince.delete(taskId);\n if (wasIdle) {\n for (const l of this.idleListeners) l(taskId, null);\n }\n }\n\n /** What a task's waiting checkpoint asks, untruncated; undefined when none waits. */\n getCheckpointQuestion(taskId: string): string | undefined {\n return this.checkpointQuestions.get(taskId);\n }\n\n approveCheckpoint(taskId: string, note?: string): void {\n this.checkpointQuestions.delete(taskId);\n this.resumeIdle(taskId);\n this.toolCheckpoints.get(taskId)?.({ kind: 'continue', ...(note ? { note } : {}) });\n }\n\n rejectCheckpoint(taskId: string, reason: string): void {\n this.checkpointQuestions.delete(taskId);\n this.resumeIdle(taskId);\n this.toolCheckpoints.get(taskId)?.({ kind: 'rejected', reason });\n }\n\n /**\n * An attempt's runner is being started, with no session to watch yet. Its\n * silence counts from here, so one whose start never resolves — stuck\n * launching, or waiting for its tools to attach — is flagged quiet as well.\n * {@link watch} starts the count again once the runner is up.\n */\n starting(taskId: string): void {\n const gen = this.bumpGeneration(taskId);\n this.stopClock(taskId);\n this.ran.delete(taskId);\n this.idlePaused.delete(taskId);\n this.openApprovals.delete(taskId);\n this.openCalls.delete(taskId);\n this.idleFlags.delete(taskId);\n this.touchIdle(taskId, gen);\n }\n\n /**\n * Attach to a spawned session. The runner's `task_complete` call on the\n * attempt's token is the only completion evidence (ADR-0022, V2); a session\n * that exits before one gets a failed verdict. A script task's session has\n * no runner to call it: its exit status is the evidence instead (ADR-0035).\n *\n * Returns the attempt's generation, what {@link signalComplete} is checked against.\n */\n watch(task: Task, session: IRunnerSession): number {\n const gen = this.bumpGeneration(task.id);\n // Silence counts from the start, not from the first output: a runner that\n // never prints went unflagged however long it stayed quiet (#117). Armed\n // before any listener, so an exit or verdict a session replays on attach\n // clears it rather than leaving it to fire. What an earlier attempt waited\n // on is not this one's to wait on.\n this.idlePaused.delete(task.id);\n this.openApprovals.delete(task.id);\n this.openCalls.delete(task.id);\n this.idleFlags.delete(task.id);\n this.touchIdle(task.id, gen);\n this.stopClock(task.id);\n this.ran.delete(task.id);\n // A script has its own timeoutMs, and a person's task has no runner (ADR-0018 W1).\n const clock = task.type === 'ai' ? new RunningLongClock(this.runningLongThreshold, (facts) => {\n if (this.generations.get(task.id) !== gen) return;\n for (const l of this.runningLongListeners) l(task.id, facts);\n }) : undefined;\n if (clock) {\n this.clocks.set(task.id, clock);\n clock.run();\n }\n session.onOutput(() => {\n if (this.generations.get(task.id) === gen) this.touchIdle(task.id, gen);\n });\n this.sessions.set(task.id, session);\n session.onTurnEnd(() => {\n if (this.generations.get(task.id) !== gen) return;\n // A call whose result never came is not in flight past its turn.\n if (this.openCalls.delete(task.id)) this.touchIdle(task.id, gen);\n // The call lives inside the turn that made it. A runner cut short by an\n // interrupt does not always cancel it, and left open it would refuse the next one.\n this.callWentAway(task.id, 'the turn it was asked in has ended.');\n // A queued follow-up supersedes this turn's evidence without ending the attempt.\n const pending = this.pendingVerdicts.get(task.id);\n this.pendingVerdicts.delete(task.id);\n if (session.turnState() === 'idle' && pending) this.publishVerdict(task.id, pending);\n });\n session.onEvent((event) => {\n if (this.generations.get(task.id) !== gen) return;\n if (event.type === 'turn_start') {\n this.supersede(task.id);\n this.resumeIdle(task.id);\n }\n // Read mid-turn, a message voids what the runner reported before it just as a new turn does (ADR-0023).\n else if (event.type === 'message_delivered') this.supersede(task.id);\n else if (event.type === 'permission_request' && !event.decided) this.waitOpened(this.openApprovals, task.id, event.id);\n else if (event.type === 'permission_decided' || event.type === 'permission_withdrawn') this.waitClosed(this.openApprovals, task.id, event.id, gen);\n else if (event.type === 'tool_call') this.waitOpened(this.openCalls, task.id, event.id);\n else if (event.type === 'tool_result') this.waitClosed(this.openCalls, task.id, event.id, gen);\n else if (event.type === 'usage') clock?.usage(event.record);\n else if (event.type === 'compaction') clock?.compaction(event.trigger, event.postTokens);\n });\n session.onTaskComplete((report, refuted) => this.signalComplete(task.id, gen, report, refuted));\n session.onScriptExit((exit) => this.signalScriptExit(task.id, gen, exit));\n session.onToolCheckpoint((question, signal) => this.raiseCheckpoint(task.id, gen, question, signal));\n session.onExit((exitCode: number) => {\n if (this.generations.get(task.id) !== gen) return;\n this.forget(task.id);\n const verdict = exitVerdict(exitCode);\n for (const l of this.listeners) l(task.id, verdict);\n });\n return gen;\n }\n\n /**\n * The runner's own `task_complete` call (ADR-0022, V1/V3): settles the\n * attempt, unless that attempt is no longer the task's current one or an\n * earlier call already settled it.\n */\n signalComplete(taskId: string, generation: number, report: TaskCompleteArgs, refuted?: VerificationCheck): void {\n if (this.generations.get(taskId) !== generation) return;\n this.acceptVerdict(taskId, reportedVerdict(report, refuted));\n }\n\n /**\n * A script task's exit status (ADR-0035): its one evidence, as a runner's\n * `task_complete` call is a runner's. It settles the attempt unless that\n * attempt is no longer the task's current one.\n */\n signalScriptExit(taskId: string, generation: number, exit: ScriptExit): void {\n if (this.generations.get(taskId) !== generation) return;\n this.acceptVerdict(taskId, scriptVerdict(exit));\n }\n\n /** The runner was told something after its evidence so far, so only what it reports from here counts. */\n private supersede(taskId: string): void {\n this.pendingVerdicts.delete(taskId);\n }\n\n private acceptVerdict(taskId: string, verdict: Verdict): void {\n if (this.pendingVerdicts.has(taskId)) return;\n // Only what a person queued is news the evidence predates. Ordewell's own\n // messages (the compaction nudge, ADR-0018 C3) restate the brief and ask\n // for this very call, so one still queued holds no verdict back.\n if (this.sessions.get(taskId)?.queued().some((message) => message.from !== 'ordewell')) {\n this.pendingVerdicts.set(taskId, verdict);\n return;\n }\n this.publishVerdict(taskId, verdict);\n }\n\n private publishVerdict(taskId: string, verdict: Verdict): void {\n this.forget(taskId);\n this.bumpGeneration(taskId);\n for (const l of this.listeners) l(taskId, verdict);\n }\n\n /**\n * The runner's `checkpoint` call (ADR-0022, V5): the task waits on the\n * user until it is settled by {@link approveCheckpoint} or {@link rejectCheckpoint}. It is\n * withdrawn, never left hanging, once the attempt is over or the call goes.\n */\n raiseCheckpoint(taskId: string, generation: number, question: string, signal: AbortSignal): Promise<CheckpointAnswer> {\n if (this.generations.get(taskId) !== generation || signal.aborted) {\n return Promise.resolve({ kind: 'withdrawn', why: 'this attempt has ended.' });\n }\n if (this.toolCheckpoints.has(taskId)) {\n return Promise.resolve({ kind: 'withdrawn', why: 'another checkpoint is still waiting for an answer. Wait for it before asking again.' });\n }\n return new Promise((resolve) => {\n const settle = (answer: CheckpointAnswer) => {\n signal.removeEventListener('abort', onAbort);\n if (this.toolCheckpoints.get(taskId) === settle) {\n this.toolCheckpoints.delete(taskId);\n this.checkpointQuestions.delete(taskId);\n }\n resolve(answer);\n };\n const onAbort = () => {\n settle({ kind: 'withdrawn', why: 'the call was cancelled.' });\n if (this.generations.get(taskId) !== generation) return;\n this.resumeIdle(taskId);\n for (const l of this.withdrawnListeners) l(taskId);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n this.toolCheckpoints.set(taskId, settle);\n this.checkpointQuestions.set(taskId, question.trim());\n for (const l of this.checkpointListeners) l(taskId, question.trim());\n });\n }\n\n /** The open `checkpoint` call can no longer be answered: refuse it, and let the task out of the wait. */\n private callWentAway(taskId: string, why: string): void {\n const open = this.toolCheckpoints.get(taskId);\n if (!open) return;\n open({ kind: 'withdrawn', why });\n this.resumeIdle(taskId);\n for (const l of this.withdrawnListeners) l(taskId);\n }\n\n private withdrawToolCheckpoint(taskId: string): void {\n this.toolCheckpoints.get(taskId)?.({ kind: 'withdrawn', why: 'this attempt has ended.' });\n }\n\n /** Something the task waits on (an approval, a call in flight) opened: its silence is expected until the last one closes. */\n private waitOpened(waits: Map<string, Set<string>>, taskId: string, id: string): void {\n const open = waits.get(taskId) ?? new Set<string>();\n open.add(id);\n waits.set(taskId, open);\n this.clearIdle(taskId);\n this.syncClock(taskId);\n }\n\n private waitClosed(waits: Map<string, Set<string>>, taskId: string, id: string, gen: number): void {\n const open = waits.get(taskId);\n if (!open?.delete(id) || open.size) return;\n waits.delete(taskId);\n this.syncClock(taskId);\n this.touchIdle(taskId, gen);\n }\n\n private bumpGeneration(taskId: string): number {\n this.lastGeneration += 1;\n this.generations.set(taskId, this.lastGeneration);\n return this.lastGeneration;\n }\n\n private forget(taskId: string): void {\n this.pendingVerdicts.delete(taskId);\n this.sessions.delete(taskId);\n this.withdrawToolCheckpoint(taskId);\n this.checkpointQuestions.delete(taskId);\n this.idlePaused.delete(taskId);\n this.openApprovals.delete(taskId);\n this.openCalls.delete(taskId);\n this.idleFlags.delete(taskId);\n this.stopClock(taskId);\n this.clearIdle(taskId);\n }\n\n /** Manual \"Mark complete\" override: a pass verdict that bypasses evidence. */\n markComplete(task: Task): Verdict {\n this.ceaseTracking(task.id);\n return {\n outcome: 'pass',\n reason: 'Manually marked complete by user.',\n checks: [\n {\n name: 'manual',\n passed: true,\n skipped: false,\n detail: 'Task was manually marked complete by the user; no automatic verification was performed.',\n },\n ],\n decidedAt: new Date().toISOString(),\n };\n }\n\n /** Clear verification state for a task (used on retry). */\n clear(task: Task): void {\n this.ceaseTracking(task.id);\n }\n\n /** Drop a task's verification state and invalidate any callbacks still holding its generation. */\n private ceaseTracking(taskId: string): void {\n this.forget(taskId);\n this.bumpGeneration(taskId);\n }\n\n /** Drop all tracking state (used on stop / loadPlan). */\n reset(): void {\n this.pendingVerdicts.clear();\n this.sessions.clear();\n for (const taskId of [...this.toolCheckpoints.keys()]) this.withdrawToolCheckpoint(taskId);\n this.checkpointQuestions.clear();\n for (const timer of this.idleTimers.values()) clearTimeout(timer);\n this.idleTimers.clear();\n this.idleSince.clear();\n this.idlePaused.clear();\n this.openApprovals.clear();\n this.openCalls.clear();\n this.idleFlags.clear();\n for (const clock of this.clocks.values()) clock.stop();\n this.clocks.clear();\n this.ran.clear();\n this.generations.clear();\n }\n}\n\nconst EXIT_CHECK = 'exit_code';\n\n/** The runner's exit decided it, not a `task_complete` report. */\nexport function endedByExit(verdict: Verdict): boolean {\n return verdict.checks.some((check) => check.name === EXIT_CHECK);\n}\n\n/** A runner that exited without reporting through `task_complete` did not finish, whatever its exit code. */\nfunction exitVerdict(exitCode: number): Verdict {\n const normalized = exitCode == null ? 0 : exitCode;\n const exitOk = normalized === 0;\n return {\n outcome: 'fail',\n reason: exitOk\n ? 'Failed verification: the runner exited cleanly but never called task_complete.'\n : `Failed verification: the runner exited with code ${normalized} without calling task_complete.`,\n checks: [\n { name: 'task_complete', passed: false, skipped: false, detail: 'the runner exited before calling task_complete' },\n { name: EXIT_CHECK, passed: exitOk, skipped: false, detail: exitOk ? 'the runner exited cleanly (code 0)' : `the runner exited with code ${normalized}` },\n ],\n decidedAt: new Date().toISOString(),\n };\n}\n\n/**\n * The host died during the attempt, so nothing was checked. Nothing was\n * reported either, so no loop reads it as a finding (ADR-0045 L2).\n */\nexport function interruptedVerdict(decidedAt: string): Verdict {\n return { outcome: 'fail', reason: 'It was interrupted when Ordewell stopped, and nothing is running it now.', checks: [], decidedAt };\n}\n\n/** How a status reads in a reason: its exit code, the signal that ended it, or why it never started. */\nfunction statusText(status: ScriptStatus): string {\n if (status.error !== undefined) return `could not start: ${status.error}`;\n if (status.signal) return `was ended by ${status.signal}`;\n return `exited with code ${status.code ?? 'unknown'}`;\n}\n\n/**\n * The tail is all a verdict quotes, and a long command's failure is often\n * above it, so a reason points at the file that holds the whole output.\n */\nfunction withTail(reason: string, errorTail: string, fullOutput?: ScriptFullOutput): string {\n const tail = errorTail.trim();\n const quoted = tail ? `${reason}\\n\\nThe end of its error output:\\n${tail}` : reason;\n if (!fullOutput) return quoted;\n // No full stop after a path: it would be copied with it.\n const cut = fullOutput.droppedChars > 0 ? `, except its last ${fullOutput.droppedChars} characters, which were not saved.` : '';\n return `${quoted}\\n\\nAll of its output is in ${fullOutput.file}${cut}`;\n}\n\n/**\n * A script task's verdict from its exit status alone (ADR-0035): every step\n * exiting 0 passes, anything else fails with the status and the tail of its\n * error output. Never an exit check — the script did not stop before it was\n * done — so it is never read as a runner that hit its usage limit.\n */\nfunction scriptVerdict(exit: ScriptExit): Verdict {\n const decidedAt = new Date().toISOString();\n const check = (passed: boolean, detail: string): VerificationCheck[] => [{ name: 'script_exit', passed, skipped: false, detail }];\n const command = exit.outcome !== 'passed' && exit.command !== undefined ? `\\`${exit.command}\\`` : undefined;\n switch (exit.outcome) {\n case 'passed':\n return { outcome: 'pass', reason: 'Verified: every step of the script exited 0.', checks: check(true, 'every step exited 0'), decidedAt, reported: 'done' };\n case 'failed': {\n const said = `${command ?? 'it'} ${statusText(exit.status)}`;\n // A step that never started found nothing about the work (ADR-0045 L2).\n const reported = exit.status.error !== undefined ? 'blocked' : 'failed';\n return { outcome: 'fail', reason: withTail(`The script failed: ${said}.`, exit.errorTail, exit.fullOutput), checks: check(false, said), decidedAt, reported };\n }\n case 'timed-out': {\n const said = `the time limit of ${durationText(exit.timeoutMs)} ran out${command ? ` while ${command} ran` : ''}, so it was ended`;\n return { outcome: 'fail', reason: withTail(`The script failed: ${said}.`, exit.errorTail, exit.fullOutput), checks: check(false, said), decidedAt, reported: 'failed' };\n }\n case 'stopped': {\n const said = `it was stopped${command ? ` while ${command} ran` : ''}`;\n return { outcome: 'fail', reason: withTail(`The script did not finish: ${said}.`, '', exit.fullOutput), checks: check(false, said), decidedAt };\n }\n }\n}\n\n/** A limit as a reader says it: minutes when it is whole minutes, else seconds. */\nfunction durationText(ms: number): string {\n if (ms % 60_000 === 0) return `${ms / 60_000} minute${ms === 60_000 ? '' : 's'}`;\n const seconds = Math.round(ms / 100) / 10;\n return `${seconds} second${seconds === 1 ? '' : 's'}`;\n}\n\n/**\n * `refuted` is a check of the work the call's own evidence failed, as a\n * delegated task's protected paths do (ADR-0055 D7): a `done` it refutes fails,\n * with what failed named, whatever the runner said.\n */\nfunction reportedVerdict(report: TaskCompleteArgs, refuted?: VerificationCheck): Verdict {\n const checks: VerificationCheck[] = [\n {\n name: 'task_complete',\n passed: report.status === 'done',\n skipped: false,\n detail: `the runner called task_complete with status \"${report.status}\"`,\n },\n ...(refuted ? [refuted] : []),\n ];\n const decidedAt = new Date().toISOString();\n // Kept apart from the outcome: `blocked` and `failed` fail alike, but only a `failed` check starts a loop's round (ADR-0045 L2).\n const reported = report.status;\n if (report.status === 'done' && refuted) return { outcome: 'fail', reason: refuted.detail, checks, decidedAt, reported: 'failed' };\n if (report.status === 'done') {\n return { outcome: 'pass', reason: 'Verified: the runner reported completion through task_complete. Task completed successfully.', checks, decidedAt, reported };\n }\n // Runners often put the why in the summary and leave `reason` out; its\n // first paragraph is their own words, where \"no reason given\" would not be.\n const why = report.reason?.trim() || report.summary?.trim().split(/\\n\\s*\\n/)[0].trim() || 'no reason given';\n return { outcome: 'fail', reason: `The runner reported the task ${report.status}: ${why}`, checks, decidedAt, reported };\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,YAAM,QAAQ,cAAc,GAAG,WAAW,IAAI,KAAK,KAAK,KAAK,OAAO,KAAK,KAAK;AAC9E,YAAM,EAAE,MAAM,QAAQ,UAAU,GAAG,EAAE,GAAG,WAAW,UAAU,OAAO,MAAM;AAC1E,aAAO,KAAK,KAAK,YAAY,CAAC,GAAG,CAAC,GAAG,WAAW,IAAI,GAAG,KAAK;AAAA,IAC9D;AAAA,EACF;AACA,SAAO,KAAK,OAAO,CAAC,CAAC;AACvB;AAEO,SAAS,cAAqC,OAAqB,IAA0C;AAClH,aAAW,OAAO,SAAS,KAAK,EAAG,KAAI,IAAI,KAAK,OAAO,GAAI,QAAO;AAClE,SAAO;AACT;AAGO,SAAS,WAAkC,OAAqB,IAAyB;AAC9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AE,SAAS,QAAQ,QAAQ,SAAS,8BAA8B,IAAI,KAAK,IAAI,KAAK,UAAU,GAAG,QAAQ,MAAM,OAAO,IAAI,GAAG,UAAU;AAAA,IAChJ;AAAA,EACF;AACF;AAGA,SAAS,aAAa,IAAoB;AACxC,MAAI,KAAK,QAAW,EAAG,QAAO,GAAG,KAAK,GAAM,UAAU,OAAO,MAAS,KAAK,GAAG;AAC9E,QAAM,UAAU,KAAK,MAAM,KAAK,GAAG,IAAI;AACvC,SAAO,GAAG,OAAO,UAAU,YAAY,IAAI,KAAK,GAAG;AACrD;AAOA,SAAS,gBAAgB,QAA0B,SAAsC;AACvF,QAAM,SAA8B;AAAA,IAClC;AAAA,MACE,MAAM;AAAA,MACN,QAAQ,OAAO,WAAW;AAAA,MAC1B,SAAS;AAAA,MACT,QAAQ,gDAAgD,OAAO,MAAM;AAAA,IACvE;AAAA,IACA,GAAI,UAAU,CAAC,OAAO,IAAI,CAAC;AAAA,EAC7B;AACA,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAEzC,QAAM,WAAW,OAAO;AACxB,MAAI,OAAO,WAAW,UAAU,QAAS,QAAO,EAAE,SAAS,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,WAAW,UAAU,SAAS;AACjI,MAAI,OAAO,WAAW,QAAQ;AAC5B,WAAO,EAAE,SAAS,QAAQ,QAAQ,gGAAgG,QAAQ,WAAW,SAAS;AAAA,EAChK;AAGA,QAAM,MAAM,OAAO,QAAQ,KAAK,KAAK,OAAO,SAAS,KAAK,EAAE,MAAM,SAAS,EAAE,CAAC,EAAE,KAAK,KAAK;AAC1F,SAAO,EAAE,SAAS,QAAQ,QAAQ,gCAAgC,OAAO,MAAM,KAAK,GAAG,IAAI,QAAQ,WAAW,SAAS;AACzH;","names":["path","replace","dependentsOf","next"]}
|
|
1
|
+
{"version":3,"sources":["../src/conversation/skillTokens.ts","../src/services/PlanTree.ts","../src/services/repoPath.ts","../src/services/LandingLedger.ts","../src/services/isolationRecord.ts","../src/models/Usage.ts","../src/models/TaskKind.ts","../src/models/Task.ts","../src/models/SkipOrigin.ts","../src/models/TaskExecution.ts","../src/services/PlanGraph.ts","../src/services/TaskRefs.ts","../src/services/RunningLong.ts","../src/services/VerdictEngine.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 type { IsolationRun, IsolationTaskRecord, LandedTask } from '../interfaces/IWorktreeIsolation';\nimport type { Task } from '../models/Task';\n\n/*\n * The landing ledger (ADR-0054): what an isolated run keeps of who landed what\n * across every attempt, after a record has gone too. That is\n * `IsolationRun.landings`, `carried`, `landedTasks`, `landedOn`,\n * `keepsEveryLanding` and `reverted`, with each record's `landedTip` for a run\n * saved before `landings` were kept. Every read and write of those goes through\n * here and none of it asks git: GitWorktreeIsolation hands it what a merge made,\n * and FakeWorktreeIsolation hands it the same facts, so both keep one set of rules.\n */\n\n/** What a run starts with: every merge kept from the first, and the record of what merges carried, empty until one does. */\nexport const freshLedger = (): Pick<IsolationRun, 'keepsEveryLanding' | 'carried'> => ({ keepsEveryLanding: true, carried: {} });\n\n/** Every run started now holds {@link IsolationRun.carried}, empty or not, so one without it was saved by a build that kept no such record. */\nexport const startedOlder = (run: IsolationRun): boolean => run.carried === undefined;\n\n/** Whether a revert was committed on the run: its branch holds commits no record names, so it carries on with no record left. */\nexport const hasReverted = (run: IsolationRun): boolean => run.reverted === true;\n\n/** What a task landed as: its record while it has one, else what the ledger kept once a retry dropped it. */\nexport function landedTaskOf(run: IsolationRun | null | undefined, taskId: string): LandedTask | undefined {\n return run?.tasks[taskId] ?? run?.landedTasks?.[taskId];\n}\n\n/** What to call a task in a refusal: the id stands in once nothing names it. */\nexport const landedTitleOf = (run: IsolationRun, taskId: string): string => landedTaskOf(run, taskId)?.title ?? taskId;\n\n/** The merges that landed a task in a repo, oldest first; a run saved before they were kept has only the record's latest. */\nexport function landingsOf(run: IsolationRun, taskId: string, repoPath: string): string[] {\n const latest = run.tasks[taskId]?.repos[repoPath]?.landedTip;\n return run.landings?.[taskId]?.[repoPath] ?? (latest ? [latest] : []);\n}\n\n/** Every kept merge in a repo, by the task it landed. */\nexport function landingsIn(run: IsolationRun, repoPath: string): Array<{ taskId: string; merge: string }> {\n return Object.entries(run.landings ?? {}).flatMap(([taskId, byRepo]) => (byRepo[repoPath] ?? []).map((merge) => ({ taskId, merge })));\n}\n\n/** Whether anything ever landed in a repo, by the ledger or a record's tip. */\nexport function hasLandingIn(run: IsolationRun, repoPath: string): boolean {\n if (Object.values(run.landings ?? {}).some((byRepo) => (byRepo[repoPath]?.length ?? 0) > 0)) return true;\n return Object.values(run.tasks).some((record) => record.repos[repoPath]?.landedTip !== undefined);\n}\n\n/** The repos the ledger holds a task's merges in. */\nexport const landedReposOf = (run: IsolationRun, taskId: string): string[] => Object.keys(run.landings?.[taskId] ?? {});\n\n/** Whether another task's merge carried a task's work, in one repo or any. */\nexport function isCarried(run: IsolationRun | null | undefined, taskId: string, repoPath?: string): boolean {\n const tips = run?.carried?.[taskId];\n return repoPath === undefined ? tips !== undefined : tips?.[repoPath] !== undefined;\n}\n\n/** Every carried tip in a repo, by the task whose work it is. */\nexport function carriedTipsIn(run: IsolationRun, repoPath: string): Array<{ taskId: string; tip: string }> {\n return Object.entries(run.carried ?? {}).flatMap(([taskId, repos]) => (repos[repoPath] ?? []).map((tip) => ({ taskId, tip })));\n}\n\n/** Whether a task has work on the integration branch in a repo: a later attempt's record says nothing of the merges before it. */\nexport function landedIn(run: IsolationRun, taskId: string, repoPath: string): boolean {\n const record = run.tasks[taskId];\n return landingsOf(run, taskId, repoPath).length > 0 || isCarried(run, taskId, repoPath) || (record?.status === 'merged' && record.repos[repoPath]?.changed === true);\n}\n\n/** Whether a landed record's work is in a repo, for what its handoff and Merge all name there. */\nexport function mergedIn(run: IsolationRun, record: IsolationTaskRecord, repoPath: string): boolean {\n return !!record.repos[repoPath]?.changed || run.landings?.[record.taskId]?.[repoPath] !== undefined;\n}\n\n/**\n * Whether a task has work of its own on the integration branch, this attempt's\n * or an earlier one's. A retry, a failed spawn or a continue that conflicted\n * leaves a record that is not `merged`, or none, over merges still on the branch.\n */\nexport function landedWork(run: IsolationRun | null, taskId: string): boolean {\n const record = run?.tasks[taskId];\n return run?.landings?.[taskId] !== undefined || isCarried(run, taskId) || (record?.status === 'merged' && Object.values(record.repos).some((r) => r.changed));\n}\n\n/** Whether a task of a run that did not keep its merges from the start can have landed in an attempt no record speaks for: nothing says it did not. */\nexport function mayHaveLanded(run: IsolationRun | null, task: Readonly<Task>): boolean {\n const record = run?.tasks[task.id];\n return !run?.keepsEveryLanding && !landedWork(run, task.id) && task.type === 'ai' && !task.ops && !record?.readOnly && (task.attempted === true || record !== undefined);\n}\n\n/** A task that landed and left the plan with no record of what it depended on, or of what to call it: whether it stands on the work nothing can say. */\nexport function unreadLanding(run: IsolationRun | null, planned: ReadonlySet<string>): string | undefined {\n if (!run) return undefined;\n const landed = [...Object.keys(run.landings ?? {}), ...Object.keys(run.carried ?? {}), ...Object.keys(run.tasks)].filter((id) => !planned.has(id) && landedWork(run, id));\n const unread = landed.find((id) => !run.landedOn?.[id] || !landedTaskOf(run, id));\n return unread === undefined ? undefined : landedTitleOf(run, unread);\n}\n\n/**\n * The title of another task recorded as landed by the same merge. No landing\n * makes one for two tasks: a run saved when a landing recorded the branch's tip\n * whether or not it had moved can say so, and reverting that merge would take\n * the work of whichever task really made it (ADR-0054).\n */\nexport function alsoLandedBy(run: IsolationRun, repoPath: string, taskId: string, merge: string): string | undefined {\n const ids = new Set([...Object.keys(run.tasks), ...Object.keys(run.landings ?? {})]);\n const other = [...ids].find((id) => id !== taskId && landingsOf(run, id, repoPath).includes(merge));\n return other === undefined ? undefined : landedTitleOf(run, other);\n}\n\n/**\n * Landed work a revert can undo (ADR-0054): a merge of its own in every repo it\n * changed, none of it in the user's branch yet, and nothing of it carried in by\n * a resolver. A task at work again keeps its mark off, and a revert would refuse\n * it. A run with no `carried` record, or none given, offers nothing: every\n * revert of such a run is refused.\n */\nexport function marksRevertible(record: IsolationTaskRecord, run?: Pick<IsolationRun, 'landings' | 'carried'>): boolean {\n if (record.inHead || record.status === 'active' || record.status === 'repairing' || !run?.carried || run.carried[record.taskId]) return false;\n const landings = run.landings?.[record.taskId];\n const changed = record.status === 'merged' ? Object.entries(record.repos).filter(([, r]) => r.changed).map(([repoPath]) => repoPath) : [];\n return (changed.length > 0 || landings !== undefined) && changed.every((repo) => record.repos[repo].landedTip || landings?.[repo]);\n}\n\n/** The tasks with merges on the branch and no record left, a retry having dropped it, that a revert can still take. */\nexport function recordlessRevertible(run: IsolationRun): string[] {\n return Object.keys(run.landings ?? {}).filter((taskId) => run.carried && !run.carried[taskId]);\n}\n\n/** What a task depends on in the plan, a check counting on its body as it does at a merge gate (ADR-0045 L9). */\nconst dependenciesOf = (task: Readonly<Task>): string[] => [...task.dependencies, ...task.loop?.body ?? []];\n\n/** What a task depends on, directly or not, for {@link keepLandedOn} to keep as it is cut and as it lands. */\nexport function landedOnOf(taskId: string, tasks: readonly Readonly<Task>[]): string[] {\n const found = new Set<string>();\n const queue = [taskId];\n for (let id = queue.shift(); id !== undefined; id = queue.shift()) {\n const task = tasks.find((t) => t.id === id);\n for (const dependency of task ? dependenciesOf(task) : []) {\n if (found.has(dependency)) continue;\n found.add(dependency);\n queue.push(dependency);\n }\n }\n return [...found];\n}\n\n/** Everything that depends on the task, directly or not, by the plan or by what the ledger kept: the plan lets go of a task that leaves it, and of what stood on it through that task. */\nexport function dependentsOf(tasks: readonly Readonly<Task>[], run: IsolationRun | null, taskId: string): Set<string> {\n const edges = new Map(tasks.map((t) => [t.id, dependenciesOf(t)]));\n for (const [id, landedOn] of Object.entries(run?.landedOn ?? {})) edges.set(id, [...edges.get(id) ?? [], ...landedOn]);\n const found = new Set<string>([taskId]);\n const queue = [taskId];\n for (let id = queue.shift(); id !== undefined; id = queue.shift()) {\n for (const [other, dependencies] of edges) {\n if (found.has(other) || !dependencies.includes(id)) continue;\n found.add(other);\n queue.push(other);\n }\n }\n found.delete(taskId);\n return found;\n}\n\n/** The tasks a revert of this one stands to change the ground of, landed or not: no start of one may be claimed while it runs. */\nexport function revertReach(taskId: string, tasks: readonly Readonly<Task>[], run: IsolationRun | null): ReadonlySet<string> {\n return new Set([taskId, ...dependentsOf(tasks, run, taskId)]);\n}\n\nconst landedTask = ({ taskId, order, title, commit }: LandedTask): LandedTask => ({ taskId, order, title, ...(commit ? { commit } : {}) });\n\n/** A task's merges, by repo, as its landing went through: each repo's tip on the record and kept in the ledger once, newest last. */\nexport function recordLanding(run: IsolationRun, record: IsolationTaskRecord, tips: readonly (readonly [repoPath: string, merge: string])[]): void {\n for (const [repoPath, tip] of tips) {\n const entry = record.repos[repoPath];\n if (entry) entry.landedTip = tip;\n ((run.landings ??= {})[record.taskId] ??= {})[repoPath] = [...landingsOf(run, record.taskId, repoPath).filter((merge) => merge !== tip), tip];\n (run.landedTasks ??= {})[record.taskId] = landedTask(record);\n }\n}\n\n/**\n * Tips of tasks yet to land that a landing's merges brought in. A run that\n * started without the record never gets one: it would miss what landed before\n * it, and its absence is what refuses a revert (ADR-0054).\n */\nexport function recordCarried(run: IsolationRun, carried: readonly { record: LandedTask; repoPath: string; tip: string }[]): void {\n if (!run.carried) return;\n for (const { record, repoPath, tip } of carried) {\n const tips = (run.carried[record.taskId] ??= {});\n tips[repoPath] = [...tips[repoPath] ?? [], tip];\n (run.landedTasks ??= {})[record.taskId] = landedTask(record);\n }\n}\n\n/** What a task depends on, added to what it ever did: a plan edit takes a link off while its worktree stays cut from the work (ADR-0054). */\nexport function keepLandedOn(run: IsolationRun, taskId: string, dependsOn: readonly string[]): void {\n (run.landedOn ??= {})[taskId] = [...new Set([...run.landedOn?.[taskId] ?? [], ...dependsOn])];\n}\n\n/**\n * The tasks a revert took back, all in one step with no await between: a\n * landed record goes; a later attempt's that never landed stays, `kept`, for\n * the worktree only it names, its conflict over and nothing to repair or land;\n * the ledger lets go of each; and the run is marked as reverted.\n */\nexport function forgetReverted(run: IsolationRun, taskIds: readonly string[]): void {\n for (const taskId of taskIds) {\n const record = run.tasks[taskId];\n if (record?.status === 'merged') delete run.tasks[taskId];\n else if (record?.status === 'conflict') {\n record.status = 'kept';\n delete record.repairBase;\n delete record.conflictRepo;\n delete record.conflictFiles;\n }\n delete run.landings?.[taskId];\n delete run.landedTasks?.[taskId];\n delete run.landedOn?.[taskId];\n }\n run.reverted = true;\n}\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';\nimport { marksRevertible, mergedIn, recordlessRevertible } from './LandingLedger';\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, run?: Pick<IsolationRun, 'landings' | 'carried'>): 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 ...(marksRevertible(record, run) ? { revertible: true as const } : {}),\n };\n}\n\n/**\n * Every task's mark in a run. A task with merges on the branch and no record\n * left, a retry having dropped it, has no state to show and can still be\n * reverted. A status this build does not know is its own mark-less task, not a\n * crash: a newer daemon may have written one.\n */\nexport function taskIsolationsOf(run: IsolationRun, repairLimit?: number): Record<string, TaskIsolation> {\n const tasks: Record<string, TaskIsolation> = {};\n for (const taskId of recordlessRevertible(run)) tasks[taskId] = { state: 'none', revertible: true };\n for (const [taskId, record] of Object.entries(run.tasks)) {\n if (isKnownStatus(record.status)) tasks[taskId] = taskIsolationOf(record, repairLimit, run);\n }\n return tasks;\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) => mergedIn(run, r, repo.path)).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 return { tasks: taskIsolationsOf(run, repairLimit), handoff: handoffOf(run) };\n}\n","/** How the runner says this session is paid for; absent means it has not said. */\nexport interface SessionBilling {\n type: 'subscription' | 'api-key';\n plan?: string;\n}\n\nexport interface CostProvenance {\n kind: 'estimate' | 'billed' | 'unknown';\n billing: SessionBilling['type'] | 'unknown' | 'mixed';\n basis?: 'list' | 'managed';\n}\n\n/**\n * What one model call consumed, as its provider or runner reported it. Shared\n * by the planner's usage line (#49) and per-attempt task usage (#26): a record\n * says nothing about who asked for the call, so either can hold a list of them.\n *\n * Every measure is optional because backends report different subsets. An\n * absent field means \"not reported\" — never zero — so a total can tell the two\n * apart.\n */\nexport interface UsageRecord {\n /** The provider or runner id that reported the call — `openai`, `claude-code`, … */\n source: string;\n model?: string;\n /** A session breakdown can name a model without identifying the current context. */\n aggregate?: true;\n /**\n * What a call outside the agent's own turns was for — OpenCode's `title`,\n * `compaction` or `generate` calls, which it bills but does not put in a\n * step. A model's totals keep them apart, so a bill that includes them can\n * be read against the turns.\n */\n purpose?: string;\n inputTokens?: number;\n outputTokens?: number;\n /** The share of `inputTokens` served from the provider's prompt cache. */\n cachedInputTokens?: number;\n /**\n * Filled only from a provider's or runner's own report, never from a price\n * table kept in Ordewell: prices go stale, and a subscription runner has no\n * per-token price at all. No report means no cost, not a guessed one.\n */\n reportedCost?: { amount: number; currency: string; kind?: 'estimate' | 'billed'; basis?: 'list' | 'managed' };\n sessionBilling?: SessionBilling;\n /**\n * The model's context window: as the runner or provider reported it, or,\n * when it reported none, from that runner's or provider's own model listing\n * (`ContextWindowFill`). Never from a table kept in Ordewell.\n */\n contextWindow?: number;\n /**\n * What the main model's context holds once this call is done, counted the\n * way its runner's own UI counts it, so the meter reads what the user would\n * see there. Runners differ, and no sum of the measures above can tell.\n * A measure of the meter only: no total adds it. Absent, the meter reads the\n * prompt.\n */\n contextTokens?: number;\n /**\n * The runner reset the main model's context outside a call — a compaction,\n * or a `/clear`: no call, so the record measures nothing but `contextTokens`,\n * the size it reported the context left at, if it did. It may name the model\n * the new context belongs to; a record that names none is about whichever\n * runs now.\n */\n compacted?: true;\n /** Set when a subagent made the call; its usage still counts toward the total. */\n subagentId?: string;\n}\n\n/** A model's window as its reporter stated it: what a plan saves of its session's windows (`SessionWindows`). */\nexport interface ReportedWindow {\n source: string;\n model: string;\n contextWindow: number;\n}\n\n/**\n * A running sum of {@link UsageRecord}s. A measure stays absent until some\n * record reports it. Cost is kept per currency: two runners may bill in\n * different ones, and there is no honest exchange rate to fold them together.\n */\nexport interface UsageTotals {\n inputTokens?: number;\n outputTokens?: number;\n cachedInputTokens?: number;\n reportedCost?: Record<string, number>;\n costProvenance?: Record<string, CostProvenance>;\n}\n\n/**\n * The input side of a call whose provider reports its prompt in parts — the\n * uncached tail, with cache reads and cache writes beside it rather than inside\n * it (Anthropic, and OpenCode after it). The prompt the model saw is all three;\n * only the reads were served from cache, since a write is billed as fresh\n * input. A part left unreported adds nothing, and with no part reported there\n * is no measure at all.\n */\nexport function partedPromptUsage(parts: { uncached?: number; cacheRead?: number; cacheWrite?: number }): Pick<UsageRecord, 'inputTokens' | 'cachedInputTokens'> {\n const reported = [parts.uncached, parts.cacheRead, parts.cacheWrite].filter((n): n is number => n !== undefined);\n return {\n ...(reported.length > 0 ? { inputTokens: reported.reduce((a, b) => a + b, 0) } : {}),\n ...(parts.cacheRead !== undefined ? { cachedInputTokens: parts.cacheRead } : {}),\n };\n}\n\nconst TOKEN_FIELDS = ['inputTokens', 'outputTokens', 'cachedInputTokens'] as const;\n\n/**\n * What a budget counts (ADR-0056 M5), of a record or of totals alike: the same\n * tokens a total holds, input and output. `cachedInputTokens` is a share of the\n * input, so cache reads count, once.\n */\nexport function spentTokens({ inputTokens, outputTokens }: Pick<UsageTotals, 'inputTokens' | 'outputTokens'>): number {\n return (inputTokens ?? 0) + (outputTokens ?? 0);\n}\n\nexport function addUsage(totals: UsageTotals, record: UsageRecord): UsageTotals {\n const next: UsageTotals = { ...totals };\n for (const field of TOKEN_FIELDS) {\n const reported = record[field];\n if (reported !== undefined) next[field] = (totals[field] ?? 0) + reported;\n }\n if (record.reportedCost) {\n const { amount, currency } = record.reportedCost;\n const provenance: CostProvenance | undefined = record.reportedCost.kind || record.sessionBilling ? {\n kind: record.reportedCost.kind ?? 'unknown', billing: record.sessionBilling?.type ?? 'unknown',\n ...(record.reportedCost.basis ? { basis: record.reportedCost.basis } : {}),\n } : undefined;\n addCost(next, currency, amount, provenance);\n }\n return next;\n}\n\nfunction addCost(totals: UsageTotals, currency: string, amount: number, provenance?: CostProvenance): void {\n const hadCost = totals.reportedCost?.[currency] !== undefined;\n const previous = totals.costProvenance?.[currency];\n totals.reportedCost = { ...totals.reportedCost, [currency]: (totals.reportedCost?.[currency] ?? 0) + amount };\n if (!previous && !provenance) return;\n const unknown: CostProvenance = { kind: 'unknown', billing: 'unknown' };\n const a = previous ?? unknown;\n const b = provenance ?? unknown;\n const merged: CostProvenance = !hadCost ? b : {\n kind: a.kind === 'estimate' || b.kind === 'estimate' ? 'estimate' : a.kind === 'billed' && b.kind === 'billed' ? 'billed' : 'unknown',\n billing: a.billing === b.billing ? a.billing : 'mixed',\n ...(a.basis && a.basis === b.basis ? { basis: a.basis } : {}),\n };\n totals.costProvenance = { ...totals.costProvenance, [currency]: merged };\n}\n\n/**\n * What the planner has consumed over a session (#49). `totals` includes every\n * `bySubagent` entry. `lastPromptTokens` and `contextWindow` track the\n * planner's own calls only — a subagent runs its own model, whose window says\n * nothing about the planner's. `lastPromptTokens` is the context the last call\n * left (its `contextTokens`, else its prompt), under the name saved sessions\n * already hold it by.\n */\nexport interface PlannerUsage {\n sessionBilling?: SessionBilling;\n totals: UsageTotals;\n bySubagent?: Record<string, UsageTotals>;\n byModel?: ModelUsage[];\n source?: string;\n model?: string;\n lastPromptTokens?: number;\n contextWindow?: number;\n}\n\nexport function addPlannerUsage(usage: PlannerUsage, record: UsageRecord): PlannerUsage {\n // The size before a compaction is gone, so the meter shows the size after\n // or none until the next call — never the old one, which reads as full. The\n // record may name the model the new context now belongs to: that is a switch\n // of its own, and the old model's window does not measure it.\n if (record.compacted) {\n // A subagent's compaction says nothing about the main model, and a\n // breakdown measures no prompt of its own.\n if (record.subagentId || record.aggregate) return usage;\n const next: PlannerUsage = { ...usage };\n if (record.source !== undefined) next.source = record.source;\n if (record.model !== undefined) {\n if (record.source !== usage.source || record.model !== usage.model) delete next.contextWindow;\n next.model = record.model;\n }\n if (record.contextTokens !== undefined) next.lastPromptTokens = record.contextTokens;\n else delete next.lastPromptTokens;\n if (record.contextWindow !== undefined) next.contextWindow = record.contextWindow > 0 ? record.contextWindow : undefined;\n return next;\n }\n if (record.sessionBilling && !record.reportedCost && record.inputTokens === undefined && record.outputTokens === undefined && record.cachedInputTokens === undefined && record.contextWindow === undefined) {\n // The fact belongs to the source that stated it: kept with no source, it\n // would be lent to whichever backend reports a cost next.\n return record.subagentId ? usage : { ...usage, sessionBilling: record.sessionBilling, source: record.source };\n }\n record = { ...record, sessionBilling: record.sessionBilling ?? (usage.source === undefined || record.source === usage.source ? usage.sessionBilling : undefined) };\n const next: PlannerUsage = { ...usage, ...(!record.subagentId && record.sessionBilling ? { sessionBilling: record.sessionBilling } : {}), totals: addUsage(usage.totals, record), byModel: addModelUsage(usage.byModel ?? [], record) };\n if (record.subagentId) {\n next.bySubagent = { ...usage.bySubagent, [record.subagentId]: addUsage(usage.bySubagent?.[record.subagentId] ?? {}, record) };\n return next;\n }\n // A session breakdown names a model without measuring any call's prompt, so\n // it never moves the meter. It still comes from a source, though: a billing\n // fact belonging to another backend does not outlive it.\n if (record.aggregate) {\n if (record.source !== usage.source && !record.sessionBilling) delete next.sessionBilling;\n return next;\n }\n if (record.source !== usage.source || record.model !== usage.model) {\n delete next.lastPromptTokens;\n delete next.contextWindow;\n }\n if (record.source !== usage.source && !record.sessionBilling) delete next.sessionBilling;\n next.source = record.source;\n next.model = record.model;\n const used = record.contextTokens ?? record.inputTokens;\n if (used !== undefined) next.lastPromptTokens = used;\n // A reported window of 0 means \"not known\", not \"no room\": keep it out so the\n // meter shows no share rather than one against a guessed zero.\n if (record.contextWindow !== undefined) next.contextWindow = record.contextWindow > 0 ? record.contextWindow : undefined;\n return next;\n}\n\n/** Whether any measure was reported: a usage line of nothing but blanks says nothing. */\nexport function isMeasured(totals: UsageTotals): boolean {\n return totals.inputTokens !== undefined || totals.outputTokens !== undefined || totals.cachedInputTokens !== undefined\n || Object.keys(totals.reportedCost ?? {}).length > 0;\n}\n\n/**\n * The main model's context: what its last call left in it, against its window\n * when that is known. A window of 0 is not known.\n */\nexport interface ContextFill {\n usedTokens: number;\n windowTokens?: number;\n /**\n * Why an API planner's automatic compaction (ADR-0002) is not running for\n * its model, as it stood when the meter was sent: the settings file turns it\n * off, or no catalog states the model's window. Absent while it runs, and on\n * a harness planner, whose agent compacts its own context.\n */\n autoCompaction?: { off: 'settings' } | { off: 'unknown_window'; model: string };\n}\n\n/** What the usage line draws of a ledger — live from its broadcast, or reloaded from the saved one. */\nexport interface UsageLine {\n sessionBilling?: SessionBilling;\n byModel?: ModelUsage[];\n model?: string;\n totals: UsageTotals;\n bySubagent?: Record<string, UsageTotals>;\n contextFill?: ContextFill;\n}\n\nexport function usageLine(usage: PlannerUsage): UsageLine {\n const contextFill = plannerContextFill(usage);\n return {\n totals: usage.totals,\n ...(usage.sessionBilling ? { sessionBilling: usage.sessionBilling } : {}),\n ...(usage.byModel ? { byModel: usage.byModel } : {}),\n ...(usage.model ? { model: usage.model } : {}),\n ...(usage.bySubagent ? { bySubagent: usage.bySubagent } : {}),\n ...(contextFill ? { contextFill } : {}),\n };\n}\n\n/**\n * The main model's context as its last call left it, or undefined before one\n * was measured and after a compaction that reported no size. `usedTokens` is\n * what that call stated as its context, else its prompt total, cached tokens\n * included: a cached token still occupies the window, so subtracting the\n * cached share would understate how full the context is. The window rides\n * along only when known; a window of 0 is treated as unknown — never guessed.\n */\nexport function plannerContextFill(usage: PlannerUsage): ContextFill | undefined {\n if (usage.lastPromptTokens === undefined) return undefined;\n return { usedTokens: usage.lastPromptTokens, ...(usage.contextWindow !== undefined && usage.contextWindow > 0 ? { windowTokens: usage.contextWindow } : {}) };\n}\n\nexport interface ModelUsage {\n source: string;\n model?: string;\n /** Set on the row of calls made outside the agent's own turns ({@link UsageRecord.purpose}). */\n purpose?: string;\n totals: UsageTotals;\n}\n\nexport function addModelUsage(models: readonly ModelUsage[], record: UsageRecord): ModelUsage[] {\n const index = models.findIndex((m) => m.source === record.source && m.model === record.model && m.purpose === record.purpose);\n if (index < 0) return [...models, { source: record.source, ...(record.model ? { model: record.model } : {}), ...(record.purpose ? { purpose: record.purpose } : {}), totals: addUsage({}, record) }];\n return models.map((m, i) => i === index ? { ...m, totals: addUsage(m.totals, record) } : m);\n}\n\n/**\n * What Ordewell has counted of a runner's own session that reports its cost\n * as a running total: that total and each model's share, in USD, as of its\n * last report. A resume of that session counts its first report's growth\n * over this; with no count kept for it, that report only sets the baseline.\n */\nexport interface RunnerSessionCost {\n sessionId: string;\n usd: number;\n modelUsd: Record<string, number>;\n}\n\nexport interface AttemptUsage extends PlannerUsage {\n attempt: number;\n runner: string;\n /** The runner session this attempt ran in, as its runner reported it: what a later Continue of it resumes. */\n sessionId?: string;\n startedAt: string;\n endedAt?: string;\n wallTimeMs: number;\n /**\n * Of its wall time, what it spent running: a wait on a person (input, a\n * checkpoint, an approval) left out (ADR-0018 W1). Absent on an attempt\n * saved before it was kept, and on one that never had a clock.\n */\n runningMs?: number;\n /** What was counted of its runner session's running cost as it ended: a continue of that session counts on from it. */\n runnerSessionCost?: RunnerSessionCost;\n}\n\nexport function startAttemptUsage(attempt: number, runner: string, startedAt: string): AttemptUsage {\n return { attempt, runner, startedAt, wallTimeMs: 0, totals: {}, byModel: [] };\n}\n\n/** What its runner reports as it winds down after the attempt ended is added without moving its end. */\nexport function addAttemptUsage(usage: AttemptUsage, record: UsageRecord, now: string): AttemptUsage {\n const folded = addPlannerUsage(usage, record);\n return { ...usage, ...folded, lastPromptTokens: folded.lastPromptTokens, contextWindow: folded.contextWindow, wallTimeMs: Math.max(0, Date.parse(usage.endedAt ?? now) - Date.parse(usage.startedAt)) };\n}\n\n/** An attempt ends once; ended again once its runner wound down, it only takes the count that runner ended on. */\nexport function endAttemptUsage(usage: AttemptUsage, now: string, runnerSessionCost?: RunnerSessionCost, sessionId?: string, runningMs?: number): AttemptUsage {\n const endedAt = usage.endedAt ?? now;\n return {\n ...usage,\n endedAt,\n wallTimeMs: Math.max(0, Date.parse(endedAt) - Date.parse(usage.startedAt)),\n ...(usage.runningMs === undefined && runningMs !== undefined ? { runningMs } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(runnerSessionCost ? { runnerSessionCost } : {}),\n };\n}\n\n/** The count a continue of `sessionId` starts from: the one its latest attempt in that session ended with. */\nexport function countedSessionCost(attempts: readonly AttemptUsage[] | undefined, sessionId: string): RunnerSessionCost | undefined {\n return [...attempts ?? []].reverse().find((usage) => usage.runnerSessionCost?.sessionId === sessionId)?.runnerSessionCost;\n}\n\n/**\n * The model a continue's session last ran on and the window it was measured\n * against: the latest earlier attempt of that same runner session that\n * reported one. An attempt that measured nothing is skipped — a continuation\n * does not undo what its session was last measured against — and a window is\n * never borrowed from another session: a fresh attempt starts one.\n */\nexport function resumedSessionWindow(attempts: readonly AttemptUsage[] | undefined, runner: string, attempt: number, sessionId: string): Pick<PlannerUsage, 'source' | 'model' | 'contextWindow'> | undefined {\n const last = [...attempts ?? []].reverse().find((usage) => usage.attempt !== attempt && usage.runner === runner && usage.sessionId === sessionId && usage.contextWindow !== undefined);\n return last ? { source: last.source, model: last.model, contextWindow: last.contextWindow } : undefined;\n}\n\nexport interface PlanUsage {\n totals: UsageTotals;\n byModel: ModelUsage[];\n wallTimeMs: number;\n attempts: number;\n}\n\nexport function addUsageTotals(totals: UsageTotals, addition: UsageTotals): UsageTotals {\n const next = addUsage(totals, { source: '', inputTokens: addition.inputTokens, outputTokens: addition.outputTokens, cachedInputTokens: addition.cachedInputTokens });\n for (const [currency, amount] of Object.entries(addition.reportedCost ?? {})) addCost(next, currency, amount, addition.costProvenance?.[currency]);\n return next;\n}\n\ninterface UsageTask { type?: string; attemptUsage?: readonly AttemptUsage[]; subtasks?: readonly UsageTask[] }\n\nexport function planUsage(tasks: readonly UsageTask[]): PlanUsage {\n const result: PlanUsage = { totals: {}, byModel: [], wallTimeMs: 0, attempts: 0 };\n for (const task of tasks) {\n const child = planUsage(task.subtasks ?? []);\n result.totals = addUsageTotals(result.totals, child.totals);\n result.wallTimeMs += child.wallTimeMs;\n result.attempts += child.attempts;\n const models = [...child.byModel];\n for (const usage of task.attemptUsage ?? []) {\n result.totals = addUsageTotals(result.totals, usage.totals);\n result.wallTimeMs += usage.wallTimeMs;\n result.attempts++;\n models.push(...usage.byModel ?? []);\n }\n for (const model of models) {\n const existing = result.byModel.find((m) => m.source === model.source && m.model === model.model && m.purpose === model.purpose);\n if (existing) existing.totals = addUsageTotals(existing.totals, model.totals);\n else result.byModel.push({ ...model, totals: addUsageTotals({}, model.totals) });\n }\n }\n return result;\n}\n\n/**\n * What one task spent across every attempt and every model it ran on, so a\n * stop, a model change and a continue never makes the earlier spend vanish. The\n * context meter is the exception: it reads the latest attempt, because only the\n * current model's window says how full the next prompt is.\n */\nexport interface TaskUsageSummary {\n totals: UsageTotals;\n attempts: number;\n contextFill?: ContextFill;\n}\n\nexport function taskUsageSummary(task: Pick<UsageTask, 'attemptUsage' | 'type'>): TaskUsageSummary {\n const attempts = task.attemptUsage ?? [];\n const latest = attempts.at(-1);\n // A delegated task's usage is its whole subtree's (ADR-0055 D20): no one session's context, so it has no meter.\n const contextFill = latest && task.type !== 'delegated' ? plannerContextFill(latest) : undefined;\n return {\n totals: attempts.reduce((sum, attempt) => addUsageTotals(sum, attempt.totals), {} as UsageTotals),\n attempts: attempts.length,\n ...(contextFill ? { contextFill } : {}),\n };\n}\n\n// ── The text surfaces draw ───────────────────────────────────────────────────\n// Surfaces draw the main model's context and the money its runner reported,\n// never a token count, and word them here so none can disagree (ADR-0017 U1).\n\n/** `950`, `1.5k`, `61k`, `261k`, `1.2M`. */\nexport function formatTokenCount(n: number): string {\n if (n < 1000) return String(n);\n if (n < 10_000) return `${(n / 1000).toFixed(1).replace(/\\.0$/, '')}k`;\n if (n < 999_500) return `${Math.round(n / 1000)}k`;\n return `${(n / 1_000_000).toFixed(1).replace(/\\.0$/, '')}M`;\n}\n\n/** Two decimals from 1 up and up to four below it: a call can cost a fraction of a cent, a session several dollars. */\nexport function formatCost(currency: string, amount: number): string {\n const value = amount >= 1 ? amount.toFixed(2) : (([whole, frac = '']) => `${whole}.${frac.padEnd(2, '0')}`)(amount.toFixed(4).replace(/0+$/, '').split('.'));\n return currency.toLowerCase() === 'usd' ? `$${value}` : `${value} ${currency.toUpperCase()}`;\n}\n\n/** `ctx 61k (6%)`, `ctx 61k` while the window is unknown, nothing before a call was measured; `· no auto-compact` when automatic compaction is not running. */\nexport function contextMeterText(fill: ContextFill | undefined): string | null {\n if (!fill) return null;\n const used = `ctx ${formatTokenCount(fill.usedTokens)}`;\n const share = fill.windowTokens ? fill.usedTokens / fill.windowTokens * 100 : undefined;\n const meter = share === undefined ? used : `${used} (${share < 1 ? '<1' : Math.round(share)}%)`;\n return fill.autoCompaction ? `${meter} · no auto-compact` : meter;\n}\n\n/** Exact counts for the meter's hover, and why automatic compaction is not running, where it is not. */\nexport function contextMeterTitle(fill: ContextFill): string {\n const used = fill.usedTokens.toLocaleString('en-US');\n const counts = fill.windowTokens ? `${used} of ${fill.windowTokens.toLocaleString('en-US')} tokens` : `${used} tokens`;\n const off = fill.autoCompaction;\n if (!off) return counts;\n const why = off.off === 'settings'\n ? 'Automatic compaction is off in the settings file'\n : off.model\n ? `Automatic compaction is off: no catalog Ordewell holds states ${off.model}'s window`\n : 'Automatic compaction is off: no planner model is selected';\n return `${counts}. ${why}; /compact still condenses the conversation.`;\n}\n\n/** USD first, then the others by code, so a sum reads the same whichever attempt reported first. */\nfunction costParts(totals: UsageTotals): string[] {\n const rank = (currency: string): string => (currency.toLowerCase() === 'usd' ? '' : currency.toUpperCase());\n return Object.entries(totals.reportedCost ?? {}).sort(([a], [b]) => rank(a).localeCompare(rank(b))).map(([currency, amount]) => {\n const provenance = totals.costProvenance?.[currency];\n const equivalent = provenance?.billing === 'subscription';\n return `${provenance?.kind === 'estimate' || equivalent ? '≈' : ''}${formatCost(currency, amount)}${equivalent ? ' API-equivalent' : ''}`;\n });\n}\n\n/** The cost per currency as reported, joined by ` · `; null when none was reported. */\nexport function costText(totals: UsageTotals): string | null {\n const parts = costParts(totals);\n return parts.length > 0 ? parts.join(' · ') : null;\n}\n\n/** The meter, then the cost, joined by ` · `; null when neither is known. */\nexport function usageText(usage: { totals: UsageTotals; contextFill?: ContextFill }): string | null {\n const parts = [contextMeterText(usage.contextFill), costText(usage.totals)].filter((p): p is string => p !== null);\n return parts.length > 0 ? parts.join(' · ') : null;\n}\n\n/** Each runner/model's reported cost for the cost's hover, leaving out models with none. */\nexport function modelCostTitle(byModel: readonly ModelUsage[]): string | undefined {\n const lines = byModel.flatMap((m) => {\n const cost = costParts(m.totals);\n const descriptions = [...new Set(Object.values(m.totals.costProvenance ?? {}).map((p) => {\n const source = m.source === 'claude-code' ? 'Claude Code' : m.source === 'opencode' ? 'OpenCode' : m.source === 'openrouter' ? 'OpenRouter' : m.source;\n const basis = p.basis === 'list' ? ' at list price' : p.basis === 'managed' ? ' at managed price' : '';\n const kind = p.kind === 'estimate' ? `${source}'s estimate${basis}` : p.kind === 'billed' ? `Amount billed by ${source}` : 'Reported cost';\n return `${kind}${p.billing === 'subscription' ? '; not billed on a subscription' : ''}`;\n }))];\n return cost.length > 0 ? [`${m.source} / ${m.model ?? 'unattributed'}${m.purpose ? ` (${m.purpose})` : ''}: ${cost.join(' · ')}${descriptions.length ? ` — ${descriptions.join('; ')}` : ''}`] : [];\n });\n return lines.length > 0 ? lines.join('\\n') : undefined;\n}\n\n/** Each subagent's reported cost for the subagent count's hover, or that it reported none. */\nexport function subagentCostTitle(bySubagent: Readonly<Record<string, UsageTotals>>): string {\n return Object.entries(bySubagent)\n .map(([id, totals]) => `${id}: ${costParts(totals).join(' · ') || 'reported no cost'}`)\n .join('\\n');\n}\n\nfunction runnersOf(tasks: readonly UsageTask[]): AttemptUsage[] {\n return tasks.flatMap((task) => [...task.attemptUsage ?? [], ...runnersOf(task.subtasks ?? [])]);\n}\n\n/**\n * `Tasks total: $3.20 · codex reports no cost`: the cost over every attempt,\n * then the runners none of whose attempts reported one — codex reports no\n * price, and a price table is not Ordewell's to keep (ADR-0017 U1). A runner is\n * named only once an attempt of it has ended having reported usage: Claude\n * Code states a cost only on a turn's last line, so a first attempt still in\n * its turn has not said yet, and one that never ran said nothing. A total has\n * no meter: each task's own model holds its own window.\n */\nexport function tasksTotalText(tasks: readonly UsageTask[]): string | null {\n const attempts = runnersOf(tasks);\n if (attempts.length === 0) return null;\n const costed = (a: AttemptUsage): boolean => Object.keys(a.totals.reportedCost ?? {}).length > 0;\n const costless = [...new Set(attempts.filter((a) => a.endedAt !== undefined && isMeasured(a.totals)).map((a) => a.runner))]\n .filter((runner) => !attempts.some((a) => a.runner === runner && costed(a)));\n const note = costless.length === 0 ? [] : [`${costless.length === 1 ? costless[0] : `${costless.slice(0, -1).join(', ')} and ${costless.at(-1)}`} ${costless.length === 1 ? 'reports' : 'report'} no cost`];\n const parts = [...costParts(planUsage(tasks).totals), ...note];\n return parts.length > 0 ? `Tasks total: ${parts.join(' · ')}` : null;\n}\n","import type { Task, TaskType } from './Task';\n\ntype Field = keyof Task | 'thinkingEffort';\n\ninterface KindRules {\n forbidden: readonly Field[];\n plannerEditForbidden: readonly Field[];\n leaving: readonly (keyof Task)[];\n entering: readonly (keyof Task)[];\n topLevelOnly: boolean;\n mayHaveSubtasks: boolean;\n runsInMode: boolean;\n hasRunner: boolean;\n mayBeOps: boolean;\n mayBeResearch: boolean;\n}\n\nconst PLANNER_EDIT_FIELDS = ['readOnly', 'thinkingEffort'] as const;\n\nconst AI_ASSIGNMENT = ['assignedModel', 'taskMode', 'autonomy', 'ops'] as const;\n\n// ADR-0035 and ADR-0055 D1: a script's body and a child's goal are not runner prompts.\nexport const TASK_KINDS = {\n ai: { forbidden: [], plannerEditForbidden: [], leaving: ['research'], entering: ['userSteps'], topLevelOnly: false, mayHaveSubtasks: true, runsInMode: true, hasRunner: true, mayBeOps: true, mayBeResearch: true },\n user: { forbidden: [], plannerEditForbidden: [], leaving: [], entering: AI_ASSIGNMENT, topLevelOnly: false, mayHaveSubtasks: true, runsInMode: false, hasRunner: false, mayBeOps: false, mayBeResearch: false },\n script: {\n forbidden: ['assignedRunner', 'assignedModel', 'thinkingEffort', 'taskMode', 'readOnly', 'prompt', 'skills', 'userSteps', 'ops', 'subtasks'],\n plannerEditForbidden: PLANNER_EDIT_FIELDS,\n leaving: ['commands', 'script', 'timeoutMs'], entering: [...AI_ASSIGNMENT, 'prompt', 'skills', 'userSteps'],\n topLevelOnly: true, mayHaveSubtasks: false, runsInMode: false, hasRunner: false, mayBeOps: false, mayBeResearch: false,\n },\n delegated: {\n forbidden: ['prompt', 'taskMode', 'skills', 'userSteps', 'ops', 'commands', 'script', 'timeoutMs', 'research'],\n plannerEditForbidden: PLANNER_EDIT_FIELDS,\n leaving: [], entering: [],\n topLevelOnly: true, mayHaveSubtasks: false, runsInMode: false, hasRunner: true, mayBeOps: false, mayBeResearch: false,\n },\n} as const satisfies Record<TaskType, KindRules>;\n\nexport function forbiddenFields(kind: TaskType, boundary: 'task' | 'plannerEdit' = 'task'): readonly Field[] {\n return boundary === 'plannerEdit' ? TASK_KINDS[kind].plannerEditForbidden : TASK_KINDS[kind].forbidden;\n}\n\n/**\n * The forbidden fields a task or an edit holds, less those `ignored` (a\n * stored default, the read-only script exception). A `null` is a value it\n * holds, so it is refused as any other.\n */\nexport function presentForbiddenFields(kind: TaskType, fields: object, ignored: readonly Field[] = []): Field[] {\n return held(forbiddenFields(kind), fields, ignored, false);\n}\n\n/** The forbidden fields the planner's JSON wrote, where a `null` is how it leaves a field out. */\nexport function writtenForbiddenFields(kind: TaskType, raw: object, boundary: 'task' | 'plannerEdit' = 'task'): Field[] {\n return held(forbiddenFields(kind, boundary), raw, [], true);\n}\n\nfunction held(forbidden: readonly Field[], fields: object, ignored: readonly Field[], nullLeavesOut: boolean): Field[] {\n const raw = fields as Partial<Record<Field, unknown>>;\n return forbidden.filter((field) => {\n const value = raw[field];\n return !ignored.includes(field) && value !== undefined && !(nullLeavesOut && value === null) && value !== false\n && !(Array.isArray(value) && value.length === 0);\n });\n}\n\n/** Delegated tasks cannot flip: a child goal cannot become another kind of work (ADR-0055 D1). */\nexport function flipClears(from: TaskType, to: TaskType): (keyof Task)[] {\n if (from === to || from === 'delegated' || to === 'delegated') return [];\n return [...new Set<keyof Task>([...TASK_KINDS[from].leaving, ...TASK_KINDS[to].entering])];\n}\n\n/** Whether `value` names a kind: an edit's or a new task's `type` reaches core unchecked from the HTTP and MCP routes. */\nexport function isTaskType(value: unknown): value is TaskType {\n return typeof value === 'string' && Object.hasOwn(TASK_KINDS, value);\n}\n\n/** Why a `type` that names no kind is refused, after the task it was written for. */\nexport function unknownTypeRefusal(value: unknown): string {\n const kinds = taskKinds(false).map((kind) => `\"${kind}\"`);\n return `has \"type\" ${JSON.stringify(value)}, which is no kind of task: use ${kinds.slice(0, -1).join(', ')} or ${kinds.at(-1)}`;\n}\n\n/** Delegation changes the planner's vocabulary only when the session grants it (ADR-0055 D1). */\nexport function taskKinds(delegates: boolean): [TaskType, ...TaskType[]] {\n return (Object.keys(TASK_KINDS) as TaskType[]).filter((kind) => delegates || kind !== 'delegated') as [TaskType, ...TaskType[]];\n}\n","import { isTaskType, TASK_KINDS } from './TaskKind';\nimport { v4 as uuidv4 } from 'uuid';\nimport type { PlanIsolation } from '../interfaces/IWorktreeIsolation';\nimport type { AttemptUsage, PlannerUsage, ReportedWindow, RunnerSessionCost, 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 { legacySkipOrigin, type SkipOrigin } from './SkipOrigin';\nimport type { HandoffDigest } from './Handoff';\nimport type { DelegatedBudget, TaskScope } from './Delegation';\nimport { executionStateOf } from './TaskExecution';\nimport type { Grant } from '../services/Mandate';\nimport { SKILL_NAME_PATTERN } from '../conversation/skillTokens';\nimport { walkPlan } from '../services/PlanTree';\nimport { remove } from '../services/PlanGraph';\nimport { migratePlanStateIsolation } from '../services/isolationRecord';\nimport { interruptedVerdict } from '../services/VerdictEngine';\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' | 'protected_paths';\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, an attempt the host died in, a\n * 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/**\n * `script` is an ops task whose body Ordewell runs with no model (ADR-0035);\n * `delegated` holds a goal, and its attempt is a child plan (ADR-0055).\n */\nexport type TaskType = 'ai' | 'user' | 'script' | 'delegated';\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 because it conflicts (`conflict`) or because git refused to commit or\n * merge it for some other reason, such as no author identity (`landing-failed`),\n * an ops task that changed tracked files (ADR-0020), or its runner's usage\n * limit. Saved, so no surface has to guess it from whether an attempt is live.\n */\nexport type AwaitingReason = 'input' | 'checkpoint' | 'question-lost' | 'conflict' | 'landing-failed' | 'files-changed' | 'usage-limit';\n\nexport function isAwaitingReason(value: unknown): value is AwaitingReason {\n return value === 'input' || value === 'checkpoint' || value === 'question-lost' || value === 'conflict' || value === 'landing-failed' || 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 // A loop's own skip was told from a person's by its text; it now says so itself (ADR-0045 L7).\n const origin = legacySkipOrigin(task);\n if (origin) task.skipOrigin = origin;\n migrateLoadedTasks(task.subtasks ?? []);\n }\n}\n\n/**\n * Nothing is running when a plan comes off disk, so a task saved in progress\n * lost its attempt with the host that ran it. It is failed, in place, so the\n * inbox lists it and what depends on it waits (ADR-0053). Its attempts and\n * logs are left as they are. A delegated task parked at its subplanner's\n * question is no failure: it says the question is lost, and its child waits\n * to be continued (ADR-0055 D17).\n */\nexport function failInterruptedTasks(tasks: readonly Task[], now: string): void {\n for (const task of flattenTasks(tasks)) {\n if (task.type === 'delegated' && task.awaitingReason === 'checkpoint') task.awaitingReason = 'question-lost';\n if (task.status !== 'in_progress') continue;\n task.status = 'failed';\n task.verdict = interruptedVerdict(now);\n }\n}\n\n/**\n * A task an edit made manual has nothing to retry, and is the user's to do: one\n * failed, or waiting on the user with no runner to hear an answer, waits as a\n * manual task does (ADR-0053). A runner still at a question keeps it, and the\n * answer is still its to read, until it ends or the plan comes off disk.\n */\nexport function releaseMadeManual(tasks: readonly Task[], live: (taskId: string) => boolean = () => false): void {\n for (const task of flattenTasks(tasks)) {\n if (task.type !== 'user' || live(task.id) || (task.status !== 'failed' && task.status !== 'awaiting_user')) continue;\n task.status = 'pending';\n delete task.awaitingReason;\n delete task.resumeAt;\n }\n}\n\n/**\n * Nothing claims a repair when a plan comes off disk: what owed it went with\n * the host that saved it. So a task saved not started whose landing conflicted\n * is a conflict waiting on the user, in place, and the inbox lists it; the\n * next Execute still repairs it (ADR-0015, ADR-0053).\n */\nexport function settleOwedRepairs(plan: LegacyPlanState): void {\n const records = plan.isolation?.run.tasks;\n if (!records) return;\n for (const task of flattenTasks(plan.tasks)) {\n if ((task.status !== 'pending' && task.status !== 'approved') || records[task.id]?.status !== 'conflict') continue;\n task.status = 'awaiting_user';\n task.awaitingReason = 'conflict';\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 // An older direct edit could store a type no kind owns, or clear it, and\n // the kind table has no rules to read for one: it becomes \"ai\", as a type\n // the planner writes that no kind owns does.\n for (const task of flattenTasks(plan.tasks)) {\n if (!isTaskType(task.type)) task.type = 'ai';\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 /**\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 * The question a delegated task's subplanner is parked on (ADR-0056 M8). The\n * live one is held in memory by what answers it, so this copy is only what a\n * restart can still say was lost (ADR-0055 D17). Goes with the wait.\n */\n parkedQuestion?: string;\n /**\n * How many waits have ended since its latest attempt started, or since the\n * task was written if none has: an attempt can wait many times, and this\n * tells one wait from the next in an escalation's id (ADR-0053). Saved with\n * the plan, so the id holds across a reload. Absent counts as none.\n */\n waitsEnded?: number;\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 or a rearm.\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 * Who skipped it, set with `skipReason` and only while `status` is `skipped`.\n * A plan saved before this field has it only on a loop's own skips, which\n * loading gives it from their text ({@link migrateLoadedTasks}); any other\n * skip of such a plan has none, and reads as not the loop's.\n */\n skipOrigin?: SkipOrigin;\n /**\n * The user reverted its landed work (ADR-0054): saved with the plan, so the\n * hold that keeps it from running again outlives this process. Set only\n * while it waits as the revert left it: its next start clears it.\n */\n reverted?: true;\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 or re-armed.\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 /** What a delegated task's child plan must achieve, in place of a prompt (ADR-0055 D1). */\n goal?: string;\n /** A delegated task's budget (ADR-0056 M5). */\n budget?: DelegatedBudget;\n /** What a delegated task asks for past the floor; absent asks for nothing (ADR-0056 M2). */\n grants?: Grant[];\n /** The paths a delegated task's child may not change, what its check runs among them (ADR-0055 D7). */\n protectedPaths?: string[];\n /** What a delegated task declares it works on (ADR-0057 R6). */\n scope?: TaskScope;\n /**\n * On a delegated task, it answers a question and lands nothing (ADR-0055 D1).\n * On a script task, it runs sealed in a throwaway worktree, past no gate (D8).\n * A read-only AI task says so by its mode (ADR-0031) and stores none.\n */\n readOnly?: boolean;\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 | { actor: 'subplanner'; depth: number }\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 /** How many decision record entries the checkpoint's seed restates (ADR-0067); absent when it restated none. */\n record?: number;\n}\n\n/** What a decision record entry holds (ADR-0067): a choice, the user's own limit, a dropped option, or something still to settle. */\nexport const DECISION_RECORD_KINDS = ['decision', 'constraint', 'rejected', 'question'] as const;\nexport type DecisionRecordKind = typeof DECISION_RECORD_KINDS[number];\n\n/**\n * One entry in the planner's decision record (ADR-0067). The record is only\n * appended to: an entry that no longer stands is superseded by a later one\n * naming it, so the record as it was at any transcript point is a prefix.\n */\nexport interface DecisionRecordEntry {\n /** The kind's letter and its count within the kind: D1, C2, R1, Q3. */\n id: string;\n kind: DecisionRecordKind;\n /** A constraint's is the user's words, verbatim. */\n text: string;\n /** Why a decision was taken or an option rejected. */\n why?: string;\n /** The id of the entry this one replaces; a decision superseding a question answers it. */\n supersedes?: string;\n /** The transcript index of the user message whose turn recorded it, so a rewind before it drops it. */\n at: number;\n timestamp: string;\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/**\n * The timestamp of the planner's latest reply when it answers wake-ups alone\n * (ADR-0029): no message of the user's came with them or since, and no wake-up\n * is still unanswered. Host notices, calls at the seam, skill loads,\n * compactions and failed turns are no reply and no input, so they are passed over.\n */\nexport function wakeUpReply(history: readonly ConversationMessage[]): string | undefined {\n let reply: ConversationMessage | undefined;\n let woke = false;\n for (let i = history.length - 1; i >= 0; i--) {\n const entry = history[i];\n if (isUserMessage(entry)) return undefined;\n if (entry.kind === 'wake_up') {\n if (!reply) return undefined;\n woke = true;\n } else if (entry.role === 'assistant' && (entry.kind === undefined || entry.kind === 'supervisor' || entry.kind === 'plan_generated')) {\n // A turn may say something and commit a plan: past its inputs is the turn before.\n if (woke) break;\n reply ??= entry;\n }\n }\n return woke ? reply?.timestamp : undefined;\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 * The tasks a supervisor input is wholly about, absent when any of it is about\n * the run. While the user has stopped all of them it opens no turn (ADR-0029).\n */\n tasks?: string[];\n /** It goes with the next turn and opens none (ADR-0057 R6). */\n rides?: true;\n /** Who a message comes from where the conversation cannot tell (ADR-0055 D20): it stands or falls with its message, and a turn says it once. */\n aside?: string;\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 * A planner tool's change in the paused turn landed its inputs with it:\n * the transcript holds them already, and they wait only for a retry to\n * answer. A retry writes none of them again, and a Stop drops every one,\n * wake-ups included, since the planner has been told them.\n */\n landed?: true;\n}\n\n/**\n * A harness planner's own session, as far as a later process needs it: a hint,\n * taken up only under the runner, model, effort and folder it was opened with.\n * The transcript stays authoritative (ADR-0009 T4).\n */\nexport interface PlannerNativeSession {\n runner: string;\n sessionId: string;\n cwd: string;\n model?: string;\n effort?: string;\n /** What was counted of its running cost, so taking it up counts nothing twice (ADR-0056 M10). */\n cost?: RunnerSessionCost;\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 /** The subplanner's native session, for a Continue to take up (ADR-0055 D17): `heard` is how much of the Model context it holds. Absent on a root plan. */\n plannerSession?: PlannerNativeSession & { heard: number };\n /** What the planner recorded as decided, required, rejected and open, resent like the plan and seeding every checkpoint (ADR-0067). */\n decisionRecord?: DecisionRecordEntry[];\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 // Keep the legacy manual-task default in saved rows, though a manual task runs in no mode.\n taskMode: overrides.taskMode ?? (TASK_KINDS[type].runsInMode || type === 'user' ? 'build' : undefined),\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.goal !== undefined ? { goal: overrides.goal } : {}),\n ...(overrides.budget !== undefined ? { budget: { ...overrides.budget } } : {}),\n ...(overrides.grants !== undefined ? { grants: [...overrides.grants] } : {}),\n ...(overrides.protectedPaths !== undefined ? { protectedPaths: [...overrides.protectedPaths] } : {}),\n ...(overrides.scope !== undefined ? { scope: structuredClone(overrides.scope) } : {}),\n ...(overrides.readOnly ? { readOnly: true as const } : {}),\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), unless it\n * is read-only: that one runs sealed in a throwaway worktree (ADR-0055 D8).\n */\nexport function runsAsOps(task: Pick<Task, 'ops' | 'type' | 'readOnly'>): boolean {\n return (task.type === 'script' && !task.readOnly) || 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/** A task out of the plan, with every edge into it: `PlanGraph.remove` owns the rewrite, as it does for merge and split. */\nexport function removeTaskFromPlan(tasks: readonly Task[], taskId: string): Task[] {\n return remove(tasks, taskId);\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\n/** Whether {@link keepExecutionState} keeps this task exactly as it stands, whatever a rewrite says of it. */\nexport function isSettledTask(task: Pick<Task, 'status'>): boolean {\n return SETTLED_STATUSES.has(task.status);\n}\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 ...executionStateOf(prior),\n status: prior?.status ?? 'pending',\n // Where a task that has run ran is fixed, like its runner session (ADR-0020).\n ...(prior?.status === 'failed' ? { ops: prior.ops } : {}),\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","/**\n * Who ended a task as skipped (ADR-0045 L7). Stored beside the reason, never\n * read off its words: a person's or a supervisor's reason may say anything,\n * the loop's own texts may be reworded, and neither may change who skipped.\n *\n * - `loop`: a loop closed and the body that had not run was not waited for.\n * A new set of rounds undoes these.\n * - `user`, `supervisor`: a person, or a supervisor at Act, skipped it. A loop\n * whose body holds one has stopped, and stays so.\n * - `resolver`: its conflict ended some other way (ADR-0015).\n */\nexport type SkipOrigin = 'loop' | 'user' | 'supervisor' | 'resolver';\n\n/** Why a loop's body that did not run ends skipped once its loop is over (ADR-0045 L6). */\nexport const LOOP_PASSED = 'not needed: its check passed';\nexport const LOOP_OUT_OF_ROUNDS = 'not run: the loop ran out of rounds';\nexport const LOOP_CHECK_MARKED_COMPLETE = 'not needed: its check was marked complete';\nexport const LOOP_CHECK_SKIPPED = 'not needed: its check was skipped';\n\n/**\n * The texts a build before skip origins saved for a loop's own skips. Read\n * only to give such a plan the origin it lacks as it loads; they stay as they\n * were written even if the loop's wording changes, so no later build can read\n * a plan saved by this one wrongly.\n */\nconst LEGACY_LOOP_SKIP_REASONS: ReadonlySet<string> = new Set([\n 'not needed: its check passed',\n 'not run: the loop ran out of rounds',\n 'not needed: its check was marked complete',\n 'not needed: its check was skipped',\n]);\n\n/** The origin a task saved before skip origins was skipped by, which only a loop's own text gives away; undefined for any other. */\nexport function legacySkipOrigin(task: { status: string; skipReason?: string; skipOrigin?: SkipOrigin }): SkipOrigin | undefined {\n if (task.skipOrigin) return task.skipOrigin;\n return task.status === 'skipped' && LEGACY_LOOP_SKIP_REASONS.has(task.skipReason ?? '') ? 'loop' : undefined;\n}\n\n/** Whether a skipped body task has stopped its loop: anyone's skip but the loop's own does (ADR-0045 L7). */\nexport function stopsLoop(body: { status: string; skipOrigin?: SkipOrigin }): boolean {\n return body.status === 'skipped' && body.skipOrigin !== 'loop';\n}\n","import type { Task } from './Task';\n\n/*\n * Which of a task's fields are the plan's and which are its execution state,\n * and what a fresh attempt clears, stated once. A planner's rewrite keeps the\n * execution state it never witnessed (`keepExecutionState`); a retry and a\n * rearm clear the same attempt either way, but where they differ, below.\n *\n * - `plan`: what the plan says to run. The planner writes it.\n * - `execution`: the task's record of having run, which outlives an attempt:\n * a fresh attempt keeps it, and only a runner, the session or the user\n * changes it.\n * - `attempt`: the latest attempt's outcome, or what it waits on. Execution\n * state too, cleared by a fresh attempt.\n */\nexport type TaskFieldKind = 'plan' | 'execution' | 'attempt';\n\n/** Every key of `Task`, classified: a field added to `Task` without a kind here fails typecheck. */\nexport const TASK_FIELDS = {\n id: 'plan',\n order: 'plan',\n title: 'plan',\n description: 'plan',\n type: 'plan',\n status: 'attempt',\n dependencies: 'plan',\n prompt: 'plan',\n userSteps: 'plan',\n subtasks: 'plan',\n verdict: 'attempt',\n outputSummary: 'attempt',\n handoff: 'attempt',\n assignedModel: 'plan',\n assignedRunner: 'plan',\n taskMode: 'plan',\n autonomy: 'plan',\n sliceType: 'plan',\n userStoriesCovered: 'plan',\n // Cleared when an attempt spawns fresh, not when one is asked for: until then Continue may still offer it.\n runnerSessionId: 'execution',\n runnerSessionOwner: 'execution',\n awaitingReason: 'attempt',\n parkedQuestion: 'attempt',\n // Moved by status changes and cleared at an attempt's start (ADR-0053), so a fresh attempt asked for leaves it.\n waitsEnded: 'execution',\n resumeAt: 'attempt',\n carriedFrom: 'attempt',\n skipReason: 'attempt',\n skipOrigin: 'attempt',\n reverted: 'attempt',\n // A plan field, but where a failed task ran is fixed once it has run (ADR-0020): see `keepExecutionState`.\n ops: 'plan',\n research: 'plan',\n // A retry still owes research's report under its original authority (ADR-0037 R3).\n researchOrigin: 'execution',\n forcedPastGate: 'attempt',\n skills: 'plan',\n attemptSkills: 'execution',\n // Set by the session, never by an op (ADR-0029): the planner cannot write it.\n addedBy: 'execution',\n attempted: 'execution',\n attemptUsage: 'execution',\n commands: 'plan',\n script: 'plan',\n timeoutMs: 'plan',\n goal: 'plan',\n budget: 'plan',\n grants: 'plan',\n protectedPaths: 'plan',\n scope: 'plan',\n readOnly: 'plan',\n loop: 'plan',\n loopRound: 'attempt',\n reportTo: 'execution',\n} as const satisfies Record<keyof Task, TaskFieldKind>;\n\ntype FieldsOf<K extends TaskFieldKind> = { [F in keyof typeof TASK_FIELDS]: (typeof TASK_FIELDS)[F] extends K ? F : never }[keyof typeof TASK_FIELDS];\n\nexport type ExecutionField = FieldsOf<'execution' | 'attempt'>;\nexport type AttemptField = FieldsOf<'attempt'>;\n\nconst fieldsOf = <F extends keyof Task>(kinds: readonly TaskFieldKind[]): readonly F[] =>\n (Object.keys(TASK_FIELDS) as (keyof typeof TASK_FIELDS)[]).filter((f) => kinds.includes(TASK_FIELDS[f])) as F[];\n\n/** Every field that is execution state: what a planner's rewrite of the task never changes. */\nexport const EXECUTION_FIELDS: readonly ExecutionField[] = fieldsOf<ExecutionField>(['execution', 'attempt']);\n\n/** What a fresh attempt clears; `status` is set to pending instead. */\nexport const ATTEMPT_FIELDS: readonly AttemptField[] = fieldsOf<AttemptField>(['attempt']);\n\nexport interface FreshAttemptOptions {\n /**\n * A resume after a usage limit goes on with the attempt the limit cut\n * short, so a loop's check stays in its round; any other fresh attempt\n * starts the rounds over (ADR-0045 L7).\n */\n sameRound?: boolean;\n /**\n * The planner's `rearm`, a plan edit rather than a start. It keeps\n * `reverted`: a revert's hold is the user's to release, by a retry or a\n * force start (ADR-0054), and the saved mark is what keeps that hold past a\n * restart, so clearing it here would let the planner's edit lift the hold at\n * the next load.\n */\n rearm?: boolean;\n}\n\n/**\n * The changes that make a task a fresh attempt, from nothing it earned:\n * pending, with every attempt field cleared (`undefined`), and its record of\n * having run kept. Spread over the task, or written into it.\n */\nexport function freshAttempt(opts: FreshAttemptOptions = {}): Partial<Task> {\n const changes: Partial<Record<keyof Task, unknown>> = {};\n for (const field of ATTEMPT_FIELDS) {\n if (field === 'loopRound' && opts.sameRound) continue;\n if (field === 'reverted' && opts.rearm) continue;\n changes[field] = undefined;\n }\n changes.status = 'pending';\n return changes as Partial<Task>;\n}\n\n/** The task's execution state, every field named whether it holds a value or not, to lay over a rewrite of it. */\nexport function executionStateOf(task: Readonly<Task> | undefined): Partial<Task> {\n const state: Partial<Record<keyof Task, unknown>> = {};\n for (const field of EXECUTION_FIELDS) state[field] = task?.[field];\n return state as Partial<Task>;\n}\n","import { renumberTasks, waitsMidAttempt, type Task } from '../models/Task';\nimport { subtreeIds } from './PlanTree';\n\n/**\n * What the plan's edges become when tasks leave it or are swapped for others,\n * and the order that keeps them. `PlanTree`'s rules say which edges may\n * exist; this is the one place that rewrites them, so removal, merge and split\n * cannot disagree about a subtask that depended on the task going away. Every\n * rewrite reaches a dependency list at any depth, and a list comes out with\n * each id once.\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 remove(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\n/**\n * Swap `ids` for `newTasks`, which take the slot of the first of them, and\n * point everything that depended on any of `ids` at `tailId` — the new task\n * that stands for what they did — wherever it sits in the tree, so a task that\n * depended on both of two merged tasks depends on the merged one once. The new\n * tasks state their own dependencies and are not rewired. An edge into a\n * subtask the swap drops is left as it is: it dangles, and the plan's\n * invariants refuse it, as they do any unknown id. A loop's check and body are\n * not touched, because a task in either cannot be swapped (`loopReshapeRefusal`).\n */\nexport function replace(tasks: readonly Task[], ids: Iterable<string>, newTasks: readonly Task[], tailId: string): Task[] {\n const gone = new Set(ids);\n let placed = false;\n const rewire = (level: readonly Task[]): Task[] => {\n const out: Task[] = [];\n for (const t of level) {\n if (gone.has(t.id)) {\n if (!placed) { out.push(...newTasks); placed = true; }\n continue;\n }\n out.push({\n ...t,\n dependencies: [...new Set(t.dependencies.map((d) => (gone.has(d) ? tailId : d)))],\n subtasks: rewire(t.subtasks),\n });\n }\n return out;\n };\n const result = rewire(tasks);\n if (!placed) result.push(...newTasks);\n return renumberTasks(result);\n}\n\n/** A task the repair may not reposition: execution has already reached it. */\nfunction isPinned(t: Task): boolean {\n return t.status === 'in_progress' || waitsMidAttempt(t) || t.status === 'completed';\n}\n\n/**\n * Reorder one list of siblings so every dependency comes before its\n * dependents, moving as little as possible: pinned tasks keep the exact slot\n * they are in, and each free slot goes to the earliest-listed movable task\n * whose dependencies are already placed — so tasks the graph does not\n * constrain keep their relative order. A dependency outside the list (a task\n * of another level) constrains nothing here. Assumes an acyclic graph (the\n * caller checks first). `moves` says what moved, as `\"B\" #2→#1, \"A\" #1→#3`, or\n * is null when nothing did.\n */\nexport function repairOrder(tasks: Task[]): { tasks: Task[]; moves: string | null } | { error: string } {\n const byId = new Map(tasks.map((t) => [t.id, t]));\n const placed = new Set<string>();\n const movable = tasks.filter((t) => !isPinned(t));\n const result: Task[] = [];\n const blockerOf = (t: Task): Task | undefined => {\n const id = t.dependencies.find((d) => byId.has(d) && !placed.has(d));\n return id ? byId.get(id) : undefined;\n };\n const place = (t: Task) => { result.push(t); placed.add(t.id); };\n\n for (const occupant of tasks) {\n if (isPinned(occupant)) {\n const blocker = blockerOf(occupant);\n if (blocker) return { error: pinnedRefusal(blocker, occupant, 'before') };\n place(occupant);\n continue;\n }\n const next = movable.findIndex((t) => !blockerOf(t));\n if (next < 0) {\n // Nothing is schedulable and the graph is acyclic, so every movable task\n // left waits — directly or through others — on a pinned task further down\n // that would have to come up to free this slot.\n const [stuck, pin] = trailToPin(movable[0], blockerOf);\n return { error: pinnedRefusal(stuck, pin, 'after') };\n }\n place(movable.splice(next, 1)[0]);\n }\n return { tasks: result, moves: describeMoves(tasks, result) };\n}\n\n/** Walk the waiting-on chain from `task` down to the pinned task holding it up. */\nfunction trailToPin(task: Task, blockerOf: (t: Task) => Task | undefined): [Task, Task] {\n let at = task;\n for (;;) {\n const blocker = blockerOf(at);\n if (!blocker || isPinned(blocker)) return [at, blocker ?? at];\n at = blocker;\n }\n}\n\nfunction describeMoves(before: Task[], after: Task[]): string | null {\n const wasAt = new Map(before.map((t, i) => [t.id, i + 1]));\n const moved = after\n .map((t, i) => ({ t, from: wasAt.get(t.id)!, to: i + 1 }))\n .filter((m) => m.from !== m.to);\n return moved.length ? moved.map((m) => `\"${m.t.title}\" #${m.from}→#${m.to}`).join(', ') : null;\n}\n\nfunction pinnedRefusal(other: Task, pin: Task, side: 'before' | 'after'): string {\n const word = pin.status === 'completed' ? 'completed' : 'running';\n return `\"${other.title}\" would have to run ${side} \"${pin.title}\", which is ${word} and cannot be moved`;\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/** {@link taskRefOf} for a whole plan tree at once: each task's reference, by id. */\nexport function taskRefsOf<T extends RefTask<T>>(tasks: readonly T[]): Map<string, string> {\n const refs = new Map<string, string>();\n for (const { task, label } of walkPlan(tasks)) if (!refs.has(task.id)) refs.set(task.id, `#${label}`);\n return refs;\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 { flattenTasks, type Task } from '../models/Task';\nimport { addPlannerUsage, type PlannerUsage, type UsageRecord } from '../models/Usage';\n\n/**\n * An attempt that has run this long is worth a look whatever its plan's\n * history: below it, a task that runs long is still within what a single\n * brief often takes.\n */\nexport const RUNNING_LONG_FLOOR_MS = 30 * 60_000;\n/** How many times the longest passed AI task's running time an attempt may run before it is flagged. */\nexport const RUNNING_LONG_FACTOR = 3;\n\n/** How long an attempt may run before it is flagged, and the passed task that set it, when one did. */\nexport interface RunningLongThreshold {\n ms: number;\n basis?: RunningLongBasis;\n}\n\n/** The AI task that passed in the longest running time, which the threshold is a multiple of. */\nexport interface RunningLongBasis {\n taskId: string;\n runningMs: number;\n}\n\n/**\n * The larger of the floor and {@link RUNNING_LONG_FACTOR} times the longest\n * running time an AI task of this plan passed in, read from the attempt that\n * passed it. A script task has its own `timeoutMs`, and a failed attempt says\n * nothing of how long the work takes, so neither counts. Its waits on a person\n * are left out, as the live clock leaves them out: a task that waited overnight\n * says nothing of how long the work takes either. An attempt saved before its\n * running time was kept has only its wall time.\n */\nexport function runningLongThreshold(tasks: readonly Task[]): RunningLongThreshold {\n let basis: RunningLongBasis | undefined;\n for (const task of flattenTasks(tasks)) {\n if (task.type !== 'ai' || task.status !== 'completed') continue;\n const attempts = task.attemptUsage ?? [];\n const last = attempts[attempts.length - 1];\n if (!last?.endedAt) continue;\n const runningMs = last.runningMs ?? last.wallTimeMs;\n if (!basis || runningMs > basis.runningMs) basis = { taskId: task.id, runningMs };\n }\n const scaled = basis ? basis.runningMs * RUNNING_LONG_FACTOR : 0;\n return basis && scaled > RUNNING_LONG_FLOOR_MS ? { ms: scaled, basis } : { ms: RUNNING_LONG_FLOOR_MS };\n}\n\n/**\n * What a running-long flag says of the attempt (ADR-0018 W1): advisory, it\n * stops and fails nothing.\n */\nexport interface RunningLongFacts {\n /** Its running time passed the threshold, or its runner's session compacted on its own. */\n reason: 'duration' | 'compaction';\n /** Time the attempt has spent running, waits on a person left out. */\n elapsedMs: number;\n /** The running time this flag was due at: the threshold, doubled for each duration flag before it. */\n thresholdMs: number;\n basis?: RunningLongBasis;\n /** What the main model's context holds now, from the last usage record or compaction. */\n contextTokens?: number;\n contextWindow?: number;\n /** Where Ordewell set the runner to compact its context, when it did: a compaction there is routine. */\n compactionWindow?: number;\n /** The most the context has held this attempt: the saved usage keeps only the last. */\n peakContextTokens?: number;\n /** Automatic compactions of the attempt's own runner session so far. */\n compactions: number;\n}\n\n/** A flag as the supervisor and the surfaces read it: the facts, of the attempt they were counted for. */\nexport type RunningLongEvent = RunningLongFacts & { attempt: number };\n\n/**\n * Compactions of a runner that Ordewell set a window for are routine, and\n * flagged from the third, then each time their count doubles: the 3rd, 6th,\n * 12th (ADR-0057 R4). Past that window each call re-reads a long prefix for\n * little new information, so a task compacts a few times in the course of\n * ordinary work.\n */\nexport const ROUTINE_COMPACTIONS = 3;\n\n/** The longest delay a timer keeps: Node fires a longer one at once. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\n/**\n * One attempt's running time, and the flags it raises. Time counts only while\n * the attempt runs: {@link hold} while it waits on a person (input, a\n * checkpoint, an approval), {@link run} once it goes on. Each duration flag\n * doubles the running time the next needs, as a quiet task's flag does.\n */\nexport class RunningLongClock {\n private accrued = 0;\n private since: number | null = null;\n private timer: NodeJS.Timeout | null = null;\n private flags = 0;\n private compactions = 0;\n /** The main model's context as the usage meter keeps it, by the same rules: a compaction or a model change clears it. */\n private meter: PlannerUsage = { totals: {} };\n private peak?: number;\n private stopped = false;\n\n constructor(\n private readonly threshold: () => RunningLongThreshold,\n private readonly flag: (facts: RunningLongFacts) => void,\n /** The size Ordewell set the runner to compact at; none where the runner compacts near its model's own window. */\n private readonly compactWindow: () => number | undefined = () => undefined,\n ) {}\n\n run(): void {\n if (this.stopped || this.since !== null) return;\n this.since = Date.now();\n this.arm();\n }\n\n hold(): void {\n if (this.since === null) return;\n this.accrued = this.runningMs();\n this.since = null;\n this.disarm();\n }\n\n stop(): void {\n this.hold();\n this.stopped = true;\n }\n\n usage(record: UsageRecord): void {\n // A subagent's context is not the attempt's, and an aggregate names no current context.\n if (this.stopped || record.subagentId || record.aggregate) return;\n const before = this.meter;\n this.meter = addPlannerUsage(this.meter, record);\n // A peak is measured against one model's window: another model's does not carry over.\n if (before.model !== this.meter.model || before.source !== this.meter.source) this.peak = undefined;\n this.measure();\n }\n\n /** A compaction of the attempt's own session: only one the runner did by itself says the context ran out. */\n compaction(trigger: 'manual' | 'auto', postTokens?: number): void {\n if (this.stopped) return;\n // The size before it is gone: with no size after, the context is unknown until the next call measures it.\n this.meter = { ...this.meter, lastPromptTokens: postTokens };\n this.measure();\n if (trigger !== 'auto') return;\n this.compactions += 1;\n if (this.compactWindow() !== undefined && !this.beyondRoutine()) return;\n this.flag(this.facts('compaction', this.due()));\n }\n\n /** The 3rd compaction, the 6th, the 12th: the first that is no longer routine, then each doubling. */\n private beyondRoutine(): boolean {\n const n = this.compactions / ROUTINE_COMPACTIONS;\n return Number.isInteger(n) && Number.isInteger(Math.log2(n));\n }\n\n private measure(): void {\n const tokens = this.meter.lastPromptTokens;\n if (tokens !== undefined) this.peak = Math.max(this.peak ?? 0, tokens);\n }\n\n /** Time spent running so far, waits on a person left out. */\n runningMs(): number {\n return this.accrued + (this.since === null ? 0 : Date.now() - this.since);\n }\n\n private due(): number {\n return this.threshold().ms * 2 ** this.flags;\n }\n\n private arm(): void {\n this.disarm();\n // A flag further off than a timer holds wakes early, and ripe() arms again.\n this.timer = setTimeout(() => this.ripe(), Math.min(MAX_TIMER_MS, Math.max(0, this.due() - this.runningMs())));\n }\n\n private disarm(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n\n /** Read again when the timer fires: a task that passed in the meantime may have raised the threshold. */\n private ripe(): void {\n this.timer = null;\n const due = this.due();\n if (this.runningMs() < due) {\n this.arm();\n return;\n }\n this.flags += 1;\n this.flag(this.facts('duration', due));\n if (!this.stopped && this.since !== null) this.arm();\n }\n\n private facts(reason: RunningLongFacts['reason'], thresholdMs: number): RunningLongFacts {\n const { basis } = this.threshold();\n return {\n reason,\n elapsedMs: this.runningMs(),\n thresholdMs,\n ...(basis ? { basis } : {}),\n ...(this.meter.lastPromptTokens !== undefined ? { contextTokens: this.meter.lastPromptTokens } : {}),\n ...(this.meter.contextWindow !== undefined ? { contextWindow: this.meter.contextWindow } : {}),\n ...(this.compactWindow() !== undefined ? { compactionWindow: this.compactWindow() } : {}),\n ...(this.peak !== undefined ? { peakContextTokens: this.peak } : {}),\n compactions: this.compactions,\n };\n }\n}\n","import type { Task, Verdict, VerificationCheck } from '../models/Task';\nimport type { IRunnerSession, ScriptExit, ScriptFullOutput, ScriptStatus } from '../interfaces/IRunner';\nimport type { CheckpointAnswer, TaskCompleteArgs } from './mcp/tools';\nimport { RUNNING_LONG_FLOOR_MS, RunningLongClock, type RunningLongFacts, type RunningLongThreshold } from './RunningLong';\n\nexport type VerdictListener = (taskId: string, verdict: Verdict) => void;\nexport type CheckpointListener = (taskId: string, summary: string) => void;\n/** A tool-raised checkpoint whose call went away while its attempt lives on, so nothing is left to answer it. */\nexport type CheckpointWithdrawnListener = (taskId: string) => void;\n/** Fires on every idleSince transition (null→timestamp on silence, timestamp→null on resume/teardown). */\nexport type IdleListener = (taskId: string, idleSince: string | null) => void;\n/** A running AI attempt ran long or compacted on its own (ADR-0018 W1): advisory, it settles nothing. */\nexport type RunningLongListener = (taskId: string, facts: RunningLongFacts) => void;\n\nexport interface VerdictEngineOptions {\n /** How long an attempt may run before it is flagged, read again as tasks pass; the floor alone when absent. */\n runningLongThreshold?: () => RunningLongThreshold;\n}\n\n/**\n * No output for this long, with no tool call in flight, marks a running task\n * idle (advisory, UI-only). Long model turns and slow builds routinely go\n * quiet for minutes, so a shorter window flagged healthy tasks as Stalled. A run that ends with a build plus\n * the full test suite can print nothing for more than 5 minutes, which flagged\n * healthy tasks quiet and woke the supervisor for nothing, hence 10.\n */\nexport const IDLE_TIMEOUT_MS = 10 * 60_000;\n\n\nexport class VerdictEngine {\n private pendingVerdicts = new Map<string, Verdict>();\n private sessions = new Map<string, IRunnerSession>();\n private listeners: VerdictListener[] = [];\n private checkpointListeners: CheckpointListener[] = [];\n private withdrawnListeners: CheckpointWithdrawnListener[] = [];\n /** The open `checkpoint` tool call per task (ADR-0022, V5): settling it is how an answer reaches the runner. */\n private toolCheckpoints = new Map<string, (answer: CheckpointAnswer) => void>();\n /** The question a task's checkpoint asks, whole, for as long as it waits. */\n private checkpointQuestions = new Map<string, string>();\n private idleListeners: IdleListener[] = [];\n /**\n * Per-task generation. Replaced on every watch(), clear() and verdict.\n * Stale callbacks (from a prior session whose generation doesn't match\n * the current one) bail out instead of delivering a verdict for the\n * wrong session.\n */\n private generations = new Map<string, number>();\n /**\n * Generations come from one counter that {@link reset} never rewinds: a\n * per-task count restarted at 1 after a reset, and the next watch handed a\n * session that outlived the reset the same generation as its successor.\n */\n private lastGeneration = 0;\n private idleTimers = new Map<string, NodeJS.Timeout>();\n private idleSince = new Map<string, string | null>();\n /** Tasks waiting on the user, whose silence is expected rather than a sign of a stuck runner. */\n private idlePaused = new Set<string>();\n /**\n * Open tool approvals per structured task. They arrive mid-turn and leave the\n * status alone (ADR-0018, W1), but a task waiting on one is waiting on the\n * user, so it is not idle either.\n */\n private openApprovals = new Map<string, Set<string>>();\n /**\n * Tool calls per structured task with no result yet. A runner waiting on a\n * command it started (a long test suite, a bench run) prints nothing until it\n * returns; it is waiting, not stalled, so it is not idle either. A runner with\n * no call in flight and no output still is.\n */\n private openCalls = new Map<string, Set<string>>();\n /**\n * How often the current attempt has been flagged idle. Each flag doubles the\n * silence the next one needs: a long review that prints a line now and then\n * was flagged again after every line, and each flag woke the planner.\n */\n private idleFlags = new Map<string, number>();\n /** The running time of each AI task's current attempt (ADR-0018 W1). */\n private clocks = new Map<string, RunningLongClock>();\n /** The running time an attempt's clock stopped at, until the task's next attempt starts. */\n private ran = new Map<string, number>();\n private runningLongListeners: RunningLongListener[] = [];\n private readonly runningLongThreshold: () => RunningLongThreshold;\n\n constructor(options: VerdictEngineOptions = {}) {\n this.runningLongThreshold = options.runningLongThreshold ?? (() => ({ ms: RUNNING_LONG_FLOOR_MS }));\n }\n\n onVerdict(listener: VerdictListener): void {\n this.listeners.push(listener);\n }\n\n onCheckpoint(listener: CheckpointListener): void {\n this.checkpointListeners.push(listener);\n }\n\n onCheckpointWithdrawn(listener: CheckpointWithdrawnListener): void {\n this.withdrawnListeners.push(listener);\n }\n\n onIdleChange(listener: IdleListener): void {\n this.idleListeners.push(listener);\n }\n\n onRunningLong(listener: RunningLongListener): void {\n this.runningLongListeners.push(listener);\n }\n\n /** Advisory silence timestamp for a task, or null if it isn't idle. */\n getIdleSince(taskId: string): string | null {\n return this.idleSince.get(taskId) ?? null;\n }\n\n /**\n * Stop watching a task's silence while it waits on the user (ADR-0018, W1).\n * Watching resumes when its next turn starts, or when a checkpoint is answered.\n */\n pauseIdle(taskId: string): void {\n this.idlePaused.add(taskId);\n this.clearIdle(taskId);\n this.syncClock(taskId);\n }\n\n private resumeIdle(taskId: string): void {\n const gen = this.generations.get(taskId);\n if (!this.idlePaused.delete(taskId) || gen === undefined) return;\n this.syncClock(taskId);\n this.touchIdle(taskId, gen);\n }\n\n /**\n * An attempt's running time stops while it waits on a person, for input, a\n * checkpoint or an approval, and goes on when it does. A tool call in flight\n * is the runner working, so it counts.\n */\n private syncClock(taskId: string): void {\n const clock = this.clocks.get(taskId);\n if (!clock) return;\n if (this.idlePaused.has(taskId) || this.openApprovals.get(taskId)?.size) clock.hold();\n else clock.run();\n }\n\n private stopClock(taskId: string): void {\n const clock = this.clocks.get(taskId);\n if (!clock) return;\n clock.stop();\n this.ran.set(taskId, clock.runningMs());\n this.clocks.delete(taskId);\n }\n\n /**\n * The current or last attempt's running time, waits on a person left out:\n * what a later task's running-long threshold is a multiple of (ADR-0018 W1).\n * Undefined for a task with no clock.\n */\n runningMs(taskId: string): number | undefined {\n return this.clocks.get(taskId)?.runningMs() ?? this.ran.get(taskId);\n }\n\n /** Restart the silence timer on fresh output; broadcasts the null transition if it was idle. */\n private touchIdle(taskId: string, gen: number): void {\n if (this.idlePaused.has(taskId) || this.openApprovals.get(taskId)?.size || this.openCalls.get(taskId)?.size) return;\n const existing = this.idleTimers.get(taskId);\n if (existing) clearTimeout(existing);\n if (this.idleSince.get(taskId)) {\n this.idleSince.set(taskId, null);\n for (const l of this.idleListeners) l(taskId, null);\n }\n this.idleTimers.set(taskId, setTimeout(() => {\n if (this.generations.get(taskId) !== gen) return;\n const now = new Date().toISOString();\n this.idleFlags.set(taskId, (this.idleFlags.get(taskId) ?? 0) + 1);\n this.idleSince.set(taskId, now);\n for (const l of this.idleListeners) l(taskId, now);\n }, IDLE_TIMEOUT_MS * 2 ** (this.idleFlags.get(taskId) ?? 0)));\n }\n\n /** Tear down idle tracking for a task; broadcasts the null transition if it was idle. */\n private clearIdle(taskId: string): void {\n const timer = this.idleTimers.get(taskId);\n if (timer) clearTimeout(timer);\n this.idleTimers.delete(taskId);\n const wasIdle = this.idleSince.get(taskId);\n this.idleSince.delete(taskId);\n if (wasIdle) {\n for (const l of this.idleListeners) l(taskId, null);\n }\n }\n\n /** What a task's waiting checkpoint asks, untruncated; undefined when none waits. */\n getCheckpointQuestion(taskId: string): string | undefined {\n return this.checkpointQuestions.get(taskId);\n }\n\n approveCheckpoint(taskId: string, note?: string): void {\n this.checkpointQuestions.delete(taskId);\n this.resumeIdle(taskId);\n this.toolCheckpoints.get(taskId)?.({ kind: 'continue', ...(note ? { note } : {}) });\n }\n\n rejectCheckpoint(taskId: string, reason: string): void {\n this.checkpointQuestions.delete(taskId);\n this.resumeIdle(taskId);\n this.toolCheckpoints.get(taskId)?.({ kind: 'rejected', reason });\n }\n\n /**\n * An attempt's runner is being started, with no session to watch yet. Its\n * silence counts from here, so one whose start never resolves — stuck\n * launching, or waiting for its tools to attach — is flagged quiet as well.\n * {@link watch} starts the count again once the runner is up.\n */\n starting(taskId: string): void {\n const gen = this.bumpGeneration(taskId);\n this.stopClock(taskId);\n this.ran.delete(taskId);\n this.idlePaused.delete(taskId);\n this.openApprovals.delete(taskId);\n this.openCalls.delete(taskId);\n this.idleFlags.delete(taskId);\n this.touchIdle(taskId, gen);\n }\n\n /**\n * Attach to a spawned session. The runner's `task_complete` call on the\n * attempt's token is the only completion evidence (ADR-0022, V2); a session\n * that exits before one gets a failed verdict. A script task's session has\n * no runner to call it: its exit status is the evidence instead (ADR-0035).\n *\n * Returns the attempt's generation, what {@link signalComplete} is checked against.\n */\n watch(task: Task, session: IRunnerSession): number {\n const gen = this.bumpGeneration(task.id);\n // Silence counts from the start, not from the first output: a runner that\n // never prints went unflagged however long it stayed quiet (#117). Armed\n // before any listener, so an exit or verdict a session replays on attach\n // clears it rather than leaving it to fire. What an earlier attempt waited\n // on is not this one's to wait on.\n this.idlePaused.delete(task.id);\n this.openApprovals.delete(task.id);\n this.openCalls.delete(task.id);\n this.idleFlags.delete(task.id);\n this.touchIdle(task.id, gen);\n this.stopClock(task.id);\n this.ran.delete(task.id);\n // A script has its own timeoutMs, and a person's task has no runner (ADR-0018 W1).\n const clock = task.type === 'ai' ? new RunningLongClock(this.runningLongThreshold, (facts) => {\n if (this.generations.get(task.id) !== gen) return;\n for (const l of this.runningLongListeners) l(task.id, facts);\n }, () => session.compactWindowTokens) : undefined;\n if (clock) {\n this.clocks.set(task.id, clock);\n clock.run();\n }\n session.onOutput(() => {\n if (this.generations.get(task.id) === gen) this.touchIdle(task.id, gen);\n });\n this.sessions.set(task.id, session);\n session.onTurnEnd(() => {\n if (this.generations.get(task.id) !== gen) return;\n // A call whose result never came is not in flight past its turn.\n if (this.openCalls.delete(task.id)) this.touchIdle(task.id, gen);\n // The call lives inside the turn that made it. A runner cut short by an\n // interrupt does not always cancel it, and left open it would refuse the next one.\n this.callWentAway(task.id, 'the turn it was asked in has ended.');\n // A queued follow-up supersedes this turn's evidence without ending the attempt.\n const pending = this.pendingVerdicts.get(task.id);\n this.pendingVerdicts.delete(task.id);\n if (session.turnState() === 'idle' && pending) this.publishVerdict(task.id, pending);\n });\n session.onEvent((event) => {\n if (this.generations.get(task.id) !== gen) return;\n if (event.type === 'turn_start') {\n this.supersede(task.id);\n this.resumeIdle(task.id);\n }\n // Read mid-turn, a message voids what the runner reported before it just as a new turn does (ADR-0023).\n else if (event.type === 'message_delivered') this.supersede(task.id);\n else if (event.type === 'permission_request' && !event.decided) this.waitOpened(this.openApprovals, task.id, event.id);\n else if (event.type === 'permission_decided' || event.type === 'permission_withdrawn') this.waitClosed(this.openApprovals, task.id, event.id, gen);\n else if (event.type === 'tool_call') this.waitOpened(this.openCalls, task.id, event.id);\n else if (event.type === 'tool_result') this.waitClosed(this.openCalls, task.id, event.id, gen);\n else if (event.type === 'usage') clock?.usage(event.record);\n else if (event.type === 'compaction') clock?.compaction(event.trigger, event.postTokens);\n });\n session.onTaskComplete((report, refuted) => this.signalComplete(task.id, gen, report, refuted));\n session.onScriptExit((exit) => this.signalScriptExit(task.id, gen, exit));\n session.onToolCheckpoint((question, signal) => this.raiseCheckpoint(task.id, gen, question, signal));\n session.onExit((exitCode: number) => {\n if (this.generations.get(task.id) !== gen) return;\n this.forget(task.id);\n const verdict = exitVerdict(exitCode);\n for (const l of this.listeners) l(task.id, verdict);\n });\n return gen;\n }\n\n /**\n * The runner's own `task_complete` call (ADR-0022, V1/V3): settles the\n * attempt, unless that attempt is no longer the task's current one or an\n * earlier call already settled it.\n */\n signalComplete(taskId: string, generation: number, report: TaskCompleteArgs, refuted?: VerificationCheck): void {\n if (this.generations.get(taskId) !== generation) return;\n this.acceptVerdict(taskId, reportedVerdict(report, refuted));\n }\n\n /**\n * A script task's exit status (ADR-0035): its one evidence, as a runner's\n * `task_complete` call is a runner's. It settles the attempt unless that\n * attempt is no longer the task's current one.\n */\n signalScriptExit(taskId: string, generation: number, exit: ScriptExit): void {\n if (this.generations.get(taskId) !== generation) return;\n this.acceptVerdict(taskId, scriptVerdict(exit));\n }\n\n /** The runner was told something after its evidence so far, so only what it reports from here counts. */\n private supersede(taskId: string): void {\n this.pendingVerdicts.delete(taskId);\n }\n\n private acceptVerdict(taskId: string, verdict: Verdict): void {\n if (this.pendingVerdicts.has(taskId)) return;\n // Only what a person queued is news the evidence predates. Ordewell's own\n // messages (the compaction nudge, ADR-0018 C3) restate the brief and ask\n // for this very call, so one still queued holds no verdict back.\n if (this.sessions.get(taskId)?.queued().some((message) => message.from !== 'ordewell')) {\n this.pendingVerdicts.set(taskId, verdict);\n return;\n }\n this.publishVerdict(taskId, verdict);\n }\n\n private publishVerdict(taskId: string, verdict: Verdict): void {\n this.forget(taskId);\n this.bumpGeneration(taskId);\n for (const l of this.listeners) l(taskId, verdict);\n }\n\n /**\n * The runner's `checkpoint` call (ADR-0022, V5): the task waits on the\n * user until it is settled by {@link approveCheckpoint} or {@link rejectCheckpoint}. It is\n * withdrawn, never left hanging, once the attempt is over or the call goes.\n */\n raiseCheckpoint(taskId: string, generation: number, question: string, signal: AbortSignal): Promise<CheckpointAnswer> {\n if (this.generations.get(taskId) !== generation || signal.aborted) {\n return Promise.resolve({ kind: 'withdrawn', why: 'this attempt has ended.' });\n }\n if (this.toolCheckpoints.has(taskId)) {\n return Promise.resolve({ kind: 'withdrawn', why: 'another checkpoint is still waiting for an answer. Wait for it before asking again.' });\n }\n return new Promise((resolve) => {\n const settle = (answer: CheckpointAnswer) => {\n signal.removeEventListener('abort', onAbort);\n if (this.toolCheckpoints.get(taskId) === settle) {\n this.toolCheckpoints.delete(taskId);\n this.checkpointQuestions.delete(taskId);\n }\n resolve(answer);\n };\n const onAbort = () => {\n settle({ kind: 'withdrawn', why: 'the call was cancelled.' });\n if (this.generations.get(taskId) !== generation) return;\n this.resumeIdle(taskId);\n for (const l of this.withdrawnListeners) l(taskId);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n this.toolCheckpoints.set(taskId, settle);\n this.checkpointQuestions.set(taskId, question.trim());\n for (const l of this.checkpointListeners) l(taskId, question.trim());\n });\n }\n\n /** The open `checkpoint` call can no longer be answered: refuse it, and let the task out of the wait. */\n private callWentAway(taskId: string, why: string): void {\n const open = this.toolCheckpoints.get(taskId);\n if (!open) return;\n open({ kind: 'withdrawn', why });\n this.resumeIdle(taskId);\n for (const l of this.withdrawnListeners) l(taskId);\n }\n\n private withdrawToolCheckpoint(taskId: string): void {\n this.toolCheckpoints.get(taskId)?.({ kind: 'withdrawn', why: 'this attempt has ended.' });\n }\n\n /** Something the task waits on (an approval, a call in flight) opened: its silence is expected until the last one closes. */\n private waitOpened(waits: Map<string, Set<string>>, taskId: string, id: string): void {\n const open = waits.get(taskId) ?? new Set<string>();\n open.add(id);\n waits.set(taskId, open);\n this.clearIdle(taskId);\n this.syncClock(taskId);\n }\n\n private waitClosed(waits: Map<string, Set<string>>, taskId: string, id: string, gen: number): void {\n const open = waits.get(taskId);\n if (!open?.delete(id) || open.size) return;\n waits.delete(taskId);\n this.syncClock(taskId);\n this.touchIdle(taskId, gen);\n }\n\n private bumpGeneration(taskId: string): number {\n this.lastGeneration += 1;\n this.generations.set(taskId, this.lastGeneration);\n return this.lastGeneration;\n }\n\n private forget(taskId: string): void {\n this.pendingVerdicts.delete(taskId);\n this.sessions.delete(taskId);\n this.withdrawToolCheckpoint(taskId);\n this.checkpointQuestions.delete(taskId);\n this.idlePaused.delete(taskId);\n this.openApprovals.delete(taskId);\n this.openCalls.delete(taskId);\n this.idleFlags.delete(taskId);\n this.stopClock(taskId);\n this.clearIdle(taskId);\n }\n\n /** Manual \"Mark complete\" override: a pass verdict that bypasses evidence. */\n markComplete(task: Task): Verdict {\n this.ceaseTracking(task.id);\n return {\n outcome: 'pass',\n reason: 'Manually marked complete by user.',\n checks: [\n {\n name: 'manual',\n passed: true,\n skipped: false,\n detail: 'Task was manually marked complete by the user; no automatic verification was performed.',\n },\n ],\n decidedAt: new Date().toISOString(),\n };\n }\n\n /** Clear verification state for a task (used on retry). */\n clear(task: Task): void {\n this.ceaseTracking(task.id);\n }\n\n /** Drop a task's verification state and invalidate any callbacks still holding its generation. */\n private ceaseTracking(taskId: string): void {\n this.forget(taskId);\n this.bumpGeneration(taskId);\n }\n\n /** Drop all tracking state (used on stop / loadPlan). */\n reset(): void {\n this.pendingVerdicts.clear();\n this.sessions.clear();\n for (const taskId of [...this.toolCheckpoints.keys()]) this.withdrawToolCheckpoint(taskId);\n this.checkpointQuestions.clear();\n for (const timer of this.idleTimers.values()) clearTimeout(timer);\n this.idleTimers.clear();\n this.idleSince.clear();\n this.idlePaused.clear();\n this.openApprovals.clear();\n this.openCalls.clear();\n this.idleFlags.clear();\n for (const clock of this.clocks.values()) clock.stop();\n this.clocks.clear();\n this.ran.clear();\n this.generations.clear();\n }\n}\n\nconst EXIT_CHECK = 'exit_code';\n\n/** The runner's exit decided it, not a `task_complete` report. */\nexport function endedByExit(verdict: Verdict): boolean {\n return verdict.checks.some((check) => check.name === EXIT_CHECK);\n}\n\n/** A runner that exited without reporting through `task_complete` did not finish, whatever its exit code. */\nfunction exitVerdict(exitCode: number): Verdict {\n const normalized = exitCode == null ? 0 : exitCode;\n const exitOk = normalized === 0;\n return {\n outcome: 'fail',\n reason: exitOk\n ? 'Failed verification: the runner exited cleanly but never called task_complete.'\n : `Failed verification: the runner exited with code ${normalized} without calling task_complete.`,\n checks: [\n { name: 'task_complete', passed: false, skipped: false, detail: 'the runner exited before calling task_complete' },\n { name: EXIT_CHECK, passed: exitOk, skipped: false, detail: exitOk ? 'the runner exited cleanly (code 0)' : `the runner exited with code ${normalized}` },\n ],\n decidedAt: new Date().toISOString(),\n };\n}\n\n/**\n * The host died during the attempt, so nothing was checked. Nothing was\n * reported either, so no loop reads it as a finding (ADR-0045 L2).\n */\nexport function interruptedVerdict(decidedAt: string): Verdict {\n return { outcome: 'fail', reason: 'It was interrupted when Ordewell stopped, and nothing is running it now.', checks: [], decidedAt };\n}\n\n/** How a status reads in a reason: its exit code, the signal that ended it, or why it never started. */\nfunction statusText(status: ScriptStatus): string {\n if (status.error !== undefined) return `could not start: ${status.error}`;\n if (status.signal) return `was ended by ${status.signal}`;\n return `exited with code ${status.code ?? 'unknown'}`;\n}\n\n/**\n * The tail is all a verdict quotes, and a long command's failure is often\n * above it, so a reason points at the file that holds the whole output.\n */\nfunction withTail(reason: string, errorTail: string, fullOutput?: ScriptFullOutput): string {\n const tail = errorTail.trim();\n const quoted = tail ? `${reason}\\n\\nThe end of its error output:\\n${tail}` : reason;\n if (!fullOutput) return quoted;\n // No full stop after a path: it would be copied with it.\n const cut = fullOutput.droppedChars > 0 ? `, except its last ${fullOutput.droppedChars} characters, which were not saved.` : '';\n return `${quoted}\\n\\nAll of its output is in ${fullOutput.file}${cut}`;\n}\n\n/**\n * A script task's verdict from its exit status alone (ADR-0035): every step\n * exiting 0 passes, anything else fails with the status and the tail of its\n * error output. Never an exit check — the script did not stop before it was\n * done — so it is never read as a runner that hit its usage limit.\n */\nfunction scriptVerdict(exit: ScriptExit): Verdict {\n const decidedAt = new Date().toISOString();\n const check = (passed: boolean, detail: string): VerificationCheck[] => [{ name: 'script_exit', passed, skipped: false, detail }];\n const command = exit.outcome !== 'passed' && exit.command !== undefined ? `\\`${exit.command}\\`` : undefined;\n switch (exit.outcome) {\n case 'passed':\n return { outcome: 'pass', reason: 'Verified: every step of the script exited 0.', checks: check(true, 'every step exited 0'), decidedAt, reported: 'done' };\n case 'failed': {\n const said = `${command ?? 'it'} ${statusText(exit.status)}`;\n // A step that never started found nothing about the work (ADR-0045 L2).\n const reported = exit.status.error !== undefined ? 'blocked' : 'failed';\n return { outcome: 'fail', reason: withTail(`The script failed: ${said}.`, exit.errorTail, exit.fullOutput), checks: check(false, said), decidedAt, reported };\n }\n case 'timed-out': {\n const said = `the time limit of ${durationText(exit.timeoutMs)} ran out${command ? ` while ${command} ran` : ''}, so it was ended`;\n return { outcome: 'fail', reason: withTail(`The script failed: ${said}.`, exit.errorTail, exit.fullOutput), checks: check(false, said), decidedAt, reported: 'failed' };\n }\n case 'stopped': {\n const said = `it was stopped${command ? ` while ${command} ran` : ''}`;\n return { outcome: 'fail', reason: withTail(`The script did not finish: ${said}.`, '', exit.fullOutput), checks: check(false, said), decidedAt };\n }\n }\n}\n\n/** A limit as a reader says it: minutes when it is whole minutes, else seconds. */\nfunction durationText(ms: number): string {\n if (ms % 60_000 === 0) return `${ms / 60_000} minute${ms === 60_000 ? '' : 's'}`;\n const seconds = Math.round(ms / 100) / 10;\n return `${seconds} second${seconds === 1 ? '' : 's'}`;\n}\n\n/**\n * `refuted` is a check of the work the call's own evidence failed, as a\n * delegated task's protected paths do (ADR-0055 D7): a `done` it refutes fails,\n * with what failed named, whatever the runner said.\n */\nfunction reportedVerdict(report: TaskCompleteArgs, refuted?: VerificationCheck): Verdict {\n const checks: VerificationCheck[] = [\n {\n name: 'task_complete',\n passed: report.status === 'done',\n skipped: false,\n detail: `the runner called task_complete with status \"${report.status}\"`,\n },\n ...(refuted ? [refuted] : []),\n ];\n const decidedAt = new Date().toISOString();\n // Kept apart from the outcome: `blocked` and `failed` fail alike, but only a `failed` check starts a loop's round (ADR-0045 L2).\n const reported = report.status;\n if (report.status === 'done' && refuted) return { outcome: 'fail', reason: refuted.detail, checks, decidedAt, reported: 'failed' };\n if (report.status === 'done') {\n return { outcome: 'pass', reason: 'Verified: the runner reported completion through task_complete. Task completed successfully.', checks, decidedAt, reported };\n }\n // Runners often put the why in the summary and leave `reason` out; its\n // first paragraph is their own words, where \"no reason given\" would not be.\n const why = report.reason?.trim() || report.summary?.trim().split(/\\n\\s*\\n/)[0].trim() || 'no reason given';\n return { outcome: 'fail', reason: `The runner reported the task ${report.status}: ${why}`, checks, decidedAt, reported };\n}\n"],"mappings":";AACO,IAAM,qBAAqB;AAQlC,IAAM,c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