@ordewell/core 0.12.0 → 0.12.2
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-CHsaoV7M.d.ts → ModeResolver-B64aUZXJ.d.ts} +1 -1
- package/dist/{ModeResolver-b_7bPlBS.d.mts → ModeResolver-CA2fUU9h.d.mts} +1 -1
- package/dist/{Task-BTEH-ztX.d.mts → Task-CxGgN6I0.d.mts} +503 -16
- package/dist/{Task-BTEH-ztX.d.ts → Task-CxGgN6I0.d.ts} +503 -16
- package/dist/{chunk-BKTDYGIP.mjs → chunk-2IFKPYPO.mjs} +441 -17
- package/dist/chunk-2IFKPYPO.mjs.map +1 -0
- package/dist/{chunk-BFLVOYNR.mjs → chunk-FX33UKAD.mjs} +8 -6
- package/dist/chunk-FX33UKAD.mjs.map +1 -0
- package/dist/{chunk-F6WS3JLQ.mjs → chunk-PKJTN2PD.mjs} +20 -11
- package/dist/chunk-PKJTN2PD.mjs.map +1 -0
- package/dist/{chunk-HP2LNKST.mjs → chunk-RZ23BMVR.mjs} +345 -134
- package/dist/chunk-RZ23BMVR.mjs.map +1 -0
- package/dist/chunk-UDUATSCJ.mjs +48 -0
- package/dist/chunk-UDUATSCJ.mjs.map +1 -0
- package/dist/{IRunner-BwzyUVIL.d.mts → eventStore-CTCSKS9E.d.ts} +916 -129
- package/dist/{IRunner-DjJkYwko.d.ts → eventStore-CcB8yELZ.d.mts} +916 -129
- package/dist/index.d.mts +677 -97
- package/dist/index.d.ts +677 -97
- package/dist/index.js +8233 -2450
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6951 -1772
- package/dist/index.mjs.map +1 -1
- package/dist/parsing.d.mts +2 -2
- package/dist/parsing.d.ts +2 -2
- package/dist/parsing.js +277 -21
- package/dist/parsing.js.map +1 -1
- package/dist/parsing.mjs +3 -3
- package/dist/plan-utils.d.mts +30 -5
- package/dist/plan-utils.d.ts +30 -5
- package/dist/plan-utils.js +163 -16
- package/dist/plan-utils.js.map +1 -1
- package/dist/plan-utils.mjs +49 -3
- package/dist/plan-utils.mjs.map +1 -1
- package/dist/{runSettingsText-x-YML2ay.d.mts → runSettingsText-DFVpe6aU.d.mts} +1142 -934
- package/dist/{runSettingsText-CvZ40IPv.d.ts → runSettingsText-lKLDsyli.d.ts} +1142 -934
- package/dist/testing.d.mts +83 -4
- package/dist/testing.d.ts +83 -4
- package/dist/testing.js +142 -1
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +126 -2
- package/dist/testing.mjs.map +1 -1
- package/docker/task.Dockerfile +22 -0
- package/package.json +2 -1
- package/skills/diagnose/SKILL.md +2 -2
- package/skills/explore/SKILL.md +1 -1
- package/dist/chunk-BFLVOYNR.mjs.map +0 -1
- package/dist/chunk-BKTDYGIP.mjs.map +0 -1
- package/dist/chunk-F6WS3JLQ.mjs.map +0 -1
- package/dist/chunk-HP2LNKST.mjs.map +0 -1
|
@@ -344,10 +344,10 @@ var VerdictEngine = class {
|
|
|
344
344
|
getCheckpointQuestion(taskId) {
|
|
345
345
|
return this.checkpointQuestions.get(taskId);
|
|
346
346
|
}
|
|
347
|
-
approveCheckpoint(taskId) {
|
|
347
|
+
approveCheckpoint(taskId, note) {
|
|
348
348
|
this.checkpointQuestions.delete(taskId);
|
|
349
349
|
this.resumeIdle(taskId);
|
|
350
|
-
this.toolCheckpoints.get(taskId)?.({ kind: "continue" });
|
|
350
|
+
this.toolCheckpoints.get(taskId)?.({ kind: "continue", ...note ? { note } : {} });
|
|
351
351
|
}
|
|
352
352
|
rejectCheckpoint(taskId, reason) {
|
|
353
353
|
this.checkpointQuestions.delete(taskId);
|
|
@@ -399,7 +399,7 @@ var VerdictEngine = class {
|
|
|
399
399
|
else if (event.type === "permission_request" && !event.decided) this.approvalOpened(task.id, event.id);
|
|
400
400
|
else if (event.type === "permission_decided" || event.type === "permission_withdrawn") this.approvalClosed(task.id, event.id, gen);
|
|
401
401
|
});
|
|
402
|
-
session.onTaskComplete((report) => this.signalComplete(task.id, gen, report));
|
|
402
|
+
session.onTaskComplete((report, refuted) => this.signalComplete(task.id, gen, report, refuted));
|
|
403
403
|
session.onScriptExit((exit) => this.signalScriptExit(task.id, gen, exit));
|
|
404
404
|
session.onToolCheckpoint((question, signal) => this.raiseCheckpoint(task.id, gen, question, signal));
|
|
405
405
|
session.onExit((exitCode) => {
|
|
@@ -415,9 +415,9 @@ var VerdictEngine = class {
|
|
|
415
415
|
* attempt, unless that attempt is no longer the task's current one or an
|
|
416
416
|
* earlier call already settled it.
|
|
417
417
|
*/
|
|
418
|
-
signalComplete(taskId, generation, report) {
|
|
418
|
+
signalComplete(taskId, generation, report, refuted) {
|
|
419
419
|
if (this.generations.get(taskId) !== generation) return;
|
|
420
|
-
this.acceptVerdict(taskId, reportedVerdict(report));
|
|
420
|
+
this.acceptVerdict(taskId, reportedVerdict(report, refuted));
|
|
421
421
|
}
|
|
422
422
|
/**
|
|
423
423
|
* A script task's exit status (ADR-0035): its one evidence, as a runner's
|
|
@@ -619,17 +619,19 @@ function durationText(ms) {
|
|
|
619
619
|
const seconds = Math.round(ms / 100) / 10;
|
|
620
620
|
return `${seconds} second${seconds === 1 ? "" : "s"}`;
|
|
621
621
|
}
|
|
622
|
-
function reportedVerdict(report) {
|
|
622
|
+
function reportedVerdict(report, refuted) {
|
|
623
623
|
const checks = [
|
|
624
624
|
{
|
|
625
625
|
name: "task_complete",
|
|
626
626
|
passed: report.status === "done",
|
|
627
627
|
skipped: false,
|
|
628
628
|
detail: `the runner called task_complete with status "${report.status}"`
|
|
629
|
-
}
|
|
629
|
+
},
|
|
630
|
+
...refuted ? [refuted] : []
|
|
630
631
|
];
|
|
631
632
|
const decidedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
632
633
|
const reported = report.status;
|
|
634
|
+
if (report.status === "done" && refuted) return { outcome: "fail", reason: refuted.detail, checks, decidedAt, reported: "failed" };
|
|
633
635
|
if (report.status === "done") {
|
|
634
636
|
return { outcome: "pass", reason: "Verified: the runner reported completion through task_complete. Task completed successfully.", checks, decidedAt, reported };
|
|
635
637
|
}
|
|
@@ -686,7 +688,7 @@ function resolveUserTaskRef(tasks, ref) {
|
|
|
686
688
|
// src/models/Task.ts
|
|
687
689
|
import { v4 as uuidv4 } from "uuid";
|
|
688
690
|
function isAwaitingReason(value) {
|
|
689
|
-
return value === "input" || value === "checkpoint" || value === "conflict" || value === "files-changed" || value === "usage-limit";
|
|
691
|
+
return value === "input" || value === "checkpoint" || value === "question-lost" || value === "conflict" || value === "files-changed" || value === "usage-limit";
|
|
690
692
|
}
|
|
691
693
|
function migrateLoadedTasks(tasks) {
|
|
692
694
|
for (const task of tasks) {
|
|
@@ -707,6 +709,7 @@ function migrateLoadedTasks(tasks) {
|
|
|
707
709
|
}
|
|
708
710
|
function failInterruptedTasks(tasks, now) {
|
|
709
711
|
for (const task of flattenTasks(tasks)) {
|
|
712
|
+
if (task.type === "delegated" && task.awaitingReason === "checkpoint") task.awaitingReason = "question-lost";
|
|
710
713
|
if (task.status !== "in_progress") continue;
|
|
711
714
|
task.status = "failed";
|
|
712
715
|
task.verdict = interruptedVerdict(now);
|
|
@@ -868,7 +871,7 @@ function createTask(overrides = {}) {
|
|
|
868
871
|
assignedModel: overrides.assignedModel,
|
|
869
872
|
assignedRunner: overrides.assignedRunner ?? DEFAULT_RUNNERS[0],
|
|
870
873
|
// A script task runs in no mode (ADR-0035): one given it would read as a mode it runs in.
|
|
871
|
-
taskMode: overrides.taskMode ?? (type === "script" ? void 0 : "build"),
|
|
874
|
+
taskMode: overrides.taskMode ?? (type === "script" || type === "delegated" ? void 0 : "build"),
|
|
872
875
|
autonomy: overrides.autonomy,
|
|
873
876
|
sliceType: overrides.sliceType,
|
|
874
877
|
userStoriesCovered: overrides.userStoriesCovered,
|
|
@@ -878,6 +881,12 @@ function createTask(overrides = {}) {
|
|
|
878
881
|
...overrides.commands !== void 0 ? { commands: overrides.commands.map((argv) => [...argv]) } : {},
|
|
879
882
|
...overrides.script !== void 0 ? { script: overrides.script } : {},
|
|
880
883
|
...overrides.timeoutMs !== void 0 ? { timeoutMs: overrides.timeoutMs } : {},
|
|
884
|
+
...overrides.goal !== void 0 ? { goal: overrides.goal } : {},
|
|
885
|
+
...overrides.budget !== void 0 ? { budget: { ...overrides.budget } } : {},
|
|
886
|
+
...overrides.grants !== void 0 ? { grants: [...overrides.grants] } : {},
|
|
887
|
+
...overrides.protectedPaths !== void 0 ? { protectedPaths: [...overrides.protectedPaths] } : {},
|
|
888
|
+
...overrides.scope !== void 0 ? { scope: structuredClone(overrides.scope) } : {},
|
|
889
|
+
...overrides.readOnly ? { readOnly: true } : {},
|
|
881
890
|
...overrides.loop ? { loop: { body: [...overrides.loop.body], maxRounds: overrides.loop.maxRounds } } : {},
|
|
882
891
|
...overrides.loopRound !== void 0 ? { loopRound: overrides.loopRound } : {},
|
|
883
892
|
...overrides.research !== void 0 ? { research: overrides.research } : {}
|
|
@@ -900,7 +909,7 @@ function opsFlag(value, type = "ai") {
|
|
|
900
909
|
return value === true && type === "ai" ? true : void 0;
|
|
901
910
|
}
|
|
902
911
|
function runsAsOps(task) {
|
|
903
|
-
return task.type === "script" || opsFlag(task.ops, task.type) === true;
|
|
912
|
+
return task.type === "script" && !task.readOnly || opsFlag(task.ops, task.type) === true;
|
|
904
913
|
}
|
|
905
914
|
function inheritedOps(from, chosen) {
|
|
906
915
|
return chosen ?? from.every((t) => opsFlag(t.ops) === true);
|
|
@@ -1125,4 +1134,4 @@ export {
|
|
|
1125
1134
|
stampOrigin,
|
|
1126
1135
|
keepExecutionState
|
|
1127
1136
|
};
|
|
1128
|
-
//# sourceMappingURL=chunk-
|
|
1137
|
+
//# sourceMappingURL=chunk-PKJTN2PD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/conversation/skillTokens.ts","../src/services/PlanTree.ts","../src/services/repoPath.ts","../src/services/isolationRecord.ts","../src/services/VerdictEngine.ts","../src/services/TaskRefs.ts","../src/models/Task.ts"],"sourcesContent":["/** A name a skill can have, lower-cased: the one pattern for a `/name` token and for a skill folder. */\nexport const SKILL_NAME_PATTERN = '[a-z0-9][a-z0-9_-]*';\n\n/**\n * A `/skill-name` token anywhere in a message: whitespace (or string start)\n * before it, a skill name in any case, optional trailing punctuation that\n * isn't part of the name, then whitespace (or string end). The punctuation\n * group is what lets \"/grilling,\" name \"grilling\".\n */\nconst SKILL_TOKEN = new RegExp(`(^|\\\\s)\\\\/(${SKILL_NAME_PATTERN})([,.!?;:]*)(?=\\\\s|$)`, 'gi');\n\n/** Where a skill name is invoked: `start` is its `/`, `end` is just past the name, before any punctuation. */\nexport interface SkillToken {\n name: string;\n start: number;\n end: number;\n}\n\n/**\n * The first `/name` token for each name in `text`, names lower-cased. Only\n * the first counts because a skill loads once per message however often it is\n * named, so a later repeat is plain text.\n */\nexport function skillTokens(text: string): SkillToken[] {\n const tokens: SkillToken[] = [];\n const seen = new Set<string>();\n for (const match of text.matchAll(SKILL_TOKEN)) {\n const name = match[2].toLowerCase();\n if (seen.has(name)) continue;\n seen.add(name);\n const start = match.index + match[1].length;\n tokens.push({ name, start, end: start + 1 + match[2].length });\n }\n return tokens;\n}\n\n/** The tokens in a sent message that loaded one of `loaded` — what a surface highlights in the user's bubble. */\nexport function loadedSkillTokens(text: string, loaded: readonly string[]): SkillToken[] {\n return skillTokens(text).filter((t) => loaded.includes(t.name));\n}\n","/** Plan placement and dependency rules, shared with browser-bundled surfaces. */\nexport interface TreeTask<T> {\n id: string;\n order: number;\n title: string;\n subtasks?: readonly T[];\n}\n\nexport interface DependencyTask<T> extends TreeTask<T> {\n dependencies: readonly string[];\n}\n\nexport interface TaskPlacement<T> {\n task: T;\n parent?: T;\n ancestors: readonly T[];\n siblings: readonly T[];\n label: string;\n}\n\nexport function* walkPlan<T extends TreeTask<T>>(tasks: readonly T[]): Generator<TaskPlacement<T>> {\n function* walk(level: readonly T[], ancestors: readonly T[], parentLabel?: string): Generator<TaskPlacement<T>> {\n for (const task of level) {\n const label = parentLabel ? `${parentLabel}.${task.order}` : String(task.order);\n yield { task, parent: ancestors.at(-1), ancestors, siblings: level, label };\n yield* walk(task.subtasks ?? [], [...ancestors, task], label);\n }\n }\n yield* walk(tasks, []);\n}\n\nexport function taskPlacement<T extends TreeTask<T>>(tasks: readonly T[], id: string): TaskPlacement<T> | undefined {\n for (const row of walkPlan(tasks)) if (row.task.id === id) return row;\n return undefined;\n}\n\n/** Includes the root: deletion has to detach every edge into the removed tree. */\nexport function subtreeIds<T extends TreeTask<T>>(tasks: readonly T[], id: string): Set<string> {\n const found = taskPlacement(tasks, id);\n return new Set(found ? [...walkPlan([found.task])].map(({ task }) => task.id) : []);\n}\n\n/** Pickers offer earlier siblings; API validity is independent of display order. */\nexport function dependencyCandidates<T extends TreeTask<T>>(tasks: readonly T[], taskId?: string): T[] {\n if (!taskId) return [...tasks];\n const found = taskPlacement(tasks, taskId);\n return found ? found.siblings.filter((t) => t.order < found.task.order) : [];\n}\n\n/** The surviving tasks whose dependency lists a subtree removal will change. */\nexport function dependentsOf<T extends DependencyTask<T>>(tasks: readonly T[], taskId: string): T[] {\n const removed = subtreeIds(tasks, taskId);\n return [...walkPlan(tasks)].map(({ task }) => task)\n .filter((t) => !removed.has(t.id) && t.dependencies.some((id) => removed.has(id)));\n}\n\nexport interface DependencyCheck { ok: boolean; error?: string }\n\n/** Target restrictions, separate from cycles so a planner batch can check its final graph. */\nexport function dependencyTargetErrors<T extends TreeTask<T>>(\n tasks: readonly T[], taskId: string, dependencies: readonly string[],\n): string[] {\n const found = taskPlacement(tasks, taskId);\n if (!found) return ['Task not found'];\n const descendants = subtreeIds(tasks, taskId);\n const errors: string[] = [];\n for (const dep of dependencies) {\n if (dep === taskId) { errors.push(`\"${found.task.title}\" cannot depend on itself`); continue; }\n const target = taskPlacement(tasks, dep)?.task;\n if (!target) { errors.push(`Unknown dependency \"${dep}\"`); continue; }\n if (found.ancestors.some((t) => t.id === dep) || descendants.has(dep)) {\n errors.push(`\"${found.task.title}\" cannot depend on \"${target.title}\", its ancestor or descendant`);\n }\n }\n return errors;\n}\n\n/** The tasks on one dependency cycle, in dependency order, or null. */\nexport function findDependencyCycle<T extends DependencyTask<T>>(tasks: readonly T[]): T[] | null {\n const byId = new Map([...walkPlan(tasks)].map(({ task }) => [task.id, task]));\n const path: string[] = [];\n const done = new Set<string>();\n const visit = (id: string): string[] | null => {\n if (done.has(id)) return null;\n const at = path.indexOf(id);\n if (at >= 0) return path.slice(at);\n path.push(id);\n for (const dep of byId.get(id)?.dependencies ?? []) {\n const hit = visit(dep);\n if (hit) return hit;\n }\n path.pop();\n done.add(id);\n return null;\n };\n for (const id of byId.keys()) {\n const hit = visit(id);\n if (hit) return hit.map((key) => byId.get(key)!);\n }\n return null;\n}\n\nexport function canSetDependencies<T extends DependencyTask<T>>(\n tasks: readonly T[], taskId: string, dependencies: readonly string[],\n): DependencyCheck {\n const [error] = dependencyTargetErrors(tasks, taskId, dependencies);\n if (error) return { ok: false, error };\n const replace = (level: readonly T[]): T[] => level.map((t) => ({\n ...t,\n dependencies: t.id === taskId ? dependencies : t.dependencies,\n subtasks: replace(t.subtasks ?? []),\n }));\n const cycle = findDependencyCycle(replace(tasks));\n return cycle\n ? { ok: false, error: `Dependency cycle detected: ${[...cycle, cycle[0]].map((t) => `\"${t.title}\"`).join(' → ')}` }\n : { ok: true };\n}\n","/**\n * The path of the repo in a workspace that is itself the repository. Kept in\n * its own module, with no imports, so a browser surface can word a merge\n * result without pulling in the isolation record's `path` dependency.\n */\nexport const SELF_REPO = '.';\n","import * as path from 'path';\nimport type {\n IsolationHandoff,\n IsolationLandedTask,\n IsolationRemoval,\n IsolationRepo,\n IsolationRun,\n IsolationTaskRecord,\n IsolationTaskStatus,\n IsolationView,\n PlanIsolation,\n PreservedWork,\n RepoGroupLayout,\n TaskIsolation,\n} from '../interfaces/IWorktreeIsolation';\nimport { SELF_REPO } from './repoPath';\n\nexport { SELF_REPO };\n\nexport function integrationBranchFor(runId: string): string {\n return `ordewell/${runId}/integration`;\n}\n\nexport function repoRootOf(workspaceRoot: string, repoPath: string): string {\n return path.join(workspaceRoot, repoPath);\n}\n\n/** A removal that kept nothing back. */\nexport function noRemoval(): IsolationRemoval {\n return { preserved: [], refused: [] };\n}\n\n/**\n * A `prepare` that failed after it had already replaced the last attempt of\n * the task: that attempt's unlanded work was kept on `preserved` first, and no\n * record names it any more, so whoever tells the user about the failure has to\n * tell them where it went. Reads as the failure it wraps.\n */\nexport class PrepareFailedError extends Error {\n constructor(readonly failure: unknown, readonly preserved: PreservedWork[]) {\n super(failure instanceof Error ? failure.message : String(failure));\n this.name = failure instanceof Error ? failure.name : 'Error';\n this.cause = failure;\n }\n}\n\n/** Add what `from` kept back to `into`. */\nexport function absorbRemoval(into: IsolationRemoval, from: IsolationRemoval): IsolationRemoval {\n into.preserved.push(...from.preserved);\n into.refused.push(...from.refused);\n return into;\n}\n\n/** The group a run isolates, as the planner is told it. */\nexport function layoutOf(run: IsolationRun): RepoGroupLayout {\n return { repos: run.repos.map((r) => r.path), shared: [...run.shared] };\n}\n\nconst ISOLATION_STATE: Record<IsolationTaskStatus, Exclude<TaskIsolation['state'], 'none'>> = {\n active: 'active',\n merged: 'integrated',\n conflict: 'conflict',\n repairing: 'repairing',\n kept: 'kept',\n failed: 'kept',\n};\n\n/** Whether a saved record's status is one this build knows; a newer daemon may have written one it does not. */\nconst isKnownStatus = (status: string): status is IsolationTaskStatus =>\n Object.prototype.hasOwnProperty.call(ISOLATION_STATE, status);\n\n/** Paths of the repos a task brought commits to. */\nexport function changedReposOf(record: IsolationTaskRecord): string[] {\n return Object.entries(record.repos).filter(([, r]) => r.changed).map(([repoPath]) => repoPath);\n}\n\n/** Whether a landed task has work in a repo: a later attempt's record says nothing of the merges before it. */\nexport function landedInRepo(run: IsolationRun, record: IsolationTaskRecord, repoPath: string): boolean {\n return !!record.repos[repoPath]?.changed || run.landings?.[record.taskId]?.[repoPath] !== undefined;\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. `landings` are the task's merges in {@link IsolationRun.landings},\n * which a later attempt's record says nothing of: a task at work again keeps its\n * mark off, and a revert would refuse it. A run with no `carried` record, or\n * none given, offers nothing: every revert of such a run is refused.\n */\nfunction revertible(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' ? changedReposOf(record) : [];\n return (changed.length > 0 || landings !== undefined) && changed.every((repo) => record.repos[repo].landedTip || landings?.[repo]);\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 ...(revertible(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 Object.keys(run.landings ?? {})) {\n if (run.carried && !run.carried[taskId]) tasks[taskId] = { state: 'none', revertible: true };\n }\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) => landedInRepo(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","import type { Task, Verdict, VerificationCheck } from '../models/Task';\nimport type { IRunnerSession, ScriptExit, ScriptFullOutput, ScriptStatus } from '../interfaces/IRunner';\nimport type { CheckpointAnswer, TaskCompleteArgs } from './mcp/tools';\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\n/**\n * No output for this long marks a running task idle (advisory, UI-only). Long\n * model turns and slow builds routinely go quiet for minutes, so a shorter\n * 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 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 /** 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 }\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.touchIdle(taskId, gen);\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) 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.idleSince.set(taskId, now);\n for (const l of this.idleListeners) l(taskId, now);\n }, IDLE_TIMEOUT_MS));\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.idlePaused.delete(taskId);\n this.openApprovals.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.touchIdle(task.id, gen);\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 // 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.approvalOpened(task.id, event.id);\n else if (event.type === 'permission_decided' || event.type === 'permission_withdrawn') this.approvalClosed(task.id, event.id, gen);\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 if (this.sessions.get(taskId)?.queued().length) {\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 private approvalOpened(taskId: string, approvalId: string): void {\n const open = this.openApprovals.get(taskId) ?? new Set<string>();\n open.add(approvalId);\n this.openApprovals.set(taskId, open);\n this.clearIdle(taskId);\n }\n\n private approvalClosed(taskId: string, approvalId: string, gen: number): void {\n const open = this.openApprovals.get(taskId);\n if (!open?.delete(approvalId) || open.size) return;\n this.openApprovals.delete(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.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.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","import { taskPlacement, walkPlan, type TreeTask } from './PlanTree';\n\n/**\n * Task references: the one grammar for naming a task in a plan, both ways.\n * A label is rendered from a task's order under its parent (\"2\", \"2.1\"), and\n * a reference written by anyone — the planner, a tool call, a command — is\n * resolved back against the plan tree. Pure so a\n * browser-bundled surface can use it through `@ordewell/core/plan-utils`.\n */\n\n/** The shape a reference resolves over: the plan's task tree, or a surface's projection of it. */\nexport type RefTask<T> = TreeTask<T>;\n\n/**\n * The parent a label extends. A label is the full path (\"3.2.1\"), so a parent\n * below the top level carries the label it was itself reached by; without one\n * the parent's order stands for it, which is right for a top-level parent.\n */\nexport interface RefParent {\n order: number;\n label?: string;\n}\n\n/** Dotted path label for a task, e.g. \"2.1\" for the first subtask of task 2, \"2.1.3\" one level down. */\nexport function taskOrderLabel(task: { order: number }, parent?: RefParent): string {\n return parent ? `${parent.label ?? parent.order}.${task.order}` : String(task.order);\n}\n\n/** How a surface refers to a task in prose: \"#2\", or \"#2.1\" for a subtask. */\nexport function taskRef(task: { order: number }, parent?: RefParent): string {\n return `#${taskOrderLabel(task, parent)}`;\n}\n\n/** A task named in full, as a confirmation or a picker title does: \"#2 Deploy\". */\nexport function titledTaskRef(task: { order: number; title: string }, parent?: RefParent): string {\n return `${taskRef(task, parent)} ${task.title}`;\n}\n\n/** A task found in a plan tree, with its parent and the full path label its reference extends. */\nexport interface RefTaskMatch<T> {\n task: T;\n parent?: T;\n label: string;\n}\n\n/** The task a plan tree holds, by id, with its parent; undefined when the tree holds none. */\nexport function findTaskRef<T extends RefTask<T>>(tasks: readonly T[], id: string): RefTaskMatch<T> | undefined {\n return taskPlacement(tasks, id);\n}\n\n/**\n * The reference {@link taskRef} renders for the task a plan tree holds, by id\n * — its full path, dotted, for a subtask. Undefined when the tree holds no such task.\n */\nexport function taskRefOf<T extends RefTask<T>>(tasks: readonly T[], id: string): string | undefined {\n const found = findTaskRef(tasks, id);\n return found && `#${found.label}`;\n}\n\n/**\n * The reference and title {@link titledTaskRef} renders for the task a plan\n * tree holds, by id — its full path, dotted, for a subtask. Undefined when the\n * tree holds no such task.\n */\nexport function titledTaskRefOf<T extends RefTask<T>>(tasks: readonly T[], id: string): string | undefined {\n const found = findTaskRef(tasks, id);\n return found && `#${found.label} ${found.task.title}`;\n}\n\n/**\n * Resolve a written reference to a task at any depth: an id, then an order\n * label with or without \"#\" (\"#2\", \"2\", \"#2.1\"), then an exact title.\n *\n * An order label is read against the tree, never a flattened list: subtask\n * orders restart at 1 under each parent, so \"#2\" always means top-level task 2\n * and a subtask is reachable only by its dotted path (\"#2.1\", \"#2.1.3\").\n */\nexport function resolveTaskRef<T extends RefTask<T>>(tasks: readonly T[], ref: string | number): T | undefined {\n const s = String(ref).trim();\n if (!s) return undefined;\n for (const { task } of walkPlan(tasks)) if (task.id === s) return task;\n const label = s.startsWith('#') ? s.slice(1) : s;\n if (/^\\d+(\\.\\d+)*$/.test(label)) {\n let level: readonly T[] | undefined = tasks;\n let found: T | undefined;\n for (const order of label.split('.').map(Number)) {\n found = level?.find((t) => t.order === order);\n level = found?.subtasks;\n }\n return found;\n }\n for (const { task } of walkPlan(tasks)) if (task.title === s) return task;\n return undefined;\n}\n\n/**\n * A reference as the user types one: {@link resolveTaskRef}, then a unique\n * prefix of a task's id at any depth. Only the user's: a model's reference\n * that names no task is refused, never matched to the one task a fragment of\n * it happens to fit.\n */\nexport function resolveUserTaskRef<T extends RefTask<T>>(tasks: readonly T[], ref: string | number): T | undefined {\n const found = resolveTaskRef(tasks, ref);\n if (found) return found;\n const prefix = String(ref).trim();\n const matches = prefix ? [...walkPlan(tasks)].filter(({ task }) => task.id.startsWith(prefix)) : [];\n return matches.length === 1 ? matches[0].task : undefined;\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport type { PlanIsolation } from '../interfaces/IWorktreeIsolation';\nimport type { AttemptUsage, PlannerUsage, ReportedWindow, UsageRecord, UsageTotals } from './Usage';\nimport type { ExecutionRecord, ScriptConsent, SupervisorLevel } from './Execution';\nimport type { SkillSource } from '../services/SkillsService';\nimport type { SupervisionMemorySnapshot } from '../services/LoopGuards';\nimport type { SupervisorSnapshot } from '../services/Supervisor';\nimport type { TaskLoop } from './Loop';\nimport type { HandoffDigest } from './Handoff';\nimport type { DelegatedBudget, TaskScope } from './Delegation';\nimport type { Grant } from '../services/Mandate';\nimport { SKILL_NAME_PATTERN } from '../conversation/skillTokens';\nimport { subtreeIds, walkPlan } from '../services/PlanTree';\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, an ops task that changed tracked files (ADR-0020), or its runner's\n * usage limit. Saved, so no surface has to guess it from whether an attempt\n * is live.\n */\nexport type AwaitingReason = 'input' | 'checkpoint' | 'question-lost' | 'conflict' | '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 === 'files-changed' || value === 'usage-limit';\n}\n\nexport interface TaskModelAssignment {\n modelId: string;\n modelLabel: string;\n thinkingEffort?: string;\n /**\n * All variant ids the model offered when this assignment was made. Carried\n * on the assignment because runners need it at spawn time (opencode's TUI\n * only honors an assigned variant when the others are config-disabled) and\n * the discovery catalog isn't available there.\n */\n availableVariants?: string[];\n}\n\nexport type RunnerId = string;\n\n/**\n * Bring loaded tasks to the structured-only shape, in place. A task saved\n * while the terminal transport existed may say it ran there, and why; neither\n * means anything now, and such a task left no session to continue. Its\n * completion marker id went with the text markers: completion is reported\n * only through `task_complete`.\n */\nexport function migrateLoadedTasks(tasks: readonly Task[]): void {\n for (const task of tasks) {\n if (typeof task.runnerSessionId !== 'string') delete task.runnerSessionId;\n if (typeof task.carriedFrom !== 'string') delete task.carriedFrom;\n if (typeof task.runnerSessionOwner !== 'string') delete task.runnerSessionOwner;\n const legacy = task as Task & { transport?: { kind?: unknown; nativeSessionId?: unknown } };\n if (!task.runnerSessionId && legacy.transport?.kind === 'structured' && typeof legacy.transport.nativeSessionId === 'string') {\n task.runnerSessionId = legacy.transport.nativeSessionId;\n }\n delete legacy.transport;\n delete (task as { completionMarker?: unknown }).completionMarker;\n // The effort once had a second home on the task; the spawn reads only the model's.\n const effort = (task as { thinkingEffort?: unknown }).thinkingEffort;\n if (typeof effort === 'string' && task.assignedModel && !task.assignedModel.thinkingEffort) task.assignedModel.thinkingEffort = effort;\n delete (task as { thinkingEffort?: unknown }).thinkingEffort;\n migrateLoadedTasks(task.subtasks ?? []);\n }\n}\n\n/**\n * 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}\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.\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 * 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.\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}\n\n/**\n * How a planner compaction ended. `condensed`: a summary stands in for the\n * older context (a checkpoint was written, or a harness planner reported its\n * own compaction done). `pruned`: older recoverable tool output was dropped\n * from the live context alone. `unchanged`: nothing needed doing. `paused`:\n * the context could not be brought to fit, so the planner waits.\n */\nexport type PlannerCompactionOutcome = 'condensed' | 'pruned' | 'unchanged' | 'stopped' | 'failed' | 'paused';\n\n/**\n * One planner compaction's lifecycle as it was observed (ADR-0017): both\n * phases share `id`, which is the checkpoint's id when one is written. Only\n * Ordewell's own compaction announces a start; a harness planner's native one\n * is reported when it is over, and nothing invents the start it never sent.\n * Sizes are only ever what a backend reported.\n */\nexport type PlannerCompaction =\n | { phase: 'started'; id: string; origin: 'ordewell'; trigger: ContextCheckpoint['trigger']; at: string }\n | {\n phase: 'ended';\n id: string;\n origin: 'ordewell' | 'native';\n trigger: ContextCheckpoint['trigger'];\n outcome: PlannerCompactionOutcome;\n at: string;\n preTokens?: number;\n postTokens?: number;\n };\n\n/**\n * One run of a planner reply's text: the segment it streamed under, its\n * settled text, and when it began. A run that never streamed (a message the\n * conversation wrote in the planner's place) has a segment no stream used.\n */\nexport interface ReplyRun {\n segmentId: string;\n text: string;\n /** ISO timestamp. */\n startedAt: string;\n}\n\n/**\n * A skill's SKILL.md as it was when loaded into a planner conversation. A\n * snapshot rather than a reference: a resumed, forked or rewound conversation\n * replays the body the planner originally saw, even after the file changed or\n * was deleted.\n */\nexport interface SkillLoad {\n invokedBy: 'user' | 'planner';\n name: string;\n source: SkillSource;\n /** The SKILL.md that won, home-abbreviated (`~/...`): which copy loaded is what a reader needs from it. */\n path: string;\n content: string;\n /**\n * Set when the user named a task skill: it is not loaded into the planner's\n * context, which is only told to attach it to the tasks it fits. `content`\n * is empty; the description is what the planner's directive quotes.\n */\n attaches?: { description: string };\n}\n\n/** A skill load as a surface announces it — the body stays with the transcript. */\nexport type SkillLoadNotice = Omit<SkillLoad, 'content'>;\n\n/** A message the user sent, as opposed to a skill load their message caused or a wake-up digest. */\nexport function isUserMessage(entry: Pick<ConversationMessage, 'role' | 'kind'>): boolean {\n return entry.role === 'user' && entry.kind !== 'skill_load' && entry.kind !== 'wake_up';\n}\n\n/** A follow-up an older build queued behind a run's batch boundary; read only to carry it over as a {@link PendingPlanTurn}. */\nexport interface QueuedMessage {\n id: string;\n text: string;\n timestamp: string;\n skills?: SkillLoad[];\n}\n\n/** Who a planner turn answers (ADR-0029): the user's message, or a wake-up batch the supervisor is given. */\nexport type PlanTurnSource = 'user' | 'supervisor';\n\n/**\n * A planner turn's input not yet answered by a turn that ended. It leaves the\n * plan with the change its turn made, in the same save, so a reload replays\n * exactly the inputs no turn answered — once. A supervisor's input is a\n * wake-up batch not yet delivered (ADR-0029): it stays until a turn lands\n * with it, whatever turns fail meanwhile.\n */\nexport interface PendingPlanTurn {\n id: string;\n source: PlanTurnSource;\n /** The user's message, or a wake-up batch's digest. */\n text: string;\n timestamp: string;\n /** What its `/name` tokens loaded when it was sent, so a replay sends the same skills. */\n skills?: SkillLoad[];\n /** Force sent: it waits ahead of every input not forced, and its turn is its own (ADR-0023, F2). */\n forced?: true;\n /**\n * A supervisor input carrying a report the planner asked for (ADR-0037, R2),\n * which opens a turn at every supervisor level: `user` for a task started in\n * the user's turn, which the turn then acts as (R3).\n */\n report?: TurnAuthority;\n /**\n * 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}\n\n/**\n * The run's own copy of the user's run settings (ADR-0030): taken when the\n * user starts it, changed at once by a change made in this session, and\n * lowered by a tripped guard or a failed supervisor.\n */\nexport interface RunSettings {\n mergeAtGatesAutomatically: boolean;\n /** Absent on a run started before supervisor levels existed: Off. */\n supervisorLevel?: SupervisorLevel;\n /** Absent on a run started before ADR-0030: the user's setting. */\n supervisorRetryLimit?: number;\n /** Absent on a run started before ADR-0030: the user's setting. */\n wakeUpReadBudget?: number;\n /** Why the supervisor stopped for the rest of this run, which carries on as Off; absent while it watches. */\n unsupervised?: string;\n}\n\n/**\n * What supervision remembers across a daemon restart (ADR-0029): the loop\n * guards' memory and the wake-up state not yet delivered with a turn.\n */\nexport interface SupervisionSnapshot {\n /** Retries, failed-attempt shapes, the supervisor's edits and what the user was told. */\n guards?: SupervisionMemorySnapshot;\n /** The events inside their debounce window and the wake-up rate's timestamps. */\n wake?: SupervisorSnapshot;\n}\n\n/**\n * What waits on the planner's usage limit. With `at`, the inputs no turn\n * answered are sent again then, on their own; without it — the reset could\n * not be read, the resend hit the limit again, or it was cancelled — they go\n * with the next input: the user's message, or a wake-up.\n */\nexport interface PlannerResendState {\n /** The runner whose account hit the limit; a planner on another one is not held by it. */\n runner?: RunnerId;\n at?: string;\n}\n\n/**\n * The planner paused on its context (ADR-0002): an API planner's call could\n * not be brought inside its model's window, so the turn ended with nothing\n * landed and the planner waits for the user's Retry compaction. What it\n * keeps is bounded: the inputs stay in `pendingTurns`, and only the calls\n * that changed something are listed, never the live context itself.\n */\nexport interface PlannerContextPause {\n /** The model the call did not fit. */\n model: string;\n at: string;\n /** What the user is told: why it paused, and what Retry compaction does. */\n reason: string;\n /** The pending inputs the paused turn took: a retry answers these, and what arrived since waits for the turn after it. */\n inputs: string[];\n /**\n * The calls the paused turn made that changed something or reached out,\n * each with the head of what it returned (`effectLedger`). It is never\n * replayed to the planner as a note: it is what lets a retry see that a\n * turn which ran effects cannot start again from the transcript, and what\n * the refusal lists for the user.\n */\n done?: string[];\n /** More such calls ran than `done` keeps: the refusal could not list all of them, and a retry without the live context stays refused. */\n doneTruncated?: true;\n}\n\nexport interface LegacyPlanState {\n /** Research profiles the planner approved as they landed: lifting one withdraws its approval (ADR-0037 R4). */\n researchApprovals?: string[];\n runSettings?: RunSettings;\n /** What supervision remembers across a daemon restart (ADR-0029); absent on plans saved before it existed. */\n supervision?: SupervisionSnapshot;\n tasks: Task[];\n generatedAt: string;\n status: PlanStatus;\n runners: RunnerId[];\n lastUpdated: string;\n researchLog?: ResearchLogEntry[];\n /** The planner dialogue — user messages and assistant messages, in order (ADR-0002). */\n conversationHistory?: ConversationMessage[];\n /** Full markdown PRD once written by the planner (PRD mode), also saved to .scratch/<slug>/PRD.md. */\n prdMarkdown?: string;\n /** Planner turn inputs no turn has answered yet (ADR-0029); a reload replays them. */\n pendingTurns?: PendingPlanTurn[];\n /** Written by builds that queued mid-run edits; a load moves it into {@link pendingTurns}. */\n queuedMessages?: QueuedMessage[];\n /**\n * The plan's isolation run (ADR-0013), written from the orchestrator at\n * persist time and read back only when a saved plan is adopted. It names\n * branches and worktrees that belong to this plan alone: a fork of the plan\n * must leave it behind rather than share it.\n */\n isolation?: PlanIsolation;\n /**\n * The id of the plan's last isolated run, which closed with everything it\n * landed merged into the user's branch; absent once a later run decides how\n * it executes. With no run record left, it is what tells a Merge all asked\n * for after that run from one in a plan that never isolated (ADR-0029).\n */\n mergedRun?: string;\n /** Kept so a reopened session shows the same token line (#49). */\n plannerUsage?: PlannerUsage;\n /** The windows reported over the session, so a reopened one knows each model's from its first call. */\n contextWindows?: ReportedWindow[];\n /** The planner hit its usage limit and the inputs its turn took wait to be sent again; absent otherwise. */\n plannerResend?: PlannerResendState;\n /** The planner's context could not fit its model's window: its turn's inputs wait for Retry compaction; absent otherwise. */\n plannerContextPause?: PlannerContextPause;\n /**\n * The tasks the user approved to run: every task when they executed the\n * plan, and each one they started or retried themselves since. A command\n * from anyone else starts only these (ADR-0029); a task the planner added\n * after the approval waits for the user's. Only tasks still in the plan: a\n * task that leaves takes its approval with it.\n */\n approvedTasks?: string[];\n /**\n * The user approved the plan to run: Execute plan, signing off a review, or\n * autorun's start (ADR-0029, ADR-0030). Kept apart from {@link status},\n * which surfaces rewrite for display; a user's start of one task approves\n * that task, not the plan.\n */\n approved?: boolean;\n}\n\nexport interface Message {\n id: string;\n role: 'user' | 'planner' | 'system';\n content: string;\n timestamp: number;\n}\n\nexport interface TaskSnapshot extends Task {\n completedAt: number;\n verdict?: Verdict;\n retryCount: number;\n finalized: boolean;\n}\n\n/** The plan a surface reads whole carries the approval record, so it can tell which tasks wait for the user (ADR-0035). */\nexport type PlanState = (\n | {\n phase: 'planning';\n history: Message[];\n message: string;\n pendingTasks: Task[];\n }\n | {\n phase: 'executing';\n history: Message[];\n message: string;\n executionLog: TaskSnapshot[];\n pendingTasks: Task[];\n goal: string;\n runners: string[];\n status: PlanStatus;\n }\n) & ApprovalRecord;\n\nfunction hasPhase(raw: unknown): raw is PlanState {\n return typeof raw === 'object' && raw !== null && 'phase' in raw;\n}\n\nfunction hasTasks(raw: unknown): raw is LegacyPlanState {\n return typeof raw === 'object' && raw !== null && 'tasks' in raw && Array.isArray((raw as Record<string, unknown>).tasks);\n}\n\nfunction logEntryToMessage(entry: ResearchLogEntry): Message {\n const timestamp = new Date(entry.timestamp).getTime();\n if (!('type' in entry)) {\n return { id: entry.id, role: 'system', content: JSON.stringify({ tool: entry.tool, args: entry.args, result: entry.result }), timestamp };\n }\n if (entry.type === 'subagent') {\n const { subagentId, brief, outcome, digest } = entry;\n return { id: entry.id, role: 'system', content: JSON.stringify({ subagentId, brief, outcome, digest }), timestamp };\n }\n return { id: entry.id, role: entry.type === 'user_prompt' ? 'user' : 'system', content: entry.content, timestamp };\n}\n\nfunction migrateHistory(raw: LegacyPlanState): Message[] {\n const messages: Message[] = [];\n\n if (raw.researchLog) {\n messages.push(...raw.researchLog.map(logEntryToMessage));\n }\n\n if (raw.queuedMessages) {\n for (const qm of raw.queuedMessages) {\n messages.push({\n id: qm.id,\n role: 'system',\n content: qm.text,\n timestamp: new Date(qm.timestamp).getTime(),\n });\n }\n }\n\n return messages;\n}\n\nexport function migratePlanState(raw: unknown): PlanState {\n if (hasPhase(raw)) return raw;\n\n if (!hasTasks(raw)) {\n return {\n phase: 'planning',\n history: [],\n message: '',\n pendingTasks: [],\n };\n }\n\n const hasExecution = raw.tasks.some(\n (t) => t.status === 'completed' || t.status === 'failed',\n );\n\n const messages = migrateHistory(raw);\n const record = approvalRecordOf(raw);\n\n if (hasExecution) {\n const executionLog: TaskSnapshot[] = raw.tasks\n .filter((t) => t.status === 'completed' || t.status === 'failed')\n .map((t) => ({\n ...t,\n completedAt: new Date(raw.lastUpdated).getTime(),\n verdict: t.verdict,\n retryCount: 0,\n finalized: true,\n }));\n\n const pendingTasks = raw.tasks.filter(\n (t) => t.status !== 'completed' && t.status !== 'failed',\n );\n\n return {\n phase: 'executing',\n history: messages,\n message: '',\n executionLog,\n pendingTasks,\n goal: '',\n runners: raw.runners,\n status: raw.status,\n ...record,\n };\n }\n\n return {\n phase: 'planning',\n history: messages,\n message: '',\n pendingTasks: raw.tasks,\n ...record,\n };\n}\n\nexport { taskOrderLabel, taskRef, taskRefOf, titledTaskRef, titledTaskRefOf, resolveTaskRef, resolveUserTaskRef } from '../services/TaskRefs';\n\nexport function createTask(overrides: Partial<Task> = {}): Task {\n const skills = skillNames(overrides.skills);\n const type = overrides.type ?? 'ai';\n return {\n id: overrides.id ?? uuidv4(),\n order: overrides.order ?? 0,\n title: overrides.title ?? '',\n description: overrides.description ?? '',\n type,\n status: overrides.status ?? 'pending',\n dependencies: overrides.dependencies ?? [],\n prompt: overrides.prompt,\n userSteps: overrides.userSteps,\n subtasks: overrides.subtasks ?? [],\n verdict: overrides.verdict,\n outputSummary: overrides.outputSummary,\n ...(overrides.handoff ? { handoff: structuredClone(overrides.handoff) } : {}),\n ...(overrides.attempted ? { attempted: true as const } : {}),\n ...(overrides.attemptUsage ? { attemptUsage: structuredClone(overrides.attemptUsage) } : {}),\n assignedModel: overrides.assignedModel,\n assignedRunner: overrides.assignedRunner ?? DEFAULT_RUNNERS[0],\n // A script task runs in no mode (ADR-0035): one given it would read as a mode it runs in.\n taskMode: overrides.taskMode ?? (type === 'script' || type === 'delegated' ? undefined : 'build'),\n autonomy: overrides.autonomy,\n sliceType: overrides.sliceType,\n userStoriesCovered: overrides.userStoriesCovered,\n ...(opsFlag(overrides.ops, overrides.type) ? { ops: true } : {}),\n ...(skills ? { skills } : {}),\n ...(overrides.addedBy === 'supervisor' ? { addedBy: 'supervisor' as const } : {}),\n ...(overrides.commands !== undefined ? { commands: overrides.commands.map((argv) => [...argv]) } : {}),\n ...(overrides.script !== undefined ? { script: overrides.script } : {}),\n ...(overrides.timeoutMs !== undefined ? { timeoutMs: overrides.timeoutMs } : {}),\n ...(overrides.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/**\n * A removed task leaves every dependency on it, and every loop's body it was\n * in (ADR-0045 L8): a loop it leaves with no body is no loop. Whether its\n * removal may go ahead at all — a loop's check may not be removed — is the\n * caller's to say.\n */\nexport function removeTaskFromPlan(tasks: readonly Task[], taskId: string): Task[] {\n const removed = subtreeIds(tasks, taskId);\n const prune = (level: readonly Task[]): Task[] => level\n .filter((t) => !removed.has(t.id))\n .map((t) => {\n const pruned: Task = {\n ...t,\n dependencies: t.dependencies.filter((depId) => !removed.has(depId)),\n subtasks: prune(t.subtasks),\n };\n if (!t.loop?.body.some((id) => removed.has(id))) return pruned;\n const body = t.loop.body.filter((id) => !removed.has(id));\n if (body.length > 0) return { ...pruned, loop: { ...t.loop, body } };\n delete pruned.loop;\n delete pruned.loopRound;\n return pruned;\n });\n return renumberTasks(prune(tasks));\n}\n\nexport function updateTaskInPlan(tasks: readonly Task[], taskId: string, changes: Partial<Task>): Task[] {\n return renumberTasks(\n tasks.map((t) => {\n if (t.id === taskId) return { ...t, ...changes, id: t.id };\n return { ...t, subtasks: updateTaskInPlan(t.subtasks, taskId, changes) };\n })\n );\n}\n\nexport function renumberTasks(tasks: readonly Task[]): Task[] {\n return tasks.map((t, i) => ({\n ...t,\n order: i + 1,\n subtasks: renumberTasks(t.subtasks),\n }));\n}\n\n/** A task waiting on the user with its attempt still live: the runner sits at a checkpoint or for input. */\nexport function waitsMidAttempt(task: Pick<Task, 'status' | 'awaitingReason'>): boolean {\n return task.status === 'awaiting_user' && (task.awaitingReason === 'checkpoint' || task.awaitingReason === 'input');\n}\n\n/** A task paused on its runner's usage limit, whether it resumes on its own or waits for the user (#84). */\nexport function pausedOnLimit(task: Readonly<Task>): boolean {\n return task.status === 'awaiting_user' && task.awaitingReason === 'usage-limit';\n}\n\n/** A task paused on a usage limit that resumes on its own when the limit resets (#84). */\nexport function waitsForReset(task: Readonly<Task>): boolean {\n return pausedOnLimit(task) && !!task.resumeAt;\n}\n\n/** The user's approval record, as a plan carries it (ADR-0029). */\nexport type ApprovalRecord = Pick<LegacyPlanState, 'approved' | 'approvedTasks'>;\n\n/** A copy of the plan's approval record, for a plan read whole; a field the plan lacks stays absent. */\nexport function approvalRecordOf(plan: ApprovalRecord): ApprovalRecord {\n return {\n ...(plan.approved !== undefined ? { approved: plan.approved } : {}),\n ...(plan.approvedTasks ? { approvedTasks: [...plan.approvedTasks] } : {}),\n };\n}\n\n/**\n * A task the scheduler leaves for the user (ADR-0035): an AI or script task\n * not started yet, in a plan they approved, outside their approval record —\n * the planner added it since, or changed a script's body. It starts once they\n * start it or execute the plan. In a plan they never approved nothing is\n * theirs yet, so nothing is singled out.\n */\nexport function waitsForApproval(task: Pick<Task, 'id' | 'type' | 'status'>, record: ApprovalRecord): boolean {\n return record.approved === true\n && task.type !== 'user'\n && (task.status === 'pending' || task.status === 'approved')\n && !(record.approvedTasks ?? []).includes(task.id);\n}\n\n/**\n * Who put each task of an adopted list in the plan. A task the plan already\n * had keeps its origin, whatever the planner wrote; a new one is the\n * supervisor's when `bySupervisor`, and nobody's in particular otherwise, so\n * no planner can mark its own task as the supervisor's. `added` lists the new\n * tasks, subtasks included.\n */\nexport function stampOrigin(before: readonly Task[], after: readonly Task[], bySupervisor: boolean): { tasks: Task[]; added: string[] } {\n const prior = new Map(flattenTasks([...before]).map((t) => [t.id, t]));\n const added: string[] = [];\n const stamp = (tasks: readonly Task[]): Task[] => tasks.map((t) => {\n const was = prior.get(t.id);\n const origin = was ? was.addedBy : bySupervisor ? 'supervisor' : undefined;\n if (!was) added.push(t.id);\n const stamped: Task = { ...t, subtasks: stamp(t.subtasks ?? []) };\n if (origin) stamped.addedBy = origin;\n else delete stamped.addedBy;\n return stamped;\n });\n return { tasks: stamp(after), added };\n}\n\n/** Done, running, or held for the user: execution state only a runner or the user can change. */\nconst SETTLED_STATUSES: ReadonlySet<TaskStatus> = new Set<TaskStatus>(['completed', 'in_progress', 'awaiting_user']);\n\nfunction holdsSettledWork(task: Task): boolean {\n return SETTLED_STATUSES.has(task.status) || (task.subtasks ?? []).some(holdsSettledWork);\n}\n\n/**\n * Lay a planner-written task list over the plan it rewrites without letting it\n * change execution state. A planner restates tasks; it never witnessed one run,\n * so the status it writes is not evidence. A settled task is kept exactly as\n * it stands wherever the rewrite names it, and put back beside its old\n * neighbour where the rewrite leaves it out. Every other task keeps the status\n * it had; a task the rewrite adds starts pending. A failed task the rewrite\n * turns into a script task or out of one is kept as it was: what ran, and\n * where, is fixed once it has run (ADR-0020, ADR-0035).\n */\nexport function keepExecutionState(current: readonly Task[], rewrite: Task[]): Task[] {\n const existing = new Map(flattenTasks(current).map((t) => [t.id, t]));\n const named = new Set(flattenTasks(rewrite).map((t) => t.id));\n\n const overlay = (tasks: Task[], was: readonly Task[]): Task[] => {\n const result = tasks.map((t): Task => {\n const prior = existing.get(t.id);\n if (prior && SETTLED_STATUSES.has(prior.status)) return { ...prior };\n if (prior?.status === 'failed' && (prior.type === 'script') !== (t.type === 'script')) return { ...prior };\n return {\n ...t,\n status: prior?.status ?? 'pending',\n skipReason: prior?.skipReason,\n reverted: prior?.reverted,\n verdict: prior?.verdict,\n outputSummary: prior?.outputSummary,\n handoff: prior?.handoff,\n runnerSessionId: prior?.runnerSessionId,\n runnerSessionOwner: prior?.runnerSessionOwner,\n carriedFrom: prior?.carriedFrom,\n attemptSkills: prior?.attemptSkills,\n attempted: prior?.attempted,\n attemptUsage: prior?.attemptUsage,\n loopRound: prior?.loopRound,\n waitsEnded: prior?.waitsEnded,\n // Where a task that has run ran is fixed, like its runner session (ADR-0020).\n ...(prior?.status === 'failed' ? { ops: prior.ops } : {}),\n forcedPastGate: prior?.forcedPastGate,\n reportTo: prior?.reportTo,\n researchOrigin: prior?.researchOrigin,\n subtasks: overlay(t.subtasks ?? [], prior?.subtasks ?? []),\n };\n });\n was.forEach((left, i) => {\n if (named.has(left.id) || !holdsSettledWork(left)) return;\n const neighbour = was.slice(0, i).reverse().find((t) => result.some((r) => r.id === t.id));\n const at = neighbour ? result.findIndex((r) => r.id === neighbour.id) + 1 : 0;\n result.splice(at, 0, { ...left });\n });\n return result;\n };\n\n return renumberTasks(overlay(rewrite, current));\n}\n"],"mappings":";AACO,IAAM,qBAAqB;AAQlC,IAAM,cAAc,IAAI,OAAO,cAAc,kBAAkB,yBAAyB,IAAI;AAcrF,SAAS,YAAY,MAA4B;AACtD,QAAM,SAAuB,CAAC;AAC9B,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,SAAS,KAAK,SAAS,WAAW,GAAG;AAC9C,UAAM,OAAO,MAAM,CAAC,EAAE,YAAY;AAClC,QAAI,KAAK,IAAI,IAAI,EAAG;AACpB,SAAK,IAAI,IAAI;AACb,UAAM,QAAQ,MAAM,QAAQ,MAAM,CAAC,EAAE;AACrC,WAAO,KAAK,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,EAAE,OAAO,CAAC;AAAA,EAC/D;AACA,SAAO;AACT;AAGO,SAAS,kBAAkB,MAAc,QAAyC;AACvF,SAAO,YAAY,IAAI,EAAE,OAAO,CAAC,MAAM,OAAO,SAAS,EAAE,IAAI,CAAC;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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