@ordewell/core 0.10.0 → 0.10.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.
Files changed (42) hide show
  1. package/dist/{IFileSystem-BCJBHFwB.d.ts → IFileSystem-CyTIoiSn.d.ts} +1 -1
  2. package/dist/{IFileSystem-Bj6fy1cG.d.mts → IFileSystem-j0naIoAQ.d.mts} +1 -1
  3. package/dist/{IRunner-C7_SSpzG.d.ts → IRunner---PfQVdc.d.mts} +25 -20
  4. package/dist/{IRunner-hWAJC4hg.d.mts → IRunner-WwL-Bjqq.d.ts} +25 -20
  5. package/dist/{ModeResolver-u5ZhRC8x.d.ts → ModeResolver-CjQ7zqTN.d.mts} +1 -1
  6. package/dist/{ModeResolver-m1d8Cb-j.d.mts → ModeResolver-DrMU-5lw.d.ts} +1 -1
  7. package/dist/{Task-CxwnCJLi.d.mts → Task-AfA1m4qW.d.mts} +35 -7
  8. package/dist/{Task-CxwnCJLi.d.ts → Task-AfA1m4qW.d.ts} +35 -7
  9. package/dist/{chunk-DJAPDO6E.mjs → chunk-3LNZDBCX.mjs} +8 -7
  10. package/dist/chunk-3LNZDBCX.mjs.map +1 -0
  11. package/dist/{chunk-DNFT4SQG.mjs → chunk-4FEARWTS.mjs} +3 -3
  12. package/dist/{chunk-2IIRSBEQ.mjs → chunk-CIL3BQIF.mjs} +4 -2
  13. package/dist/chunk-CIL3BQIF.mjs.map +1 -0
  14. package/dist/{chunk-CH5IGWFS.mjs → chunk-UQGR3UCA.mjs} +35 -3
  15. package/dist/chunk-UQGR3UCA.mjs.map +1 -0
  16. package/dist/index.d.mts +49 -36
  17. package/dist/index.d.ts +49 -36
  18. package/dist/index.js +15816 -15877
  19. package/dist/index.js.map +1 -1
  20. package/dist/index.mjs +14846 -14941
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/parsing.d.mts +2 -2
  23. package/dist/parsing.d.ts +2 -2
  24. package/dist/parsing.js +3 -2
  25. package/dist/parsing.js.map +1 -1
  26. package/dist/parsing.mjs +3 -3
  27. package/dist/{plan-utils-CKXdD1AD.d.mts → plan-utils-DL7yOuJs.d.mts} +39 -8
  28. package/dist/{plan-utils-B6yJdpgi.d.ts → plan-utils-gpeqV-Lp.d.ts} +39 -8
  29. package/dist/plan-utils.d.mts +4 -4
  30. package/dist/plan-utils.d.ts +4 -4
  31. package/dist/plan-utils.js +44 -0
  32. package/dist/plan-utils.js.map +1 -1
  33. package/dist/plan-utils.mjs +7 -3
  34. package/dist/testing.d.mts +3 -3
  35. package/dist/testing.d.ts +3 -3
  36. package/dist/testing.js.map +1 -1
  37. package/dist/testing.mjs +1 -1
  38. package/package.json +5 -1
  39. package/dist/chunk-2IIRSBEQ.mjs.map +0 -1
  40. package/dist/chunk-CH5IGWFS.mjs.map +0 -1
  41. package/dist/chunk-DJAPDO6E.mjs.map +0 -1
  42. /package/dist/{chunk-DNFT4SQG.mjs.map → chunk-4FEARWTS.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/services/JsonExtractor.ts","../src/services/ModeResolver.ts","../src/taskRow/status.ts","../src/services/ModelAllowlistResolver.ts","../src/services/PlannedTask.ts","../src/services/TaskEditValidator.ts","../src/services/TaskOps.ts"],"sourcesContent":["/** The envelope key a full plan reply is keyed by: `{\"tasks\":[...]}`. */\nexport const PLAN_ENVELOPE_KEY = 'tasks';\n/** The envelope key a targeted-edits reply is keyed by: `{\"taskOps\":[...]}`. */\nexport const TASK_OPS_ENVELOPE_KEY = 'taskOps';\n/** The envelope key a read-only detail request is keyed by: `{\"taskQuery\":{...}}`. */\nexport const TASK_QUERY_ENVELOPE_KEY = 'taskQuery';\n\n/** Thrown when an LLM plan response cannot be parsed into a valid plan. Carries the raw text so callers can log it or retry. */\nexport class PlanParseError extends Error {\n readonly raw: string;\n /**\n * True when the reply was cut off mid-object (output-token limit) rather\n * than malformed — the two need different repairs: a truncated emission will\n * be cut at the same point again unless the retry frees context or asks for\n * terser output.\n */\n readonly truncated: boolean;\n /**\n * True when the JSON parsed fine and a *shape* rule rejected it. The generic\n * \"could not be parsed as JSON\" corrective is a lie for these, so the model\n * re-sends the same object; a semantic rejection must be repaired by naming\n * the rule it broke.\n */\n readonly semantic: boolean;\n constructor(message: string, raw: string, opts?: { truncated?: boolean; semantic?: boolean }) {\n super(message);\n this.name = 'PlanParseError';\n this.raw = raw;\n this.truncated = opts?.truncated ?? false;\n this.semantic = opts?.semantic ?? false;\n }\n}\n/**\n * Strip the noise reasoning models wrap around their answer: markdown code\n * fences and `<think>…</think>` chain-of-thought blocks (which routinely contain\n * stray braces that would otherwise derail brace-balancing). Reasoning captured\n * out-of-band by the service never reaches here, but a model that inlines its\n * thinking in the content channel still must not corrupt parsing.\n */\nexport function stripModelNoise(raw: string): string {\n return raw\n .replace(/<think>[\\s\\S]*?<\\/think>/gi, '')\n .replace(/```json\\s*/gi, '')\n .replace(/```\\s*/g, '')\n .trim();\n}\n\nconst THINK_OPEN = '<think>';\nconst THINK_CLOSE = '</think>';\nconst FENCE = '```';\nconst FENCE_JSON_TAG = 'json';\n\n/**\n * Whether a reply that begins with `prefix` opens with a JSON object once the\n * noise {@link stripModelNoise} removes is skipped — the streaming counterpart\n * of it, answering from the start of a reply that has not finished arriving.\n * Undefined while the prefix cannot tell yet: blank, inside an unclosed think\n * block, or partway through a fence or a tag.\n */\nexport function opensWithJsonObject(prefix: string): boolean | undefined {\n let rest = prefix;\n for (;;) {\n rest = rest.trimStart();\n if (!rest) return undefined;\n const head = rest.slice(0, THINK_OPEN.length).toLowerCase();\n if (head === THINK_OPEN) {\n const close = rest.toLowerCase().indexOf(THINK_CLOSE);\n if (close < 0) return undefined;\n rest = rest.slice(close + THINK_CLOSE.length);\n continue;\n }\n if (rest.startsWith(FENCE)) {\n rest = rest.slice(FENCE.length);\n const tag = rest.slice(0, FENCE_JSON_TAG.length).toLowerCase();\n if (tag === FENCE_JSON_TAG) rest = rest.slice(FENCE_JSON_TAG.length);\n else if (tag === rest.toLowerCase() && FENCE_JSON_TAG.startsWith(tag)) return undefined;\n continue;\n }\n if (THINK_OPEN.startsWith(head) || FENCE.startsWith(rest)) return undefined;\n return rest.startsWith('{');\n }\n}\n\n/**\n * Scan from `start` (which must point at a `{`) for the matching balanced close,\n * ignoring braces inside strings. Returns the object substring and whether it was\n * balanced; an unbalanced result means the input was truncated mid-object.\n */\nfunction balancedObjectAt(text: string, start: number): { json: string; balanced: boolean } {\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === '\\\\') escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') inString = true;\n else if (ch === '{') depth++;\n else if (ch === '}') {\n depth--;\n if (depth === 0) return { json: text.slice(start, i + 1), balanced: true };\n }\n }\n return { json: text.slice(start), balanced: false };\n}\n\n/**\n * Scan an LLM response for every balanced `{…}` object carrying a `\"<key>\":`\n * entry. Strips fences and `<think>` blocks first. A matching object is\n * skipped over wholesale, so its nested braces don't produce fragment\n * candidates; non-matching objects are descended into, so a match wrapped in\n * an unrelated outer object is still found. `fallback` preserves the legacy\n * behavior for callers with no keyed match: the first balanced object, else\n * the stripped text so a JSON.parse error still surfaces.\n */\nexport function extractObjectsWithKey(raw: string, key: string): {\n matches: string[];\n fallback: { json: string; balanced: boolean };\n sawBrace: boolean;\n /** An object ran to EOF unclosed — the classic signature of truncated output. */\n sawUnbalanced: boolean;\n} {\n const stripped = stripModelNoise(raw);\n const keyRe = new RegExp(`\"${key}\"\\\\s*:`);\n\n const matches: string[] = [];\n let firstObject: string | null = null;\n let sawBrace = false;\n let sawUnbalanced = false;\n let inString = false;\n let escaped = false;\n for (let i = 0; i < stripped.length; i++) {\n const ch = stripped[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === '\\\\') escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') { inString = true; continue; }\n if (ch !== '{') continue;\n\n sawBrace = true;\n const obj = balancedObjectAt(stripped, i);\n // A stray brace in a reasoning preamble produces an unbalanced candidate,\n // which we skip so it can't swallow the real object that follows.\n if (obj.balanced && keyRe.test(obj.json)) {\n matches.push(obj.json);\n i += obj.json.length - 1;\n continue;\n }\n if (!obj.balanced) sawUnbalanced = true;\n if (!firstObject && obj.balanced) firstObject = obj.json;\n }\n\n return {\n matches,\n fallback: firstObject !== null ? { json: firstObject, balanced: true } : { json: stripped, balanced: false },\n sawBrace,\n sawUnbalanced,\n };\n}\n\n/**\n * Pull the JSON object out of an LLM response and report whether it was balanced.\n * Strips fences and `<think>` blocks, then walks every top-level `{…}` and\n * returns the FIRST one that contains a `\"tasks\"` key — so a brace appearing\n * earlier in reasoning (or an unrelated preamble object) can't make us parse the\n * wrong thing. Falls back to the first balanced object and, failing that, the\n * first `{` onwards so a genuine `JSON.parse` error still surfaces.\n */\nexport function extractObjectWithBalance(raw: string): { json: string; balanced: boolean; sawBrace: boolean } {\n const { matches, fallback, sawBrace } = extractObjectsWithKey(raw, PLAN_ENVELOPE_KEY);\n if (matches.length > 0) return { json: matches[0], balanced: true, sawBrace };\n return { ...fallback, sawBrace };\n}\n\n/**\n * Pull the JSON object out of an LLM response. Strips markdown code fences and\n * `<think>` blocks, prefers the object containing a `tasks` key, and tolerates a\n * prose preamble and trailing prose. Returns the fence-stripped text unchanged\n * if no `{` is present so the caller's JSON.parse produces a clear failure.\n */\nexport function extractJsonObject(raw: string): string {\n return extractObjectWithBalance(raw).json;\n}\n\n/** Drop trailing commas before a closing `}` or `]` — a common model quirk. */\nexport function stripTrailingCommas(json: string): string {\n return json.replace(/,(\\s*[}\\]])/g, '$1');\n}\n\n/**\n * Escape raw control characters that appear INSIDE string literals — budget\n * models routinely emit multi-line `prompt` strings with literal newlines,\n * which strict JSON.parse rejects (\"bad control character\"). Characters\n * outside strings (formatting whitespace) are left untouched.\n */\nexport function escapeControlCharsInStrings(json: string): string {\n let out = '';\n let inString = false;\n let escaped = false;\n for (const ch of json) {\n if (inString) {\n if (escaped) { out += ch; escaped = false; continue; }\n if (ch === '\\\\') { out += ch; escaped = true; continue; }\n if (ch === '\"') { out += ch; inString = false; continue; }\n if (ch === '\\n') { out += '\\\\n'; continue; }\n if (ch === '\\r') { out += '\\\\r'; continue; }\n if (ch === '\\t') { out += '\\\\t'; continue; }\n out += ch;\n continue;\n }\n if (ch === '\"') inString = true;\n out += ch;\n }\n return out;\n}\n","import { flattenTasks, type RunnerId, type Task } from '../models/Task';\n\nexport interface RunnerModeInfo {\n id: string;\n label: string;\n description: string;\n autonomous?: boolean;\n safe?: boolean;\n readOnly?: boolean;\n sandboxed?: boolean;\n /** Why this mode cannot be used on this host (a failed probe); such a mode is shown, never assigned. */\n unavailable?: string;\n}\n\n/** The slice of RunnerRegistry this module needs — structural, so nothing here depends on the manifest layer. */\nexport interface ManifestLookup {\n getManifest(runner: RunnerId): { modes?: RunnerModeInfo[] } | undefined;\n}\n\n/**\n * A runner's modes are declared only in its manifest, never through a service,\n * so every caller that needs them fuses registry and runner list by hand. This\n * is that fusion, in one place: the planner prompt, the mode pickers on each\n * surface, and the runner-change retarget all read modes the same way.\n *\n * A runner with no modes maps to `[]` rather than being dropped — callers\n * distinguish \"declares no modes\" from \"not asked about\".\n */\nexport function runnerModesFrom(registry: ManifestLookup, runners: RunnerId[]): Record<RunnerId, RunnerModeInfo[]> {\n return Object.fromEntries(runners.map((r) => [r, registry.getManifest(r)?.modes ?? []] as const));\n}\n\n/**\n * Find the mode ID a runner resolves to under the given toggle state.\n * Tag-based first (autonomous/safe); falls back to positional last non-plan\n * if no tag is present on any mode (degrades gracefully on untagged manifests).\n * Returns undefined if `modes` is empty or undefined.\n */\nexport function resolveDefaultMode(\n modes: readonly RunnerModeInfo[] | undefined,\n autonomousDefault = true,\n): string | undefined {\n if (!modes || modes.length === 0) return undefined;\n const tag: 'autonomous' | 'safe' = autonomousDefault ? 'autonomous' : 'safe';\n const tagged = modes.find((m) => m[tag]);\n if (tagged) return tagged.id;\n for (let i = modes.length - 1; i >= 0; i--) {\n if (!modes[i].readOnly && modes[i].id !== 'plan') return modes[i].id;\n }\n return undefined;\n}\n\n/** The user-facing name of the `autonomousMode` boolean's two states. */\nexport function autonomyLevelLabel(autonomous: boolean): 'Full' | 'Guarded' {\n return autonomous ? 'Full' : 'Guarded';\n}\n\n/** `full`/`guarded` name the levels; `on`/`off` and `auto` are older words for them. Null for anything else. */\nexport function parseAutonomyLevel(arg: string | undefined): boolean | null {\n switch (arg?.trim().toLowerCase()) {\n case 'full': case 'on': return true;\n case 'guarded': case 'auto': case 'off': return false;\n default: return null;\n }\n}\n\n/**\n * The mode a manifest tags `readOnly` — never found by id, so a runner with no\n * tag has none. A mode this host cannot run is still the runner's read-only\n * mode: it is how a task already on it is recognized, and why a move of that\n * task is refused rather than made writable.\n */\nexport function taggedReadOnlyMode(modes: readonly RunnerModeInfo[] | undefined): string | undefined {\n return modes?.find((m) => m.readOnly)?.id;\n}\n\n/** The read-only mode a task can be given on this host: the tagged one, unless it is unavailable here. */\nexport function readOnlyMode(modes: readonly RunnerModeInfo[] | undefined): string | undefined {\n const mode = modes?.find((m) => m.readOnly);\n return mode && !mode.unavailable ? mode.id : undefined;\n}\n\n/** Why a mode cannot be used on this host, when it cannot. */\nexport function unavailableModeReason(modes: readonly RunnerModeInfo[] | undefined, id: string | undefined): string | undefined {\n return id === undefined ? undefined : modes?.find((m) => m.id === id)?.unavailable;\n}\n\nfunction unavailableModeError(runner: RunnerId, id: string, reason: string): string {\n return `Mode \"${id}\" of runner \"${runner}\" is unavailable on this host: ${reason}`;\n}\n\n/** What a task fails with at spawn when its planned mode is one this host cannot run; undefined when it can. */\nexport function unavailableTaskModeMessage(\n manifest: { displayName: string; modes?: readonly RunnerModeInfo[] },\n mode: string | undefined,\n): string | undefined {\n const reason = unavailableModeReason(manifest.modes, mode);\n return reason ? `Mode \"${mode}\" of ${manifest.displayName} is unavailable on this host: ${reason}` : undefined;\n}\n\n/** What the planner says about a task's mode (ADR-0031): read-only or not, and the mode the task has now, if any. */\nexport interface ModeRequest {\n readOnly?: boolean;\n current?: string;\n}\n\nexport type PlannedMode = { ok: true; mode: string | undefined } | { ok: false; error: string };\n\n/**\n * The mode a task the planner writes lands on (ADR-0031). The planner names no\n * mode: a read-only task gets its runner's read-only mode; any other keeps the\n * mode it has when the runner offers it — a mode the user picked survives an\n * edit that does not ask for a change — and otherwise gets the runner's mode\n * for the level. `readOnly: false` is the one request that moves a task off\n * its read-only mode. Undefined mode when the runner's modes are unknown.\n */\nexport function plannedMode(\n runner: RunnerId,\n runnerModes: Partial<Record<RunnerId, readonly RunnerModeInfo[]>> | undefined,\n { readOnly, current }: ModeRequest,\n autonomousDefault = true,\n): PlannedMode {\n if (!runnerModes) return { ok: true, mode: undefined };\n const modes = runnerModes[runner] ?? [];\n const readOnlyId = readOnlyMode(modes);\n if (readOnly === true) {\n if (readOnlyId) return { ok: true, mode: readOnlyId };\n const able = readOnlyRunners(runnerModes);\n const reason = unavailableModeReason(modes, taggedReadOnlyMode(modes));\n return {\n ok: false,\n error: `Runner \"${runner}\" has no read-only mode${reason ? ' available on this host' : ''} — assign a read-only task to ${able.length > 0 ? `one of: ${able.join(', ')}` : 'no runner: none of the enabled runners has one'}, or drop \"readOnly\"${reason ? `. ${reason}` : ''}`,\n };\n }\n const keep = current !== undefined && modes.some((m) => m.id === current) && !(readOnly === false && current === taggedReadOnlyMode(modes));\n const mode = keep ? current : resolveDefaultMode(modes, autonomousDefault);\n // Refused, never swapped for another mode: that would hand a task the\n // planner or user meant to be sandboxed a level of access nobody chose (ADR-0001).\n const reason = unavailableModeReason(modes, mode);\n if (mode !== undefined && reason) return { ok: false, error: unavailableModeError(runner, mode, reason) };\n return { ok: true, mode };\n}\n\n/**\n * A plan the planner restates over an existing one comes back with every mode\n * decided afresh. A restatement says read-only or not for each task, so that\n * answer stands; what it cannot say is a mode the user picked. So where a\n * task it names was planned before and is not read-only now, the earlier mode\n * is kept when its runner offers it — the rule an edit follows.\n */\nexport function carryPlannedModes(\n before: readonly Task[],\n rewrite: Task[],\n catalog: { runnerModes: Partial<Record<RunnerId, readonly RunnerModeInfo[]>>; autonomousDefault?: boolean },\n): Task[] {\n const prior = new Map(flattenTasks(before).map((t) => [t.id, t]));\n const carry = (t: Task): Task => {\n const subtasks = (t.subtasks ?? []).map(carry);\n const was = prior.get(t.id);\n if (t.type === 'user' || !was || was.type === 'user' || t.taskMode === taggedReadOnlyMode(catalog.runnerModes[t.assignedRunner])) return { ...t, subtasks };\n const mode = plannedMode(t.assignedRunner, catalog.runnerModes, { readOnly: false, current: was.taskMode }, catalog.autonomousDefault ?? true);\n return { ...t, subtasks, ...(mode.ok && mode.mode !== undefined ? { taskMode: mode.mode } : {}) };\n };\n return rewrite.map(carry);\n}\n\n/** The runners a read-only task may go to, as the planner's prompt names them. */\nexport function readOnlyRunners(runnerModes: Partial<Record<RunnerId, readonly RunnerModeInfo[]>>): RunnerId[] {\n return Object.entries(runnerModes).filter(([, ms]) => readOnlyMode(ms)).map(([id]) => id);\n}\n","import type { AwaitingReason } from '../models/Task';\n\n/**\n * What a row's status means to a reader, before any surface picks a word,\n * icon or colour for it. `quiet` is a running task whose runner has printed\n * nothing for a while — the status is still `in_progress`, so only the row,\n * never the store, tells the two apart.\n */\nexport type TaskStatusKind = 'todo' | 'running' | 'quiet' | 'awaiting' | 'blocked' | 'failed' | 'skipped' | 'done';\n\n/** A task with a runner live behind it. `in_progress` is the store's own status. */\nexport const isTaskRunning = (task: { status: string }): boolean =>\n task.status === 'in_progress' || task.status === 'running';\n\n/** Statuses of a task that has not started: what can still be started by hand, or flipped between change and ops (ADR-0020). */\nexport const NOT_STARTED: ReadonlySet<string> = new Set(['pending', 'approved', 'blocked']);\n\nexport function taskStatusKind(task: { status: string; idleSince?: string | null }): TaskStatusKind {\n switch (task.status) {\n case 'completed': return 'done';\n case 'failed': return 'failed';\n case 'skipped': return 'skipped';\n case 'blocked': return 'blocked';\n case 'awaiting_user': return 'awaiting';\n }\n if (!isTaskRunning(task)) return 'todo';\n return task.status === 'in_progress' && task.idleSince ? 'quiet' : 'running';\n}\n\nconst AWAITING_LABELS: Record<AwaitingReason, string> = {\n input: 'Waiting for your input',\n checkpoint: 'Checkpoint',\n conflict: 'Merge conflict',\n 'files-changed': 'Changed tracked files',\n 'usage-limit': 'Paused on a usage limit',\n};\n\n/** What an awaiting_user task waits on (ADR-0018, W1); null when no reason was saved. */\nexport function awaitingLabel(task: { status: string; awaitingReason?: AwaitingReason }): string | null {\n return task.status === 'awaiting_user' && task.awaitingReason ? AWAITING_LABELS[task.awaitingReason] : null;\n}\n\n/** \"Blocked by #1, #2.1\": the failed tasks a blocked task waits on, by reference (ADR-0034). */\nexport function blockedByLabel(refs: readonly string[]): string {\n return `Blocked by ${refs.join(', ')}`;\n}\n\n/** \"Skipped: no GPU on this host\", or \"Skipped\" when no reason was given. */\nexport function skippedLabel(reason: string | null): string {\n return reason ? `Skipped: ${reason}` : 'Skipped';\n}\n\n/** Runner requests a task waits on (ADR-0018, A1); null when none do. */\nexport function approvalLabel(count: number | undefined): string | null {\n if (!count) return null;\n return count > 1 ? `Waiting for approval (${count})` : 'Waiting for approval';\n}\n\n/**\n * When a paused task resumes, as a reader's clock shows it: \"8:10pm\", or\n * \"Oct 14, 8:10pm\" when it is not today. Read in the local time zone of\n * whoever formats it.\n */\nexport function resumeTime(at: Date, now: Date = new Date()): string {\n const clock = at.toLocaleTimeString('en-US', { hour: 'numeric', minute: at.getMinutes() === 0 ? undefined : '2-digit', hour12: true })\n .replace(/[ \\u202f]([AP]M)$/i, (_m, meridiem: string) => meridiem.toLowerCase());\n if (at.toDateString() === now.toDateString()) return clock;\n return `${at.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}, ${clock}`;\n}\n\n/** \"Resumes at 8:10pm\" for a task paused on a usage limit that resumes on its own; null for any other. */\nexport function resumeLabel(task: { status: string; awaitingReason?: AwaitingReason; resumeAt?: string | null }, now: Date = new Date()): string | null {\n if (task.status !== 'awaiting_user' || task.awaitingReason !== 'usage-limit' || !task.resumeAt) return null;\n const at = new Date(task.resumeAt);\n return Number.isNaN(at.getTime()) ? null : `Resumes at ${resumeTime(at, now)}`;\n}\n","import type { DiscoveredModel, RunnerId, Task } from '../models/Task';\n\n/**\n * The ids a runner may actually run: the user's allowlist with the ids that\n * provably belong to a *different* runner dropped. `undefined` means no\n * restriction.\n *\n * Model ids are scoped to the agent that lists them, so an OpenRouter slug\n * allowlisted for Claude Code does not limit it — it points it at something it\n * cannot spawn, and the plan only dies once a task is already running. But\n * \"this runner didn't list it\" is not enough to call an id wrong: discovery can\n * be stale or return no list at all. What settles it is\n * whether *another* runner listed the id. So:\n *\n * - listed for this runner → keep;\n * - listed for no runner → unknown, and the user said it explicitly, so keep it\n * and let the runner validate last (the same call `coerceAssignments` and\n * `TaskRetarget` make);\n * - listed only for other runners → provably not this runner's, so drop it.\n *\n * When that leaves nothing, the whole allowlist was about some other runner\n * (a settings file written before a surface scoped its picker to one). No\n * restriction is the only safe reading — the alternative is handing the planner\n * a list of models that cannot run.\n */\nexport function effectiveAllowlist(\n allowlist: string[] | undefined,\n runner: string,\n modelsByRunner: Partial<Record<RunnerId, DiscoveredModel[]>> | undefined,\n): string[] | undefined {\n if (!allowlist || allowlist.length === 0) return undefined;\n if (!modelsByRunner) return allowlist;\n\n const own = new Set((modelsByRunner[runner] ?? []).map((m) => m.modelId));\n const elsewhere = new Set<string>();\n for (const [other, models] of Object.entries(modelsByRunner)) {\n if (other === runner) continue;\n for (const m of models ?? []) elsewhere.add(m.modelId);\n }\n\n const kept = allowlist.filter((id) => own.has(id) || !elsewhere.has(id));\n return kept.length > 0 ? kept : undefined;\n}\n\nexport function filterModelsForPrompt(\n modelsByRunner: Partial<Record<RunnerId, DiscoveredModel[]>>,\n perRunnerAllowlist: Partial<Record<RunnerId, string[]>>,\n): Partial<Record<RunnerId, DiscoveredModel[]>> {\n const result: Partial<Record<RunnerId, DiscoveredModel[]>> = {};\n for (const [runner, models] of Object.entries(modelsByRunner)) {\n if (!models) continue;\n const allowed = effectiveAllowlist(perRunnerAllowlist[runner], runner, modelsByRunner);\n if (!allowed) {\n result[runner] = models;\n continue;\n }\n const allowedSet = new Set(allowed);\n const intersection = models.filter((m) => allowedSet.has(m.modelId));\n // A set allowlist is a hard constraint: the planner must never see models\n // outside it. An allowed id no runner has listed is one discovery doesn't\n // cover, so synthesize an entry rather than leaking the full list.\n const covered = new Set(intersection.map((m) => m.modelId));\n const missing = allowed\n .filter((id) => !covered.has(id))\n .map((id) => ({ modelId: id, modelLabel: id.split('/').pop() || id, variants: [] }));\n result[runner] = [...intersection, ...missing];\n }\n return result;\n}\n\n/** Canonical low→high ordering of the well-known effort ladder. */\nconst EFFORT_LADDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];\n/** Runner-specific spellings mapped onto the ladder. */\nconst EFFORT_ALIASES: Record<string, string> = { disabled: 'none', adaptive: 'medium' };\n\n/**\n * Clamp a planner/user-supplied thinking effort to what the model actually\n * offers. Invalid values map to the nearest rung the model supports (so a\n * Claude-style \"xhigh\" on a low/medium/high model becomes \"high\") and fall\n * back to undefined — the runner's own default — when no mapping exists.\n */\nexport function clampThinkingEffort(\n effort: string | undefined,\n variants: { id: string }[],\n): string | undefined {\n if (!effort) return undefined;\n if (variants.length === 0) return undefined;\n const ids = new Set(variants.map((v) => v.id));\n if (ids.has(effort)) return effort;\n const canon = EFFORT_ALIASES[effort] ?? effort;\n if (ids.has(canon)) return canon;\n const idx = EFFORT_LADDER.indexOf(canon);\n if (idx < 0) return undefined;\n for (let d = 1; d < EFFORT_LADDER.length; d++) {\n const lower = EFFORT_LADDER[idx - d];\n if (lower && ids.has(lower)) return lower;\n const higher = EFFORT_LADDER[idx + d];\n if (higher && ids.has(higher)) return higher;\n }\n return undefined;\n}\n\n/** A change coercion made to a planned task, named so it is never silent (ADR-0001). */\nexport interface Coercion {\n taskId: string;\n title: string;\n field: 'assignedModel' | 'thinkingEffort';\n from: string | null;\n to: string | null;\n}\n\nexport interface CoercedTasks {\n tasks: Task[];\n /** What changed, subtasks included, in plan order. */\n coerced: Coercion[];\n}\n\n/**\n * Snap each AI task's assignment, subtasks included, to what its runner may\n * run: a model outside the allowlist moves to the allowlist's first, a missing\n * one is filled in, and an effort is clamped to the model's variants. The\n * runner is never changed — one the plan may not use is refused before a task\n * gets here (`checkPlanInvariants`).\n */\nexport function coerceAssignments(\n tasks: readonly Task[],\n perRunnerAllowlist: Partial<Record<RunnerId, string[]>>,\n modelsByRunner?: Partial<Record<RunnerId, DiscoveredModel[]>>,\n): CoercedTasks {\n // When the discovered catalog is available, snap each assignment's\n // thinkingEffort to a variant the model really has and stamp the model's\n // variant ids on the assignment (runners need them at spawn time); a model\n // we can't find in the catalog keeps its effort untouched (the runner\n // validates last).\n const clampVariant = (task: Task): Task => {\n if (!task.assignedModel || !modelsByRunner) return task;\n const model = modelsByRunner[task.assignedRunner]?.find(\n (m) => m.modelId === task.assignedModel!.modelId,\n );\n if (!model) return task;\n const clamped = clampThinkingEffort(task.assignedModel.thinkingEffort, model.variants);\n return {\n ...task,\n assignedModel: {\n ...task.assignedModel,\n thinkingEffort: clamped,\n availableVariants: model.variants.map((v) => v.id),\n },\n };\n };\n\n // One reading of the allowlist for the whole pass, so the models a task is\n // snapped to are the same ones the planner was shown (`filterModelsForPrompt`).\n const allowedFor = (runner: RunnerId): string[] | undefined =>\n effectiveAllowlist(perRunnerAllowlist[runner], runner, modelsByRunner);\n\n // A snapped-to model keeps the catalog's label and variant list where we have\n // one — an id alone reads as the model's name in every surface, and leaves the\n // effort picker with nothing to offer.\n const assignmentFor = (runner: RunnerId, modelId: string): NonNullable<Task['assignedModel']> => {\n const known = modelsByRunner?.[runner]?.find((m) => m.modelId === modelId);\n return {\n modelId,\n modelLabel: known?.modelLabel ?? modelId,\n thinkingEffort: undefined,\n ...(known ? { availableVariants: known.variants.map((v) => v.id) } : {}),\n };\n };\n\n const coerceOne = (task: Task): Task => {\n if (task.type === 'user') return task;\n const allowlist = allowedFor(task.assignedRunner);\n // No model assigned: fill in from the allowlist or discovered catalog so\n // merge/split/add outputs (which may omit assignedModel) always land with a\n // valid model for the task's runner.\n if (!task.assignedModel) {\n if (allowlist && allowlist.length > 0) {\n return clampVariant({ ...task, assignedModel: assignmentFor(task.assignedRunner, allowlist[0]) });\n }\n const discovered = modelsByRunner?.[task.assignedRunner]?.[0];\n if (discovered) {\n return clampVariant({ ...task, assignedModel: assignmentFor(task.assignedRunner, discovered.modelId) });\n }\n return task;\n }\n if (!allowlist || allowlist.length === 0) return clampVariant(task);\n if (allowlist.includes(task.assignedModel.modelId)) return clampVariant(task);\n return { ...task, assignedModel: assignmentFor(task.assignedRunner, allowlist[0]) };\n };\n\n const coerced: Coercion[] = [];\n const walk = (list: readonly Task[]): Task[] => list.map((task) => {\n const after = coerceOne(task);\n const [fromModel, toModel] = [task.assignedModel?.modelId ?? null, after.assignedModel?.modelId ?? null];\n if (fromModel !== toModel) coerced.push({ taskId: task.id, title: task.title, field: 'assignedModel', from: fromModel, to: toModel });\n const [fromEffort, toEffort] = [task.assignedModel?.thinkingEffort ?? null, after.assignedModel?.thinkingEffort ?? null];\n if (fromEffort !== toEffort) coerced.push({ taskId: task.id, title: task.title, field: 'thinkingEffort', from: fromEffort, to: toEffort });\n return { ...after, subtasks: walk(task.subtasks ?? []) };\n });\n return { tasks: walk(tasks), coerced };\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport { Task, RunnerId, TaskModelAssignment, DEFAULT_RUNNERS, createTask, flattenTasksWithParents, inheritedSkills, skillNames } from '../models/Task';\nimport { plannedMode, type RunnerModeInfo } from './ModeResolver';\nimport { checkModelAndModeValidity, type EditCatalog } from './TaskEditValidator';\n\n/** One reason a planned task was refused, pinned to the task and field it is about. */\nexport interface PlanTaskError {\n /** Absent when the envelope itself is wrong rather than one of its tasks. */\n taskId?: string;\n field: string;\n message: string;\n}\n\n/** What a planned task may be given: the runners it may run on and their modes. */\nexport interface IntakeCatalog {\n runners: readonly RunnerId[];\n /** Absent when no runner's modes are known: the mode is then guessed (ADR-0031). */\n runnerModes?: Partial<Record<RunnerId, readonly RunnerModeInfo[]>>;\n autonomousDefault?: boolean;\n /**\n * An edit's assigned models are checked against the catalog and refused; a\n * submitted plan's are coerced after it lands instead (ADR-0003).\n */\n models?: EditCatalog;\n}\n\n/** Where a planned task lands, which decides what it inherits. */\nexport interface Placement {\n /** The task it is a subtask of. */\n parent?: Pick<Task, 'title' | 'sliceType' | 'autonomy'> & { readOnly: boolean };\n /**\n * A task made from others — a merge, or a split part: what the planner\n * leaves out comes from these fields, and it stays read-only when they were.\n */\n from?: { fields: Partial<Task>; readOnly: boolean };\n /**\n * An edit's tasks get ids of their own, so a planner cannot name one after\n * a task already in the plan. A submitted plan keeps the planner's, which\n * its dependencies are written against; one it left out is made up.\n */\n freshIds?: boolean;\n}\n\nexport interface PlannedTask {\n task: Task;\n /** Rules the task, or one of its subtasks, breaks on its own. */\n errors: PlanTaskError[];\n /**\n * What the planner asked for that is not its to set — a mode, or read-only\n * on a manual task (ADR-0031). A whole plan lands without it; an edit is\n * refused.\n */\n ignored: PlanTaskError[];\n /** The planner's id for each task of the tree that was given a fresh one. */\n renamed: Map<string, string>;\n}\n\n/** The planner names no mode (ADR-0031): it says read-only, and the mode follows. */\nexport const MODE_NOT_THE_PLANNERS = '\"taskMode\" is the user\\'s to choose — set \"readOnly\": true on a task that must not change files, and leave it out otherwise';\n\n/** A manual task runs in no mode, so it cannot be read-only. */\nexport const MANUAL_NOT_READ_ONLY = '\"readOnly\" is for AI tasks — a manual task runs in no mode';\n\n/** An ops task acts — runs commands — in the session's mode (ADR-0020); a read-only mode refuses that. */\nexport const OPS_NOT_READ_ONLY = '\"readOnly\" is not for an ops task — it runs commands, in the session\\'s mode, and a read-only mode refuses them';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' || typeof value === 'number' ? String(value) : undefined;\n}\n\n/**\n * Why a task may not be an ops task (ADR-0020), or null when it may: the flag\n * decides where the task runs, and a manual task runs nowhere, a subtask\n * where its parent does.\n */\nexport function opsPlacementRefusal(type: Task['type'], isSubtask: boolean): string | null {\n if (type !== 'ai') return 'is a manual task — only an AI task can be an ops task';\n if (isSubtask) return 'is a subtask, which runs with its parent — only a top-level task can be an ops task';\n return null;\n}\n\n/** How an error names a task, so the planner can find the object it wrote. */\nexport function taskWhere(title: string, parentTitle?: string): string {\n return parentTitle !== undefined ? `subtask \"${title}\" of \"${parentTitle}\"` : `Task \"${title}\"`;\n}\n\n/**\n * What each planned task asked to attach, as the planner wrote it. Kept beside\n * the task rather than on it: {@link skillNames} drops a name no skill could\n * have, and the plan's skill check still owes a warning for it. A copy of the\n * task (assignment coercion) does not carry it, so check what was planned.\n */\nconst skillsAsked = new WeakMap<Task, unknown[]>();\n\n/** The `skills` a planned task was submitted with, before normalization; undefined for a task not planned here. */\nexport function requestedSkills(task: Task): readonly unknown[] | undefined {\n return skillsAsked.get(task);\n}\n\n/** The model as a task stores it; a top-level `thinkingEffort` is the model's, as the effort has one home. */\nfunction modelOf(raw: Record<string, unknown>, from: TaskModelAssignment | undefined): TaskModelAssignment | undefined {\n const effort = text(raw.thinkingEffort);\n if (isRecord(raw.assignedModel)) {\n const m = raw.assignedModel;\n return {\n modelId: text(m.modelId) ?? '',\n modelLabel: text(m.modelLabel) ?? '',\n thinkingEffort: text(m.thinkingEffort) ?? effort,\n };\n }\n return from && effort !== undefined ? { ...from, thinkingEffort: effort } : from;\n}\n\n/**\n * Build a task from what a planner wrote, by whichever route it arrived: a\n * submitted plan, or an edit that adds, merges or splits. Every fallback a\n * planner's omission meets is here, so the routes cannot drift apart:\n *\n * - the runner is the one named, else the task's it is made from, else the\n * first one allowed — never a substitute for one named but unknown, which\n * {@link checkPlanInvariants} refuses;\n * - an AI task's prompt is its own, else its description, else its title, so\n * it is never unschedulable;\n * - the mode is decided here from read-only or not, never named (ADR-0031);\n * - an AI subtask with no slice classification takes its parent's: an `ai`\n * sub-step of an AFK slice is AFK. Not a blanket default, which would strip\n * a human gate the planner intended; a manual subtask must still say HITL.\n */\nexport function plannedTask(spec: unknown, catalog: IntakeCatalog, at: Placement = {}): PlannedTask {\n const raw = isRecord(spec) ? spec : {};\n const { parent, from, freshIds } = at;\n const base = from?.fields ?? {};\n const errors: PlanTaskError[] = [];\n const ignored: PlanTaskError[] = [];\n const renamed = new Map<string, string>();\n\n const title = text(raw.title) ?? '';\n const where = taskWhere(title, parent?.title);\n const plannerId = text(raw.id);\n const id = freshIds || !plannerId ? uuidv4() : plannerId;\n if (freshIds && plannerId) renamed.set(plannerId, id);\n\n const type: Task['type'] = raw.type === 'user' || raw.type === 'ai' ? raw.type : base.type ?? 'ai';\n const ai = type === 'ai';\n const assignedRunner = text(raw.assignedRunner) ?? base.assignedRunner ?? catalog.runners[0] ?? DEFAULT_RUNNERS[0];\n const description = text(raw.description) ?? base.description ?? title;\n\n // A manual task stores no ops flag, so this is the one place it can still be seen.\n if (raw.ops === true && !ai) errors.push({ taskId: id, field: 'ops', message: `${where} ${opsPlacementRefusal(type, !!parent)}` });\n if (raw.taskMode !== undefined) ignored.push({ taskId: id, field: 'taskMode', message: `${where}: ${MODE_NOT_THE_PLANNERS}` });\n if (!ai && raw.readOnly === true) ignored.push({ taskId: id, field: 'readOnly', message: `${where}: ${MANUAL_NOT_READ_ONLY}` });\n const ops = raw.ops !== undefined ? raw.ops === true : base.ops;\n if (ai && ops && raw.readOnly === true) ignored.push({ taskId: id, field: 'readOnly', message: `${where}: ${OPS_NOT_READ_ONLY}` });\n // A read-only task's subtasks run as tasks of their own, so they would\n // otherwise get write access the planner said the work must not have.\n const asked = typeof raw.readOnly === 'boolean' ? raw.readOnly : undefined;\n const readOnly = ai && !ops && (asked ?? from?.readOnly ?? parent?.readOnly ?? false);\n\n let taskMode = base.taskMode;\n if (ai && catalog.runners.includes(assignedRunner)) {\n const mode = plannedMode(assignedRunner, catalog.runnerModes, { readOnly, current: base.taskMode }, catalog.autonomousDefault ?? true);\n if (!mode.ok) errors.push({ taskId: id, field: 'readOnly', message: `${where}: ${mode.error}` });\n else if (mode.mode !== undefined) taskMode = mode.mode;\n }\n // With no runner modes to read, `plan` is the guess that keeps a read-only task from writing.\n if (taskMode === undefined && readOnly && !catalog.runnerModes) taskMode = 'plan';\n\n const assignedModel = ai ? modelOf(raw, base.assignedModel) : undefined;\n // Only a model the planner named: one carried over from the tasks a merge or split is made of was never its pick.\n if (assignedModel && isRecord(raw.assignedModel) && catalog.models && catalog.runners.includes(assignedRunner)) {\n const validity = checkModelAndModeValidity(assignedRunner, assignedModel, undefined, catalog.models);\n if (!validity.ok) errors.push({ taskId: id, field: 'assignedModel', message: `${where}: ${validity.error}` });\n }\n\n const slice = (value: unknown): 'AFK' | 'HITL' | undefined => (value === 'AFK' || value === 'HITL' ? value : undefined);\n // Explicit child values always win; inheritance only fills a gap, and only for `ai` tasks.\n const autonomy = ai ? slice(raw.autonomy) ?? base.autonomy ?? parent?.autonomy : undefined;\n const sliceType = slice(raw.sliceType) ?? base.sliceType ?? (ai ? parent?.sliceType : undefined);\n\n const subtasks: Task[] = [];\n if (Array.isArray(raw.subtasks)) {\n for (const s of raw.subtasks) {\n const child = plannedTask(s, catalog, { parent: { title, sliceType, autonomy, readOnly }, freshIds });\n subtasks.push(child.task);\n errors.push(...child.errors);\n ignored.push(...child.ignored);\n for (const [was, now] of child.renamed) renamed.set(was, now);\n }\n }\n\n const task = createTask({\n id,\n order: Number(raw.order ?? 0),\n title,\n description,\n type,\n dependencies: Array.isArray(raw.dependencies) ? raw.dependencies.map(String) : base.dependencies ?? [],\n prompt: text(raw.prompt) || base.prompt || (ai ? description || title || undefined : undefined),\n userSteps: Array.isArray(raw.userSteps)\n ? raw.userSteps.map((s) => (isRecord(s) ? s : {})).map((s) => ({ order: Number(s.order ?? 0), instruction: String(s.instruction ?? ''), completed: false }))\n : base.userSteps,\n subtasks,\n assignedModel,\n assignedRunner,\n taskMode,\n autonomy,\n sliceType,\n userStoriesCovered: Array.isArray(raw.userStoriesCovered) ? raw.userStoriesCovered.map(String) : base.userStoriesCovered,\n ops,\n skills: from ? inheritedSkills(raw.skills, base.skills) : skillNames(raw.skills),\n });\n if (Array.isArray(raw.skills)) skillsAsked.set(task, raw.skills);\n return { task, errors, ignored, renamed };\n}\n\n/**\n * The rules a plan's tasks are held to together, subtasks included, whichever\n * route they arrived by.\n */\nexport function checkPlanInvariants(tasks: readonly Task[], runners: readonly RunnerId[]): PlanTaskError[] {\n const rows = flattenTasksWithParents(tasks);\n const errors: PlanTaskError[] = [];\n const seen = new Set<string>();\n for (const { task: t, parent } of rows) {\n const where = taskWhere(t.title, parent?.title);\n const fail = (field: string, message: string) => errors.push({ taskId: t.id, field, message });\n if (seen.has(t.id)) fail('id', `${where} has id \"${t.id}\", which another task in the plan has too: every task, subtasks included, needs an id of its own`);\n seen.add(t.id);\n if (t.autonomy === 'AFK' && t.userSteps && t.userSteps.length > 0) {\n fail('userSteps', `${where} has autonomy \"AFK\" but contains userSteps. AFK tasks must not have user touchpoints.`);\n }\n if (t.type === 'user' && t.sliceType && t.sliceType !== 'HITL') {\n fail('sliceType', `User ${where} has sliceType \"${t.sliceType}\". User tasks must have sliceType \"HITL\".`);\n }\n const opsRefused = t.ops ? opsPlacementRefusal(t.type, parent !== null) : null;\n if (opsRefused) fail('ops', `${where} ${opsRefused}`);\n if (t.type !== 'user' && !runners.includes(t.assignedRunner)) {\n fail('assignedRunner', `${where} has invalid assignedRunner \"${t.assignedRunner}\". Expected one of: ${runners.join(', ')}`);\n }\n }\n const ids = new Set(rows.map((r) => r.task.id));\n for (const { task: t, parent } of rows) {\n for (const dep of t.dependencies) {\n if (!ids.has(dep)) errors.push({ taskId: t.id, field: 'dependencies', message: `${taskWhere(t.title, parent?.title)} depends on \"${dep}\", which is not a task in the plan` });\n }\n }\n const cycle = findCycle(rows.map((r) => r.task));\n // Pinned to a task on the cycle: a plan whose only fault is a rule a task\n // breaks is worth naming back to the planner, not re-asking for as JSON.\n if (cycle) errors.push({ taskId: cycle[0].id, field: 'dependencies', message: `Dependency cycle detected: ${[...cycle, cycle[0]].map((t) => `\"${t.title}\"`).join(' → ')}` });\n return errors;\n}\n\n/** The tasks on one dependency cycle, in dependency order, or null when there is none. A self-dependency is a cycle of one. */\nexport function findCycle(tasks: readonly Task[]): Task[] | null {\n const byId = new Map(tasks.map((t) => [t.id, t]));\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 t of tasks) {\n const hit = visit(t.id);\n if (hit) return hit.map((id) => byId.get(id)!);\n }\n return null;\n}\n\n/** The title of a task on a dependency cycle, or null when there is none. */\nexport function detectCycle(tasks: readonly Task[]): string | null {\n return findCycle(tasks)?.[0].title ?? null;\n}\n","import { Task, flattenTasksWithParents, RunnerId, DiscoveredModel, TaskModelAssignment, TaskMode } from '../models/Task';\nimport { canSetDependencies } from './TaskOps';\nimport { effectiveAllowlist } from './ModelAllowlistResolver';\nimport { unavailableModeReason, type RunnerModeInfo } from './ModeResolver';\nimport { NOT_STARTED } from '../taskRow/status';\nimport { opsPlacementRefusal } from './PlannedTask';\n\n/**\n * Who is making the edit. The planner (`applyTaskOps`) and the direct-edit\n * path (`Session.updateTask`/`setTaskDependencies`, reached by the TUI, the\n * webview task card, and `PUT /tasks/:taskId`) are deliberately asymmetric —\n * see CONTEXT.md, \"Direct edit vs planner edit\". The planner may not reach\n * into a task that is running or already finished; the direct path may,\n * because it is the user editing their own plan, and pays what that costs at\n * the call site (cancelling a live runner, releasing blocked dependents).\n */\nexport type TaskEditActor = 'planner' | 'direct';\n\nexport interface TaskEditCheck {\n ok: boolean;\n error?: string;\n /**\n * Fields a type flip strips of meaning, to be force-cleared by the caller\n * (set to `undefined` in the applied changes) and named in whatever summary\n * reaches the transcript. Only lists fields the target actually had a value\n * for — nothing to clear reads as nothing lost.\n */\n clear?: (keyof Task)[];\n /** Fields a flip forces to a value rather than strips — a user task is always HITL — applied with {@link clear}. */\n set?: Partial<Task>;\n}\n\n/**\n * Why the planner may not touch a task execution has reached, worded with what\n * would be accepted instead: the note goes back to the model, mid-run\n * included, so it can act on it rather than retry the same edit (ADR-0029).\n * Null for a task the planner may edit.\n */\nexport function lockedTaskRefusal(task: Pick<Task, 'title' | 'status'>, action = 'changed'): string | null {\n if (task.status === 'in_progress') return `\"${task.title}\" is running and cannot be ${action} now: the user can stop it first, or change it after it finishes`;\n if (task.status === 'completed') return `\"${task.title}\" is completed and cannot be ${action}: rearm it to run it again, or add a new task for further work`;\n return null;\n}\n\nconst AI_ONLY_FIELDS = ['assignedModel', 'taskMode', 'autonomy', 'ops'] as const satisfies readonly (keyof Task)[];\n\n/**\n * The catalog a model/task-mode edit is checked against — the same discovered\n * models and manifest modes the planner was shown in the per-turn catalog\n * block (`PlannerConversation.catalogBlock`), so a refusal here can never name something\n * as invalid that the planner was never told about, or vice versa.\n */\nexport interface EditCatalog {\n modelsByRunner: Partial<Record<RunnerId, DiscoveredModel[]>>;\n runnerModes: Partial<Record<RunnerId, RunnerModeInfo[]>>;\n /** Raw (unfiltered) allowlist, keyed by runner — the same shape `coerceAssignments` takes. */\n perRunnerAllowlist?: Partial<Record<RunnerId, string[]>>;\n /** Full (true) or Guarded: the mode a task the planner writes lands on unless it is read-only (ADR-0031). Full when absent. */\n autonomousDefault?: boolean;\n}\n\n/**\n * Whether an assigned model and task mode are things the target runner\n * actually offers. Invented ids are refused rather than silently substituted\n * downstream (`coerceAssignments` remains the safety net for paths that never\n * go through this validator) — the planner gets the refusal, with the runner\n * named, through the same repair loop as every other edit rejection.\n *\n * `catalog` is optional: callers with no discovered catalog on hand (most unit\n * tests, a runner with no manifest modes) skip these checks rather than\n * refusing everything sight-unseen.\n */\nexport function checkModelAndModeValidity(\n runner: RunnerId,\n assignedModel: TaskModelAssignment | undefined,\n taskMode: TaskMode | undefined,\n catalog: EditCatalog | undefined,\n): TaskEditCheck {\n if (!catalog) return { ok: true };\n\n if (assignedModel) {\n const models = catalog.modelsByRunner[runner];\n if (models) {\n const modelId = assignedModel.modelId;\n const allowed = effectiveAllowlist(catalog.perRunnerAllowlist?.[runner], runner, catalog.modelsByRunner);\n // An allowlisted id discovery doesn't list is one `filterModelsForPrompt`\n // shows the planner anyway — refusing it here would contradict the\n // catalog block; the runner validates it last.\n if (!models.some((m) => m.modelId === modelId) && !allowed?.includes(modelId)) {\n return { ok: false, error: `Runner \"${runner}\" does not offer model \"${modelId}\"` };\n }\n if (allowed && !allowed.includes(modelId)) {\n return { ok: false, error: `Model \"${modelId}\" is excluded by the allowlist for runner \"${runner}\"` };\n }\n }\n }\n\n if (taskMode !== undefined) {\n const modes = catalog.runnerModes[runner];\n if (modes && modes.length > 0 && !modes.some((m) => m.id === taskMode)) {\n return { ok: false, error: `Runner \"${runner}\" has no task mode \"${taskMode}\" — valid modes: ${modes.map((m) => m.id).join(', ')}` };\n }\n const unavailable = unavailableModeReason(modes, taskMode);\n if (unavailable) return { ok: false, error: `Mode \"${taskMode}\" of runner \"${runner}\" is unavailable on this host: ${unavailable}` };\n }\n\n return { ok: true };\n}\n\n/**\n * Coherence between `type` and the fields that only make sense for one side\n * of it. Deriving user steps from an AI prompt (or vice versa) would fabricate\n * instructions nobody wrote (ADR-0001: the plan is the source of truth), so a\n * flip that lacks the content the new type needs is refused rather than\n * silently patched — the planner gets that refusal back through the repair\n * loop; a direct edit gets it as a thrown reason. A flip that IS well-formed\n * clears the fields that stopped meaning anything, named for the caller.\n */\nfunction typeCoherenceCheck(target: Task, changes: Partial<Task>): TaskEditCheck | null {\n if (!changes.type || changes.type === target.type) return null;\n\n if (changes.type === 'user') {\n if (!Array.isArray(changes.userSteps) || changes.userSteps.length === 0) {\n return { ok: false, error: `\"${target.title}\" cannot become a manual task without user steps — include \"userSteps\" in this edit` };\n }\n return {\n ok: true,\n clear: AI_ONLY_FIELDS.filter((f) => target[f] !== undefined),\n // User tasks are held to HITL, so a flip that kept the AI task's slice would be refused by the plan's own rules.\n ...(target.sliceType !== 'HITL' ? { set: { sliceType: 'HITL' as const } } : {}),\n };\n }\n\n // changes.type === 'ai'\n if (!changes.prompt || !changes.prompt.trim()) {\n return { ok: false, error: `\"${target.title}\" cannot become an AI task without a prompt — include \"prompt\" in this edit` };\n }\n return { ok: true, clear: target.userSteps && target.userSteps.length > 0 ? ['userSteps'] : [] };\n}\n\n/**\n * Whether a task may become an ops task, or stop being one (ADR-0020). Only a\n * top-level AI task can be ops, and the flag decides where the task runs, so\n * once it has started it is fixed, like its runner session.\n */\nfunction opsCheck(target: Task, isSubtask: boolean, changes: Partial<Task>): TaskEditCheck | null {\n if (!('ops' in changes) || !!changes.ops === !!target.ops) return null;\n if (!NOT_STARTED.has(target.status)) {\n return { ok: false, error: `\"${target.title}\" has started, so whether it is an ops task is fixed` };\n }\n if (!changes.ops) return null;\n const refused = opsPlacementRefusal(changes.type ?? target.type, isSubtask);\n return refused ? { ok: false, error: `\"${target.title}\" ${refused}` } : null;\n}\n\n/**\n * The rules governing one task edit, shared by both actors. Lock rules\n * (running/completed) apply to the planner only. Well-formedness rules — like\n * a hand-set dependency list, the one edit that can leave the plan\n * unschedulable, and type/content coherence on an AI↔MAN flip — describe the\n * task rather than who asked, so they run for both, through the same\n * {@link canSetDependencies} guard the pickers and the API read.\n *\n * `tasks` is the plan tree: the target is found at any depth, and its\n * dependencies are checked among its siblings, the list its order is in.\n */\nexport function validateTaskEdit(\n actor: TaskEditActor,\n tasks: readonly Task[],\n taskId: string,\n changes: Partial<Task>,\n catalog?: EditCatalog,\n): TaskEditCheck {\n const found = flattenTasksWithParents(tasks).find(({ task }) => task.id === taskId);\n if (!found) return { ok: false, error: 'Task not found' };\n const { task: target, parent } = found;\n\n const locked = actor === 'planner' ? lockedTaskRefusal(target, 'modified') : null;\n if (locked) return { ok: false, error: locked };\n\n if (changes.dependencies) {\n const depCheck = canSetDependencies(parent?.subtasks ?? tasks, taskId, changes.dependencies);\n if (!depCheck.ok) return depCheck;\n }\n\n const coherence = typeCoherenceCheck(target, changes);\n if (coherence && !coherence.ok) return coherence;\n\n const ops = opsCheck(target, parent !== null, changes);\n if (ops) return ops;\n\n const validity = checkModelAndModeValidity(changes.assignedRunner ?? target.assignedRunner, changes.assignedModel, changes.taskMode, catalog);\n if (!validity.ok) return validity;\n\n return coherence ?? { ok: true };\n}\n","import {\n Task, RunnerId, flattenTasks,\n addTaskToPlan, removeTaskFromPlan, updateTaskInPlan, renumberTasks,\n opsFlag, inheritedOps, skillNames,\n} from '../models/Task';\nimport { resolveTaskRef } from './TaskRefs';\nimport { extractObjectsWithKey, stripTrailingCommas, escapeControlCharsInStrings, PlanParseError, TASK_OPS_ENVELOPE_KEY } from './JsonExtractor';\nimport { validateTaskEdit, lockedTaskRefusal, type EditCatalog, type TaskEditActor, type TaskEditCheck } from './TaskEditValidator';\nimport { plannedTask, checkPlanInvariants, detectCycle, taskWhere, MODE_NOT_THE_PLANNERS, MANUAL_NOT_READ_ONLY, OPS_NOT_READ_ONLY, type IntakeCatalog, type PlannedTask, type PlanTaskError } from './PlannedTask';\nimport { plannedMode, taggedReadOnlyMode, type PlannedMode } from './ModeResolver';\n\n/**\n * Targeted task edits emitted by the planner conversation (the 'task_ops'\n * ConversationTurn). Task references accept a task id, a \"#<order>\" ref, or a\n * bare order number — cheap models rarely echo UUIDs correctly.\n */\n/**\n * A task as the planner writes it: its fields, less the mode, plus whether it\n * must not change files (ADR-0031), and `thinkingEffort` as a name for its\n * model's effort, so an effort can change without restating the model.\n */\nexport type PlannerTaskSpec = Partial<Task> & { readOnly?: boolean; thinkingEffort?: string | null };\n\nexport type TaskOp =\n | { op: 'update'; taskId: string; changes: PlannerTaskSpec }\n | { op: 'add'; task: PlannerTaskSpec; handle?: string }\n | { op: 'remove'; taskId: string }\n | { op: 'reorder'; taskIds: string[] }\n | { op: 'merge'; taskIds: string[]; merged: PlannerTaskSpec; handle?: string }\n | { op: 'split'; taskId: string; parts: PlannerTaskSpec[]; handle?: string }\n | { op: 'rearm'; taskId: string; changes?: PlannerTaskSpec };\n\n/** Fields the planner may change on an existing task. Everything else (id, status, verdict…) is system-owned. */\nexport const UPDATABLE_FIELDS: (keyof Task)[] = [\n 'title', 'description', 'prompt', 'dependencies', 'assignedRunner', 'assignedModel', 'taskMode', 'type', 'userSteps', 'autonomy', 'sliceType', 'ops', 'skills',\n];\n\n/**\n * The edit protocol as the planner reads it, kept beside the applier so the\n * prose can never undersell (or oversell) what {@link applyTaskOps} accepts.\n * `executionNote` rides on the ordering rule because that is the rule a\n * running execution changes.\n */\nexport function taskOpsProtocol(executionNote = '', tools = false): string[] {\n const updateChanges = [...UPDATABLE_FIELDS.filter((f) => f !== 'taskMode'), 'thinkingEffort', 'readOnly']\n .map((f) => (f === 'dependencies' ? '\"dependencies\"?:[\"<id or #order>\"]' : `\"${f}\"?`))\n .join(',');\n return [\n tools ? '- To modify specific tasks, call edit_plan, never a JSON reply. Its argument is:' : '- To modify specific tasks, reply with ONLY this JSON object:',\n tools ? ' {\"ops\": [' : ' {\"taskOps\": [',\n ` {\"op\":\"update\",\"taskId\":\"<id or #order>\",\"changes\":{${updateChanges}}},`,\n ' {\"op\":\"add\",\"task\":{\"title\",\"description\",\"prompt\",\"dependencies\":[\"<id or #order>\"],\"assignedRunner\"?,\"assignedModel\"?,\"readOnly\"?,\"ops\"?},\"handle\"?:\"<name>\"},',\n ' {\"op\":\"remove\",\"taskId\":\"<id or #order>\"},',\n ' {\"op\":\"reorder\",\"taskIds\":[\"<id or #order>\", \"... every task exactly once\"]}, // only to re-prioritise INDEPENDENT tasks',\n ' {\"op\":\"merge\",\"taskIds\":[\"<id or #order>\", \"...\"],\"merged\":{\"title\",\"description\",\"prompt\"?,\"assignedRunner\"?,\"assignedModel\"?,...},\"handle\"?:\"<name>\"},',\n ' {\"op\":\"split\",\"taskId\":\"<id or #order>\",\"parts\":[{\"title\",\"description\",\"prompt\"?,\"assignedRunner\"?,\"assignedModel\"?,...}, ...],\"handle\"?:\"<name>\"},',\n ` {\"op\":\"rearm\",\"taskId\":\"<id or #order>\",\"changes\"?:{${updateChanges}}}`,\n ' ]}',\n tools ? '- For sweeping changes, you may instead call submit_plan with the full plan.' : '- For sweeping changes, you may instead emit a full {\"tasks\":[...]} plan JSON.',\n 'Every \"<id or #order>\" ref in a batch resolves against the plan shown above, before any op in the batch runs — an earlier remove/merge/split never shifts what a later \"#N\" means. \"#N\" is top-level task N; a subtask is named by its dotted label (\"#2.1\"), as the plan lists it.',\n 'Give \"add\", \"merge\", or \"split\" a \"handle\" (any name you choose, unused elsewhere in this batch) to let a LATER op in the same batch reference the task it produces — for \"split\", the handle names its last part. A handle used before its defining op is rejected.',\n `When creating or changing tasks, set \"assignedRunner\" and \"assignedModel\" ({\"modelId\",\"modelLabel\",\"thinkingEffort\"?}) using only the runners and models ${tools ? 'list_runners and list_models return' : 'listed in <available_models>'}.`,\n 'Set \"readOnly\": true on a task that must not change any file, never on one that must run commands (tests, scripts, builds) or an ops task, and \"readOnly\": false to lift it; you never set \"taskMode\". A task you move, split or edit keeps being read-only or not unless you say otherwise, and so do the subtasks of a read-only task you add.',\n 'Keep dependencies consistent: no cycles, no references to removed tasks, and never touch running or completed tasks — \"rearm\" is the one exception, below.',\n ...(tools ? ['edit_plan checks the batch when you call it and answers with what it will change, or with the error to fix — call it again in the same reply. The edit is applied when your reply ends; edits you make in one reply join one batch.'] : []),\n 'Just declare the dependencies you want — display order is repaired for you afterwards, so a rewire or a newly added prerequisite never needs a \"reorder\" op. Only a task that is running or completed cannot be shifted, so an edit that would need one to move is rejected.' + executionNote,\n 'Flipping \"type\" between \"ai\" and \"user\" is a content change, not just a label: an update to \"user\" needs \"userSteps\" in the SAME op, and an update to \"ai\" needs \"prompt\" in the SAME op — the model/mode/effort/autonomy fields (flipping to \"user\", which also makes the task HITL) or the userSteps (flipping to \"ai\") are cleared automatically.',\n '\"skills\" in \"changes\" REPLACES the task\\'s whole skill list. To add one, send the names the plan block shows in its skills:[...] plus the new one; to drop one, send the rest; [] removes them all.',\n '\"rearm\" puts a failed OR completed task back to pending — verdict and output summary are cleared, any dependents it had blocked are released, and it may carry field changes (e.g. a corrected \"prompt\") applied in the same op. A running task cannot be re-armed. Never rearm a task just to relabel it — only when it should actually run again.',\n ];\n}\n\nexport function textHasTaskOps(text: string): boolean {\n return text.includes(`\"${TASK_OPS_ENVELOPE_KEY}\"`);\n}\n\n/** Parse a `{\"taskOps\":[...]}` reply. Throws PlanParseError when the JSON is unusable. */\nexport function parseTaskOpsJson(text: string): TaskOp[] {\n // Extract by the taskOps key specifically — a reply may also carry a\n // tasks-keyed object (schema echo, example), which must not shadow the ops.\n // Candidates are tried back to front: the last emission is the final answer.\n const { matches, fallback } = extractObjectsWithKey(text, TASK_OPS_ENVELOPE_KEY);\n const candidates = matches.length > 0 ? [...matches].reverse() : [fallback.json];\n\n let lastError: PlanParseError | null = null;\n for (const json of candidates) {\n try {\n return parseTaskOpsObject(json, text);\n } catch (err) {\n if (!(err instanceof PlanParseError)) throw err;\n if (!lastError) lastError = err;\n }\n }\n throw lastError ?? new PlanParseError('No JSON object found in task-ops reply', text);\n}\n\nfunction parseTaskOpsObject(json: string, text: string): TaskOp[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(escapeControlCharsInStrings(stripTrailingCommas(json)));\n } catch (err) {\n throw new PlanParseError(`Task-ops JSON is invalid: ${err instanceof Error ? err.message : String(err)}`, text);\n }\n const ops = (parsed as { taskOps?: unknown }).taskOps;\n if (!Array.isArray(ops) || ops.length === 0) {\n throw new PlanParseError('\"taskOps\" must be a non-empty array', text);\n }\n for (const op of ops) {\n if (typeof op !== 'object' || op === null || typeof (op as { op?: unknown }).op !== 'string') {\n throw new PlanParseError('Every task op needs an \"op\" field (update | add | remove | reorder | merge | split)', text);\n }\n }\n return ops as TaskOp[];\n}\n\ntype RefResolution = { id: string } | { error: string };\n\n/**\n * Resolve an op's task reference to a task id: a batch handle, or anything\n * {@link resolveTaskRef} reads.\n *\n * Order labels and title matches are pinned to `originalTree` — the plan as it\n * stood before the batch began — so an earlier op's renumbering can never\n * make a later op's \"#4\" land on a different task than the planner saw. A\n * literal id has no such drift (ids are stable across mutations), so id\n * matches check `liveTree` — the batch's current, mutated tasks — which is\n * also how a later op reaches a task created earlier in the same batch\n * without a handle (e.g. a split's own chained parts).\n */\nfunction resolveRef(\n ref: unknown,\n originalTree: readonly Task[],\n liveTree: Task[],\n handleOwner: Map<string, number>,\n handleId: Map<string, string>,\n opIndex: number,\n): RefResolution {\n if (typeof ref !== 'string' && typeof ref !== 'number') return { error: `invalid reference \"${String(ref)}\"` };\n const s = String(ref).trim();\n\n const ownerIdx = handleOwner.get(s);\n if (ownerIdx !== undefined) {\n if (ownerIdx >= opIndex) {\n return { error: `handle \"${s}\" is defined by a later op in this batch and cannot be referenced yet` };\n }\n const id = handleId.get(s);\n if (!id) return { error: `handle \"${s}\" was never resolved` };\n return { id };\n }\n\n if (findInTasks(liveTree, s)) return { id: s };\n const task = resolveTaskRef(originalTree, s);\n return task ? { id: task.id } : { error: `task \"${s}\" not found` };\n}\n\n/** The fields of a planner's `changes` it may set, with the ops flag read as every entry point reads it. */\nfunction updatableChanges(raw: Partial<Task> | undefined): Partial<Task> {\n const changes: Partial<Task> = {};\n for (const key of UPDATABLE_FIELDS) {\n if (raw && key in raw) (changes as Record<string, unknown>)[key] = (raw as Record<string, unknown>)[key];\n }\n if ('ops' in changes) changes.ops = opsFlag(changes.ops);\n if ('skills' in changes) changes.skills = skillNames(changes.skills);\n return changes;\n}\n\nfunction findInTasks(tasks: readonly Task[], id: string): Task | undefined {\n return flattenTasks(tasks).find((t) => t.id === id);\n}\n\nfunction findTopLevel(tasks: Task[], id: string): Task | undefined {\n return tasks.find((t) => t.id === id);\n}\n\n/** A task the repair may not reposition: execution has already reached it. */\nfunction isPinned(t: Task): boolean {\n return t.status === 'in_progress' || t.status === 'completed';\n}\n\n/**\n * Reorder top-level tasks so every dependency comes before its dependents,\n * moving as little as possible: pinned tasks keep the exact slot they are in,\n * and each free slot goes to the earliest-listed movable task whose\n * dependencies are already placed — so tasks the graph does not constrain keep\n * their relative order. Assumes an acyclic graph (the caller checks first).\n */\nfunction repairOrder(tasks: Task[]): { tasks: Task[] } | { error: string } {\n const byId = new Map(tasks.map((t) => [t.id, t]));\n const placed = new Set<string>();\n const movable = tasks.filter((t) => !isPinned(t));\n const result: Task[] = [];\n // Dependencies outside this list (a subtask id) constrain nothing here.\n const blockerOf = (t: Task): Task | undefined => {\n const id = t.dependencies.find((d) => byId.has(d) && !placed.has(d));\n return id ? byId.get(id) : undefined;\n };\n const place = (t: Task) => { result.push(t); placed.add(t.id); };\n\n for (const occupant of tasks) {\n if (isPinned(occupant)) {\n const blocker = blockerOf(occupant);\n if (blocker) return { error: pinnedRefusal(blocker, occupant, 'before') };\n place(occupant);\n continue;\n }\n const next = movable.findIndex((t) => !blockerOf(t));\n if (next < 0) {\n // Nothing is schedulable and the graph is acyclic, so every movable task\n // left waits — directly or through others — on a pinned task further down\n // that would have to come up to free this slot.\n const [stuck, pin] = trailToPin(movable[0], blockerOf);\n return { error: pinnedRefusal(stuck, pin, 'after') };\n }\n place(movable.splice(next, 1)[0]);\n }\n return { tasks: result };\n}\n\n/** Walk the waiting-on chain from `task` down to the pinned task holding it up. */\nfunction trailToPin(task: Task, blockerOf: (t: Task) => Task | undefined): [Task, Task] {\n let at = task;\n for (;;) {\n const blocker = blockerOf(at);\n if (!blocker || isPinned(blocker)) return [at, blocker ?? at];\n at = blocker;\n }\n}\n\n/** `\"B\" #2→#1, \"A\" #1→#3` for every task the repair actually moved, or null. */\nfunction describeMoves(before: Task[], after: Task[]): string | null {\n const wasAt = new Map(before.map((t, i) => [t.id, i + 1]));\n const moved = after\n .map((t, i) => ({ t, from: wasAt.get(t.id)!, to: i + 1 }))\n .filter((m) => m.from !== m.to);\n return moved.length ? moved.map((m) => `\"${m.t.title}\" #${m.from}→#${m.to}`).join(', ') : null;\n}\n\nfunction pinnedRefusal(other: Task, pin: Task, side: 'before' | 'after'): string {\n const word = pin.status === 'in_progress' ? 'running' : 'completed';\n return `\"${other.title}\" would have to run ${side} \"${pin.title}\", which is ${word} and cannot be moved`;\n}\n\nexport interface ApplyTaskOpsResult {\n ok: boolean;\n tasks: readonly Task[];\n errors: string[];\n /** Human-readable summary of what changed, for the chat transcript. */\n summary: string[];\n}\n\n/**\n * Pre-flight check for a merge: would collapsing the selected tasks into one\n * (rewiring every dependent of any selected task to the survivor) keep the\n * dependency graph valid? Rejects locked tasks and merges whose rewiring would\n * introduce a cycle. Display order is NOT checked here — neither\n * consecutiveness (a UI concern) nor a dependency the merge pulls out of order,\n * which {@link applyTaskOps} repairs; refusing on order would make this\n * pre-flight stricter than the applier it stands in for.\n */\nexport function canMergeTasks(tasks: readonly Task[], selectedIds: string[]): { ok: boolean; error?: string } {\n if (selectedIds.length < 2) return { ok: false, error: 'Select at least two tasks to merge' };\n const idSet = new Set(selectedIds);\n const toMerge = tasks.filter((t) => idSet.has(t.id));\n if (toMerge.length < 2) return { ok: false, error: 'At least two valid tasks are required to merge' };\n for (const t of toMerge) {\n if (t.status === 'in_progress') return { ok: false, error: `\"${t.title}\" is running and cannot be merged` };\n if (t.status === 'completed') return { ok: false, error: `\"${t.title}\" is completed and cannot be merged` };\n }\n const ordered = [...toMerge].sort((a, b) => a.order - b.order);\n const survivorId = '__merge_sim__';\n const sim: Task[] = tasks\n .filter((t) => !idSet.has(t.id))\n .map((t) => ({ ...t, dependencies: t.dependencies.map((d) => (idSet.has(d) ? survivorId : d)).filter((d) => d !== t.id) }));\n const unionDeps = [...new Set(toMerge.flatMap((t) => t.dependencies))].filter((d) => !idSet.has(d));\n sim.push({ ...ordered[0], id: survivorId, title: '__merge_sim__', order: ordered[0].order, dependencies: unionDeps });\n const cycle = detectCycle(sim);\n if (cycle) return { ok: false, error: `Merging would create a dependency cycle involving \"${cycle}\"` };\n return { ok: true };\n}\n\n/**\n * The shape the dependency helpers below read. Structural rather than `Task`,\n * because the TUI projects tasks into its own `TaskView`: a surface's\n * dependency picker and the API's validation must agree on which dependencies\n * are legal, and a signature only core can satisfy would have forced the TUI\n * to keep a second copy of the rule.\n */\nexport interface TaskRef {\n id: string;\n order: number;\n title: string;\n dependencies: string[];\n}\n\n/** The tasks listing `taskId` as a dependency — exactly what removing it detaches. */\nexport function dependentsOf<T extends Pick<TaskRef, 'id' | 'dependencies'>>(tasks: T[], taskId: string): T[] {\n return tasks.filter((t) => t.id !== taskId && t.dependencies.includes(taskId));\n}\n\n/**\n * The tasks that may become dependencies of `taskId`: those displayed before it.\n *\n * Offering only earlier tasks is what keeps a hand-edited graph valid without a\n * cycle check — dependencies then only ever point backwards in display order,\n * the same invariant `applyTaskOps` enforces. Omit `taskId` for a task that does\n * not exist yet: it lands last, so every current task is a candidate.\n */\nexport function dependencyCandidates<T extends Pick<TaskRef, 'id' | 'order'>>(tasks: readonly T[], taskId?: string): T[] {\n if (!taskId) return [...tasks];\n const target = tasks.find((t) => t.id === taskId);\n return target ? tasks.filter((t) => t.order < target.order) : [];\n}\n\n/** Pre-flight check for a hand-edited dependency list: every id exists and comes earlier. */\nexport function canSetDependencies<T extends TaskRef>(\n tasks: readonly T[],\n taskId: string,\n dependencies: string[],\n): { ok: boolean; error?: string } {\n const target = tasks.find((t) => t.id === taskId);\n if (!target) return { ok: false, error: 'Task not found' };\n const allowed = new Set(dependencyCandidates(tasks, taskId).map((t) => t.id));\n for (const dep of dependencies) {\n if (dep === taskId) return { ok: false, error: `\"${target.title}\" cannot depend on itself` };\n const found = tasks.find((t) => t.id === dep);\n if (!found) return { ok: false, error: `Unknown dependency \"${dep}\"` };\n if (!allowed.has(dep)) {\n return { ok: false, error: `\"${target.title}\" cannot depend on \"${found.title}\", which comes after it in the plan` };\n }\n }\n return { ok: true };\n}\n\n/** Pre-flight check for a split: the task exists and is not locked by execution. */\nexport function canSplitTask(tasks: readonly Task[], taskId: string): { ok: boolean; error?: string } {\n const target = tasks.find((t) => t.id === taskId);\n if (!target) return { ok: false, error: 'Task not found' };\n if (target.status === 'in_progress') return { ok: false, error: `\"${target.title}\" is running and cannot be split` };\n if (target.status === 'completed') return { ok: false, error: `\"${target.title}\" is completed and cannot be split` };\n return { ok: true };\n}\n\n\nfunction askedReadOnly(spec: PlannerTaskSpec | undefined): boolean | undefined {\n return typeof spec?.readOnly === 'boolean' ? spec.readOnly : undefined;\n}\n\nfunction isReadOnly(task: Task, catalog: EditCatalog | undefined): boolean {\n return task.taskMode !== undefined && task.taskMode === taggedReadOnlyMode(catalog?.runnerModes[task.assignedRunner]);\n}\n\n/**\n * The mode a planner edit lands a task on (ADR-0031). A task stays read-only\n * or not unless the planner says otherwise, so a move or split never quietly\n * gives a read-only task write access. Undefined mode with no catalog to read\n * the runner's modes from.\n */\nfunction landingMode(runner: RunnerId, readOnly: boolean | undefined, current: string | undefined, catalog: EditCatalog | undefined): PlannedMode {\n return plannedMode(runner, catalog?.runnerModes, { readOnly, current }, catalog?.autonomousDefault ?? true);\n}\n\n/** The fields an edit changed, as the planner names them: `readOnly` when that flipped, never the mode it landed on (ADR-0031). */\nfunction changedFields(target: Task, changes: Partial<Task>, catalog: EditCatalog | undefined): string[] {\n const fields = Object.keys(changes).filter((f) => f !== 'taskMode');\n if ('taskMode' in changes && isReadOnly({ ...target, ...changes }, catalog) !== isReadOnly(target, catalog)) fields.push('readOnly');\n return fields;\n}\n\n/**\n * Apply task ops to a snapshot of the plan, atomically: either every op\n * applies and the result validates (deps resolve, no cycles, running and\n * completed tasks untouched), or nothing is returned and `errors` explains\n * why. The caller commits `tasks` on ok.\n */\nexport function applyTaskOps(\n currentTasks: readonly Task[],\n newOps: TaskOp[],\n runners: RunnerId[],\n catalog?: EditCatalog,\n held: readonly TaskOp[] = [],\n): ApplyTaskOpsResult {\n // Ops already accepted earlier in the batch apply first; errors number only\n // the new ones, as the planner wrote them in the call it is answered for.\n const ops = [...held, ...newOps];\n const opLabel = (i: number) => (i < held.length ? `earlier op ${i + 1} (${ops[i].op})` : `op ${i - held.length + 1} (${ops[i].op})`);\n let tasks: Task[] = JSON.parse(JSON.stringify(currentTasks));\n const errors: string[] = [];\n const summary: string[] = [];\n\n // Batch handles: planner-chosen names for a task an add/merge/split op is\n // about to create, so a later op in the same batch can reference it before\n // it has a real id. Pre-scanned up front — a bad handle refuses the whole\n // batch before anything mutates.\n const handleOwner = new Map<string, number>();\n const handleId = new Map<string, string>();\n for (const [i, op] of ops.entries()) {\n const handle = (op as { handle?: unknown }).handle;\n if (handle === undefined) continue;\n if (typeof handle !== 'string' || !handle.trim()) {\n errors.push(`${opLabel(i)}: handle must be a non-empty string`);\n continue;\n }\n if (handleOwner.has(handle)) {\n errors.push(`${opLabel(i)}: handle \"${handle}\" is already used earlier in this batch`);\n continue;\n }\n if (resolveTaskRef(currentTasks, handle)) {\n errors.push(`${opLabel(i)}: handle \"${handle}\" collides with an existing task reference`);\n continue;\n }\n handleOwner.set(handle, i);\n }\n if (errors.length) return { ok: false, tasks: currentTasks, errors, summary: [] };\n\n const resolveDeps = (deps: unknown, opIndex: number): { ids: string[]; bad: string[] } => {\n const ids: string[] = [];\n const bad: string[] = [];\n const liveFlat = flattenTasks(tasks);\n for (const d of Array.isArray(deps) ? deps : []) {\n const r = resolveRef(d, currentTasks, tasks, handleOwner, handleId, opIndex);\n if ('error' in r) { bad.push(`${String(d)} (${r.error})`); continue; }\n if (!liveFlat.some((t) => t.id === r.id)) { bad.push(`${String(d)} (no longer exists in this batch)`); continue; }\n ids.push(r.id);\n }\n return { ids, bad };\n };\n\n const intake: IntakeCatalog = { runners, runnerModes: catalog?.runnerModes, autonomousDefault: catalog?.autonomousDefault, models: catalog };\n\n /**\n * A planned task's dependency refs, at every depth, as ids: a subtask may\n * name a task of its own tree by the id the planner gave it, or any task in\n * the plan the way every op does.\n */\n const resolveTree = (planned: PlannedTask, opIndex: number): { task: Task } | { error: string } => {\n const walk = (t: Task, parentTitle?: string): Task | string => {\n const ids: string[] = [];\n const bad: string[] = [];\n for (const d of t.dependencies) {\n const own = planned.renamed.get(d);\n if (own) { ids.push(own); continue; }\n const r = resolveDeps([d], opIndex);\n ids.push(...r.ids);\n bad.push(...r.bad);\n }\n if (bad.length) return `unknown dependencies${parentTitle !== undefined ? ` of ${taskWhere(t.title, parentTitle)}` : ''}: ${bad.join(', ')}`;\n const subtasks: Task[] = [];\n for (const sub of t.subtasks) {\n const done = walk(sub, t.title);\n if (typeof done === 'string') return done;\n subtasks.push(done);\n }\n return { ...t, dependencies: ids.filter((id) => id !== t.id), subtasks };\n };\n const done = walk(planned.task);\n return typeof done === 'string' ? { error: done } : { task: done };\n };\n\n /** Why the edit cannot have this planned task: a rule it breaks, or something it asked for that is not the planner's. */\n const refusalOf = (planned: PlannedTask): string | undefined => [...planned.ignored, ...planned.errors][0]?.message;\n\n /**\n * The resolve-and-validate half shared by \"update\" and \"rearm\": resolve the\n * target, apply the field allowlist and runner check, run the edit validator\n * under the op's audience, then resolve any dependency refs. `refuseRunning`\n * is rearm's extra lock check, kept before the field work so its message wins.\n */\n const prepareEdit = (\n op: { taskId: string; changes?: PlannerTaskSpec },\n opIndex: number,\n label: string,\n audience: TaskEditActor,\n refuseRunning = false,\n ): { target: Task; changes: Partial<Task>; check: TaskEditCheck } | { error: string } => {\n const ref = resolveRef(op.taskId, currentTasks, tasks, handleOwner, handleId, opIndex);\n if ('error' in ref) return { error: `${label}: ${ref.error}` };\n const target = findInTasks(tasks, ref.id);\n if (!target) return { error: `${label}: task \"${op.taskId}\" no longer exists in this batch (removed, merged, or split by an earlier op)` };\n if (refuseRunning && target.status === 'in_progress') return { error: `${label}: ${lockedTaskRefusal(target, 're-armed')}` };\n if (op.changes && 'taskMode' in op.changes) return { error: `${label}: ${MODE_NOT_THE_PLANNERS}` };\n const changes = updatableChanges(op.changes);\n if (op.changes && 'thinkingEffort' in op.changes) {\n const model = changes.assignedModel ?? target.assignedModel;\n if (!model) return { error: `${label}: \"thinkingEffort\" is the assigned model's — set \"assignedModel\" with it` };\n changes.assignedModel = { ...model, thinkingEffort: op.changes.thinkingEffort ?? undefined };\n }\n // Dependency refs are still unresolved (e.g. \"#3\") at this point, so the\n // check runs on everything but them; resolveDeps below handles them once\n // they're real ids.\n const changesForCheck: Partial<Task> = { ...changes };\n delete changesForCheck.dependencies;\n const check = validateTaskEdit(audience, tasks, target.id, changesForCheck, catalog);\n if (!check.ok) return { error: `${label}: ${check.error}` };\n for (const field of check.clear ?? []) (changes as Record<string, unknown>)[field] = undefined;\n Object.assign(changes, check.set);\n const readOnly = askedReadOnly(op.changes);\n if (readOnly === true && (changes.type ?? target.type) === 'user') return { error: `${label}: ${MANUAL_NOT_READ_ONLY}` };\n if ((changes.ops ?? target.ops) && (readOnly ?? isReadOnly(target, catalog))) return { error: `${label}: ${OPS_NOT_READ_ONLY}` };\n const moved = changes.assignedRunner !== undefined && changes.assignedRunner !== target.assignedRunner;\n const becomesAi = changes.type === 'ai' && target.type === 'user';\n // A runner not allowed has no mode to land on; the plan's rules refuse it once the op is applied.\n const known = runners.includes(changes.assignedRunner ?? target.assignedRunner);\n if (known && (readOnly !== undefined || moved || becomesAi) && (changes.type ?? target.type) !== 'user') {\n const mode = landingMode(changes.assignedRunner ?? target.assignedRunner, readOnly ?? isReadOnly(target, catalog), target.taskMode, catalog);\n if (!mode.ok) return { error: `${label}: ${mode.error}` };\n if (mode.mode !== undefined && mode.mode !== target.taskMode) changes.taskMode = mode.mode;\n }\n if ('dependencies' in changes) {\n const { ids, bad } = resolveDeps(changes.dependencies, opIndex);\n if (bad.length) return { error: `${label}: unknown dependencies: ${bad.join(', ')}` };\n changes.dependencies = ids.filter((id) => id !== target.id);\n }\n return { target, changes, check };\n };\n\n // A rule the batch ends in breach of is the op's that first broke it. What\n // the plan already broke before the batch — a task on a runner disabled\n // since, say — is not, so it never blocks an unrelated edit. A breach is\n // told by its task and rule, not its wording: the wording carries the title,\n // which an edit may change.\n const breachKey = (e: PlanTaskError) => `${e.taskId ?? ''}\\u0000${e.field}`;\n const standing = new Set(checkPlanInvariants(currentTasks, runners).map(breachKey));\n const brokenBy = new Map<string, string>();\n let lastLabel = opLabel(0);\n\n for (const [i, op] of ops.entries()) {\n const label = opLabel(i);\n switch (op.op) {\n case 'update': {\n const prep = prepareEdit(op, i, label, 'planner');\n if ('error' in prep) { errors.push(prep.error); break; }\n const { target, changes, check } = prep;\n if (Object.keys(changes).length === 0) {\n const readOnly = askedReadOnly(op.changes);\n if (readOnly !== undefined && isReadOnly(target, catalog) === readOnly) { summary.push(`\"${target.title}\" is already ${readOnly ? '' : 'not '}read-only`); break; }\n errors.push(`${label}: no valid changes provided`);\n break;\n }\n tasks = updateTaskInPlan(tasks, target.id, changes);\n const clearedNote = check.clear?.length ? `; cleared ${check.clear.join(', ')}` : '';\n const fields = changedFields(target, changes, catalog);\n summary.push(`Updated \"${target.title}\"${fields.length ? ` (${fields.join(', ')})` : ''}${clearedNote}`);\n break;\n }\n case 'add': {\n const spec = op.task ?? {};\n if (!spec.title) { errors.push(`${label}: new task needs a title`); break; }\n const planned = plannedTask(spec, intake, { freshIds: true });\n const refused = refusalOf(planned);\n if (refused) { errors.push(`${label}: ${refused}`); break; }\n const resolved = resolveTree(planned, i);\n if ('error' in resolved) { errors.push(`${label}: ${resolved.error}`); break; }\n tasks = addTaskToPlan(tasks, resolved.task);\n if (op.handle) handleId.set(op.handle, resolved.task.id);\n summary.push(`Added \"${spec.title}\"`);\n break;\n }\n case 'remove': {\n const ref = resolveRef(op.taskId, currentTasks, tasks, handleOwner, handleId, i);\n if ('error' in ref) { errors.push(`${label}: ${ref.error}`); break; }\n const target = findInTasks(tasks, ref.id);\n if (!target) { errors.push(`${label}: task \"${op.taskId}\" no longer exists in this batch (removed, merged, or split by an earlier op)`); break; }\n const locked = lockedTaskRefusal(target, 'removed');\n if (locked) { errors.push(`${label}: ${locked}`); break; }\n tasks = removeTaskFromPlan(tasks, target.id);\n summary.push(`Removed \"${target.title}\"`);\n break;\n }\n case 'reorder': {\n const refs = (op.taskIds ?? []).map((r) => resolveRef(r, currentTasks, tasks, handleOwner, handleId, i));\n const badRef = refs.find((r): r is { error: string } => 'error' in r);\n if (badRef) { errors.push(`${label}: ${badRef.error}`); break; }\n const resolved = (refs as { id: string }[]).map((r) => findTopLevel(tasks, r.id));\n if (resolved.some((t) => !t)) { errors.push(`${label}: unknown task in reorder list`); break; }\n const orderIds = resolved.map((t) => t!.id);\n if (new Set(orderIds).size !== tasks.length) {\n errors.push(`${label}: reorder must list every top-level task exactly once (${tasks.length} tasks)`);\n break;\n }\n const byId = new Map(tasks.map((t) => [t.id, t]));\n tasks = renumberTasks(orderIds.map((id) => byId.get(id)!));\n summary.push('Reordered tasks');\n break;\n }\n case 'merge': {\n const refs = (op.taskIds ?? []).map((r) => resolveRef(r, currentTasks, tasks, handleOwner, handleId, i));\n const badRef = refs.find((r): r is { error: string } => 'error' in r);\n if (badRef) { errors.push(`${label}: ${badRef.error}`); break; }\n const resolved = (refs as { id: string }[]).map((r) => findTopLevel(tasks, r.id));\n if (resolved.some((t) => !t)) { errors.push(`${label}: unknown task in merge list (already removed, merged, or split by an earlier op)`); break; }\n const toMerge = [...new Map(resolved.map((t) => [t!.id, t!])).values()].sort((a, b) => a.order - b.order);\n if (toMerge.length < 2) { errors.push(`${label}: merge needs at least two tasks`); break; }\n const locked = toMerge.map((t) => lockedTaskRefusal(t, 'merged')).find((refusal) => refusal !== null);\n if (locked) { errors.push(`${label}: ${locked}`); break; }\n const idSet = new Set(toMerge.map((t) => t.id));\n const unionDepsRaw = [...new Set(toMerge.flatMap((t) => t.dependencies))].filter((d) => !idSet.has(d));\n const { ids, bad } = resolveDeps(unionDepsRaw, i);\n if (bad.length) { errors.push(`${label}: unknown dependencies: ${bad.join(', ')}`); break; }\n const spec = op.merged ?? {};\n if (!spec.title) { errors.push(`${label}: merged task needs a title`); break; }\n // Read-only only when every merged task was: one that writes makes the merged task write.\n const writes = toMerge.find((t) => !isReadOnly(t, catalog));\n const stories = [...new Set(toMerge.flatMap((t) => t.userStoriesCovered ?? []))];\n const planned = plannedTask(spec, intake, {\n freshIds: true,\n from: {\n readOnly: !writes,\n fields: {\n description: toMerge.map((t) => t.description).filter(Boolean).join('\\n\\n'),\n prompt: toMerge.map((t) => t.prompt).filter(Boolean).join('\\n\\n---\\n\\n') || undefined,\n type: toMerge.some((t) => t.type === 'user') ? 'user' : 'ai',\n assignedRunner: toMerge[0].assignedRunner,\n assignedModel: toMerge.find((t) => t.assignedModel)?.assignedModel,\n taskMode: (writes ?? toMerge[0]).taskMode,\n autonomy: toMerge.find((t) => t.autonomy)?.autonomy,\n sliceType: toMerge.find((t) => t.sliceType)?.sliceType,\n ops: inheritedOps(toMerge),\n skills: toMerge.flatMap((t) => t.skills ?? []),\n userStoriesCovered: stories.length ? stories : undefined,\n },\n },\n });\n const refused = refusalOf(planned);\n if (refused) { errors.push(`${label}: ${refused}`); break; }\n const built = resolveTree({ ...planned, task: { ...planned.task, dependencies: [] } }, i);\n if ('error' in built) { errors.push(`${label}: ${built.error}`); break; }\n const mergedTask: Task = { ...built.task, dependencies: ids };\n const mergedId = mergedTask.id;\n const firstId = toMerge[0].id;\n const result: Task[] = [];\n let inserted = false;\n for (const t of tasks) {\n if (idSet.has(t.id)) {\n if (!inserted && t.id === firstId) { result.push(mergedTask); inserted = true; }\n continue;\n }\n result.push({ ...t, dependencies: t.dependencies.map((d) => (idSet.has(d) ? mergedId : d)) });\n }\n if (!inserted) result.push(mergedTask);\n tasks = renumberTasks(result);\n if (op.handle) handleId.set(op.handle, mergedId);\n summary.push(`Merged ${toMerge.length} tasks into \"${spec.title}\"`);\n break;\n }\n case 'split': {\n const ref = resolveRef(op.taskId, currentTasks, tasks, handleOwner, handleId, i);\n if ('error' in ref) { errors.push(`${label}: ${ref.error}`); break; }\n const target = findTopLevel(tasks, ref.id);\n if (!target) { errors.push(`${label}: task \"${op.taskId}\" not found`); break; }\n const locked = lockedTaskRefusal(target, 'split');\n if (locked) { errors.push(`${label}: ${locked}`); break; }\n const parts = op.parts ?? [];\n if (parts.length < 2) { errors.push(`${label}: split needs at least two parts`); break; }\n const newTasks: Task[] = [];\n let prevId: string | undefined;\n let buildError = false;\n for (let p = 0; p < parts.length; p++) {\n const spec = parts[p];\n if (!spec || !spec.title) { errors.push(`${label}: split part ${p + 1} needs a title`); buildError = true; break; }\n // Part 0 inherits the original's (external) dependencies, resolved\n // against the current plan. Later parts chain onto the previous part\n // — a sibling id created in this same op, so it needs no resolution.\n let deps: string[];\n if (p === 0) {\n const { ids, bad } = resolveDeps(target.dependencies, i);\n if (bad.length) { errors.push(`${label}: split part 1 unknown dependencies: ${bad.join(', ')}`); buildError = true; break; }\n deps = ids;\n } else {\n deps = prevId ? [prevId] : [];\n }\n const planned = plannedTask(spec, intake, {\n freshIds: true,\n from: {\n readOnly: isReadOnly(target, catalog),\n fields: {\n type: target.type,\n assignedRunner: target.assignedRunner,\n assignedModel: target.assignedModel,\n taskMode: target.taskMode,\n autonomy: target.autonomy,\n sliceType: target.sliceType,\n ops: inheritedOps([target]),\n skills: target.skills,\n userStoriesCovered: target.userStoriesCovered,\n },\n },\n });\n const refused = refusalOf(planned);\n if (refused) { errors.push(`${label}: split part ${p + 1}: ${refused}`); buildError = true; break; }\n const resolved = resolveTree({ ...planned, task: { ...planned.task, dependencies: [] } }, i);\n if ('error' in resolved) { errors.push(`${label}: split part ${p + 1}: ${resolved.error}`); buildError = true; break; }\n const nt: Task = { ...resolved.task, dependencies: deps };\n newTasks.push(nt);\n prevId = nt.id;\n }\n if (buildError) break;\n const tailId = newTasks[newTasks.length - 1].id;\n const result: Task[] = [];\n for (const t of tasks) {\n if (t.id === target.id) { result.push(...newTasks); continue; }\n result.push({ ...t, dependencies: t.dependencies.map((d) => (d === target.id ? tailId : d)) });\n }\n tasks = renumberTasks(result);\n if (op.handle) handleId.set(op.handle, tailId);\n summary.push(`Split \"${target.title}\" into ${newTasks.length} tasks`);\n break;\n }\n case 'rearm': {\n // Re-arming is the sanctioned exception to the planner lock — its whole\n // point is to touch a task the lock would otherwise refuse — so it\n // validates as a direct edit; well-formedness still applies.\n const prep = prepareEdit(op, i, label, 'direct', true);\n if ('error' in prep) { errors.push(prep.error); break; }\n const { target, changes, check } = prep;\n tasks = updateTaskInPlan(tasks, target.id, { ...changes, status: 'pending', verdict: undefined, outputSummary: undefined, awaitingReason: undefined, resumeAt: undefined, skipReason: undefined });\n // Dependents parked at 'blocked' by this task's earlier failure have\n // nothing else to release them — the scheduler reads `status` directly,\n // not a live recomputation of the dependency graph.\n for (const dep of flattenTasks(tasks)) {\n if (dep.status === 'blocked' && dep.dependencies.includes(target.id)) {\n tasks = updateTaskInPlan(tasks, dep.id, { status: 'pending' });\n }\n }\n const clearedNote = check.clear?.length ? `; cleared ${check.clear.join(', ')}` : '';\n const fields = changedFields(target, changes, catalog);\n const changedNote = fields.length ? ` (${fields.join(', ')})` : '';\n summary.push(`Re-armed \"${target.title}\"${changedNote}${clearedNote}`);\n break;\n }\n default:\n errors.push(`${label}: unknown op \"${(op as { op: string }).op}\"`);\n }\n if (errors.length) break;\n lastLabel = label;\n // Invariants are judged on the final state, so a later op may complete an\n // earlier one; here they only record which op a breach belongs to.\n const now = new Set(checkPlanInvariants(tasks, runners).map(breachKey));\n for (const key of brokenBy.keys()) if (!now.has(key)) brokenBy.delete(key);\n for (const key of now) if (!standing.has(key) && !brokenBy.has(key)) brokenBy.set(key, label);\n }\n\n if (!errors.length) {\n for (const e of checkPlanInvariants(tasks, runners)) {\n const key = breachKey(e);\n if (!standing.has(key)) errors.push(`${brokenBy.get(key) ?? lastLabel}: ${e.message}`);\n }\n }\n\n // Display order is maintained, not demanded: whatever the batch produced,\n // the plan comes back with dependencies ahead of their dependents. The\n // planner never has to re-declare the whole order to move one task.\n if (!errors.length) {\n const repaired = repairOrder(tasks);\n if ('error' in repaired) {\n errors.push(repaired.error);\n } else {\n const moves = describeMoves(tasks, repaired.tasks);\n if (moves) summary.push(`Reordered to keep dependencies first: ${moves}`);\n tasks = renumberTasks(repaired.tasks);\n }\n }\n\n return errors.length\n ? { ok: false, tasks: currentTasks, errors, summary: [] }\n : { ok: true, tasks, errors: [], summary };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AACO,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB;AAE9B,IAAM,0BAA0B;AAGhC,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA,EACT,YAAY,SAAiB,KAAa,MAAoD;AAC5F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,MAAM;AACX,SAAK,YAAY,MAAM,aAAa;AACpC,SAAK,WAAW,MAAM,YAAY;AAAA,EACpC;AACF;AAQO,SAAS,gBAAgB,KAAqB;AACnD,SAAO,IACJ,QAAQ,8BAA8B,EAAE,EACxC,QAAQ,gBAAgB,EAAE,EAC1B,QAAQ,WAAW,EAAE,EACrB,KAAK;AACV;AAEA,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,QAAQ;AACd,IAAM,iBAAiB;AAShB,SAAS,oBAAoB,QAAqC;AACvE,MAAI,OAAO;AACX,aAAS;AACP,WAAO,KAAK,UAAU;AACtB,QAAI,CAAC,KAAM,QAAO;AAClB,UAAM,OAAO,KAAK,MAAM,GAAG,WAAW,MAAM,EAAE,YAAY;AAC1D,QAAI,SAAS,YAAY;AACvB,YAAM,QAAQ,KAAK,YAAY,EAAE,QAAQ,WAAW;AACpD,UAAI,QAAQ,EAAG,QAAO;AACtB,aAAO,KAAK,MAAM,QAAQ,YAAY,MAAM;AAC5C;AAAA,IACF;AACA,QAAI,KAAK,W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as,
9
9
  taskWhere
10
- } from "./chunk-DJAPDO6E.mjs";
10
+ } from "./chunk-3LNZDBCX.mjs";
11
11
  import {
12
12
  flattenTasksWithParents
13
- } from "./chunk-2IIRSBEQ.mjs";
13
+ } from "./chunk-CIL3BQIF.mjs";
14
14
 
