@ordewell/core 0.4.15 → 0.4.17

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 (37) hide show
  1. package/dist/{ITerminalRunner-DqAs12sy.d.ts → ITerminalRunner-CbLHKXT5.d.ts} +1 -1
  2. package/dist/{ITerminalRunner-D_RBDoHa.d.mts → ITerminalRunner-E3-6QNUS.d.mts} +1 -1
  3. package/dist/{ModeResolver-CzZd-i6T.d.ts → ModeResolver-Ob-ihQbI.d.ts} +1 -1
  4. package/dist/{ModeResolver-CCKYqdZC.d.mts → ModeResolver-mtIWrLXn.d.mts} +1 -1
  5. package/dist/{Task-cGrfYRXK.d.mts → Task-4rDGr8Su.d.mts} +1 -1
  6. package/dist/{Task-cGrfYRXK.d.ts → Task-4rDGr8Su.d.ts} +1 -1
  7. package/dist/{chunk-YTJ7EOV6.mjs → chunk-DV3YIKRA.mjs} +2 -2
  8. package/dist/{chunk-YTJ7EOV6.mjs.map → chunk-DV3YIKRA.mjs.map} +1 -1
  9. package/dist/{chunk-UEJ3SZQ7.mjs → chunk-QJ63PD5K.mjs} +2 -2
  10. package/dist/{chunk-N6HTBUKG.mjs → chunk-T4KGVP4N.mjs} +1 -1
  11. package/dist/chunk-T4KGVP4N.mjs.map +1 -0
  12. package/dist/index.d.mts +38 -20
  13. package/dist/index.d.ts +38 -20
  14. package/dist/index.js +44 -21
  15. package/dist/index.js.map +1 -1
  16. package/dist/index.mjs +47 -24
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/order-labels.d.mts +1 -1
  19. package/dist/order-labels.d.ts +1 -1
  20. package/dist/{parsing-D87zKtTe.d.ts → parsing-BJoHbA-t.d.ts} +2 -2
  21. package/dist/{parsing-BT-dvFcu.d.mts → parsing-BWfpLch9.d.mts} +2 -2
  22. package/dist/parsing.d.mts +3 -3
  23. package/dist/parsing.d.ts +3 -3
  24. package/dist/parsing.js.map +1 -1
  25. package/dist/parsing.mjs +2 -2
  26. package/dist/{plan-utils-BbC9KdK4.d.ts → plan-utils-DJm2a7Zp.d.ts} +4 -2
  27. package/dist/{plan-utils-DHBIvkiT.d.mts → plan-utils-s6VL8NDF.d.mts} +4 -2
  28. package/dist/plan-utils.d.mts +3 -3
  29. package/dist/plan-utils.d.ts +3 -3
  30. package/dist/plan-utils.js.map +1 -1
  31. package/dist/plan-utils.mjs +2 -2
  32. package/dist/testing.d.mts +2 -2
  33. package/dist/testing.d.ts +2 -2
  34. package/package.json +1 -1
  35. package/skills/improve-codebase-architecture/SKILL.md +59 -0
  36. package/dist/chunk-N6HTBUKG.mjs.map +0 -1
  37. /package/dist/{chunk-UEJ3SZQ7.mjs.map → chunk-QJ63PD5K.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/plan-utils.ts","../src/services/TaskOps.ts","../src/services/researchStepSummary.ts","../src/services/SessionMessage.ts"],"sourcesContent":["/**\n * Browser-safe entry point: pure plan-validation utilities with no Node or\n * AI-service dependencies. UI surfaces (the VS Code webview runs in a browser)\n * import runtime values from here instead of the main barrel, which bundles the\n * Gemini/OpenAI services and their `fs`/`child_process` imports.\n */\nexport { canMergeTasks, canSplitTask, canSetDependencies, dependencyCandidates, dependentsOf } from './services/TaskOps';\nexport type { TaskRef } from './services/TaskOps';\nexport { summarizeToolCall } from './services/researchStepSummary';\nexport { truncateCheckpointSummary, CHECKPOINT_TRUNCATE_LENGTH } from './services/SessionMessage';\n","import { v4 as uuidv4 } from 'uuid';\nimport {\n Task, RunnerId, flattenTasks,\n addTaskToPlan, removeTaskFromPlan, updateTaskInPlan, renumberTasks,\n createTask,\n} from '../models/Task';\nimport { extractObjectsWithKey, stripTrailingCommas, escapeControlCharsInStrings, PlanParseError, TASK_OPS_ENVELOPE_KEY } from './JsonExtractor';\nimport { validateTaskEdit, checkModelAndModeValidity, type EditCatalog } from './TaskEditValidator';\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 */\nexport type TaskOp =\n | { op: 'update'; taskId: string; changes: Partial<Task> }\n | { op: 'add'; task: Partial<Task>; handle?: string }\n | { op: 'remove'; taskId: string }\n | { op: 'reorder'; taskIds: string[] }\n | { op: 'merge'; taskIds: string[]; merged: Partial<Task>; handle?: string }\n | { op: 'split'; taskId: string; parts: Partial<Task>[]; handle?: string }\n | { op: 'rearm'; taskId: string; changes?: Partial<Task> };\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', 'thinkingEffort', 'type', 'userSteps', 'autonomy', 'sliceType',\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 a task reference (id, \"#3\", \"3\", or a batch handle) to a task id.\n *\n * `#order` and title matches are pinned to `originalScope` — 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 `liveScope` — 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 originalScope: Task[],\n liveScope: 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 later in this batch (op ${ownerIdx + 1}) 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 const byLiveId = liveScope.find((t) => t.id === s);\n if (byLiveId) return { id: byLiveId.id };\n const orderStr = s.startsWith('#') ? s.slice(1) : s;\n if (/^\\d+$/.test(orderStr)) {\n const order = Number(orderStr);\n const byOrder = originalScope.filter((t) => t.order === order);\n if (byOrder.length === 1) return { id: byOrder[0].id };\n }\n const byTitle = originalScope.find((t) => t.title === s);\n if (byTitle) return { id: byTitle.id };\n return { error: `task \"${s}\" not found` };\n}\n\n/** Whether `name` already denotes an existing task by id, `#order`, or title. */\nfunction refCollidesWithExisting(name: string, originalFlatAll: Task[]): boolean {\n if (originalFlatAll.some((t) => t.id === name)) return true;\n const orderStr = name.startsWith('#') ? name.slice(1) : name;\n if (/^\\d+$/.test(orderStr) && originalFlatAll.some((t) => t.order === Number(orderStr))) return true;\n return originalFlatAll.some((t) => t.title === name);\n}\n\nfunction findInTasks(tasks: 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\nfunction detectCycle(tasks: Task[]): string | null {\n const byId = new Map(tasks.map((t) => [t.id, t]));\n const visiting = new Set<string>();\n const done = new Set<string>();\n const visit = (id: string): string | null => {\n if (done.has(id)) return null;\n if (visiting.has(id)) return id;\n visiting.add(id);\n for (const dep of byId.get(id)?.dependencies ?? []) {\n const hit = visit(dep);\n if (hit) return hit;\n }\n visiting.delete(id);\n done.add(id);\n return null;\n };\n for (const t of tasks) {\n const hit = visit(t.id);\n if (hit) return byId.get(hit)?.title ?? hit;\n }\n return null;\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: 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: 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: 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: 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: 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/**\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(currentTasks: Task[], ops: TaskOp[], runners: RunnerId[], catalog?: EditCatalog): ApplyTaskOpsResult {\n let tasks: Task[] = JSON.parse(JSON.stringify(currentTasks));\n const errors: string[] = [];\n const summary: string[] = [];\n\n // Frozen snapshot every ref resolves `#order`/title matches against, so an\n // earlier op's renumbering can never shift what a later op's \"#N\" means.\n const originalFlatAll = flattenTasks(currentTasks);\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(`op ${i + 1} (${op.op}): handle must be a non-empty string`);\n continue;\n }\n if (handleOwner.has(handle)) {\n errors.push(`op ${i + 1} (${op.op}): handle \"${handle}\" is already used earlier in this batch`);\n continue;\n }\n if (refCollidesWithExisting(handle, originalFlatAll)) {\n errors.push(`op ${i + 1} (${op.op}): 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, originalFlatAll, liveFlat, 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 for (const [i, op] of ops.entries()) {\n const label = `op ${i + 1} (${op.op})`;\n switch (op.op) {\n case 'update': {\n const ref = resolveRef(op.taskId, originalFlatAll, flattenTasks(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 changes: Partial<Task> = {};\n for (const key of UPDATABLE_FIELDS) {\n if (op.changes && key in op.changes) (changes as Record<string, unknown>)[key] = (op.changes as Record<string, unknown>)[key];\n }\n if (changes.assignedRunner && !runners.includes(changes.assignedRunner)) {\n errors.push(`${label}: runner \"${changes.assignedRunner}\" is not in this plan's runner set [${runners.join(', ')}]`);\n break;\n }\n // Dependency refs are still unresolved (e.g. \"#3\") at this point, so\n // this check runs on everything but them; resolveDeps below handles\n // dependency well-formedness once they're real ids.\n const changesForCheck: Partial<Task> = { ...changes };\n delete changesForCheck.dependencies;\n const check = validateTaskEdit('planner', flattenTasks(tasks), target.id, changesForCheck, catalog);\n if (!check.ok) { errors.push(`${label}: ${check.error}`); break; }\n for (const field of check.clear ?? []) (changes as Record<string, unknown>)[field] = undefined;\n if ('dependencies' in changes) {\n const { ids, bad } = resolveDeps(changes.dependencies, i);\n if (bad.length) { errors.push(`${label}: unknown dependencies: ${bad.join(', ')}`); break; }\n changes.dependencies = ids.filter((id) => id !== target.id);\n }\n if (Object.keys(changes).length === 0) { errors.push(`${label}: no valid changes provided`); break; }\n tasks = updateTaskInPlan(tasks, target.id, changes);\n const clearedNote = check.clear?.length ? `; cleared ${check.clear.join(', ')}` : '';\n summary.push(`Updated \"${target.title}\" (${Object.keys(changes).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 { ids, bad } = resolveDeps(spec.dependencies, i);\n if (bad.length) { errors.push(`${label}: unknown dependencies: ${bad.join(', ')}`); break; }\n const runner = spec.assignedRunner && runners.includes(spec.assignedRunner) ? spec.assignedRunner : runners[0];\n const validity = checkModelAndModeValidity(runner, spec.assignedModel, spec.taskMode, catalog);\n if (!validity.ok) { errors.push(`${label}: ${validity.error}`); break; }\n const newId = uuidv4();\n tasks = addTaskToPlan(tasks, {\n ...spec,\n id: newId,\n dependencies: ids,\n assignedRunner: runner,\n description: spec.description ?? spec.title,\n prompt: spec.prompt ?? spec.description ?? spec.title,\n });\n if (op.handle) handleId.set(op.handle, newId);\n summary.push(`Added \"${spec.title}\"`);\n break;\n }\n case 'remove': {\n const ref = resolveRef(op.taskId, originalFlatAll, flattenTasks(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 if (target.status === 'in_progress') { errors.push(`${label}: \"${target.title}\" is running and cannot be removed`); break; }\n if (target.status === 'completed') { errors.push(`${label}: \"${target.title}\" is completed and cannot be removed`); 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 = resolved.map((t) => t!).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.find((t) => t.status === 'in_progress' || t.status === 'completed');\n if (locked) {\n errors.push(`${label}: \"${locked.title}\" is ${locked.status === 'in_progress' ? 'running' : 'completed'} and cannot be merged`);\n break;\n }\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 const runner = spec.assignedRunner && runners.includes(spec.assignedRunner) ? spec.assignedRunner : toMerge[0].assignedRunner;\n const mergedTask = createTask({\n title: spec.title,\n description: spec.description ?? toMerge.map((t) => t.description).filter(Boolean).join('\\n\\n'),\n prompt: spec.prompt ?? (toMerge.map((t) => t.prompt).filter(Boolean).join('\\n\\n---\\n\\n') || undefined),\n type: spec.type ?? (toMerge.some((t) => t.type === 'user') ? 'user' : 'ai'),\n dependencies: ids,\n assignedRunner: runner,\n assignedModel: spec.assignedModel ?? toMerge.find((t) => t.assignedModel)?.assignedModel,\n thinkingEffort: spec.thinkingEffort ?? toMerge.find((t) => t.thinkingEffort)?.thinkingEffort,\n taskMode: spec.taskMode ?? toMerge[0].taskMode,\n autonomy: spec.autonomy ?? toMerge.find((t) => t.autonomy)?.autonomy,\n sliceType: spec.sliceType ?? toMerge.find((t) => t.sliceType)?.sliceType,\n userStoriesCovered: spec.userStoriesCovered ?? (toMerge.flatMap((t) => t.userStoriesCovered ?? []).length\n ? [...new Set(toMerge.flatMap((t) => t.userStoriesCovered ?? []))]\n : undefined),\n });\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 if (target.status === 'in_progress') { errors.push(`${label}: \"${target.title}\" is running and cannot be split`); break; }\n if (target.status === 'completed') { errors.push(`${label}: \"${target.title}\" is completed and cannot be split`); 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 runner = spec.assignedRunner && runners.includes(spec.assignedRunner) ? spec.assignedRunner : target.assignedRunner;\n const nt = createTask({\n title: spec.title,\n description: spec.description ?? spec.title,\n prompt: spec.prompt ?? spec.description ?? spec.title,\n type: spec.type ?? target.type,\n dependencies: deps,\n assignedRunner: runner,\n assignedModel: spec.assignedModel ?? target.assignedModel,\n taskMode: spec.taskMode ?? target.taskMode,\n autonomy: spec.autonomy ?? target.autonomy,\n sliceType: spec.sliceType ?? target.sliceType,\n userStoriesCovered: spec.userStoriesCovered ?? target.userStoriesCovered,\n });\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 const ref = resolveRef(op.taskId, originalFlatAll, flattenTasks(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 if (target.status === 'in_progress') { errors.push(`${label}: \"${target.title}\" is running and cannot be re-armed`); break; }\n const changes: Partial<Task> = {};\n for (const key of UPDATABLE_FIELDS) {\n if (op.changes && key in op.changes) (changes as Record<string, unknown>)[key] = (op.changes as Record<string, unknown>)[key];\n }\n if (changes.assignedRunner && !runners.includes(changes.assignedRunner)) {\n errors.push(`${label}: runner \"${changes.assignedRunner}\" is not in this plan's runner set [${runners.join(', ')}]`);\n break;\n }\n // Validated as a direct edit (not 'planner'): re-arming is the sanctioned\n // exception to the planner lock — its whole point is to touch a task the\n // lock would otherwise refuse. Well-formedness (type coherence, model/mode\n // validity, dependency shape) still applies, same as every other edit.\n const changesForCheck: Partial<Task> = { ...changes };\n delete changesForCheck.dependencies;\n const check = validateTaskEdit('direct', flattenTasks(tasks), target.id, changesForCheck, catalog);\n if (!check.ok) { errors.push(`${label}: ${check.error}`); break; }\n for (const field of check.clear ?? []) (changes as Record<string, unknown>)[field] = undefined;\n if ('dependencies' in changes) {\n const { ids, bad } = resolveDeps(changes.dependencies, i);\n if (bad.length) { errors.push(`${label}: unknown dependencies: ${bad.join(', ')}`); break; }\n changes.dependencies = ids.filter((id) => id !== target.id);\n }\n tasks = updateTaskInPlan(tasks, target.id, { ...changes, status: 'pending', verdict: undefined, outputSummary: 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 changedNote = Object.keys(changes).length ? ` (${Object.keys(changes).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 }\n\n if (!errors.length) {\n const flat = flattenTasks(tasks);\n const idSet = new Set(flat.map((t) => t.id));\n for (const t of flat) {\n for (const dep of t.dependencies) {\n if (!idSet.has(dep)) errors.push(`\"${t.title}\" depends on a task that no longer exists (${dep})`);\n }\n }\n const cycleAt = detectCycle(flat);\n if (cycleAt) errors.push(`Dependency cycle detected involving \"${cycleAt}\"`);\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\n return errors.length\n ? { ok: false, tasks: currentTasks, errors, summary: [] }\n : { ok: true, tasks, errors: [], summary };\n}\n","import type { ResearchStepOutcome } from '../models/Task';\n\n/**\n * One-line human summary of a research tool call, shared by every surface that\n * renders live planner progress (VS Code webview, CLI, TUI). Kept in core so\n * the arg-shape heuristics (file path vs. pattern vs. shell command) live in\n * one place instead of being re-derived per surface — which also means a new\n * tool becomes readable in all three UIs by being handled here once.\n */\n\nfunction ellipsize(text: string, max: number): string {\n const oneLine = text.replace(/\\s+/g, ' ').trim();\n return oneLine.length > max ? `${oneLine.slice(0, max)}…` : oneLine;\n}\n\n/**\n * @param toolLabel The agent's own name for the tool, when a harness planner\n * produced the call (ADR-0009). It replaces the member name in the summary, so\n * the timeline says `Edit` rather than the catch-all `agent_tool` — and says\n * `WebFetch` rather than claiming a shell command ran.\n */\nexport function summarizeToolCall(tool: string, argsJson: string, toolLabel?: string): string {\n const display = toolLabel?.trim() || tool;\n if (tool === 'agent_tool') {\n // No Ordewell equivalent, so no arg shape to rely on: show the agent's name\n // plus whichever conventional field the call happens to carry.\n try {\n const args = JSON.parse(argsJson);\n const hint = args.path ?? args.file_path ?? args.filePath ?? args.pattern ?? args.query ?? args.url ?? args.command;\n if (hint) return `${display} ${ellipsize(String(hint), 50)}`;\n } catch {\n // fall through to the bare name\n }\n return display;\n }\n\n if (tool === 'spawn_research_agent') {\n try {\n const args = JSON.parse(argsJson);\n const prompt = typeof args.prompt === 'string' ? args.prompt : '';\n const oneLine = prompt.replace(/\\s+/g, ' ').trim();\n return `spawn: \"${oneLine.slice(0, 60)}${oneLine.length > 60 ? '…' : ''}\"`;\n } catch {\n return 'spawn_research_agent';\n }\n }\n\n try {\n const args = JSON.parse(argsJson);\n\n // Ordered by specificity: a tool's defining argument wins over the generic\n // `path`, which several of the newer tools also accept as a search root.\n if (tool === 'find_symbol' && args.symbol) {\n return `find_symbol ${args.symbol}${args.language ? ` [${args.language}]` : ''}`;\n }\n if (tool === 'web_search' && args.query) {\n return `web_search \"${ellipsize(String(args.query), 50)}\"`;\n }\n if (tool === 'fetch' && args.url) {\n return `fetch ${ellipsize(String(args.url), 60)}`;\n }\n // The pattern is what a glob is about; the generic `path` below is only its\n // search root, and reporting that read as \"glob src\" for every call.\n if (tool === 'glob' && args.pattern) {\n return `glob ${ellipsize(String(args.pattern), 50)}`;\n }\n if (tool === 'grep' && args.pattern) {\n const mode = args.output_mode && args.output_mode !== 'content' ? ` (${args.output_mode})` : '';\n const scope = args.include ? ` in ${args.include}` : '';\n return `grep ${ellipsize(String(args.pattern), 40)}${scope}${mode}`;\n }\n\n const path = args.filePath || args.file_path || args.path;\n if (path) {\n const basename = String(path).split('/').pop() || String(path);\n return `${display} ${basename}`;\n }\n if (args.pattern) {\n return `${display} ${args.pattern}`;\n }\n if (args.command) {\n return `bash: ${String(args.command).slice(0, 40)}`;\n }\n } catch {\n // fall through to the bare tool name below\n }\n return display;\n}\n\n/**\n * Classify a tool outcome from its result text and success flag, so a surface\n * can render a refused `rm` or a denied `npm test` distinctly from a\n * successful run without re-deriving the refusal signatures per surface. The\n * refusal/denial strings come from `commandPolicy.ts`, `BaseFileSystem.ts`,\n * and the research-subagent wrapper — keeping the matching here means the\n * signatures stay in one place alongside the human summary.\n */\nexport function classifyOutcome(success: boolean, output: string): ResearchStepOutcome {\n if (!success) {\n if (/^Command refused:/.test(output) || /is not available\\. You are a read-only research subagent/.test(output)) return 'refused';\n if (/not approved/i.test(output) || /^Access denied:/.test(output) || /needs user approval/i.test(output)) return 'denied';\n return 'failure';\n }\n return 'success';\n}\n","import type { LegacyPlanState, QueuedMessage, ResearchStep, RunnerId, Task, Verdict } from '../models/Task';\nimport type { ApprovalKind } from '../interfaces/IApproval';\nimport type { ApprovalSource } from './ApprovalPolicy';\n\nexport type SerializedTaskStatus = {\n id: string;\n status: string;\n verdict: { outcome: 'pass' | 'fail'; reason: string; checks: Verdict['checks'] } | null;\n /** Advisory silence timestamp from VerdictEngine — not part of task status semantics. */\n idleSince?: string | null;\n};\n\nexport type SerializedTask = {\n id: string;\n order: number;\n title: string;\n type: string;\n description: string;\n dependencies: string[];\n assignedRunner: RunnerId;\n assignedModel: Task['assignedModel'] | null;\n taskMode: string;\n prompt: string | null;\n subtasks: SerializedTask[];\n userSteps: Task['userSteps'];\n thinkingEffort: Task['thinkingEffort'];\n autonomy: Task['autonomy'];\n sliceType: Task['sliceType'];\n userStoriesCovered: Task['userStoriesCovered'];\n};\n\nexport type SerializedPlan = {\n tasks: SerializedTask[];\n runners: RunnerId[];\n generatedAt: string;\n conversationHistory?: LegacyPlanState['conversationHistory'];\n prdMarkdown?: string;\n queuedMessages?: QueuedMessage[];\n};\n\nexport type SessionMessage =\n | { type: 'plan_generated'; plan: SerializedPlan; goal: string; runners: RunnerId[] }\n | { type: 'planner_message'; content: string; timestamp: string }\n | { type: 'status_update'; tasks: SerializedTaskStatus[] }\n | { type: 'review_needed'; tasks: SerializedTask[] }\n | { type: 'review_approved' }\n | { type: 'checkpoint'; taskId: string; taskTitle: string; summary: string }\n | { type: 'execution_complete'; summary: { total: number; completed: number; failed: number } }\n | { type: 'execution_stopped' }\n | { type: 'queue_ready' }\n | { type: 'task_updated'; taskId: string; changes: Record<string, unknown> }\n | { type: 'task_started'; taskId: string; order: number; title: string; runner: RunnerId; modelId?: string }\n | { type: 'task_output'; taskId: string; text: string }\n | { type: 'plan_thinking'; text: string }\n // `toolLabel` carries a harness planner's own name for the tool (ADR-0009) —\n // always set when `tool` is `agent_tool`, so no surface has to render the\n // catch-all member name at the user.\n | { type: 'research_step'; tool: string; toolLabel?: string; args: string; subagentId?: string; toolCallId?: string }\n | { type: 'plan_token'; token: string }\n | { type: 'research_step_done'; step: ResearchStep; subagentId?: string }\n // Planner research wants something outside its default envelope and is\n // blocked until a human answers. Broadcast rather than returned, because the\n // human may be on any surface (or several at once) and the request outlives\n // whichever HTTP call triggered it.\n | { type: 'approval_request'; id: string; kind: ApprovalKind; subject: string; scope: string; detail?: string }\n | { type: 'approval_settled'; id: string; granted: boolean }\n // A decision reached with no round-trip prompt: pre-approved via config,\n // remembered from earlier in this session, or the operator's mode floor\n // (allow/deny skipping the human entirely). The interactive path above\n // already has full visibility via approval_request/approval_settled; this\n // is the one that previously had none — a model silently auto-running\n // `npm test` because the scope was already granted looked identical, from\n // every UI, to it never having been asked in the first place.\n | {\n type: 'approval_decided';\n kind: ApprovalKind;\n subject: string;\n scope: string;\n detail?: string;\n granted: boolean;\n source: Exclude<ApprovalSource, 'asked'>;\n };\n\nexport type SessionBroadcaster = (msg: SessionMessage) => void;\n\nexport function serializeTask(t: Task): SerializedTask {\n return {\n id: t.id,\n order: t.order,\n title: t.title,\n type: t.type,\n description: t.description,\n dependencies: t.dependencies || [],\n assignedRunner: t.assignedRunner,\n assignedModel: t.assignedModel || null,\n taskMode: t.taskMode || 'build',\n prompt: t.prompt || null,\n subtasks: (t.subtasks || []).map(serializeTask),\n userSteps: t.userSteps || undefined,\n thinkingEffort: t.thinkingEffort || undefined,\n autonomy: t.autonomy || undefined,\n sliceType: t.sliceType || undefined,\n userStoriesCovered: t.userStoriesCovered || undefined,\n };\n}\n\nexport function serializeTaskStatus(t: Task, idleSince: string | null = null): SerializedTaskStatus {\n return {\n id: t.id,\n status: t.status,\n verdict: t.verdict\n ? { outcome: t.verdict.outcome, reason: t.verdict.reason, checks: t.verdict.checks || [] }\n : null,\n idleSince,\n };\n}\n\nexport function serializePlan(plan: LegacyPlanState): SerializedPlan {\n return {\n tasks: plan.tasks.map(serializeTask),\n runners: plan.runners,\n generatedAt: plan.generatedAt,\n conversationHistory: plan.conversationHistory,\n prdMarkdown: plan.prdMarkdown,\n queuedMessages: plan.queuedMessages,\n };\n}\n\nexport function executionSummary(tasks: Task[]): { total: number; completed: number; failed: number } {\n return {\n total: tasks.length,\n completed: tasks.filter((t) => t.status === 'completed').length,\n failed: tasks.filter((t) => t.status === 'failed').length,\n };\n}\n\nexport const CHECKPOINT_TRUNCATE_LENGTH = 120;\n\n/** Truncate a checkpoint summary to a single line of at most CHECKPOINT_TRUNCATE_LENGTH chars. */\nexport function truncateCheckpointSummary(summary: string): string {\n // Take the first line only (checkpoint summaries often contain reasoning across lines)\n const firstLine = summary.split('\\n')[0].trim();\n if (firstLine.length <= CHECKPOINT_TRUNCATE_LENGTH) return firstLine;\n return firstLine.slice(0, CHECKPOINT_TRUNCATE_LENGT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AAgB,YAAY,KAAK,KAAK,WAAW,MAAM;AAC7F,YAAM,QAAQ,KAAK,UAAU,OAAO,KAAK,OAAO,KAAK;AACrD,aAAO,QAAQ,UAAU,OAAO,KAAK,OAAO,GAAG,EAAE,CAAC,GAAG,KAAK,GAAG,IAAI;AAAA,IACnE;AAEA,UAAM,OAAO,KAAK,YAAY,KAAK,aAAa,KAAK;AACrD,QAAI,MAAM;AACR,YAAM,WAAW,OAAO,IAAI,EAAE,MAAM,GAAG,EAAE,IAAI,KAAK,OAAO,IAAI;AAC7D,aAAO,GAAG,OAAO,IAAI,QAAQ;AAAA,IAC/B;AACA,QAAI,KAAK,SAAS;AAChB,aAAO,GAAG,OAAO,IAAI,KAAK,OAAO;AAAA,IACnC;AACA,QAAI,KAAK,SAAS;AAChB,aAAO,SAAS,OAAO,KAAK,OAAO,EAAE,MAAM,GAAG,EAAE,CAAC;AAAA,IACnD;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;;;ACiDO,IAAM,6BAA6B;AAGnC,SAAS,0BAA0B,SAAyB;AAEjE,QAAM,YAAY,QAAQ,MAAM,IAAI,EAAE,CAAC,EAAE,KAAK;AAC9C,MAAI,UAAU,UAAU,2BAA4B,QAAO;AAC3D,SAAO,UAAU,MAAM,GAAG,6BAA6B,CAAC,IAAI;AAC9D;","names":[]}
1
+ {"version":3,"sources":["../src/plan-utils.ts","../src/services/TaskOps.ts","../src/services/researchStepSummary.ts","../src/services/SessionMessage.ts"],"sourcesContent":["/**\n * Browser-safe entry point: pure plan-validation utilities with no Node or\n * AI-service dependencies. UI surfaces (the VS Code webview runs in a browser)\n * import runtime values from here instead of the main barrel, which bundles the\n * Gemini/OpenAI services and their `fs`/`child_process` imports.\n */\nexport { canMergeTasks, canSplitTask, canSetDependencies, dependencyCandidates, dependentsOf } from './services/TaskOps';\nexport type { TaskRef } from './services/TaskOps';\nexport { summarizeToolCall } from './services/researchStepSummary';\nexport { truncateCheckpointSummary, CHECKPOINT_TRUNCATE_LENGTH } from './services/SessionMessage';\n","import { v4 as uuidv4 } from 'uuid';\nimport {\n Task, RunnerId, flattenTasks,\n addTaskToPlan, removeTaskFromPlan, updateTaskInPlan, renumberTasks,\n createTask,\n} from '../models/Task';\nimport { extractObjectsWithKey, stripTrailingCommas, escapeControlCharsInStrings, PlanParseError, TASK_OPS_ENVELOPE_KEY } from './JsonExtractor';\nimport { validateTaskEdit, checkModelAndModeValidity, type EditCatalog } from './TaskEditValidator';\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 */\nexport type TaskOp =\n | { op: 'update'; taskId: string; changes: Partial<Task> }\n | { op: 'add'; task: Partial<Task>; handle?: string }\n | { op: 'remove'; taskId: string }\n | { op: 'reorder'; taskIds: string[] }\n | { op: 'merge'; taskIds: string[]; merged: Partial<Task>; handle?: string }\n | { op: 'split'; taskId: string; parts: Partial<Task>[]; handle?: string }\n | { op: 'rearm'; taskId: string; changes?: Partial<Task> };\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', 'thinkingEffort', 'type', 'userSteps', 'autonomy', 'sliceType',\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 a task reference (id, \"#3\", \"3\", or a batch handle) to a task id.\n *\n * `#order` and title matches are pinned to `originalScope` — 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 `liveScope` — 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 originalScope: Task[],\n liveScope: 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 later in this batch (op ${ownerIdx + 1}) 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 const byLiveId = liveScope.find((t) => t.id === s);\n if (byLiveId) return { id: byLiveId.id };\n const orderStr = s.startsWith('#') ? s.slice(1) : s;\n if (/^\\d+$/.test(orderStr)) {\n const order = Number(orderStr);\n const byOrder = originalScope.filter((t) => t.order === order);\n if (byOrder.length === 1) return { id: byOrder[0].id };\n }\n const byTitle = originalScope.find((t) => t.title === s);\n if (byTitle) return { id: byTitle.id };\n return { error: `task \"${s}\" not found` };\n}\n\n/** Whether `name` already denotes an existing task by id, `#order`, or title. */\nfunction refCollidesWithExisting(name: string, originalFlatAll: Task[]): boolean {\n if (originalFlatAll.some((t) => t.id === name)) return true;\n const orderStr = name.startsWith('#') ? name.slice(1) : name;\n if (/^\\d+$/.test(orderStr) && originalFlatAll.some((t) => t.order === Number(orderStr))) return true;\n return originalFlatAll.some((t) => t.title === name);\n}\n\nfunction findInTasks(tasks: 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\nfunction detectCycle(tasks: Task[]): string | null {\n const byId = new Map(tasks.map((t) => [t.id, t]));\n const visiting = new Set<string>();\n const done = new Set<string>();\n const visit = (id: string): string | null => {\n if (done.has(id)) return null;\n if (visiting.has(id)) return id;\n visiting.add(id);\n for (const dep of byId.get(id)?.dependencies ?? []) {\n const hit = visit(dep);\n if (hit) return hit;\n }\n visiting.delete(id);\n done.add(id);\n return null;\n };\n for (const t of tasks) {\n const hit = visit(t.id);\n if (hit) return byId.get(hit)?.title ?? hit;\n }\n return null;\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: 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: 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: 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: 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: 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/**\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(currentTasks: Task[], ops: TaskOp[], runners: RunnerId[], catalog?: EditCatalog): ApplyTaskOpsResult {\n let tasks: Task[] = JSON.parse(JSON.stringify(currentTasks));\n const errors: string[] = [];\n const summary: string[] = [];\n\n // Frozen snapshot every ref resolves `#order`/title matches against, so an\n // earlier op's renumbering can never shift what a later op's \"#N\" means.\n const originalFlatAll = flattenTasks(currentTasks);\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(`op ${i + 1} (${op.op}): handle must be a non-empty string`);\n continue;\n }\n if (handleOwner.has(handle)) {\n errors.push(`op ${i + 1} (${op.op}): handle \"${handle}\" is already used earlier in this batch`);\n continue;\n }\n if (refCollidesWithExisting(handle, originalFlatAll)) {\n errors.push(`op ${i + 1} (${op.op}): 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, originalFlatAll, liveFlat, 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 for (const [i, op] of ops.entries()) {\n const label = `op ${i + 1} (${op.op})`;\n switch (op.op) {\n case 'update': {\n const ref = resolveRef(op.taskId, originalFlatAll, flattenTasks(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 changes: Partial<Task> = {};\n for (const key of UPDATABLE_FIELDS) {\n if (op.changes && key in op.changes) (changes as Record<string, unknown>)[key] = (op.changes as Record<string, unknown>)[key];\n }\n if (changes.assignedRunner && !runners.includes(changes.assignedRunner)) {\n errors.push(`${label}: runner \"${changes.assignedRunner}\" is not in this plan's runner set [${runners.join(', ')}]`);\n break;\n }\n // Dependency refs are still unresolved (e.g. \"#3\") at this point, so\n // this check runs on everything but them; resolveDeps below handles\n // dependency well-formedness once they're real ids.\n const changesForCheck: Partial<Task> = { ...changes };\n delete changesForCheck.dependencies;\n const check = validateTaskEdit('planner', flattenTasks(tasks), target.id, changesForCheck, catalog);\n if (!check.ok) { errors.push(`${label}: ${check.error}`); break; }\n for (const field of check.clear ?? []) (changes as Record<string, unknown>)[field] = undefined;\n if ('dependencies' in changes) {\n const { ids, bad } = resolveDeps(changes.dependencies, i);\n if (bad.length) { errors.push(`${label}: unknown dependencies: ${bad.join(', ')}`); break; }\n changes.dependencies = ids.filter((id) => id !== target.id);\n }\n if (Object.keys(changes).length === 0) { errors.push(`${label}: no valid changes provided`); break; }\n tasks = updateTaskInPlan(tasks, target.id, changes);\n const clearedNote = check.clear?.length ? `; cleared ${check.clear.join(', ')}` : '';\n summary.push(`Updated \"${target.title}\" (${Object.keys(changes).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 { ids, bad } = resolveDeps(spec.dependencies, i);\n if (bad.length) { errors.push(`${label}: unknown dependencies: ${bad.join(', ')}`); break; }\n const runner = spec.assignedRunner && runners.includes(spec.assignedRunner) ? spec.assignedRunner : runners[0];\n const validity = checkModelAndModeValidity(runner, spec.assignedModel, spec.taskMode, catalog);\n if (!validity.ok) { errors.push(`${label}: ${validity.error}`); break; }\n const newId = uuidv4();\n tasks = addTaskToPlan(tasks, {\n ...spec,\n id: newId,\n dependencies: ids,\n assignedRunner: runner,\n description: spec.description ?? spec.title,\n prompt: spec.prompt ?? spec.description ?? spec.title,\n });\n if (op.handle) handleId.set(op.handle, newId);\n summary.push(`Added \"${spec.title}\"`);\n break;\n }\n case 'remove': {\n const ref = resolveRef(op.taskId, originalFlatAll, flattenTasks(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 if (target.status === 'in_progress') { errors.push(`${label}: \"${target.title}\" is running and cannot be removed`); break; }\n if (target.status === 'completed') { errors.push(`${label}: \"${target.title}\" is completed and cannot be removed`); 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 = resolved.map((t) => t!).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.find((t) => t.status === 'in_progress' || t.status === 'completed');\n if (locked) {\n errors.push(`${label}: \"${locked.title}\" is ${locked.status === 'in_progress' ? 'running' : 'completed'} and cannot be merged`);\n break;\n }\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 const runner = spec.assignedRunner && runners.includes(spec.assignedRunner) ? spec.assignedRunner : toMerge[0].assignedRunner;\n const mergedTask = createTask({\n title: spec.title,\n description: spec.description ?? toMerge.map((t) => t.description).filter(Boolean).join('\\n\\n'),\n prompt: spec.prompt ?? (toMerge.map((t) => t.prompt).filter(Boolean).join('\\n\\n---\\n\\n') || undefined),\n type: spec.type ?? (toMerge.some((t) => t.type === 'user') ? 'user' : 'ai'),\n dependencies: ids,\n assignedRunner: runner,\n assignedModel: spec.assignedModel ?? toMerge.find((t) => t.assignedModel)?.assignedModel,\n thinkingEffort: spec.thinkingEffort ?? toMerge.find((t) => t.thinkingEffort)?.thinkingEffort,\n taskMode: spec.taskMode ?? toMerge[0].taskMode,\n autonomy: spec.autonomy ?? toMerge.find((t) => t.autonomy)?.autonomy,\n sliceType: spec.sliceType ?? toMerge.find((t) => t.sliceType)?.sliceType,\n userStoriesCovered: spec.userStoriesCovered ?? (toMerge.flatMap((t) => t.userStoriesCovered ?? []).length\n ? [...new Set(toMerge.flatMap((t) => t.userStoriesCovered ?? []))]\n : undefined),\n });\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 if (target.status === 'in_progress') { errors.push(`${label}: \"${target.title}\" is running and cannot be split`); break; }\n if (target.status === 'completed') { errors.push(`${label}: \"${target.title}\" is completed and cannot be split`); 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 runner = spec.assignedRunner && runners.includes(spec.assignedRunner) ? spec.assignedRunner : target.assignedRunner;\n const nt = createTask({\n title: spec.title,\n description: spec.description ?? spec.title,\n prompt: spec.prompt ?? spec.description ?? spec.title,\n type: spec.type ?? target.type,\n dependencies: deps,\n assignedRunner: runner,\n assignedModel: spec.assignedModel ?? target.assignedModel,\n taskMode: spec.taskMode ?? target.taskMode,\n autonomy: spec.autonomy ?? target.autonomy,\n sliceType: spec.sliceType ?? target.sliceType,\n userStoriesCovered: spec.userStoriesCovered ?? target.userStoriesCovered,\n });\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 const ref = resolveRef(op.taskId, originalFlatAll, flattenTasks(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 if (target.status === 'in_progress') { errors.push(`${label}: \"${target.title}\" is running and cannot be re-armed`); break; }\n const changes: Partial<Task> = {};\n for (const key of UPDATABLE_FIELDS) {\n if (op.changes && key in op.changes) (changes as Record<string, unknown>)[key] = (op.changes as Record<string, unknown>)[key];\n }\n if (changes.assignedRunner && !runners.includes(changes.assignedRunner)) {\n errors.push(`${label}: runner \"${changes.assignedRunner}\" is not in this plan's runner set [${runners.join(', ')}]`);\n break;\n }\n // Validated as a direct edit (not 'planner'): re-arming is the sanctioned\n // exception to the planner lock — its whole point is to touch a task the\n // lock would otherwise refuse. Well-formedness (type coherence, model/mode\n // validity, dependency shape) still applies, same as every other edit.\n const changesForCheck: Partial<Task> = { ...changes };\n delete changesForCheck.dependencies;\n const check = validateTaskEdit('direct', flattenTasks(tasks), target.id, changesForCheck, catalog);\n if (!check.ok) { errors.push(`${label}: ${check.error}`); break; }\n for (const field of check.clear ?? []) (changes as Record<string, unknown>)[field] = undefined;\n if ('dependencies' in changes) {\n const { ids, bad } = resolveDeps(changes.dependencies, i);\n if (bad.length) { errors.push(`${label}: unknown dependencies: ${bad.join(', ')}`); break; }\n changes.dependencies = ids.filter((id) => id !== target.id);\n }\n tasks = updateTaskInPlan(tasks, target.id, { ...changes, status: 'pending', verdict: undefined, outputSummary: 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 changedNote = Object.keys(changes).length ? ` (${Object.keys(changes).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 }\n\n if (!errors.length) {\n const flat = flattenTasks(tasks);\n const idSet = new Set(flat.map((t) => t.id));\n for (const t of flat) {\n for (const dep of t.dependencies) {\n if (!idSet.has(dep)) errors.push(`\"${t.title}\" depends on a task that no longer exists (${dep})`);\n }\n }\n const cycleAt = detectCycle(flat);\n if (cycleAt) errors.push(`Dependency cycle detected involving \"${cycleAt}\"`);\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\n return errors.length\n ? { ok: false, tasks: currentTasks, errors, summary: [] }\n : { ok: true, tasks, errors: [], summary };\n}\n","import type { ResearchStepOutcome } from '../models/Task';\n\n/**\n * One-line human summary of a research tool call, shared by every surface that\n * renders live planner progress (VS Code webview, CLI, TUI). Kept in core so\n * the arg-shape heuristics (file path vs. pattern vs. shell command) live in\n * one place instead of being re-derived per surface — which also means a new\n * tool becomes readable in all three UIs by being handled here once.\n */\n\nfunction ellipsize(text: string, max: number): string {\n const oneLine = text.replace(/\\s+/g, ' ').trim();\n return oneLine.length > max ? `${oneLine.slice(0, max)}…` : oneLine;\n}\n\n/**\n * @param toolLabel The agent's own name for the tool, when a harness planner\n * produced the call (ADR-0009). It replaces the member name in the summary, so\n * the timeline says `Edit` rather than the catch-all `agent_tool` — and says\n * `WebFetch` rather than claiming a shell command ran.\n */\nexport function summarizeToolCall(tool: string, argsJson: string, toolLabel?: string): string {\n const display = toolLabel?.trim() || tool;\n if (tool === 'agent_tool') {\n // No Ordewell equivalent, so no arg shape to rely on: show the agent's name\n // plus whichever conventional field the call happens to carry.\n try {\n const args = JSON.parse(argsJson);\n const hint = args.path ?? args.file_path ?? args.filePath ?? args.pattern ?? args.query ?? args.url ?? args.command;\n if (hint) return `${display} ${ellipsize(String(hint), 50)}`;\n } catch {\n // fall through to the bare name\n }\n return display;\n }\n\n if (tool === 'spawn_research_agent') {\n try {\n const args = JSON.parse(argsJson);\n const prompt = typeof args.prompt === 'string' ? args.prompt : '';\n const oneLine = prompt.replace(/\\s+/g, ' ').trim();\n return `spawn: \"${oneLine.slice(0, 60)}${oneLine.length > 60 ? '…' : ''}\"`;\n } catch {\n return 'spawn_research_agent';\n }\n }\n\n try {\n const args = JSON.parse(argsJson);\n\n // Ordered by specificity: a tool's defining argument wins over the generic\n // `path`, which several of the newer tools also accept as a search root.\n if (tool === 'find_symbol' && args.symbol) {\n return `find_symbol ${args.symbol}${args.language ? ` [${args.language}]` : ''}`;\n }\n if (tool === 'web_search' && args.query) {\n return `web_search \"${ellipsize(String(args.query), 50)}\"`;\n }\n if (tool === 'fetch' && args.url) {\n return `fetch ${ellipsize(String(args.url), 60)}`;\n }\n // The pattern is what a glob is about; the generic `path` below is only its\n // search root, and reporting that read as \"glob src\" for every call.\n if (tool === 'glob' && args.pattern) {\n return `glob ${ellipsize(String(args.pattern), 50)}`;\n }\n if (tool === 'grep' && args.pattern) {\n const mode = args.output_mode && args.output_mode !== 'content' ? ` (${args.output_mode})` : '';\n const scope = args.include ? ` in ${args.include}` : '';\n return `grep ${ellipsize(String(args.pattern), 40)}${scope}${mode}`;\n }\n\n const path = args.filePath || args.file_path || args.path;\n if (path) {\n const basename = String(path).split('/').pop() || String(path);\n return `${display} ${basename}`;\n }\n if (args.pattern) {\n return `${display} ${args.pattern}`;\n }\n if (args.command) {\n return `bash: ${String(args.command).slice(0, 40)}`;\n }\n } catch {\n // fall through to the bare tool name below\n }\n return display;\n}\n\n/**\n * Classify a tool outcome from its result text and success flag, so a surface\n * can render a refused `rm` or a denied `npm test` distinctly from a\n * successful run without re-deriving the refusal signatures per surface. The\n * refusal/denial strings come from `commandPolicy.ts`, `BaseFileSystem.ts`,\n * and the research-subagent wrapper — keeping the matching here means the\n * signatures stay in one place alongside the human summary.\n */\nexport function classifyOutcome(success: boolean, output: string): ResearchStepOutcome {\n if (!success) {\n if (/^Command refused:/.test(output) || /is not available\\. You are a read-only research subagent/.test(output)) return 'refused';\n if (/not approved/i.test(output) || /^Access denied:/.test(output) || /needs user approval/i.test(output)) return 'denied';\n return 'failure';\n }\n return 'success';\n}\n","import type { LegacyPlanState, QueuedMessage, ResearchStep, RunnerId, Task, Verdict } from '../models/Task';\nimport type { ApprovalKind } from '../interfaces/IApproval';\nimport type { ApprovalSource } from './ApprovalPolicy';\n\nexport type SerializedTaskStatus = {\n id: string;\n status: string;\n verdict: { outcome: 'pass' | 'fail'; reason: string; checks: Verdict['checks'] } | null;\n /** Advisory silence timestamp from VerdictEngine — not part of task status semantics. */\n idleSince?: string | null;\n};\n\nexport type SerializedTask = {\n id: string;\n order: number;\n title: string;\n type: string;\n description: string;\n dependencies: string[];\n assignedRunner: RunnerId;\n assignedModel: Task['assignedModel'] | null;\n taskMode: string;\n prompt: string | null;\n subtasks: SerializedTask[];\n userSteps: Task['userSteps'];\n thinkingEffort: Task['thinkingEffort'];\n autonomy: Task['autonomy'];\n sliceType: Task['sliceType'];\n userStoriesCovered: Task['userStoriesCovered'];\n};\n\nexport type SerializedPlan = {\n tasks: SerializedTask[];\n runners: RunnerId[];\n generatedAt: string;\n conversationHistory?: LegacyPlanState['conversationHistory'];\n prdMarkdown?: string;\n queuedMessages?: QueuedMessage[];\n};\n\nexport type SessionMessage =\n | { type: 'plan_generated'; plan: SerializedPlan; goal: string; runners: RunnerId[] }\n | { type: 'planner_message'; content: string; timestamp: string }\n | { type: 'status_update'; tasks: SerializedTaskStatus[] }\n | { type: 'review_needed'; tasks: SerializedTask[] }\n | { type: 'review_approved' }\n | { type: 'checkpoint'; taskId: string; taskTitle: string; summary: string }\n | { type: 'execution_complete'; summary: { total: number; completed: number; failed: number } }\n | { type: 'execution_stopped' }\n | { type: 'queue_ready' }\n | { type: 'task_updated'; taskId: string; changes: Record<string, unknown> }\n | { type: 'task_started'; taskId: string; order: number; title: string; runner: RunnerId; modelId?: string }\n | { type: 'task_output'; taskId: string; text: string }\n | { type: 'plan_thinking'; text: string }\n // Carries no content — see `ResearchProgress['liveness']`. Exists only so a\n // surface's idle watchdog sees the harness process working even during a\n // stretch that produces nothing visible.\n | { type: 'planner_liveness' }\n // `toolLabel` carries a harness planner's own name for the tool (ADR-0009) —\n // always set when `tool` is `agent_tool`, so no surface has to render the\n // catch-all member name at the user.\n | { type: 'research_step'; tool: string; toolLabel?: string; args: string; subagentId?: string; toolCallId?: string }\n | { type: 'plan_token'; token: string }\n | { type: 'research_step_done'; step: ResearchStep; subagentId?: string }\n // Planner research wants something outside its default envelope and is\n // blocked until a human answers. Broadcast rather than returned, because the\n // human may be on any surface (or several at once) and the request outlives\n // whichever HTTP call triggered it.\n | { type: 'approval_request'; id: string; kind: ApprovalKind; subject: string; scope: string; detail?: string }\n | { type: 'approval_settled'; id: string; granted: boolean }\n // A decision reached with no round-trip prompt: pre-approved via config,\n // remembered from earlier in this session, or the operator's mode floor\n // (allow/deny skipping the human entirely). The interactive path above\n // already has full visibility via approval_request/approval_settled; this\n // is the one that previously had none — a model silently auto-running\n // `npm test` because the scope was already granted looked identical, from\n // every UI, to it never having been asked in the first place.\n | {\n type: 'approval_decided';\n kind: ApprovalKind;\n subject: string;\n scope: string;\n detail?: string;\n granted: boolean;\n source: Exclude<ApprovalSource, 'asked'>;\n };\n\nexport type SessionBroadcaster = (msg: SessionMessage) => void;\n\nexport function serializeTask(t: Task): SerializedTask {\n return {\n id: t.id,\n order: t.order,\n title: t.title,\n type: t.type,\n description: t.description,\n dependencies: t.dependencies || [],\n assignedRunner: t.assignedRunner,\n assignedModel: t.assignedModel || null,\n taskMode: t.taskMode || 'build',\n prompt: t.prompt || null,\n subtasks: (t.subtasks || []).map(serializeTask),\n userSteps: t.userSteps || undefined,\n thinkingEffort: t.thinkingEffort || undefined,\n autonomy: t.autonomy || undefined,\n sliceType: t.sliceType || undefined,\n userStoriesCovered: t.userStoriesCovered || undefined,\n };\n}\n\nexport function serializeTaskStatus(t: Task, idleSince: string | null = null): SerializedTaskStatus {\n return {\n id: t.id,\n status: t.status,\n verdict: t.verdict\n ? { outcome: t.verdict.outcome, reason: t.verdict.reason, checks: t.verdict.checks || [] }\n : null,\n idleSince,\n };\n}\n\nexport function serializePlan(plan: LegacyPlanState): SerializedPlan {\n return {\n tasks: plan.tasks.map(serializeTask),\n runners: plan.runners,\n generatedAt: plan.generatedAt,\n conversationHistory: plan.conversationHistory,\n prdMarkdown: plan.prdMarkdown,\n queuedMessages: plan.queuedMessages,\n };\n}\n\nexport function executionSummary(tasks: Task[]): { total: number; completed: number; failed: number } {\n return {\n total: tasks.length,\n completed: tasks.filter((t) => t.status === 'completed').length,\n failed: tasks.filter((t) => t.status === 'failed').length,\n };\n}\n\nexport const CHECKPOINT_TRUNCATE_LENGTH = 120;\n\n/** Truncate a checkpoint summary to a single line of at most CHECKPOINT_TRUNCATE_LENGTH chars. */\nexport function truncateCheckpointSummary(summary: string): string {\n // Take the first line only (checkpoint summaries often contain reasoning across lines)\n const firstLine = summary.split('\\n')[0].trim();\n if (firstLine.length <= CHECKPOINT_TRUNCATE_LENGTH) return firstLine;\n return firstLine.slice(0, CHECKPOINT_TRUNCATE_LENGTH - 1) + '…';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAA6B;AAsI7B,SAAS,YAAY,OAA8B;AACjD,QAAM,OAAO,IAAI,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;AAChD,QAAM,WAAW,oBAAI,IAAY;AACjC,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,QAAQ,CAAC,OAA8B;AAC3C,QAAI,KAAK,IAAI,EAAE,EAAG,QAAO;AACzB,QAAI,SAAS,IAAI,EAAE,EAAG,QAAO;AAC7B,aAAS,IAAI,EAAE;AACf,eAAW,OAAO,KAAK,IAAI,EAAE,GAAG,gBAAgB,CAAC,GAAG;AAClD,YAAM,MAAM,MAAM,GAAG;AACrB,UAAI,IAAK,QAAO;AAAA,IAClB;AACA,aAAS,OAAO,EAAE;AAClB,SAAK,IAAI,EAAE;AACX,WAAO;AAAA,EACT;AACA,aAAW,KAAK,OAAO;AACrB,UAAM,MAAM,MAAM,EAAE,EAAE;AACtB,QAAI,IAAK,QAAO,KAAK,IAAI,GAAG,GAAG,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3D,SAAO,UAAU,MAAM,GAAG,6BAA6B,CAAC,IAAI;AAC9D;","names":[]}
@@ -7,8 +7,8 @@ import {
7
7
  dependentsOf,
8
8
  summarizeToolCall,
9
9
  truncateCheckpointSummary
10
- } from "./chunk-YTJ7EOV6.mjs";
11
- import "./chunk-N6HTBUKG.mjs";
10
+ } from "./chunk-DV3YIKRA.mjs";
11
+ import "./chunk-T4KGVP4N.mjs";
12
12
  import "./chunk-HPNUFBIT.mjs";
13
13
  export {
14
14
  CHECKPOINT_TRUNCATE_LENGTH,
@@ -1,6 +1,6 @@
1
- import { i as ITerminalSession, I as IConfig, f as IFileSystem } from './ITerminalRunner-D_RBDoHa.mjs';
1
+ import { i as ITerminalSession, I as IConfig, f as IFileSystem } from './ITerminalRunner-E3-6QNUS.mjs';
2
2
  import './ApprovalPolicy-BVhGdECT.mjs';
3
- import './Task-cGrfYRXK.mjs';
3
+ import './Task-4rDGr8Su.mjs';
4
4
 
5
5
  declare function fakeConfig(overrides?: Partial<IConfig>): IConfig;
6
6
  /**
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { i as ITerminalSession, I as IConfig, f as IFileSystem } from './ITerminalRunner-DqAs12sy.js';
1
+ import { i as ITerminalSession, I as IConfig, f as IFileSystem } from './ITerminalRunner-CbLHKXT5.js';
2
2
  import './ApprovalPolicy-BVhGdECT.js';
3
- import './Task-cGrfYRXK.js';
3
+ import './Task-4rDGr8Su.js';
4
4
 
5
5
  declare function fakeConfig(overrides?: Partial<IConfig>): IConfig;
6
6
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordewell/core",
3
- "version": "0.4.15",
3
+ "version": "0.4.17",
4
4
  "description": "Ordewell core — planner, orchestrator, runners and verification engine.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Alessandro Costanzo Ciano",
@@ -0,0 +1,59 @@
1
+ ---
2
+ name: improve-codebase-architecture
3
+ description: Scan the codebase for deepening opportunities, prioritize them, then turn as many as the user wants into ordered plan tasks.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones, aimed at testability and AI-navigability. This skill never edits code itself — it never could, the planner is read-only — so the outcome is plan tasks, not a live refactor. Each candidate the user picks becomes one task for a runner to execute later, out of this conversation's sight.
8
+
9
+ ## Vocabulary
10
+
11
+ - **Module / interface / depth** — a module is deep when its interface is much simpler than what it hides; shallow when the interface is nearly as complex as the implementation.
12
+ - **Seam** — a boundary a test double or adapter swap crosses. **Locality** — how close the code that causes a bug sits to the code that shows it; extracting a pure function for testability without moving where the real logic runs loses locality.
13
+ - **Leverage** — how much simpler calling code gets once a module is deepened.
14
+ - **Deletion test** — would deleting this module concentrate complexity elsewhere (worth deepening), or just move it (not worth it)?
15
+
16
+ If the project keeps its own domain glossary (a `CONTEXT.md` or similar) or an ADR log (`docs/adr/` or similar), use its terms in place of these where they overlap, and read the ADRs that touch the area you're exploring before proposing anything that contradicts one.
17
+
18
+ ## Process
19
+
20
+ ### 1. Explore
21
+
22
+ Scope before you scan — put weight on what changes often, not everywhere:
23
+
24
+ - User named a direction (a module, a subsystem, a pain point)? Take it, skip the inference below.
25
+ - Otherwise walk `git log --oneline` for hot spots and let those pull your attention first. Scattered history with no clear hot spot → widen the net.
26
+
27
+ Explore read-only, delegating to a research subagent where one is available to you instead of reading everything inline. Don't follow rigid heuristics; explore organically and note where you experience friction — where understanding one concept means bouncing between many small modules, where an interface is nearly as complex as its implementation, where a pure function was extracted for testability but the real bug lives in how it's called, where modules leak across their seam, what's untested or hard to test through its current interface. Apply the deletion test to anything you suspect is shallow.
28
+
29
+ ### 2. Present candidates, prioritized
30
+
31
+ List every candidate directly in the conversation — no report file; nothing in this step touches disk. For each:
32
+
33
+ - **Title** — names the deepening (e.g. "Collapse the Order intake pipeline")
34
+ - **Files**
35
+ - **Problem** / **Solution** — one sentence each, in the project's own vocabulary where it has one
36
+ - **Benefits** — explained in terms of locality and leverage, and how tests would improve; this is what the recommendation strength below has to be earned by, not asserted
37
+ - **Recommendation**: `Strong`, `Worth exploring`, or `Speculative`
38
+ - **Overlaps** — which other candidates touch the same files; this drives task ordering in step 4
39
+ - If it contradicts an existing ADR, a one-line callout naming it (e.g. _"contradicts ADR-0007, but worth reopening because…"_) — only when the friction is real enough to warrant reopening the decision, not for every refactor an ADR happens to forbid
40
+
41
+ Order the list `Strong` → `Worth exploring` → `Speculative`, and close with which one you'd tackle first and why. Do not propose interfaces yet.
42
+
43
+ Ask: **how many of these should become tasks?** Default, unless told otherwise: every `Strong` candidate, none of the rest. The user may instead name specific candidates, a count ("top 3"), or "all" — whatever they say overrides the default.
44
+
45
+ ### 3. Resolve open questions per selected candidate
46
+
47
+ For each candidate going into the plan, settle whatever a runner would otherwise have to guess: the target seam, what sits behind it, what's explicitly out of scope, which tests survive. Interview only where the answer is genuinely unclear for that candidate — number the open questions, give your recommended answer, wait for the user before the next round. Don't grill a candidate that's already unambiguous.
48
+
49
+ If the user rejects a candidate with a load-bearing reason ("not now, that would break the plugin API"), offer: _"Want a one-line ADR task recording this, so a future run of this skill doesn't re-suggest it?"_ Only offer when the reason would actually be needed by a future run to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones.
50
+
51
+ ### 4. Convert to tasks
52
+
53
+ One task per selected candidate, unless a candidate is large enough that a runner would reasonably split it into a short dependent sequence itself — say so rather than forcing it into one prompt.
54
+
55
+ Write each task's prompt as self-contained: the runner executing it won't see this conversation. Include the problem, the solution, the files/seam involved, what "done" looks like, and — if the project keeps a glossary or ADR log — an instruction to update it when the task introduces or sharpens a term.
56
+
57
+ Order tasks `Strong` → `Worth exploring` → `Speculative`. Two selected candidates that touch overlapping files must not run concurrently: make the later one depend on the earlier one even when nothing else connects them, since two runners editing the same file in parallel is a conflict, not a coincidence.
58
+
59
+ Propose the task outline in prose and get the user's confirmation — the same convergence point any planning conversation reaches. Do not emit the task plan JSON until they've confirmed it.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/models/Task.ts","../src/services/JsonExtractor.ts"],"sourcesContent":["import { v4 as uuidv4 } from 'uuid';\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. */\nexport interface VerificationCheck {\n name: 'exit_code' | 'completion_marker' | '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 logTail: string;\n capturedAt: string;\n}\n\nexport type TaskType = 'ai' | 'user';\nexport type TaskStatus = 'pending' | 'approved' | 'in_progress' | 'completed' | 'failed' | 'blocked' | 'awaiting_user';\nexport type TaskMode = string;\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\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 thinkingEffort?: string;\n taskMode?: TaskMode;\n completionMarker: string;\n autonomy?: 'AFK' | 'HITL';\n sliceType?: 'HITL' | 'AFK';\n userStoriesCovered?: string[];\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 /**\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 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 ResearchLogEntry = ResearchStep | UserPromptEntry;\n\nexport interface ResearchProgress {\n type: 'thinking' | 'tool_call' | 'tool_result' | 'plan_token' | 'interrupted';\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}\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\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. Absent for ordinary chat turns, so\n * sessions saved before markers existed degrade gracefully.\n */\n kind?: 'plan_generated' | 'system';\n}\n\nexport interface QueuedMessage {\n id: string;\n text: string;\n timestamp: string;\n}\n\nexport interface PlanModificationWarnings {\n deletedCompleted: string[];\n changedCompleted: string[];\n deletedInProgress: string[];\n modifiedInProgress: string[];\n brokenDependencies: string[];\n}\n\nexport function emptyWarnings(): PlanModificationWarnings {\n return { deletedCompleted: [], changedCompleted: [], deletedInProgress: [], modifiedInProgress: [], brokenDependencies: [] };\n}\n\nexport interface LegacyPlanState {\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 /** Follow-ups queued while tasks execute — applied as plan modifications between batches. */\n queuedMessages?: QueuedMessage[];\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 migrateHistory(raw: LegacyPlanState): Message[] {\n const messages: Message[] = [];\n\n if (raw.researchLog) {\n for (const entry of raw.researchLog) {\n if ('type' in entry && entry.type === 'user_prompt') {\n messages.push({\n id: entry.id,\n role: 'user',\n content: (entry as UserPromptEntry).content,\n timestamp: new Date(entry.timestamp).getTime(),\n });\n } else {\n const step = entry as ResearchStep;\n messages.push({\n id: step.id,\n role: 'system',\n content: JSON.stringify({ tool: step.tool, args: step.args, result: step.result }),\n timestamp: new Date(step.timestamp).getTime(),\n });\n }\n }\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 function migrateLegacyPlan(legacy: LegacyPlanState): PlanState {\n const messages: Message[] = [];\n\n if (legacy.researchLog) {\n for (const entry of legacy.researchLog) {\n if ('type' in entry && entry.type === 'user_prompt') {\n messages.push({\n id: entry.id,\n role: 'user',\n content: (entry as UserPromptEntry).content,\n timestamp: new Date(entry.timestamp).getTime(),\n });\n } else {\n const step = entry as ResearchStep;\n messages.push({\n id: step.id,\n role: 'system',\n content: JSON.stringify({ tool: step.tool, args: step.args, result: step.result }),\n timestamp: new Date(step.timestamp).getTime(),\n });\n }\n }\n }\n\n if (legacy.queuedMessages) {\n for (const qm of legacy.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 const isPlanning = legacy.status === 'draft' || legacy.status === 'approved' || legacy.status === 'rejected';\n\n if (isPlanning) {\n return {\n phase: 'planning',\n history: messages,\n message: 'Plan generation',\n pendingTasks: legacy.tasks.filter((t) => t.status === 'pending' || t.status === ('draft' as never)),\n };\n }\n\n const nonCompletedTasks = legacy.tasks.filter(\n (t) => t.status !== 'completed' && t.status !== 'failed' && t.status !== 'blocked'\n );\n\n const completedSnapshot: TaskSnapshot[] = legacy.tasks\n .filter((t) => t.status === 'completed' || t.status === 'failed')\n .map((t) => ({\n ...t,\n completedAt: new Date(legacy.lastUpdated).getTime(),\n verdict: t.verdict,\n retryCount: 0,\n finalized: true,\n }));\n\n return {\n phase: 'executing',\n history: messages,\n message: 'Plan migration',\n executionLog: completedSnapshot,\n pendingTasks: nonCompletedTasks,\n goal: 'Plan migration',\n runners: legacy.runners,\n status: legacy.status,\n };\n}\n\nexport { taskOrderLabel, resolveOrderLabel } from '../order-labels';\n\nexport function createTask(overrides: Partial<Task> = {}): Task {\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 assignedModel: overrides.assignedModel,\n assignedRunner: overrides.assignedRunner ?? 'claude-code',\n thinkingEffort: overrides.thinkingEffort,\n taskMode: overrides.taskMode ?? 'build',\n completionMarker: overrides.completionMarker ?? uuidv4(),\n autonomy: overrides.autonomy,\n sliceType: overrides.sliceType,\n userStoriesCovered: overrides.userStoriesCovered,\n };\n}\n\nexport function createEmptyPlan(): LegacyPlanState {\n return {\n tasks: [],\n generatedAt: new Date().toISOString(),\n status: 'draft',\n runners: ['claude-code'],\n lastUpdated: new Date().toISOString(),\n };\n}\n\nexport function flattenTasks(tasks: Task[]): Task[] {\n return tasks.flatMap((t) => [t, ...flattenTasks(t.subtasks ?? [])]);\n}\n\n/** A flattened task with the parent it hangs under, null for a top-level task. */\nexport interface TaskWithParent {\n task: Task;\n parent: Task | null;\n}\n\nexport function flattenTasksWithParents(tasks: Task[]): TaskWithParent[] {\n const rows: TaskWithParent[] = [];\n const walk = (t: Task, parent: Task | null) => {\n rows.push({ task: t, parent });\n for (const sub of t.subtasks ?? []) walk(sub, t);\n };\n for (const t of tasks) walk(t, null);\n return rows;\n}\n\nexport function migrateTask(task: Record<string, unknown>): Task {\n if (!task.assignedModel) {\n task.assignedModel = undefined;\n }\n if (!task.assignedRunner) {\n task.assignedRunner = 'claude-code';\n }\n if (!task.thinkingEffort) {\n task.thinkingEffort = undefined;\n }\n if (!task.completionMarker) {\n task.completionMarker = uuidv4();\n }\n if (task.verdict && task.verification) {\n delete task.verification;\n }\n if (!task.autonomy) {\n task.autonomy = undefined;\n }\n if (!task.sliceType) {\n task.sliceType = undefined;\n }\n if (!task.userStoriesCovered) {\n task.userStoriesCovered = undefined;\n }\n return task as unknown as Task;\n}\n\nexport function addTaskToPlan(tasks: 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: 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: 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: Task[]): Task[] {\n return tasks.map((t, i) => ({\n ...t,\n order: i + 1,\n subtasks: renumberTasks(t.subtasks),\n }));\n}\n\nexport function validateModifiedPlan(original: Task[], modified: Task[]): PlanModificationWarnings {\n const allOriginal = flattenTasks(original);\n const allModified = flattenTasks(modified);\n const warnings = emptyWarnings();\n const originalMap = new Map(allOriginal.map((t) => [t.id, t]));\n const modifiedIds = new Set(allModified.map((t) => t.id));\n\n for (const ot of originalMap.values()) {\n if (ot.status === 'completed' && !modifiedIds.has(ot.id)) {\n warnings.deletedCompleted.push(ot.title);\n } else if (ot.status === 'in_progress' && !modifiedIds.has(ot.id)) {\n warnings.deletedInProgress.push(ot.title);\n }\n }\n\n for (const mt of allModified) {\n const orig = originalMap.get(mt.id);\n if (orig) {\n if (orig.status === 'completed' && mt.status !== 'completed') {\n warnings.changedCompleted.push(orig.title);\n }\n if (orig.status === 'in_progress' && (mt.status !== 'in_progress' || mt.prompt !== orig.prompt)) {\n warnings.modifiedInProgress.push(orig.title);\n }\n if (orig.status === 'failed' && mt.status === 'pending') {\n for (const dt of allModified) {\n if (dt.dependencies.includes(mt.id) && dt.status === 'blocked') {\n dt.status = 'pending';\n }\n }\n }\n }\n }\n\n for (const t of allModified) {\n for (const depId of t.dependencies) {\n if (!modifiedIds.has(depId)) {\n warnings.brokenDependencies.push(`${t.title} → ${depId}`);\n }\n }\n }\n\n return warnings;\n}\n\nexport interface ActiveTaskSession {\n id: string;\n taskId: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n}\n\nexport interface ValidationContext {\n executionLog: TaskSnapshot[];\n oldPending: Task[];\n newPending: Task[];\n activeSessions: Map<string, ActiveTaskSession>;\n}\n\nexport type ValidationCheck = (ctx: ValidationContext) => ValidationResult;\n\nexport function warningsText(w: PlanModificationWarnings): string | null {\n const lines: string[] = [];\n if (w.deletedCompleted.length) lines.push(`Completed tasks deleted: ${w.deletedCompleted.join(', ')}`);\n if (w.changedCompleted.length) lines.push(`Completed tasks modified: ${w.changedCompleted.join(', ')}`);\n if (w.deletedInProgress.length) lines.push(`In-progress tasks deleted: ${w.deletedInProgress.join(', ')}`);\n if (w.modifiedInProgress.length) lines.push(`In-progress tasks modified: ${w.modifiedInProgress.join(', ')}`);\n if (w.brokenDependencies.length) lines.push(`Broken dependencies: ${w.brokenDependencies.join(', ')}`);\n return lines.length > 0 ? lines.join('\\n') : null;\n}\n","/** 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\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') {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