15
15
  // src/services/PlanValidator.ts
16
16
  function parsePlanJson(raw, runners, runnerModes, autonomousDefault = true) {
@@ -94,4 +94,4 @@ export {
94
94
  validatePlanTasks,
95
95
  looksLikePlanAttempt
96
96
  };
97
- //# sourceMappingURL=chunk-DNFT4SQG.mjs.map
97
+ //# sourceMappingURL=chunk-4FEARWTS.mjs.map
@@ -72,6 +72,7 @@ function isAwaitingReason(value) {
72
72
  function migrateLoadedTasks(tasks) {
73
73
  for (const task of tasks) {
74
74
  if (typeof task.runnerSessionId !== "string") delete task.runnerSessionId;
75
+ if (typeof task.carriedFrom !== "string") delete task.carriedFrom;
75
76
  const legacy = task;
76
77
  if (!task.runnerSessionId && legacy.transport?.kind === "structured" && typeof legacy.transport.nativeSessionId === "string") {
77
78
  task.runnerSessionId = legacy.transport.nativeSessionId;
@@ -181,7 +182,7 @@ function createTask(overrides = {}) {
181
182
  outputSummary: overrides.outputSummary,
182
183
  ...overrides.attemptUsage ? { attemptUsage: structuredClone(overrides.attemptUsage) } : {},
183
184
  assignedModel: overrides.assignedModel,
184
- assignedRunner: overrides.assignedRunner ?? "claude-code",
185
+ assignedRunner: overrides.assignedRunner ?? DEFAULT_RUNNERS[0],
185
186
  taskMode: overrides.taskMode ?? "build",
186
187
  autonomy: overrides.autonomy,
187
188
  sliceType: overrides.sliceType,
@@ -319,6 +320,7 @@ function keepExecutionState(current, rewrite) {
319
320
  verdict: prior?.verdict,
320
321
  outputSummary: prior?.outputSummary,
321
322
  runnerSessionId: prior?.runnerSessionId,
323
+ carriedFrom: prior?.carriedFrom,
322
324
  attemptSkills: prior?.attemptSkills,
323
325
  attemptUsage: prior?.attemptUsage,
324
326
  // Where a task that has run ran is fixed, like its runner session (ADR-0020).
@@ -371,4 +373,4 @@ export {
371
373
  stampOrigin,
372
374
  keepExecutionState
373
375
  };
374
- //# sourceMappingURL=chunk-2IIRSBEQ.mjs.map
376
+ //# sourceMappingURL=chunk-CIL3BQIF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/conversation/skillTokens.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","/**\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 and import-free 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 interface RefTask<T> {\n id: string;\n order: number;\n title: string;\n subtasks?: readonly T[];\n}\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\nfunction* depthFirst<T extends RefTask<T>>(tasks: readonly T[], parent?: T, parentLabel?: string): Generator<RefTaskMatch<T>> {\n for (const task of tasks) {\n const label = taskOrderLabel(task, parent ? { order: parent.order, label: parentLabel } : undefined);\n yield { task, parent, label };\n yield* depthFirst(task.subtasks ?? [], task, label);\n }\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 for (const match of depthFirst(tasks)) if (match.task.id === id) return match;\n return undefined;\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 depthFirst(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 depthFirst(tasks)) if (task.title === s) return task;\n return undefined;\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport type { PlanIsolation } from '../interfaces/IWorktreeIsolation';\nimport type { AttemptUsage, PlannerUsage, UsageRecord, UsageTotals } from './Usage';\nimport type { ExecutionRecord, SupervisorLevel } from './Execution';\nimport type { SkillSource } from '../services/SkillsService';\nimport type { SupervisionMemorySnapshot } from '../services/LoopGuards';\nimport type { SupervisorSnapshot } from '../services/Supervisor';\nimport { SKILL_NAME_PATTERN } from '../conversation/skillTokens';\nimport { taskOrderLabel } from '../services/TaskRefs';\n\nexport interface UserStep {\n order: number;\n instruction: string;\n completed: boolean;\n}\n\n/** One deterministic signal gathered while verifying a completed task. `completion_marker` is only in verdicts saved before completion was reported through `task_complete` alone. */\nexport interface VerificationCheck {\n name: 'exit_code' | 'completion_marker' | 'task_complete' | 'manual';\n passed: boolean;\n /** A check that did not apply. Skipped checks don't affect the verdict. */\n skipped: boolean;\n detail: string;\n}\n\n/** Evidence-based verdict for a completed task. Single end-to-end outcome produced by verification. */\nexport interface Verdict {\n outcome: 'pass' | 'fail';\n reason: string;\n checks: VerificationCheck[];\n decidedAt: string;\n}\n\nexport interface TaskOutputSummary {\n reviewReason: string;\n /** The `task_complete` summary, the task's report; absent when the attempt ended without one, and from sessions saved before it was kept. */\n report?: string;\n /** Empty when there is a report: the turn's final text is the report itself. */\n logTail: string;\n capturedAt: string;\n}\n\nexport type TaskType = 'ai' | 'user';\n/**\n * `skipped` is terminal and verdict-less: the task will not be waited for, and\n * nothing it did lands. Its dependents go ahead without it.\n */\nexport type TaskStatus = 'pending' | 'approved' | 'in_progress' | 'completed' | 'failed' | 'blocked' | 'awaiting_user' | 'skipped';\nexport type TaskMode = string;\n\n/**\n * Why an `awaiting_user` task waits (ADR-0018, W1): a structured turn that\n * ended without a `task_complete` call, a checkpoint question, work that did not\n * land, an ops task that changed tracked files (ADR-0020), or its runner's\n * usage limit. Saved, so no surface has to guess it from whether an attempt\n * is live.\n */\nexport type AwaitingReason = 'input' | 'checkpoint' | 'conflict' | 'files-changed' | 'usage-limit';\n\nexport function isAwaitingReason(value: unknown): value is AwaitingReason {\n return value === 'input' || value === 'checkpoint' || value === 'conflict' || value === 'files-changed' || value === 'usage-limit';\n}\n\nexport interface TaskModelAssignment {\n modelId: string;\n modelLabel: string;\n thinkingEffort?: string;\n /**\n * All variant ids the model offered when this assignment was made. Carried\n * on the assignment because runners need it at spawn time (opencode's TUI\n * only honors an assigned variant when the others are config-disabled) and\n * the discovery catalog isn't available there.\n */\n availableVariants?: string[];\n}\n\nexport type RunnerId = string;\n\n/**\n * Bring loaded tasks to the structured-only shape, in place. A task saved\n * while the terminal transport existed may say it ran there, and why; neither\n * means anything now, and such a task left no session to continue. Its\n * completion marker id went with the text markers: completion is reported\n * only through `task_complete`.\n */\nexport function migrateLoadedTasks(tasks: readonly Task[]): void {\n for (const task of tasks) {\n if (typeof task.runnerSessionId !== 'string') delete task.runnerSessionId;\n if (typeof task.carriedFrom !== 'string') delete task.carriedFrom;\n const legacy = task as Task & { transport?: { kind?: unknown; nativeSessionId?: unknown } };\n if (!task.runnerSessionId && legacy.transport?.kind === 'structured' && typeof legacy.transport.nativeSessionId === 'string') {\n task.runnerSessionId = legacy.transport.nativeSessionId;\n }\n delete legacy.transport;\n delete (task as { completionMarker?: unknown }).completionMarker;\n // The effort once had a second home on the task; the spawn reads only the model's.\n const effort = (task as { thinkingEffort?: unknown }).thinkingEffort;\n if (typeof effort === 'string' && task.assignedModel && !task.assignedModel.thinkingEffort) task.assignedModel.thinkingEffort = effort;\n delete (task as { thinkingEffort?: unknown }).thinkingEffort;\n migrateLoadedTasks(task.subtasks ?? []);\n }\n}\n\n/**\n * A task skill as one attempt received it: read from the task's own worktree\n * (or global) at spawn, kept so the user can see what the runner was told\n * even after the skill's file changes.\n */\nexport interface TaskSkillSnapshot {\n name: string;\n source: SkillSource;\n path: string;\n content: string;\n}\n\n/** A task skill as a surface is told of it: the body stays in the task's log file and the session. */\nexport type TaskSkillNotice = Omit<TaskSkillSnapshot, 'content'>;\n\nexport interface Task {\n id: string;\n order: number;\n title: string;\n description: string;\n type: TaskType;\n status: TaskStatus;\n dependencies: string[];\n prompt?: string;\n userSteps?: UserStep[];\n subtasks: Task[];\n verdict?: Verdict;\n outputSummary?: TaskOutputSummary;\n assignedModel?: TaskModelAssignment;\n assignedRunner: RunnerId;\n taskMode?: TaskMode;\n autonomy?: 'AFK' | 'HITL';\n sliceType?: 'HITL' | 'AFK';\n userStoriesCovered?: string[];\n /** The runner's saved session for a later continue; cleared when a fresh attempt starts. */\n runnerSessionId?: string;\n /** Set only while `status` is `awaiting_user`, and not always then — a pause saved by an older build has none. */\n awaitingReason?: AwaitingReason;\n /**\n * When a task paused on its runner's usage limit is resumed on its own (ISO\n * time): the reset the runner announced, plus a short margin. Absent when no\n * reset time could be read or the user cancelled the resume — the task then\n * waits for a manual retry. Set only with `awaitingReason` `usage-limit`.\n */\n resumeAt?: string;\n /**\n * The runner a task paused on its usage limit was moved off (ADR-0018, U1):\n * its next attempt is a carry-over, a fresh session that starts from that\n * attempt's files. Cleared once that attempt runs, and by a retry.\n */\n carriedFrom?: RunnerId;\n /** Why the task was skipped, as whoever skipped it put it; set only while `status` is `skipped`, and not always then. */\n skipReason?: string;\n /**\n * An ops task (ADR-0020): it changes no repository files, runs at the\n * workspace root rather than in a worktree, and waits for the change tasks\n * it depends on to be merged into the user's branch. Top-level AI tasks\n * only; absent means a change task.\n */\n ops?: boolean;\n /**\n * The dependencies, by title, whose work was not merged into the user's\n * branch when the user force-started this task past its merge gate\n * (ADR-0020). Cleared when the task is retried.\n */\n forcedPastGate?: string[];\n /**\n * Task skills (`applies-to: task`) attached by name. Their bodies are put in\n * the runner's prompt at spawn, resolved where the task runs — a subtask's\n * are its own, never its parent's. Absent means none.\n */\n skills?: string[];\n /** The skills the latest attempt was given, as read when it spawned. */\n attemptSkills?: TaskSkillSnapshot[];\n /**\n * Who put the task in the plan, when it was not the user's own planning:\n * `supervisor` for a task an Act supervisor added during a run, which\n * counts as approved to run (ADR-0029). Set by the session, never by an op.\n */\n addedBy?: 'supervisor';\n attemptUsage?: AttemptUsage[];\n}\n\nexport interface DiscoveredMode {\n id: string;\n label: string;\n description: string;\n}\n\nexport type ResearchToolType =\n | 'read_file' | 'read_files' | 'glob' | 'grep' | 'find_symbol' | 'list_dir'\n | 'bash' | 'fetch' | 'web_search' | 'spawn_research_agent'\n | 'task_query' | 'task_output' | 'task_diff'\n /**\n * A tool belonging to a harness planner's own toolbox (ADR-0009) that has no\n * Ordewell equivalent — Edit, WebFetch, TodoWrite, whatever a coding agent\n * ships next. The real name travels in `toolLabel` rather than being\n * relabelled as a tool it is not; the union stays closed so the\n * exhaustiveness checks in every surface's icon/label switch survive.\n */\n | 'agent_tool';\n\n/**\n * What happened when a research tool call ran, for honest per-surface\n * rendering. The broadcast seam carries this on every `research_step_done` so\n * surfaces do not have to pattern-match refusal text to tell a refused `rm`\n * from a successful `rm` — the old render path flipped a `✓` for both.\n */\nexport type ResearchStepOutcome = 'success' | 'failure' | 'refused' | 'denied' | 'not_executed';\n\nexport interface ResearchStep {\n id: string;\n tool: ResearchToolType;\n /** The tool's own name when it came from a harness planner — always set for `agent_tool`. */\n toolLabel?: string;\n args: string;\n result: string;\n success: boolean;\n outcome: ResearchStepOutcome;\n /** The model's tool_call id, so a surface can match `tool_result` to the\n * pending `tool_call` it announced — robust under parallel same-tool rounds. */\n toolCallId?: string;\n /** The research subagent that ran the call, so a reload regroups it under that subagent. */\n subagentId?: string;\n timestamp: string;\n thinkingText?: string;\n}\n\nexport interface UserPromptEntry {\n id: string;\n type: 'user_prompt' | 'system';\n content: string;\n timestamp: string;\n}\n\nexport type SubagentOutcome = 'done' | 'failed' | 'stopped';\n\n/**\n * One subagent's whole run, logged when it finishes: what it was asked, how it\n * ended and what it reported. Its steps stay separate entries carrying the same\n * `subagentId`, so an older reader that knows only steps still shows them.\n */\nexport interface SubagentLogEntry {\n id: string;\n type: 'subagent';\n subagentId: string;\n brief: string;\n model?: string;\n outcome: SubagentOutcome;\n digest: string;\n usage?: UsageTotals;\n timestamp: string;\n}\n\nexport type ResearchLogEntry = ResearchStep | UserPromptEntry | SubagentLogEntry;\n\nexport interface ResearchProgress {\n // 'liveness' carries no content: a raw-line signal from the harness process\n // (ADR-0009) that reaches a surface even when a turn is producing nothing\n // visible — a subagent's filtered chatter, most often — so an idle watchdog\n // downstream doesn't mistake \"nothing to show\" for \"nothing happening\".\n //\n // The turn-scoped kinds below carry one planner turn's stream (#47); see the\n // matching SessionMessage variants for the invariants each one keeps.\n // 'text_delta' is reply text as the model streams it (`text`, `segmentId`),\n // an envelope included: the turn's owner routes each segment to prose or to\n // the plan display, so no backend has to tell them apart. 'text_retracted'\n // takes back an attempt's text: `segmentId`'s, or when absent everything the\n // backend call that sends it has streamed.\n // 'usage' reports one model call (`record`). 'subagent_started' carries\n // `brief` and `model`; 'subagent_finished' carries `outcome`, `digest` and\n // `usage`.\n type:\n | 'thinking' | 'tool_call' | 'tool_result' | 'plan_token' | 'interrupted' | 'liveness'\n | 'text_delta' | 'text_retracted' | 'usage' | 'subagent_started' | 'subagent_finished';\n /** Minted by whoever runs the turn and passed through untouched; absent outside a turn. */\n turnId?: string;\n /** One continuous run of model text — text before a tool call is its own segment. */\n segmentId?: string;\n text?: string;\n tool?: string;\n /** Harness planners (ADR-0009): the agent's own name for a tool Ordewell has no member for. */\n toolLabel?: string;\n toolArgs?: string;\n toolResult?: string;\n planToken?: string;\n step?: ResearchStep;\n /** The model's tool_call id, threaded on tool_call and tool_result so a\n * surface can match the result to its pending call — robust under parallel\n * same-tool rounds where LIFO-by-name matching mislabels summaries. */\n toolCallId?: string;\n /** Present when this event originates from (or reports on) one spawned research subagent (issue #34). */\n subagentId?: string;\n record?: UsageRecord;\n brief?: string;\n model?: string;\n outcome?: SubagentOutcome;\n digest?: string;\n usage?: UsageTotals;\n}\n\nexport interface ThinkingBlock {\n id: string;\n text: string;\n}\n\nexport interface StreamThinkingEvent {\n type: 'thinking';\n block: ThinkingBlock;\n}\n\nexport interface StreamStepEvent {\n type: 'step';\n step: ResearchStep;\n}\n\nexport type StreamEvent = StreamThinkingEvent | StreamStepEvent;\n\nexport interface DiscoveredModel {\n modelId: string;\n modelLabel: string;\n runnerProvider?: string;\n /**\n * Human-facing provider name as the runner itself reports it (e.g.\n * \"OpenCode Zen\" for `runnerProvider: 'opencode'`). Populated from the\n * runner's own provider catalog when available; when absent the UI derives a\n * label from `runnerProvider` by title-casing.\n */\n runnerProviderLabel?: string;\n /**\n * The runner whose catalog listed this model. Stamped once, at the single\n * `ModelDiscovery.discover` choke point, so a flat cross-runner list can\n * still say where each entry came from — `runnerProvider` alone cannot:\n * OpenCode reports most of its catalog as `openrouter`, which names the\n * serving backend, not the agent Ordewell would spawn.\n */\n runnerId?: string;\n /** The runner's display name (`OpenCode`), from its manifest. */\n runnerLabel?: string;\n variants: { id: string; label: string }[];\n /**\n * The model's context window when the runner or catalog reports it (#49).\n * Read by the planner-model lookup so context fill can be shown; absent when\n * unknown rather than defaulted to zero.\n */\n contextWindow?: number;\n}\n\nexport type PlanStatus = 'draft' | 'approved' | 'rejected' | 'running' | 'completed';\n\n/**\n * One entry of the planner's persisted dialogue (ADR-0002). The single source\n * of truth for both UI redisplay and conversational context. Tool-call results\n * are NOT stored here — they live in the AI service's tool-use history;\n * `researchLog` remains the persisted tool trace for the UI.\n */\nexport interface ConversationMessage {\n role: 'user' | 'assistant';\n content: string;\n timestamp: string;\n /**\n * Timeline marker: 'plan_generated' records the point in the dialogue where\n * the plan was committed (the UI anchors the plan card there on restore);\n * 'system' is a host-injected notice; 'compaction' is the summary a\n * user-triggered compaction left in place of the earlier messages — always\n * the transcript's first entry. 'skill_load' is a skill loaded into the\n * conversation, its snapshot in `skill`; one the user invoked follows the\n * message that named it. 'execution' is a call at the command seam\n * (ADR-0029), its record in `execution`. 'wake_up' is the digest a wake-up\n * gave the supervisor (role 'user': the model was told it), and\n * 'supervisor' what the supervisor said in a wake-up turn (ADR-0029).\n * 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';\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\n/**\n * A skill's SKILL.md as it was when loaded into a planner conversation. A\n * snapshot rather than a reference: a resumed, forked or rewound conversation\n * replays the body the planner originally saw, even after the file changed or\n * was deleted.\n */\nexport interface SkillLoad {\n invokedBy: 'user' | 'planner';\n name: string;\n source: SkillSource;\n /** The SKILL.md that won, home-abbreviated (`~/...`): which copy loaded is what a reader needs from it. */\n path: string;\n content: string;\n /**\n * Set when the user named a task skill: it is not loaded into the planner's\n * context, which is only told to attach it to the tasks it fits. `content`\n * is empty; the description is what the planner's directive quotes.\n */\n attaches?: { description: string };\n}\n\n/** A skill load as a surface announces it — the body stays with the transcript. */\nexport type SkillLoadNotice = Omit<SkillLoad, 'content'>;\n\n/** A message the user sent, as opposed to a skill load their message caused or a wake-up digest. */\nexport function isUserMessage(entry: Pick<ConversationMessage, 'role' | 'kind'>): boolean {\n return entry.role === 'user' && entry.kind !== 'skill_load' && entry.kind !== 'wake_up';\n}\n\n/** A follow-up an older build queued behind a run's batch boundary; read only to carry it over as a {@link PendingPlanTurn}. */\nexport interface QueuedMessage {\n id: string;\n text: string;\n timestamp: string;\n skills?: SkillLoad[];\n}\n\n/** Who a planner turn answers (ADR-0029): the user's message, or a wake-up batch the supervisor is given. */\nexport type PlanTurnSource = 'user' | 'supervisor';\n\n/**\n * A planner turn's input not yet answered by a turn that ended. It leaves the\n * plan with the change its turn made, in the same save, so a reload replays\n * exactly the inputs no turn answered — once. A supervisor's input is a\n * wake-up batch not yet delivered (ADR-0029): it stays until a turn lands\n * with it, whatever turns fail meanwhile.\n */\nexport interface PendingPlanTurn {\n id: string;\n source: PlanTurnSource;\n /** The user's message, or a wake-up batch's digest. */\n text: string;\n timestamp: string;\n /** What its `/name` tokens loaded when it was sent, so a replay sends the same skills. */\n skills?: SkillLoad[];\n /** Force sent: it waits ahead of every input not forced, and its turn is its own (ADR-0023, F2). */\n forced?: true;\n}\n\n/**\n * The run's own copy of the user's run settings (ADR-0030): taken when the\n * user starts it, changed at once by a change made in this session, and\n * lowered by a tripped guard or a failed supervisor.\n */\nexport interface RunSettings {\n mergeAtGatesAutomatically: boolean;\n /** Absent on a run started before supervisor levels existed: Off. */\n supervisorLevel?: SupervisorLevel;\n /** Absent on a run started before ADR-0030: the user's setting. */\n supervisorRetryLimit?: number;\n /** Absent on a run started before ADR-0030: the user's setting. */\n wakeUpReadBudget?: number;\n /** Why the supervisor stopped for the rest of this run, which carries on as Off; absent while it watches. */\n unsupervised?: string;\n}\n\n/**\n * What supervision remembers across a daemon restart (ADR-0029): the loop\n * guards' memory and the wake-up state not yet delivered with a turn.\n */\nexport interface SupervisionSnapshot {\n /** Retries, failed-attempt shapes, the supervisor's edits and what the user was told. */\n guards?: SupervisionMemorySnapshot;\n /** The events inside their debounce window and the wake-up rate's timestamps. */\n wake?: SupervisorSnapshot;\n}\n\nexport interface LegacyPlanState {\n runSettings?: RunSettings;\n /** What supervision remembers across a daemon restart (ADR-0029); absent on plans saved before it existed. */\n supervision?: SupervisionSnapshot;\n tasks: Task[];\n generatedAt: string;\n status: PlanStatus;\n runners: RunnerId[];\n lastUpdated: string;\n researchLog?: ResearchLogEntry[];\n /** The planner dialogue — user messages and assistant messages, in order (ADR-0002). */\n conversationHistory?: ConversationMessage[];\n /** Full markdown PRD once written by the planner (PRD mode), also saved to .scratch/<slug>/PRD.md. */\n prdMarkdown?: string;\n /** Planner turn inputs no turn has answered yet (ADR-0029); a reload replays them. */\n pendingTurns?: PendingPlanTurn[];\n /** Written by builds that queued mid-run edits; a load moves it into {@link pendingTurns}. */\n queuedMessages?: QueuedMessage[];\n /**\n * The plan's isolation run (ADR-0013), written from the orchestrator at\n * persist time and read back only when a saved plan is adopted. It names\n * branches and worktrees that belong to this plan alone: a fork of the plan\n * must leave it behind rather than share it.\n */\n isolation?: PlanIsolation;\n /** Kept so a reopened session shows the same token line (#49). */\n plannerUsage?: PlannerUsage;\n /**\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.\n */\n approvedTasks?: string[];\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\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\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\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' && t.status !== 'blocked',\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 };\n }\n\n return {\n phase: 'planning',\n history: messages,\n message: '',\n pendingTasks: raw.tasks,\n };\n}\n\nexport { taskOrderLabel, taskRef, taskRefOf, titledTaskRef, titledTaskRefOf, resolveTaskRef } from '../services/TaskRefs';\n\nexport function createTask(overrides: Partial<Task> = {}): Task {\n const skills = skillNames(overrides.skills);\n return {\n id: overrides.id ?? uuidv4(),\n order: overrides.order ?? 0,\n title: overrides.title ?? '',\n description: overrides.description ?? '',\n type: overrides.type ?? 'ai',\n status: overrides.status ?? 'pending',\n dependencies: overrides.dependencies ?? [],\n prompt: overrides.prompt,\n userSteps: overrides.userSteps,\n subtasks: overrides.subtasks ?? [],\n verdict: overrides.verdict,\n outputSummary: overrides.outputSummary,\n ...(overrides.attemptUsage ? { attemptUsage: structuredClone(overrides.attemptUsage) } : {}),\n assignedModel: overrides.assignedModel,\n assignedRunner: overrides.assignedRunner ?? DEFAULT_RUNNERS[0],\n taskMode: overrides.taskMode ?? 'build',\n autonomy: overrides.autonomy,\n sliceType: overrides.sliceType,\n userStoriesCovered: overrides.userStoriesCovered,\n ...(opsFlag(overrides.ops, overrides.type) ? { ops: true } : {}),\n ...(skills ? { skills } : {}),\n ...(overrides.addedBy === 'supervisor' ? { addedBy: 'supervisor' as const } : {}),\n };\n}\n\n/**\n * A name a skill can have, lower-cased as `/name` is. Anything else — a path\n * separator, `..` — is joined into a path and could only reach outside the\n * skill dirs.\n */\nconst SKILL_NAME = new RegExp(`^${SKILL_NAME_PATTERN}$`);\n\nexport function isSkillName(name: string): boolean {\n return SKILL_NAME.test(name);\n}\n\n/**\n * The `skills` field as a task stores it, however it arrived: the planner's\n * JSON is untyped. Names are trimmed, lower-cased and deduplicated, and one\n * no skill could have is dropped; none at all is stored absent, so a plan\n * without skills reads exactly as it did before them.\n */\nexport function skillNames(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const names = [...new Set(value.filter((v): v is string => typeof v === 'string').map((v) => v.trim().toLowerCase()).filter(isSkillName))];\n return names.length > 0 ? names : undefined;\n}\n\n/**\n * The skills of a task a merge or a split makes from others: what the edit\n * chose when it named any, none when it chose an explicit `[]`, else what the\n * tasks it came from had — a malformed value is not a request to drop them.\n */\nexport function inheritedSkills(chosen: unknown, inherited: readonly string[] | undefined): string[] | undefined {\n if (Array.isArray(chosen) && chosen.length === 0) return undefined;\n return skillNames(chosen) ?? skillNames(inherited);\n}\n\n/**\n * The `ops` flag as a task stores it (ADR-0020), however it arrived. Only a\n * literal `true` on an AI task marks an ops task: the planner's JSON is\n * untyped, and a quoted \"true\" read as ops would move a task out of its\n * worktree. Anything else is a change task, stored absent so saved plans need\n * no migration. Whether the task may be ops at all — a subtask may not — is\n * for whoever knows where it sits: the planner intake refuses it (`checkPlanInvariants`).\n */\nexport function opsFlag(value: unknown, type: Task['type'] = 'ai'): true | undefined {\n return value === true && type === 'ai' ? true : undefined;\n}\n\n/**\n * The flag of a task a merge or a split makes from others: what the edit\n * chose, else ops only when every task it came from was. A merge that takes\n * in a change edits files, so it is a change; a split part runs where its\n * task did.\n */\nexport function inheritedOps(from: readonly Pick<Task, 'ops'>[], chosen?: boolean): boolean {\n return chosen ?? from.every((t) => opsFlag(t.ops) === true);\n}\n\n/**\n * The runner set a plan has until one is chosen. The one runner named outside\n * its declaration on purpose: a default is a product choice that no manifest\n * or connector implies.\n */\nexport const DEFAULT_RUNNERS: readonly RunnerId[] = ['claude-code'];\n\nexport function createEmptyPlan(): LegacyPlanState {\n return {\n tasks: [],\n generatedAt: new Date().toISOString(),\n status: 'draft',\n runners: [...DEFAULT_RUNNERS],\n lastUpdated: new Date().toISOString(),\n };\n}\n\nexport function flattenTasks(tasks: readonly Task[]): Task[] {\n return tasks.flatMap((t) => [t, ...flattenTasks(t.subtasks ?? [])]);\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 const rows: TaskWithParent[] = [];\n const walk = (t: Task, parent: Task | null, parentLabel?: string) => {\n const label = taskOrderLabel(t, parent ? { order: parent.order, label: parentLabel } : undefined);\n rows.push({ task: t, parent, label, ref: `#${label}` });\n for (const sub of t.subtasks ?? []) walk(sub, t, label);\n };\n for (const t of tasks) walk(t, null);\n return rows;\n}\n\nexport function addTaskToPlan(tasks: readonly Task[], partial: Partial<Task>): Task[] {\n const maxOrder = tasks.reduce((max, t) => Math.max(max, t.order), 0);\n const newTask = createTask({\n ...partial,\n order: partial.order ?? maxOrder + 1,\n status: 'pending',\n });\n return renumberTasks([...tasks, newTask]);\n}\n\nexport function removeTaskFromPlan(tasks: readonly Task[], taskId: string): Task[] {\n const result = tasks\n .filter((t) => t.id !== taskId)\n .map((t) => ({\n ...t,\n dependencies: t.dependencies.filter((depId) => depId !== taskId),\n subtasks: removeTaskFromPlan(t.subtasks, taskId),\n }));\n return renumberTasks(result);\n}\n\nexport function updateTaskInPlan(tasks: readonly Task[], taskId: string, changes: Partial<Task>): Task[] {\n return renumberTasks(\n tasks.map((t) => {\n if (t.id === taskId) return { ...t, ...changes, id: t.id };\n return { ...t, subtasks: updateTaskInPlan(t.subtasks, taskId, changes) };\n })\n );\n}\n\nexport function renumberTasks(tasks: readonly Task[]): Task[] {\n return tasks.map((t, i) => ({\n ...t,\n order: i + 1,\n subtasks: renumberTasks(t.subtasks),\n }));\n}\n\n/** A task paused on its runner's usage limit, whether it resumes on its own or waits for the user (#84). */\nexport function pausedOnLimit(task: Readonly<Task>): boolean {\n return task.status === 'awaiting_user' && task.awaitingReason === 'usage-limit';\n}\n\n/** A task paused on a usage limit that resumes on its own when the limit resets (#84). */\nexport function waitsForReset(task: Readonly<Task>): boolean {\n return pausedOnLimit(task) && !!task.resumeAt;\n}\n\n/**\n * Who put each task of an adopted list in the plan. A task the plan already\n * had keeps its origin, whatever the planner wrote; a new one is the\n * supervisor's when `bySupervisor`, and nobody's in particular otherwise, so\n * no planner can mark its own task as the supervisor's. `added` lists the new\n * tasks, subtasks included.\n */\nexport function stampOrigin(before: readonly Task[], after: readonly Task[], bySupervisor: boolean): { tasks: Task[]; added: string[] } {\n const prior = new Map(flattenTasks([...before]).map((t) => [t.id, t]));\n const added: string[] = [];\n const stamp = (tasks: readonly Task[]): Task[] => tasks.map((t) => {\n const was = prior.get(t.id);\n const origin = was ? was.addedBy : bySupervisor ? 'supervisor' : undefined;\n if (!was) added.push(t.id);\n const stamped: Task = { ...t, subtasks: stamp(t.subtasks ?? []) };\n if (origin) stamped.addedBy = origin;\n else delete stamped.addedBy;\n return stamped;\n });\n return { tasks: stamp(after), added };\n}\n\n/** Done, running, or held for the user: execution state only a runner or the user can change. */\nconst SETTLED_STATUSES: ReadonlySet<TaskStatus> = new Set<TaskStatus>(['completed', 'in_progress', 'awaiting_user']);\n\nfunction holdsSettledWork(task: Task): boolean {\n return SETTLED_STATUSES.has(task.status) || (task.subtasks ?? []).some(holdsSettledWork);\n}\n\n/**\n * Lay a planner-written task list over the plan it rewrites without letting it\n * change execution state. A planner restates tasks; it never witnessed one run,\n * so the status it writes is not evidence. A settled task is kept exactly as\n * it stands wherever the rewrite names it, and put back beside its old\n * neighbour where the rewrite leaves it out. Every other task keeps the status\n * it had; a task the rewrite adds starts pending.\n */\nexport function keepExecutionState(current: readonly Task[], rewrite: Task[]): Task[] {\n const existing = new Map(flattenTasks(current).map((t) => [t.id, t]));\n const named = new Set(flattenTasks(rewrite).map((t) => t.id));\n\n const overlay = (tasks: Task[], was: readonly Task[]): Task[] => {\n const result = tasks.map((t): Task => {\n const prior = existing.get(t.id);\n if (prior && SETTLED_STATUSES.has(prior.status)) return { ...prior };\n return {\n ...t,\n status: prior?.status ?? 'pending',\n verdict: prior?.verdict,\n outputSummary: prior?.outputSummary,\n runnerSessionId: prior?.runnerSessionId,\n carriedFrom: prior?.carriedFrom,\n attemptSkills: prior?.attemptSkills,\n attemptUsage: prior?.attemptUsage,\n // Where a task that has run ran is fixed, like its runner session (ADR-0020).\n ...(prior?.status === 'failed' ? { ops: prior.ops } : {}),\n forcedPastGate: prior?.forcedPastGate,\n subtasks: overlay(t.subtasks ?? [], prior?.subtasks ?? []),\n };\n });\n was.forEach((left, i) => {\n if (named.has(left.id) || !holdsSettledWork(left)) return;\n const neighbour = was.slice(0, i).reverse().find((t) => result.some((r) => r.id === t.id));\n const at = neighbour ? result.findIndex((r) => r.id === neighbour.id) + 1 : 0;\n result.splice(at, 0, { ...left });\n });\n return result;\n };\n\n return renumberTasks(overlay(rewrite, current));\n}\n"],"mappings":";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;AAAA,MAC3D;AAAA,IACF,CAAC;AACD,QAAI,QAAQ,CAAC,MAAM,MAAM;AACvB,UAAI,MAAM,IAAI,KAAK,EAAE,KAAK,CAAC,iBAAiB,IAAI,EAAG;AACnD,YAAM,YAAY,IAAI,MAAM,GAAG,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,MAAM,OAAO,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC;AACzF,YAAM,KAAK,YAAY,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,IAAI,IAAI;AAC5E,aAAO,OAAO,IAAI,GAAG,EAAE,GAAG,KAAK,CAAC;AAAA,IAClC,CAAC;AACD,WAAO;AAAA,EACT;AAEA,SAAO,cAAc,QAAQ,SAAS,OAAO,CAAC;AAChD;","names":[]}
@@ -5,7 +5,7 @@ import {
5
5
  isTaskRunning,
6
6
  resumeLabel,
7
7
  taskStatusKind
8
- } from "./chunk-DJAPDO6E.mjs";
8
+ } from "./chunk-3LNZDBCX.mjs";
9
9
  import {
10
10
  pausedOnLimit,
11
11
  rejoinPlanTree,
@@ -13,7 +13,7 @@ import {
13
13
  taskRefOf,
14
14
  titledTaskRef,
15
15
  titledTaskRefOf
16
- } from "./chunk-2IIRSBEQ.mjs";
16
+ } from "./chunk-CIL3BQIF.mjs";
17
17
 
18
18
  // src/models/Usage.ts
19
19
  function partedPromptUsage(parts) {
@@ -1648,6 +1648,36 @@ function taskStartedNotice(title, runner) {
1648
1648
  return runner ? `Started "${title}" \xB7 ${runner}` : `Started "${title}"`;
1649
1649
  }
1650
1650
 
1651
+ // src/conversation/markdown.ts
1652
+ import MarkdownIt from "markdown-it";
1653
+ var md = new MarkdownIt({ html: false, linkify: true, breaks: true });
1654
+ md.linkify.set({ fuzzyLink: false, fuzzyEmail: false });
1655
+ md.validateLink = (url) => /^https?:/i.test(url);
1656
+ md.core.ruler.after("linkify", "image_as_text", (state) => {
1657
+ for (const block of state.tokens) {
1658
+ if (!block.children) continue;
1659
+ block.children = block.children.map((token) => {
1660
+ if (token.type !== "image") return token;
1661
+ const text2 = new state.Token("text", "", 0);
1662
+ text2.content = token.content || (token.attrGet("src") ?? "");
1663
+ return text2;
1664
+ });
1665
+ }
1666
+ });
1667
+ md.renderer.rules.link_open = (tokens, idx, options, _env, self) => {
1668
+ tokens[idx].attrSet("target", "_blank");
1669
+ tokens[idx].attrSet("rel", "noopener");
1670
+ return self.renderToken(tokens, idx, options);
1671
+ };
1672
+ md.renderer.rules.table_open = (tokens, idx, options, _env, self) => `<div class="md-table">${self.renderToken(tokens, idx, options)}`;
1673
+ md.renderer.rules.table_close = () => "</table></div>\n";
1674
+ function markdownTokens(text2) {
1675
+ return md.parse(text2, {});
1676
+ }
1677
+ function markdownHtml(text2) {
1678
+ return md.render(text2);
1679
+ }
1680
+
1651
1681
  // src/taskRow/actions.ts
1652
1682
  var UNSTARTED_AI = (t) => t.type === "ai" && NOT_STARTED.has(t.status);
1653
1683
  var QUEUED = (t) => t.status === "pending" || t.status === "approved";
@@ -1819,6 +1849,8 @@ export {
1819
1849
  stopTurn,
1820
1850
  hasHiddenDetail,
1821
1851
  taskStartedNotice,
1852
+ markdownTokens,
1853
+ markdownHtml,
1822
1854
  taskRowActions,
1823
1855
  markAction,
1824
1856
  markRequestFor,
@@ -1830,4 +1862,4 @@ export {
1830
1862
  pastGateConfirmation,
1831
1863
  newTaskFields
1832
1864
  };
1833
- //# sourceMappingURL=chunk-CH5IGWFS.mjs.map
1865
+ //# sourceMappingURL=chunk-UQGR3UCA.mjs.map