{"version":3,"file":"mcp.cjs","names":["DELETED_STATUS","DELETED_STATUS","DOOM_DELEGATION_ACCEPTED_EVENT","DOOM_DELEGATION_STARTED_EVENT","DOOM_DELEGATION_UPDATED_EVENT","DOOM_DELEGATION_FINISHED_EVENT","path","randomUUID","os","path","SUBAGENT_CHILD_ENV","SUBAGENT_PARENT_SESSION_ENV","fs","path","Type","InlineAgentSchema","DELETED_STATUS","Check","defineMcpTool","defineMcpPlugin","toolTask"],"sources":["../../src/services/config/index.ts","../../src/models/taskGraph.ts","../../src/types/telemetry.ts","../../src/models/task.ts","../../src/services/processLiveness/index.ts","../../src/services/reconcile/index.ts","../../src/services/delegation/index.ts","../../src/services/delegationPlatform/index.ts","../../src/services/paths/index.ts","../../src/services/invariants/index.ts","../../src/services/taskStore/index.ts","../../src/schemas/task.ts","../../src/services/reducer/index.ts","../../src/services/taskResult/index.ts","../../src/services/taskTool/index.ts","../../src/extensions/workspaces/sessions/(backend)/tool/task.mcp.ts","../../generated/mcp.ts"],"sourcesContent":["/**\n * Extension configuration, read from the environment.\n *\n * Env rather than a config file: doom-pi already carries per-launch state to Pi\n * through env vars, so this keeps doom-task consistent with how the harness\n * configures the rest of the extension set.\n */\n\nexport const MAX_WIDGET_LINES_ENV = 'DOOM_TASK_MAX_WIDGET_LINES';\nexport const MAX_TASKS_ENV = 'DOOM_TASK_MAX_TASKS';\nexport const COLLAPSE_KEY_ENV = 'DOOM_TASK_COLLAPSE_KEY';\nexport const STORE_TTL_MS_ENV = 'DOOM_TASK_STORE_TTL_MS';\nexport const DELEGATION_TIMEOUT_MS_ENV = 'DOOM_TASK_DELEGATION_TIMEOUT_MS';\n\nexport const DEFAULT_MAX_WIDGET_LINES = 12;\nexport const DEFAULT_MAX_TASKS = 15;\nexport const DEFAULT_COLLAPSE_KEY = 'ctrl+shift+t';\nexport const DEFAULT_STORE_TTL_MS = 30 * 24 * 60 * 60 * 1000;\n/** Deliberately under the subagents auto-drain ceiling (30 min) so a headless\n * session still gets the failure and a model turn before draining gives up. */\nexport const DEFAULT_DELEGATION_TIMEOUT_MS = 20 * 60 * 1000;\nexport const COLLAPSE_KEY_OFF = 'off';\n\nconst MIN_WIDGET_LINES = 3;\nconst MAX_WIDGET_LINES = 60;\n\nexport interface PiTaskConfig {\n  maxWidgetLines: number;\n  maxTasks: number;\n  storeTtlMs: number;\n  collapseKey: string;\n  delegationTimeoutMs: number;\n}\n\nfunction configRecord(value: unknown): Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\n/** Parse configuration only after the Pi host has applied its project-trust policy. */\nexport function parsePiTaskConfig(value: unknown): PiTaskConfig {\n  const config = configRecord(value);\n  const maxWidgetLines =\n    typeof config.maxWidgetLines === 'number' && Number.isFinite(config.maxWidgetLines)\n      ? Math.min(Math.max(config.maxWidgetLines, MIN_WIDGET_LINES), MAX_WIDGET_LINES)\n      : DEFAULT_MAX_WIDGET_LINES;\n  const maxTasks =\n    typeof config.maxTasks === 'number' && Number.isSafeInteger(config.maxTasks) && config.maxTasks > 0\n      ? config.maxTasks\n      : DEFAULT_MAX_TASKS;\n  const storeTtlMs =\n    typeof config.storeTtlMs === 'number' && Number.isFinite(config.storeTtlMs) && config.storeTtlMs > 0\n      ? config.storeTtlMs\n      : DEFAULT_STORE_TTL_MS;\n  const delegationTimeoutMs =\n    typeof config.delegationTimeoutMs === 'number' &&\n    Number.isFinite(config.delegationTimeoutMs) &&\n    config.delegationTimeoutMs > 0\n      ? config.delegationTimeoutMs\n      : DEFAULT_DELEGATION_TIMEOUT_MS;\n  const collapseKey =\n    typeof config.collapseKey === 'string' && config.collapseKey.trim()\n      ? config.collapseKey.trim().toLowerCase() === COLLAPSE_KEY_OFF\n        ? COLLAPSE_KEY_OFF\n        : config.collapseKey.trim()\n      : DEFAULT_COLLAPSE_KEY;\n\n  return { maxWidgetLines, maxTasks, storeTtlMs, collapseKey, delegationTimeoutMs };\n}\n\n/** Rows the overlay may use for content, clamped to a sane range. */\nexport function getMaxWidgetLines(env: NodeJS.ProcessEnv = process.env): number {\n  const raw = Number.parseInt(env[MAX_WIDGET_LINES_ENV] ?? '', 10);\n  if (!Number.isFinite(raw)) return DEFAULT_MAX_WIDGET_LINES;\n  return Math.min(Math.max(raw, MIN_WIDGET_LINES), MAX_WIDGET_LINES);\n}\n\n/** Maximum number of non-deleted tasks retained on one board. */\nexport function getMaxTasks(env: NodeJS.ProcessEnv = process.env): number {\n  const raw = Number(env[MAX_TASKS_ENV]);\n  return Number.isSafeInteger(raw) && raw > 0 ? raw : DEFAULT_MAX_TASKS;\n}\n\n/** Retention window for inactive session-tree stores. */\nexport function getStoreTtlMs(env: NodeJS.ProcessEnv = process.env): number {\n  const raw = Number(env[STORE_TTL_MS_ENV]);\n  return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_STORE_TTL_MS;\n}\n\n/** How long a delegated run may go without reporting a result. */\nexport function getDelegationTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n  const raw = Number(env[DELEGATION_TIMEOUT_MS_ENV]);\n  return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_DELEGATION_TIMEOUT_MS;\n}\n\n/** Collapse shortcut, or the `off` sentinel when the user disabled it. */\nexport function resolveCollapseKey(env: NodeJS.ProcessEnv = process.env): string {\n  const configured = env[COLLAPSE_KEY_ENV]?.trim();\n  if (!configured) return DEFAULT_COLLAPSE_KEY;\n  return configured.toLowerCase() === COLLAPSE_KEY_OFF ? COLLAPSE_KEY_OFF : configured;\n}\n","import type { Task } from './task';\n\nconst COMPLETED_STATUS: Task['status'] = 'completed';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\n/** True when a non-empty list has no visible work left to finish. */\nexport function isTaskListComplete(taskList: readonly Task[]): boolean {\n  const visible = taskList.filter((task) => task.status !== DELETED_STATUS);\n  return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);\n}\n\n/**\n * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?\n *\n * Takes the proposed additions explicitly so the reducer can ask the question\n * before mutating anything.\n */\nexport function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean {\n  const edges = new Map<number, number[]>();\n  for (const task of taskList) {\n    if (task.id === taskId) {\n      edges.set(task.id, [...new Set([...(task.blockedBy ?? []), ...newBlockedBy])]);\n    } else {\n      edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);\n    }\n  }\n\n  const visiting = new Set<number>();\n  const visited = new Set<number>();\n  const hasCycleFrom = (node: number): boolean => {\n    if (visiting.has(node)) return true;\n    if (visited.has(node)) return false;\n    visiting.add(node);\n    for (const next of edges.get(node) ?? []) {\n      if (hasCycleFrom(next)) return true;\n    }\n    visiting.delete(node);\n    visited.add(node);\n    return false;\n  };\n\n  for (const node of edges.keys()) {\n    if (hasCycleFrom(node)) return true;\n  }\n  return false;\n}\n\n/** Inverse adjacency: for each task, which tasks list it in their blockedBy. */\nexport function deriveBlocks(taskList: readonly Task[]): Map<number, number[]> {\n  const blocks = new Map<number, number[]>();\n  for (const task of taskList) {\n    for (const dep of task.blockedBy ?? []) {\n      const dependents = blocks.get(dep) ?? [];\n      dependents.push(task.id);\n      blocks.set(dep, dependents);\n    }\n  }\n  return blocks;\n}\n\n/**\n * Blocking dependencies of a task that are not yet resolved.\n *\n * `completed` clears a dependency; `failed` deliberately does not, so a failed\n * delegation keeps its dependents blocked instead of silently releasing work\n * that was never actually finished.\n */\nexport function unresolvedBlockers(taskList: readonly Task[], task: Task): number[] {\n  return (task.blockedBy ?? []).filter((dep) => {\n    const blocker = taskList.find((candidate) => candidate.id === dep);\n    if (!blocker) return false;\n    return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS;\n  });\n}\n\nexport function isBlocked(taskList: readonly Task[], task: Task): boolean {\n  return unresolvedBlockers(taskList, task).length > 0;\n}\n","export const TASK_EVENT = {\n  notificationFailed: 'doom_task.notification_failed',\n  storeReadFailed: 'doom_task.store_read_failed',\n  storeLockTimeout: 'doom_task.store_lock_timeout',\n  storeLockBreakFailed: 'doom_task.store_lock_break_failed',\n  storeWatchFailed: 'doom_task.store_watch_failed',\n  storeListenerFailed: 'doom_task.store_listener_failed',\n  storeCommitListenerFailed: 'doom_task.store_commit_listener_failed',\n  storeSweepFailed: 'doom_task.store_sweep_failed',\n  sessionStartFailed: 'doom_task.session_start_failed',\n  sessionStartDegraded: 'doom_task.session_start_degraded',\n  toolFailed: 'doom_task.tool_failed',\n  delegationRequestFailed: 'doom_task.delegation_request_failed',\n  delegationStartFailed: 'doom_task.delegation_start_failed',\n  delegationResponseFailed: 'doom_task.delegation_response_failed',\n  delegationSettleFailed: 'doom_task.delegation_settle_failed',\n  delegationTimedOut: 'doom_task.delegation_timed_out',\n  delegationOrphaned: 'doom_task.delegation_orphaned',\n  // Info-level lifecycle events. These are the measurement pair: the shape of\n  // the brief that went out, and the cost of the run it produced.\n  delegationAssigned: 'doom_task.delegation_assigned',\n  delegationCompleted: 'doom_task.delegation_completed',\n} as const;\n\nexport type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];\nexport type TaskErrorAttributes = Record<string, string | number | boolean>;\nexport type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;\nexport type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;\n\n/** Host-neutral telemetry port consumed by Task services and store adapters. */\nexport interface TaskFailureReporter {\n  error: TaskErrorSink;\n  warn: TaskErrorSink;\n  /** Info-level event sink. Required so an unwired reporter fails to compile. */\n  event: TaskEventSink;\n}\n","/**\n * Domain types for the file-backed task store.\n *\n * The on-disk document is the durable source of truth (unlike rpiv-todo, which\n * replayed state from the transcript). Every field here round-trips through\n * JSON, so nothing may hold non-serializable values.\n */\n\nimport type { InlineAgent } from '@agimon-ai/doompi-core/delegation';\n\nexport type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'deleted';\n\nexport const DELETED_STATUS: TaskStatus = 'deleted';\n\nexport type TaskAction = 'upsert' | 'list' | 'get' | 'delete' | 'clear' | 'assign' | 'cancel';\n\nexport type DelegationState = 'requested' | 'running' | 'completed' | 'failed' | 'cancelled';\n\n/** Terminal result of a delegated subagent run, copied off the delegation response. */\nexport interface DelegationResult {\n  status: string;\n  output?: string;\n  outputPath?: string;\n  sessionFile?: string;\n  error?: string;\n  durationMs?: number;\n  toolCount?: number;\n}\n\n/**\n * Delegation bookkeeping attached to a task that was handed to a subagent.\n *\n * `pid` is the harness process that owns the run: it is the only way to tell an\n * genuinely-running delegation from one orphaned by a harness crash, since the\n * child dies with its parent but the file survives.\n */\nexport interface TaskDelegation {\n  requestId: string;\n  agent: string;\n  state: DelegationState;\n  sessionId?: string;\n  pid?: number;\n  runId?: string;\n  model?: string;\n  startedAt?: string;\n  endedAt?: string;\n  result?: DelegationResult;\n}\n\nexport interface Task {\n  id: number;\n  subject: string;\n  description?: string;\n  activeForm?: string;\n  status: TaskStatus;\n  blockedBy?: number[];\n  owner?: string;\n  metadata?: Record<string, unknown>;\n  createdAt?: string;\n  updatedAt?: string;\n  delegation?: TaskDelegation;\n}\n\nexport const STORE_SCHEMA_VERSION = 1;\n\n/** The complete on-disk document. `rev` increments on every committed write. */\nexport interface TaskDocument {\n  version: number;\n  rev: number;\n  nextId: number;\n  tasks: Task[];\n}\n\nexport function emptyDocument(): TaskDocument {\n  return { version: STORE_SCHEMA_VERSION, rev: 0, nextId: 1, tasks: [] };\n}\n\n/**\n * A dependency target inside an upsert item: an existing task id, or the `ref`\n * of a task created earlier in the same call.\n *\n * Refs must start with a letter (see `REF_PATTERN`), so a ref is structurally\n * unconfusable with a stringified id and the discrimination is just `typeof`.\n */\nexport type DepToken = number | string;\n\n/**\n * One entry of an `upsert` call. No `id` creates a task; an `id` updates one.\n *\n * `blockedBy` (absolute set) is create-only and `addBlockedBy`/`removeBlockedBy`\n * (additive merge) are update-only, matching the split the two former actions\n * had. A field used against the wrong kind fails that item rather than being\n * silently ignored.\n */\nexport interface TaskItemMutation {\n  id?: number;\n  ref?: string;\n  subject?: string;\n  description?: string;\n  activeForm?: string;\n  status?: TaskStatus;\n  blockedBy?: DepToken[];\n  addBlockedBy?: DepToken[];\n  removeBlockedBy?: DepToken[];\n  owner?: string;\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * What one upsert item did. `index` is its position in the request array, so a\n * model reading a partial result can tell which entries still need resending.\n *\n * `message` is unprefixed: the `item[N] failed:` framing belongs to the\n * formatter, because the Task Space overlay shows this text on its own.\n */\nexport type UpsertItemOutcome =\n  | {\n      index: number;\n      kind: 'created';\n      id: number;\n      subject: string;\n      status: TaskStatus;\n      ref?: string;\n      blockedBy?: number[];\n    }\n  | { index: number; kind: 'updated'; id: number; fromStatus: TaskStatus; toStatus: TaskStatus }\n  | { index: number; kind: 'unchanged'; id: number; status: TaskStatus }\n  | { index: number; kind: 'failed'; message: string; id?: number; ref?: string };\n\n/** Which tasks an upsert touched, so renderResult names them instead of guessing. */\nexport interface UpsertSummary {\n  /** Ids of applied entries, in request order. A failed entry contributes nothing. */\n  applied: number[];\n  failed: number;\n}\n\n/** One task-to-agent handoff inside a native assignment batch. */\nexport interface TaskAssignment {\n  id: number;\n  agent: string;\n  inlineAgent?: InlineAgent;\n  instructions?: string;\n  relevantFiles?: string[];\n  priorFindings?: string;\n  model?: string;\n  context?: 'fresh' | 'fork';\n}\n\n/** Which assignment entries started, so renderResult can show one consolidated batch. */\nexport interface AssignmentSummary {\n  /** Ids of successful entries, in request order. A failed entry contributes nothing. */\n  assigned: number[];\n  failed: number;\n}\n\n/**\n * Open-shape input bag the reducer accepts. The index signature lets the\n * runtime pass a TypeBox `Static<typeof TaskParamsSchema>` through without\n * casting each field.\n *\n * Per-task fields live on `tasks[]`, not here: a top-level `subject` or\n * `status` would be ambiguous once one call can carry many tasks.\n */\nexport interface TaskMutationParams {\n  [key: string]: unknown;\n  tasks?: TaskItemMutation[];\n  /** `assign` only: independent task-to-agent handoffs dispatched by one tool call. */\n  assignments?: TaskAssignment[];\n  /** `list` filter only. To set a status, upsert the task by id. */\n  status?: TaskStatus;\n  /** `get`, `delete`, and `cancel` only. Assign ids live in `assignments[]`. */\n  id?: number;\n  includeDeleted?: boolean;\n}\n\n/** Snapshot returned under a tool result's `details` for renderResult. */\nexport interface TaskDetails {\n  action: TaskAction;\n  params: Record<string, unknown>;\n  tasks: Task[];\n  nextId: number;\n  rev: number;\n  error?: string;\n  upsert?: UpsertSummary;\n  assignment?: AssignmentSummary;\n}\n\n/**\n * A delegation is \"live\" while the owning run may still produce a response.\n *\n * Takes the delegation shape rather than `Task` so the cockpit's `WebTask`,\n * which carries the state as a plain string, answers the question the same way\n * the store does.\n */\nexport function isDelegationActive(task: { delegation?: { state?: string } }): boolean {\n  const state = task.delegation?.state;\n  return state === 'requested' || state === 'running';\n}\n","/**\n * Is a process still running?\n *\n * Signal 0 performs the permission and existence check without delivering a\n * signal. EPERM means the process exists but belongs to another user, which\n * still counts as alive.\n */\nexport function isProcessAlive(pid: number): boolean {\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch (error) {\n    return (error as NodeJS.ErrnoException).code === 'EPERM';\n  }\n}\n","import { isDelegationActive, type Task, type TaskDocument } from '../../models/task';\nimport { isProcessAlive } from '../processLiveness';\n\nexport const ERR_ORPHANED_BY_RESTART = 'Delegation orphaned by harness restart';\nexport const ERR_ORPHANED_BY_SESSION = 'Delegation orphaned by session restart';\n\nexport interface ReconcileResult {\n  document: TaskDocument;\n  orphaned: Task[];\n}\n\n/** The delegations this process can still settle, used to spot its own leftovers. */\nexport interface ReconcileSelf {\n  pid: number;\n  liveRequestIds: ReadonlySet<string>;\n}\n\n/**\n * Recover tasks that no longer have anyone able to finish them.\n *\n * A subagent run dies with the harness that spawned it, but the store file\n * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two\n * kinds of delegation qualify as dead:\n *\n * - the owning pid is gone, so nothing is left to report a result;\n * - the owning pid is *this* process, yet the request is absent from the live\n *   set. Settling requires an in-memory record, so an in-process session\n *   restart (which clears that map without writing to the store) leaves rows\n *   nothing can ever resolve. Checking pid liveness alone misses these, because\n *   the pid is our own and very much alive.\n *\n * Delegations owned by a different, still-running pid belong to a parallel\n * session and are left untouched.\n */\nexport function reconcileOrphanedDelegations(\n  document: TaskDocument,\n  now: string = new Date().toISOString(),\n  isAlive: (pid: number) => boolean = isProcessAlive,\n  self?: ReconcileSelf,\n): ReconcileResult {\n  const orphaned: Task[] = [];\n\n  const tasks = document.tasks.map((task) => {\n    if (!isDelegationActive(task)) return task;\n    const pid = task.delegation?.pid;\n    if (pid === undefined) return task;\n\n    const ownedByThisSession = self !== undefined && pid === self.pid;\n    const abandonedHere = ownedByThisSession && !self.liveRequestIds.has(task.delegation!.requestId);\n    if (!abandonedHere && isAlive(pid)) return task;\n\n    const recovered: Task = {\n      ...task,\n      status: 'pending',\n      updatedAt: now,\n      delegation: {\n        ...task.delegation!,\n        state: 'failed',\n        endedAt: now,\n        result: {\n          status: 'failed',\n          error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART,\n        },\n      },\n    };\n    orphaned.push(recovered);\n    return recovered;\n  });\n\n  if (orphaned.length === 0) return { document, orphaned };\n  return { document: { ...document, tasks }, orphaned };\n}\n","import {\n  type DelegationAccepted as DelegationAcceptedPayload,\n  DOOM_DELEGATION_ACCEPTED_EVENT,\n  DOOM_DELEGATION_FINISHED_EVENT,\n  DOOM_DELEGATION_STARTED_EVENT,\n  DOOM_DELEGATION_UPDATED_EVENT,\n  type DoomDelegationService,\n  type DelegationResult,\n  type DelegationStarted as DelegationStartedPayload,\n  type DelegationUpdate,\n  type InlineAgent,\n} from '@agimon-ai/doompi-core/delegation';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { isBlocked, isTaskListComplete } from '../../models/taskGraph';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry';\nimport { reconcileOrphanedDelegations } from '../reconcile';\nimport type { TaskStore } from '../taskStore';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../../models/task';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n  'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n  'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n  agent: string;\n  currentTool?: string;\n  toolCount?: number;\n  tokens?: number;\n  /** Latest child-runtime duration baseline, excluding assignment wait. */\n  durationMs?: number;\n  /** Wall-clock time at which durationMs was observed or rebased. */\n  durationObservedAt?: number;\n  /** Assign-time context-pack shape, carried so the completion event can be\n   * grouped by it without joining back to the assignment event. */\n  contextFileCount?: number;\n  contextNotesLength?: number;\n}\n\nexport type DelegationNotifier = (\n  message: { customType: string; content: string; display: boolean },\n  options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n) => void;\n\nexport interface DelegationPlatform {\n  readonly environment: Readonly<Record<string, string | undefined>>;\n  readonly processId: number;\n  readonly createRequestId: () => string;\n  readonly formatBriefPath: (entry: string, cwd: string) => string;\n}\n\nexport interface DelegationManagerOptions {\n  store: TaskStore;\n  cwd: string;\n  platform: DelegationPlatform;\n  notify?: DelegationNotifier;\n  getSessionId?: () => string | undefined;\n  onChange?: () => void;\n  startedTimeoutMs?: number;\n  /** How long a started run may go without reporting a result. */\n  runTimeoutMs?: number;\n  /** How long to wait for a cancelled run to report back before forcing it. */\n  cancelTimeoutMs?: number;\n  now?: () => string;\n  nowMs?: () => number;\n  /** Called when a completion notification could not be delivered. */\n  onNotifyError: (error: unknown, taskId: number) => void;\n  /** Where other swallowed delegation failures go. */\n  report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n  agent?: string;\n  inlineAgent?: InlineAgent;\n  instructions?: string;\n  /** Paths the parent already located, rendered into the brief so the child\n   * skips rediscovering them. */\n  relevantFiles?: string[];\n  /** Facts the parent already established, rendered into the brief so the child\n   * does not re-derive them. */\n  priorFindings?: string;\n  model?: string;\n  context?: 'fresh' | 'fork';\n  signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n  ok: boolean;\n  message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n  task?: Task;\n}\n\ninterface PendingTask {\n  readonly taskId: number;\n  readonly sessionId?: string;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n  if (!value) return undefined;\n  return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n  files: string[];\n  notes?: string;\n}\n\n/** Normalize the parent context with host-owned path semantics. */\nfunction briefContext(options: AssignOptions, cwd: string, platform: DelegationPlatform): BriefContext {\n  const files = new Set<string>();\n  for (const entry of options.relevantFiles ?? []) {\n    if (files.size >= MAX_BRIEF_FILES) break;\n    const normalized = platform.formatBriefPath(entry.trim(), cwd);\n    if (normalized && normalized !== '.') files.add(normalized);\n  }\n  return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n  const sections = [`Task #${task.id}: ${task.subject}`];\n  if (task.description) sections.push(task.description);\n  if (instructions) sections.push(instructions);\n  if (context.files.length > 0 || context.notes) {\n    const contextLines = ['Parent context — consume before repository discovery:'];\n    if (context.files.length > 0) {\n      contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n    }\n    if (context.notes) {\n      contextLines.push(\n        `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n      );\n    }\n    contextLines.push(\n      'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n    );\n    sections.push(contextLines.join('\\n'));\n  }\n  sections.push(\n    'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n  );\n  return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides Team's injected Cordis service rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that service is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n  private readonly options: DelegationManagerOptions;\n  private readonly progress = new Map<string, DelegationProgress>();\n  private readonly pendingTasks = new Map<string, PendingTask>();\n  private readonly settlingRequests = new Set<string>();\n  private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n  private readonly subscriptions: Array<() => void> = [];\n  private service: DoomDelegationService | undefined;\n\n  constructor(options: DelegationManagerOptions) {\n    this.options = options;\n  }\n\n  private now(): string {\n    return this.options.now?.() ?? new Date().toISOString();\n  }\n\n  private nowMs(): number {\n    return this.options.nowMs?.() ?? Date.now();\n  }\n\n  private get runTimeoutMs(): number {\n    return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n  }\n\n  private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n    this.options.report?.error(event, error, attributes);\n  }\n\n  /** True in a session that is itself a subagent child. */\n  get isChildSession(): boolean {\n    return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);\n  }\n\n  /** Live progress for a task, for the overlay to render. */\n  progressFor(task: Task): DelegationProgress | undefined {\n    const requestId = task.delegation?.requestId;\n    return requestId ? this.progress.get(requestId) : undefined;\n  }\n\n  /** Displayed runtime duration, rebased from the latest child observation. */\n  static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n    const baseline = progress.durationMs ?? 0;\n    const observedAt = progress.durationObservedAt ?? nowMs;\n    return baseline + Math.max(0, nowMs - observedAt);\n  }\n\n  /** Rebind to the active Team service without stacking lifecycle listeners. */\n  bind(ctx: Context, service: DoomDelegationService): () => void {\n    this.unbind();\n    this.service = service;\n    this.subscriptions.push(\n      ctx.on(DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {\n        this.handleAccepted(event);\n      }),\n      ctx.on(DOOM_DELEGATION_STARTED_EVENT, (event) => {\n        this.handleStarted(event);\n      }),\n      ctx.on(DOOM_DELEGATION_UPDATED_EVENT, (event) => {\n        this.handleUpdate(event);\n      }),\n      ctx.on(DOOM_DELEGATION_FINISHED_EVENT, (event) => {\n        void this.handleResponse(event).catch((error: unknown) => {\n          this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n        });\n      }),\n    );\n    return () => {\n      if (this.service === service) this.unbind();\n    };\n  }\n\n  /** Remove only the cross-package binding; task state and watchdogs remain live. */\n  unbind(): void {\n    for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();\n    this.service = undefined;\n  }\n\n  /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n  listActiveWork(): Array<{ id: string; sessionId: string }> {\n    return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) =>\n      pending.sessionId ? [{ id: `task-${pending.taskId}:${requestId}`, sessionId: pending.sessionId }] : [],\n    );\n  }\n\n  /**\n   * Return tasks nothing can finish to `pending`.\n   *\n   * The live request set is read inside the mutation so a delegation assigned\n   * while the lock was contended is not mistaken for a leftover.\n   */\n  async reconcile(isCurrent: () => boolean = () => true): Promise<Task[]> {\n    const { value } = await this.options.store.mutate((document) => {\n      if (!isCurrent()) return { value: [] as Task[] };\n      const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n        pid: this.options.platform.processId,\n        liveRequestIds: new Set(this.pendingTasks.keys()),\n      });\n      if (result.orphaned.length === 0) return { value: [] as Task[] };\n      return { document: result.document, value: result.orphaned };\n    });\n\n    if (!isCurrent()) return [];\n    for (const task of value) {\n      this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n        [TASK_ID_ATTRIBUTE]: task.id,\n        ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n        ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n      });\n    }\n\n    if (value.length > 0) this.options.onChange?.();\n    return value;\n  }\n\n  async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n    const agent = options.agent?.trim();\n    if (!agent) return { ok: false, message: 'agent required for assign' };\n    if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n    if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n    const requestId = this.options.platform.createRequestId();\n    const startedAt = this.now();\n    const sessionId = this.options.getSessionId?.();\n    const context = briefContext(options, this.options.cwd, this.options.platform);\n\n    const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n      const index = current.tasks.findIndex((task) => task.id === taskId);\n      if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n      const task = current.tasks[index];\n      if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n      if (task.status === COMPLETED_STATE) {\n        return { value: { ok: false, message: `#${taskId} is already completed` } };\n      }\n      if (isDelegationActive(task)) {\n        return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n      }\n      if (isBlocked(current.tasks, task)) {\n        const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n        return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n      }\n\n      const delegation: TaskDelegation = {\n        requestId,\n        agent,\n        state: 'requested',\n        pid: this.options.platform.processId,\n        startedAt,\n        ...(sessionId ? { sessionId } : {}),\n        ...(options.model ? { model: options.model } : {}),\n      };\n\n      const tasks = [...current.tasks];\n      tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n      return {\n        document: { ...current, tasks },\n        value: { ok: true, message: '', task: tasks[index] },\n      };\n    });\n\n    if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n    const contextNotesLength = context.notes?.length ?? 0;\n    this.pendingTasks.set(requestId, { taskId, sessionId });\n    this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n    this.armStartedTimeout(requestId);\n    this.options.onChange?.();\n    const request = {\n      requestId,\n      taskId,\n      agent,\n      ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n      prompt: buildBrief(outcome.task, options.instructions, context),\n      ...(options.context ? { context: options.context } : {}),\n      cwd: this.options.cwd,\n      artifacts: true,\n      timeoutMs: this.runTimeoutMs,\n      runMode: 'detached' as const,\n      teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n      ...(options.model ? { model: options.model } : {}),\n    };\n\n    try {\n      const service = this.service;\n      if (!service) throw new Error(ERR_NO_RUNTIME);\n      void service.request(request).catch((error: unknown) => {\n        this.report(TASK_EVENT.delegationRequestFailed, error, {\n          [TASK_ID_ATTRIBUTE]: taskId,\n          [REQUEST_ID_ATTRIBUTE]: requestId,\n          [AGENT_ATTRIBUTE]: agent,\n        });\n        this.settleDetached(requestId, FAILED_STATE, {\n          status: FAILED_STATE,\n          error: `Delegation request failed: ${messageOf(error)}`,\n        });\n      });\n    } catch (error) {\n      this.report(TASK_EVENT.delegationRequestFailed, error, {\n        [TASK_ID_ATTRIBUTE]: taskId,\n        [REQUEST_ID_ATTRIBUTE]: requestId,\n        [AGENT_ATTRIBUTE]: agent,\n      });\n      const detail = messageOf(error);\n      await this.settle(requestId, FAILED_STATE, {\n        status: FAILED_STATE,\n        error: `Delegation request failed: ${detail}`,\n      });\n      return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n    }\n\n    // Recorded only after the service accepted the request call, so it means a\n    // brief actually entered Team's state machine rather than merely being assembled.\n    this.options.report?.event(TASK_EVENT.delegationAssigned, {\n      [TASK_ID_ATTRIBUTE]: taskId,\n      [REQUEST_ID_ATTRIBUTE]: requestId,\n      [AGENT_ATTRIBUTE]: agent,\n      [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n      [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n      [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n      [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n    });\n\n    return {\n      ok: true,\n      message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`,\n    };\n  }\n\n  async cancel(taskId: number): Promise<DelegationOutcome> {\n    const document = this.options.store.read();\n    const task = document.tasks.find((candidate) => candidate.id === taskId);\n    if (!task) return { ok: false, message: `#${taskId} not found` };\n    if (!task.delegation || !isDelegationActive(task)) {\n      return { ok: false, message: `#${taskId} has no running delegation` };\n    }\n\n    const { requestId } = task.delegation;\n    this.service?.cancel({ requestId });\n    // Only this session can force the outcome; a delegation owned elsewhere\n    // gets the request and nothing more.\n    this.armCancelTimeout(requestId);\n    return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n  }\n\n  /** Settle without awaiting, reporting rather than dropping a failure. */\n  private settleDetached(\n    requestId: string,\n    state: SettlementState,\n    result: TaskDelegation['result'],\n    event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n  ): void {\n    void this.settle(requestId, state, result).catch((error: unknown) => {\n      this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n    });\n  }\n\n  /**\n   * Fail a delegation that nobody acknowledged.\n   *\n   * Provider loss or a stalled Team runtime can still leave a dispatched\n   * request silent. Without this acknowledgement deadline the task would sit\n   * in `requested` forever.\n   */\n  private armStartedTimeout(requestId: string): void {\n    this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n      this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n    });\n  }\n\n  /**\n   * Bound a run that already started.\n   *\n   * The request carries the same budget, so in the normal case the runtime ends\n   * the run itself and reports a richer result. The grace period biases toward\n   * that answer; this timer only covers a runtime that goes silent, which is\n   * precisely the case where no response event will ever arrive.\n   */\n  private armRunTimeout(requestId: string): void {\n    const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n    this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n      const taskId = this.pendingTasks.get(requestId)?.taskId;\n      const agent = this.progress.get(requestId)?.agent;\n      const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n      this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n        ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n        [REQUEST_ID_ATTRIBUTE]: requestId,\n        ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n      });\n      this.service?.cancel({ requestId, reason: error.message });\n      this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n    });\n  }\n\n  /**\n   * Guarantee a cancel reaches a terminal state.\n   *\n   * Calling the service is a request, not an outcome: a runtime that has\n   * already forgotten the request answers nothing at all. The window still\n   * favours a real response, which carries the run's partial output.\n   */\n  private armCancelTimeout(requestId: string): void {\n    if (!this.pendingTasks.has(requestId)) return;\n    this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n      this.settleDetached(requestId, CANCELLED_STATE, {\n        status: CANCELLED_STATE,\n        error: ERR_CANCEL_UNACKNOWLEDGED,\n      });\n    });\n  }\n\n  private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n    this.clearTimer(requestId);\n    const timer = setTimeout(onFire, delayMs);\n    timer.unref?.();\n    this.timers.set(requestId, timer);\n  }\n\n  private clearTimer(requestId: string): void {\n    const timer = this.timers.get(requestId);\n    if (timer) clearTimeout(timer);\n    this.timers.delete(requestId);\n  }\n\n  /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n  private handleAccepted(event: DelegationAcceptedPayload): void {\n    if (!this.pendingTasks.has(event.requestId)) return;\n    this.armRunTimeout(event.requestId);\n  }\n\n  private handleStarted(event: DelegationStartedPayload): void {\n    const { runId } = event;\n    const taskId = this.pendingTasks.get(event.requestId)?.taskId;\n    if (taskId === undefined) return;\n    this.armRunTimeout(event.requestId);\n    const existing = this.progress.get(event.requestId);\n    if (existing) {\n      this.progress.set(event.requestId, {\n        ...existing,\n        durationMs: existing.durationMs ?? 0,\n        durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n      });\n    }\n\n    void this.options.store\n      .mutate((document) =>\n        this.patchDelegation(document, event.requestId, (task, delegation) => ({\n          ...task,\n          status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n          delegation: {\n            ...delegation,\n            state: 'running',\n            startedAt: delegation.startedAt ?? this.now(),\n            ...(runId ? { runId } : {}),\n          },\n        })),\n      )\n      .then(() => this.options.onChange?.())\n      .catch((error: unknown) => {\n        this.report(TASK_EVENT.delegationStartFailed, error, {\n          [TASK_ID_ATTRIBUTE]: taskId,\n          [REQUEST_ID_ATTRIBUTE]: event.requestId,\n        });\n      });\n  }\n\n  private handleUpdate(event: DelegationUpdate): void {\n    const existing = this.progress.get(event.requestId);\n    if (!existing) return;\n\n    const observedAt = this.nowMs();\n    const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n    const hasDuration = event.durationMs !== undefined;\n    this.progress.set(event.requestId, {\n      // Spread, not field-by-field: anything carried on progress that this\n      // event does not report (the assign-time context shape) must survive the\n      // first update, or the completion event reports it as absent.\n      ...existing,\n      currentTool: event.currentTool ?? existing.currentTool,\n      toolCount:\n        event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n      tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n      durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n      durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n    });\n    this.options.onChange?.();\n  }\n\n  private async handleResponse(event: DelegationResult): Promise<void> {\n    if (!this.pendingTasks.has(event.requestId)) return;\n\n    const succeeded = event.status === COMPLETED_STATE && !event.error;\n    const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n    await this.settle(event.requestId, state, {\n      status: event.status,\n      error: event.error,\n      output: truncate(event.output),\n      outputPath: event.outputPath,\n      sessionFile: event.sessionFile,\n      durationMs: event.durationMs,\n      toolCount: event.toolCount,\n    });\n  }\n\n  /**\n   * Apply the terminal state of a delegation and tell the model about it.\n   *\n   * A cancelled run returns the task to `pending` (the work is still wanted,\n   * just not by that agent); a failure marks it `failed` so it stays visible\n   * rather than silently rejoining the backlog.\n   *\n   * The request is claimed in `settlingRequests` while it remains published as\n   * active work. It is removed only after the terminal state and model notification\n   * have been handed off, so an auto-stop observer cannot end the session between\n   * receiving the result and delivering it to the model.\n   */\n  private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n    const pending = this.pendingTasks.get(requestId);\n    if (!pending || this.settlingRequests.has(requestId)) return;\n    this.settlingRequests.add(requestId);\n    this.clearTimer(requestId);\n    const { taskId } = pending;\n    const progress = this.progress.get(requestId);\n\n    try {\n      const endedAt = this.now();\n      let task: Task | undefined;\n      try {\n        const { value } = await this.options.store.mutate((document) =>\n          this.patchDelegation(document, requestId, (current, delegation) => ({\n            ...current,\n            status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n            updatedAt: endedAt,\n            delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n          })),\n        );\n        task = value;\n      } catch (error) {\n        this.report(TASK_EVENT.delegationSettleFailed, error, {\n          [TASK_ID_ATTRIBUTE]: taskId,\n          [REQUEST_ID_ATTRIBUTE]: requestId,\n        });\n      }\n\n      const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n      const subject = task?.subject ?? `#${taskId}`;\n\n      // Repeats the assign-time context shape so the cost question (\"did packs\n      // reduce child tool calls?\") is one grouping rather than a self-join.\n      // A run that never started reports neither metric, keeping the medians clean.\n      this.options.report?.event(TASK_EVENT.delegationCompleted, {\n        [TASK_ID_ATTRIBUTE]: taskId,\n        [REQUEST_ID_ATTRIBUTE]: requestId,\n        [AGENT_ATTRIBUTE]: agent,\n        [OUTCOME_ATTRIBUTE]: state,\n        [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n        [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n        [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n        ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n        ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n      });\n      const listComplete =\n        state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n      this.notifyModel(state, taskId, subject, agent, result, listComplete);\n    } finally {\n      this.pendingTasks.delete(requestId);\n      this.progress.delete(requestId);\n      this.settlingRequests.delete(requestId);\n      this.options.onChange?.();\n    }\n  }\n\n  private notifyModel(\n    state: SettlementState,\n    taskId: number,\n    subject: string,\n    agent: string,\n    result: TaskDelegation['result'],\n    listComplete: boolean,\n  ): void {\n    const notify = this.options.notify;\n    if (!notify) return;\n\n    const headline =\n      state === COMPLETED_STATE\n        ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n        : state === CANCELLED_STATE\n          ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n          : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n    const lines = [headline];\n    if (listComplete) {\n      lines.push(\n        '',\n        'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n      );\n    }\n    if (result?.error) lines.push(`Error: ${result.error}`);\n    if (result?.output) lines.push('', result.output);\n    if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n    try {\n      notify(\n        { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n        { triggerTurn: true, deliverAs: 'steer' },\n      );\n    } catch (error) {\n      // The delegation state is already committed to the store, so a failed\n      // notification costs the model its wake-up, not the result. Report it\n      // rather than rethrowing, which would strand the settled run.\n      this.options.onNotifyError(error, taskId);\n    }\n  }\n\n  /**\n   * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n   *\n   * Terminal delegations are left alone. The document here is the freshest one,\n   * read under the store lock, which is the only place the check is meaningful:\n   * a `started` event can land after a cancel already settled the run, and\n   * without this guard its write would resurrect a delegation that nothing is\n   * tracking any more.\n   */\n  private patchDelegation(\n    document: TaskDocument,\n    requestId: string,\n    patch: (task: Task, delegation: TaskDelegation) => Task,\n  ): { document?: TaskDocument; value: Task | undefined } {\n    const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n    if (index === -1) return { value: undefined };\n\n    const task = document.tasks[index];\n    if (!isDelegationActive(task)) return { value: task };\n\n    const updated = patch(task, task.delegation!);\n    if (updated === task) return { value: task };\n    const tasks = [...document.tasks];\n    tasks[index] = updated;\n    return { document: { ...document, tasks }, value: updated };\n  }\n\n  dispose(): void {\n    this.unbind();\n    this.reset();\n  }\n\n  /** Clear one Pi session's transient delegation state without losing service injection. */\n  reset(): void {\n    const changed = this.pendingTasks.size > 0 || this.progress.size > 0;\n    for (const timer of this.timers.values()) clearTimeout(timer);\n    this.timers.clear();\n    this.pendingTasks.clear();\n    this.settlingRequests.clear();\n    this.progress.clear();\n    if (changed) this.options.onChange?.();\n  }\n}\n","import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\n\nimport type { DelegationPlatform } from '../delegation';\n\nfunction formatBriefPath(entry: string, cwd: string): string {\n  if (!path.isAbsolute(entry)) return path.normalize(entry);\n  const relative = path.relative(cwd, entry);\n  // Outside the run directory the original beats a `../../` chain.\n  return relative && !relative.startsWith('..') ? relative : entry;\n}\n\n/** Supply Node-owned process and path facilities to the host-neutral manager. */\nexport function createNodeDelegationPlatform(\n  environment: Readonly<Record<string, string | undefined>> = process.env,\n): DelegationPlatform {\n  return {\n    environment,\n    processId: process.pid,\n    createRequestId: randomUUID,\n    formatBriefPath,\n  };\n}\n","import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-core/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n  try {\n    const output = execFileSync('git', args, {\n      cwd,\n      encoding: FILE_ENCODING,\n      stdio: ['ignore', 'pipe', 'ignore'],\n    });\n    const trimmed = output.trim();\n    return trimmed.length > 0 ? trimmed : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n  return new Promise((resolve) => {\n    execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n      if (error) {\n        resolve(undefined);\n        return;\n      }\n      const trimmed = stdout.trim();\n      resolve(trimmed.length > 0 ? trimmed : undefined);\n    });\n  });\n}\n\nfunction resolveAgentDirectory(env: Readonly<Record<string, string | undefined>>): string {\n  const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n  if (configured === HOME_ALIAS) return os.homedir();\n  if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n    return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n  }\n  return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n  const relative = path.relative(path.resolve(root), path.resolve(candidate));\n  return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(\n  rootSessionId: string,\n  env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n  if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n  const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n  if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n  return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n  _cwd: string = process.cwd(),\n  env: Readonly<Record<string, string | undefined>> = process.env,\n  sessionKey: string = 'standalone',\n): string {\n  const override = env[STORE_PATH_ENV]?.trim();\n  if (override) return path.resolve(override);\n\n  const trimmedSessionKey = sessionKey.trim();\n  if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n  return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n  return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n  const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n  return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n  const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n  return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n  removed: string[];\n  errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n  const result: StoreSweepResult = { removed: [], errors: [] };\n  const target = resolveLegacyStoreDirectory(cwd);\n  if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n  try {\n    if (!fs.existsSync(target)) return result;\n    fs.rmSync(target, { recursive: true, force: true });\n    result.removed.push(target);\n  } catch (error) {\n    result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n  }\n  return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n  currentStorePath: string,\n  cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n  const result: StoreSweepResult = { removed: [], errors: [] };\n  const target = await resolveLegacyStoreDirectoryAsync(cwd);\n  if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n  try {\n    await fs.promises.access(target);\n    await fs.promises.rm(target, { recursive: true, force: true });\n    result.removed.push(target);\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n      result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n    }\n  }\n  return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n  const result: StoreSweepResult = { removed: [], errors: [] };\n  const currentSessionDirectory = path.dirname(currentStorePath);\n  const storeDirectory = path.dirname(currentSessionDirectory);\n  let entries: string[];\n  try {\n    entries = fs.readdirSync(storeDirectory);\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n    result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n    return result;\n  }\n\n  for (const entry of entries) {\n    const sessionDirectory = path.join(storeDirectory, entry);\n    const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n    if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n    try {\n      if (fs.existsSync(lockPathFor(candidate))) continue;\n      JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n      if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n      fs.rmSync(sessionDirectory, { recursive: true, force: true });\n      result.removed.push(sessionDirectory);\n    } catch (error) {\n      result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n    }\n  }\n  return result;\n}\n\nexport async function sweepStoreFilesAsync(\n  currentStorePath: string,\n  ttlMs: number,\n  now: number = Date.now(),\n): Promise<StoreSweepResult> {\n  const result: StoreSweepResult = { removed: [], errors: [] };\n  const currentSessionDirectory = path.dirname(currentStorePath);\n  const storeDirectory = path.dirname(currentSessionDirectory);\n  let entries: string[];\n  try {\n    entries = await fs.promises.readdir(storeDirectory);\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n    result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n    return result;\n  }\n\n  for (const entry of entries) {\n    const sessionDirectory = path.join(storeDirectory, entry);\n    const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n    if (sessionDirectory === currentSessionDirectory) continue;\n    try {\n      await fs.promises.access(candidate);\n      try {\n        await fs.promises.access(lockPathFor(candidate));\n        continue;\n      } catch (error) {\n        if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n      }\n      JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n      if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n      await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n      result.removed.push(sessionDirectory);\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n      result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n    }\n  }\n  return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n  return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n  return `${storePath}.tmp.${pid}`;\n}\n","import type { Task, TaskStatus } from '../../models/task';\n\n/**\n * Collapse a malformed snapshot to one row per task id.\n *\n * Normal writes replace tasks in place, but older or externally edited stores\n * can contain both a stale and a current copy. Prefer the copy with the newest\n * ISO update timestamp; equal or missing timestamps use the later array entry.\n * The winning row keeps the id's original position so repair does not reorder\n * an otherwise stable task list.\n */\nexport function canonicalizeTasks(tasks: readonly Task[]): Task[] {\n  const canonical: Task[] = [];\n  const indexById = new Map<number, number>();\n\n  for (const task of tasks) {\n    const existingIndex = indexById.get(task.id);\n    if (existingIndex === undefined) {\n      indexById.set(task.id, canonical.length);\n      canonical.push(task);\n      continue;\n    }\n\n    const existing = canonical[existingIndex];\n    if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) {\n      canonical[existingIndex] = task;\n    }\n  }\n\n  return canonical;\n}\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n  pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n  in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n  failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n  completed: new Set<TaskStatus>(['deleted']),\n  deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n  if (from === to) return true;\n  return VALID_TRANSITIONS[from].has(to);\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;\n\nexport interface TaskStoreOptions {\n  cwd?: string;\n  env?: Readonly<Record<string, string | undefined>>;\n  storePath?: string;\n  onCommitted?: TaskStoreCommitListener;\n  /** How long to wait for the advisory lock before proceeding lock-free. */\n  lockTimeoutMs?: number;\n  /** Where swallowed failures go, so silent degradation stays visible. */\n  report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n  if (!parsed || typeof parsed !== 'object') return emptyDocument();\n  const candidate = parsed as Partial<TaskDocument>;\n  if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n  const tasks = canonicalizeTasks(\n    candidate.tasks.filter(\n      (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n    ),\n  );\n  const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n  return {\n    version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n    rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n    nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n    tasks,\n  };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n  storePath: string;\n\n  private readonly cwd: string;\n  private readonly env: Readonly<Record<string, string | undefined>>;\n  private cached: TaskDocument = emptyDocument();\n  private readonly listeners = new Set<(document: TaskDocument) => void>();\n  private readonly lockTimeoutMs: number;\n  private readonly report?: TaskFailureReporter;\n  private readonly onCommitted?: TaskStoreCommitListener;\n\n  constructor(options: TaskStoreOptions = {}) {\n    this.cwd = options.cwd ?? process.cwd();\n    this.env = options.env ?? process.env;\n    this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n    this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n    this.report = options.report;\n    this.onCommitted = options.onCommitted;\n  }\n\n  /** Bind a default store to the current session tree before reading it. */\n  configureSession(sessionKey: string): void {\n    if (this.env[STORE_PATH_ENV]?.trim()) return;\n    this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n    this.cached = emptyDocument();\n  }\n\n  /** Last document read from disk, without hitting the filesystem. */\n  get snapshot(): TaskDocument {\n    return this.cached;\n  }\n\n  read(): TaskDocument {\n    try {\n      const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n      this.cached = normalizeDocument(JSON.parse(raw));\n    } catch (error) {\n      // A missing file is the normal state before the first write. Anything\n      // else means the task list just silently became empty, which is worth a\n      // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n      if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n        this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n      }\n      this.cached = emptyDocument();\n    }\n    return this.cached;\n  }\n\n  async readAsync(shouldApply: () => boolean = () => true): Promise<TaskDocument> {\n    const storePath = this.storePath;\n    const document = await this.readDocumentAsync(storePath);\n    if (!shouldApply()) return document;\n    this.cached = document;\n    return document;\n  }\n\n  private async readDocumentAsync(storePath: string = this.storePath): Promise<TaskDocument> {\n    try {\n      const raw = await fs.promises.readFile(storePath, UTF8_ENCODING);\n      return normalizeDocument(JSON.parse(raw));\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n        this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });\n      }\n      return emptyDocument();\n    }\n  }\n\n  /**\n   * Apply a mutation under the store lock.\n   *\n   * `mutate` receives the freshest on-disk document and returns either the next\n   * document to commit or `undefined` for a read-only action (list/get), which\n   * skips the write entirely so queries never bump `rev`.\n   */\n  async mutate<T>(\n    mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n  ): Promise<{ document: TaskDocument; value: T }> {\n    const release = await this.acquireLock();\n    const outcome = (() => {\n      try {\n        const current = this.read();\n        const mutation = mutate(current);\n        if (!mutation.document) {\n          return { result: { document: current, value: mutation.value } };\n        }\n        const committed = this.write(mutation.document);\n        return {\n          result: { document: committed, value: mutation.value },\n          notification: { previous: current, committed },\n        };\n      } finally {\n        release();\n      }\n    })();\n    if (outcome.notification) {\n      this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);\n    }\n    return outcome.result;\n  }\n\n  private notifyCommitted(previous: TaskDocument, committed: TaskDocument): void {\n    try {\n      this.onCommitted?.(previous, committed);\n    } catch (error) {\n      this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n    }\n    for (const listener of this.listeners) {\n      try {\n        listener(committed);\n      } catch (error) {\n        this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n      }\n    }\n  }\n\n  private write(document: TaskDocument): TaskDocument {\n    const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n    fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n    const temp = tempPathFor(this.storePath);\n    fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n    fs.renameSync(temp, this.storePath);\n    this.cached = next;\n    return next;\n  }\n\n  private async acquireLock(): Promise<() => void> {\n    const lockPath = lockPathFor(this.storePath);\n    fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n    const deadline = Date.now() + this.lockTimeoutMs;\n\n    for (;;) {\n      try {\n        const handle = fs.openSync(lockPath, 'wx');\n        fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n        fs.closeSync(handle);\n        return () => fs.rmSync(lockPath, { force: true });\n      } catch (error) {\n        if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n        // The deadline is checked before breaking a stale lock so a peer that\n        // keeps recreating one cannot spin this loop without bound.\n        if (Date.now() >= deadline) {\n          // Proceeding lock-free beats stalling the agent: the rename is atomic,\n          // so the worst case is a lost concurrent update, not a corrupt file.\n          // Reported because a lost update here can strand a delegation.\n          this.report?.warn(\n            TASK_EVENT.storeLockTimeout,\n            new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n            { [STORE_PATH_ATTRIBUTE]: this.storePath },\n          );\n          return () => {};\n        }\n        // Clearing a dead holder's lock still goes through the backoff. Yielding\n        // on every iteration is what stops a peer that keeps recreating the\n        // lock from turning this into a spin.\n        this.breakStaleLock(lockPath);\n        await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n      }\n    }\n  }\n\n  /** Remove a lock left behind by a dead process or one held implausibly long. */\n  private breakStaleLock(lockPath: string): boolean {\n    try {\n      const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n      const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n      const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n      if (!expired && !dead) return false;\n      fs.unlinkSync(lockPath);\n      return true;\n    } catch (error) {\n      // Losing the race to another breaker is normal; a persistent failure here\n      // shows up as the lock timeout above, so this stays a warning.\n      if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n        this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n      }\n      return false;\n    }\n  }\n\n  /**\n   * Listen for commits made through this store instance.\n   *\n   * Live cross-process updates use the owning session's direct event bus. This\n   * listener remains for local terminal views and never watches the filesystem.\n   */\n  onExternalChange(listener: (document: TaskDocument) => void): () => void {\n    this.listeners.add(listener);\n    return () => this.listeners.delete(listener);\n  }\n\n  dispose(): void {\n    this.listeners.clear();\n  }\n}\n","export { COMMAND_NAME } from '../constants/task';\nimport { InlineAgentSchema } from '@agimon-ai/doompi-core/delegation';\nimport { type Static, Type } from 'typebox';\n\nimport type { TaskAction } from '../models/task';\nimport { MAX_BRIEF_FILES } from '../types/delegation';\n\nexport const TASK_ACTIONS = ['upsert', 'list', 'get', 'delete', 'clear', 'assign', 'cancel'] as const;\nexport const TASK_STATUSES = ['pending', 'in_progress', 'completed', 'failed', 'deleted'] as const;\nexport const TASK_CONTEXTS = ['fresh', 'fork'] as const;\n\nexport const TOOL_NAME = 'task';\nexport const TOOL_LABEL = 'Task';\n\nexport const ERR_REQUIRES_INTERACTIVE = '/tasks requires interactive mode';\nexport const MSG_NO_TASKS = 'No tasks yet. Ask the agent to add some!';\n\n/**\n * Which top-level fields each action accepts.\n *\n * The params object is flat and shared across every action, so the schema alone\n * cannot express \"upsert has no top-level id\". That gap matters: a call like\n * `{\"action\":\"upsert\",\"id\":3,\"tasks\":[{\"status\":\"completed\"}]}` would otherwise\n * silently create a duplicate task, because the entry itself carries no id.\n */\nexport const TASK_ACTION_FIELDS = {\n  upsert: ['action', 'tasks'],\n  list: ['action', 'status', 'includeDeleted'],\n  get: ['action', 'id'],\n  delete: ['action', 'id'],\n  clear: ['action'],\n  assign: ['action', 'assignments'],\n  cancel: ['action', 'id'],\n} as const satisfies Record<TaskAction, readonly string[]>;\n\nexport function taskActionAcceptsField(action: TaskAction, field: string): boolean {\n  return (TASK_ACTION_FIELDS[action] as readonly string[]).includes(field);\n}\n\n/** Correction hint appended when a per-task field lands at the top level. */\nexport const MSG_UPSERT_FIELD_MISPLACED =\n  'Per-task fields belong inside each tasks[] entry, not at the top level: {\"action\":\"upsert\",\"tasks\":[{\"id\":3,\"status\":\"completed\"}]}.';\n\n/**\n * A dependency target: an existing task id, or the `ref` of a task created\n * earlier in the same call.\n */\nconst DepTokenSchema = Type.Union([Type.Integer(), Type.String()]);\n\n/**\n * One entry of an upsert. `additionalProperties: false` is load-bearing: pi\n * validates tool arguments against this schema before `execute` runs, so a\n * stray `{\"action\":\"update\"}` inside an entry is rejected at the boundary.\n */\nexport const TaskItemSchema = Type.Object(\n  {\n    id: Type.Optional(\n      Type.Integer({\n        description:\n          'Existing task id to change. Omit to create. An unknown id fails only that entry; it never creates.',\n      }),\n    ),\n    ref: Type.Optional(\n      Type.String({\n        description:\n          'Temporary name for a task created by this entry, so a LATER entry in this array can list it in blockedBy. Must start with a letter; never stored.',\n      }),\n    ),\n    subject: Type.Optional(\n      Type.String({\n        description: 'Short imperative subject. Required when the entry has no id; on an entry with an id it renames.',\n      }),\n    ),\n    description: Type.Optional(\n      Type.String({ description: 'Long-form detail; becomes the brief handed to the subagent on assign.' }),\n    ),\n    activeForm: Type.Optional(\n      Type.String({ description: \"Present-continuous label shown while in_progress (e.g. 'writing tests')\" }),\n    ),\n    status: Type.Optional(\n      Type.String({\n        enum: [...TASK_STATUSES],\n        description:\n          'New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal.',\n      }),\n    ),\n    blockedBy: Type.Optional(\n      Type.Array(DepTokenSchema, {\n        description:\n          'Dependencies for a NEW entry: task ids, or refs of tasks created EARLIER in this array. On an entry with an id use addBlockedBy / removeBlockedBy instead.',\n      }),\n    ),\n    addBlockedBy: Type.Optional(\n      Type.Array(DepTokenSchema, {\n        description: 'Dependencies to add (ids or earlier refs). Additive; do not resend the full array.',\n      }),\n    ),\n    removeBlockedBy: Type.Optional(\n      Type.Array(DepTokenSchema, {\n        description: 'Dependencies to remove. Additive; do not resend the full array.',\n      }),\n    ),\n    owner: Type.Optional(Type.String({ description: 'Owner label; assign sets it to the subagent name.' })),\n    metadata: Type.Optional(\n      Type.Record(Type.String(), Type.Unknown(), {\n        description: 'Merged into the task; a null value deletes that key.',\n      }),\n    ),\n  },\n  { additionalProperties: false },\n);\n\n/** One task-to-agent handoff in a native assignment batch. */\nexport const TaskAssignmentSchema = Type.Object(\n  {\n    id: Type.Integer({ description: 'Pending, unblocked task id to delegate' }),\n    agent: Type.String({ description: 'Exact discovered subagent name' }),\n    inlineAgent: Type.Optional(InlineAgentSchema),\n    instructions: Type.Optional(Type.String({ description: 'Extra instructions appended to this delegated brief' })),\n    relevantFiles: Type.Optional(\n      Type.Array(Type.String(), {\n        description: `Files already read or located, relative to the working directory; at most ${MAX_BRIEF_FILES} are used.`,\n      }),\n    ),\n    priorFindings: Type.Optional(\n      Type.String({ description: 'Established facts this child should consume rather than re-derive' }),\n    ),\n    model: Type.Optional(Type.String({ description: 'Model override for this delegated run' })),\n    context: Type.Optional(\n      Type.String({\n        enum: [...TASK_CONTEXTS],\n        description: \"Starting context for this child: 'fresh' or 'fork'\",\n      }),\n    ),\n  },\n  { additionalProperties: false },\n);\n\n/**\n * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so\n * wording changes here change model behaviour.\n */\nexport const TaskParamsSchema = Type.Object({\n  action: Type.String({ enum: [...TASK_ACTIONS] }),\n  tasks: Type.Optional(\n    Type.Array(TaskItemSchema, {\n      minItems: 1,\n      description:\n        'upsert only. An entry with an id changes that task, an entry without an id creates one. Entries apply in array order, so a later entry can depend on an earlier one by ref.',\n    }),\n  ),\n  assignments: Type.Optional(\n    Type.Array(TaskAssignmentSchema, {\n      minItems: 1,\n      description: 'Required for assign, one entry per task, including when there is only one.',\n    }),\n  ),\n  id: Type.Optional(\n    Type.Integer({\n      description:\n        'Task id, for get, delete and cancel. Not accepted by upsert or assign: those carry ids inside tasks[] and assignments[] entries.',\n    }),\n  ),\n  status: Type.Optional(\n    Type.String({\n      enum: [...TASK_STATUSES],\n      description: 'list only: return just the tasks in this status. To SET a status, upsert the task by id.',\n    }),\n  ),\n  includeDeleted: Type.Optional(\n    Type.Boolean({ description: 'list only: also return deleted tombstones. Default false.' }),\n  ),\n});\n\nexport type TaskItemParams = Static<typeof TaskItemSchema>;\nexport type TaskAssignmentParams = Static<typeof TaskAssignmentSchema>;\nexport type TaskParams = Static<typeof TaskParamsSchema>;\n","import {\n  DELETED_STATUS,\n  type DepToken,\n  isDelegationActive,\n  type Task,\n  type TaskAction,\n  type TaskDocument,\n  type TaskItemMutation,\n  type TaskMutationParams,\n  type TaskStatus,\n  type UpsertItemOutcome,\n} from '../../models/task';\nimport { detectCycle } from '../../models/taskGraph';\nimport { isTransitionValid } from '../invariants';\n\n/** Default board capacity when a caller does not provide a configured limit. */\nconst DEFAULT_REDUCER_MAX_TASKS = 15;\n\n/** Bounds the work one call can do, and with it the size of one committed write. */\nexport const MAX_UPSERT_ITEMS = 100;\n\n/**\n * A ref must start with a letter, which makes it structurally unconfusable with\n * a stringified id. That is why resolving a dependency token is just a `typeof`\n * check with no coercion heuristics.\n */\nexport const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;\n\n/**\n * Reducer outcome. Closed tagged union: adding an action requires extending\n * this union and the response formatter, which the compiler enforces.\n *\n * `upsert` carries one outcome per request item. It is returned even when every\n * item failed — `error` is reserved for whole-call faults — so the tool layer\n * still has the per-item messages to report.\n */\nexport type Op =\n  | { kind: 'upsert'; items: UpsertItemOutcome[]; applied: number; failed: number }\n  | { kind: 'delete'; id: number; subject: string }\n  | { kind: 'list'; statusFilter?: TaskStatus; includeDeleted: boolean }\n  | { kind: 'get'; task: Task }\n  | { kind: 'clear'; count: number }\n  | { kind: 'error'; message: string };\n\nexport interface ApplyResult {\n  document: TaskDocument;\n  op: Op;\n}\n\n/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */\nexport type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;\n\n/**\n * Does this op represent state that must reach disk?\n *\n * The exhaustive switch is the point: a future `Op` variant cannot be added\n * without declaring its persistence intent, so nothing silently starts or stops\n * bumping `rev`.\n */\nexport function isCommittingOp(op: Op): boolean {\n  switch (op.kind) {\n    case 'error':\n    case 'list':\n    case 'get':\n      return false;\n    case 'upsert':\n      return op.items.some((item) => item.kind === 'created' || item.kind === 'updated');\n    case 'delete':\n    case 'clear':\n      return true;\n  }\n}\n\n/** Joined per-item failures, for the thrown error when an upsert applied nothing. */\nexport function formatUpsertFailure(op: Extract<Op, { kind: 'upsert' }>): string {\n  return op.items\n    .filter((item) => item.kind === 'failed')\n    .map((item) => `item[${item.index}]: ${item.message}`)\n    .join('\\n');\n}\n\n/** The single item's outcome, for callers that only ever send a batch of one. */\nexport function singleItemOutcome(op: Op): UpsertItemOutcome | undefined {\n  return op.kind === 'upsert' ? op.items[0] : undefined;\n}\n\nfunction errorResult(document: TaskDocument, message: string): ApplyResult {\n  return { document, op: { kind: 'error', message } };\n}\n\nfunction sameNumberList(a: number[] | undefined, b: number[] | undefined): boolean {\n  const x = a ?? [];\n  const y = b ?? [];\n  return x.length === y.length && x.every((value, index) => value === y[index]);\n}\n\nfunction sameRecord(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n  return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n}\n\n/**\n * Did this update change anything? A no-effect update (status re-set to its\n * current value, fields re-sent unchanged) reports \"No change\" rather than\n * \"Updated #N\" — without the distinction a model can loop re-issuing the same\n * call believing it never landed.\n */\nfunction taskChanged(before: Task, after: Task): boolean {\n  return (\n    before.subject !== after.subject ||\n    before.status !== after.status ||\n    before.description !== after.description ||\n    before.activeForm !== after.activeForm ||\n    before.owner !== after.owner ||\n    !sameNumberList(before.blockedBy, after.blockedBy) ||\n    !sameRecord(before.metadata, after.metadata)\n  );\n}\n\nfunction withTasks(document: TaskDocument, tasks: Task[], nextId = document.nextId): TaskDocument {\n  return { ...document, tasks, nextId };\n}\n\n/** Merge incoming metadata over a base; a `null` value deletes its key. */\nfunction mergeMetadata(\n  base: Record<string, unknown> | undefined,\n  incoming: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n  const merged: Record<string, unknown> = { ...base };\n  for (const [key, value] of Object.entries(incoming)) {\n    if (value === null) delete merged[key];\n    else merged[key] = value;\n  }\n  return Object.keys(merged).length ? merged : undefined;\n}\n\n/** Copy the optional scalar fields an item may set onto a task, in place. */\nfunction assignScalars(target: Task, item: TaskItemMutation): void {\n  if (item.subject !== undefined) target.subject = item.subject;\n  if (item.description !== undefined) target.description = item.description;\n  if (item.activeForm !== undefined) target.activeForm = item.activeForm;\n  if (item.owner !== undefined) target.owner = item.owner;\n  if (item.metadata !== undefined) {\n    const merged = mergeMetadata(target.metadata, item.metadata);\n    if (merged === undefined) delete target.metadata;\n    else target.metadata = merged;\n  }\n}\n\n/**\n * Working state threaded item to item, so entry N observes every effect of\n * entries 1..N-1. `refIds` and `failedRefs` are what make the cascade work:\n * refs resolve backward only, so an entry that names a failed sibling is always\n * processed after the failure that killed it.\n */\ninterface UpsertContext {\n  tasks: Task[];\n  nextId: number;\n  maxTasks: number;\n  refIds: Map<string, number>;\n  failedRefs: Map<string, number>;\n}\n\ntype Resolved = { ok: true; id: number } | { ok: false; message: string };\n\nfunction resolveDep(context: UpsertContext, field: string, token: DepToken): Resolved {\n  if (typeof token === 'number') return { ok: true, id: token };\n  if (!REF_PATTERN.test(token)) {\n    return { ok: false, message: `${field}: \"${token}\" is not a valid ref; pass an existing task id as a number` };\n  }\n  const id = context.refIds.get(token);\n  if (id !== undefined) return { ok: true, id };\n  const failedAt = context.failedRefs.get(token);\n  if (failedAt !== undefined) {\n    return { ok: false, message: `${field}: ref \"${token}\" refers to item[${failedAt}], which failed` };\n  }\n  return {\n    ok: false,\n    message: `${field}: unknown ref \"${token}\" — a ref must be declared by an earlier entry in the same call`,\n  };\n}\n\ntype ItemResult = { ok: true; outcome: UpsertItemOutcome } | { ok: false; message: string };\n\nfunction fail(message: string): ItemResult {\n  return { ok: false, message };\n}\n\n/** Structural checks that apply to every entry, whichever kind it is. */\nfunction checkShape(context: UpsertContext, item: TaskItemMutation): string | undefined {\n  if (item.ref !== undefined) {\n    if (item.id !== undefined) return 'ref is only valid when creating a task; drop the id, or drop the ref';\n    if (!REF_PATTERN.test(item.ref)) {\n      return `ref \"${item.ref}\" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;\n    }\n    const owner = context.refIds.get(item.ref) !== undefined || context.failedRefs.has(item.ref);\n    if (owner) return `duplicate ref \"${item.ref}\": it was already declared by an earlier entry`;\n  }\n  return undefined;\n}\n\nfunction applyCreateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n  if (item.subject === undefined) return fail('subject is required when the entry has no id');\n  if (!item.subject.trim()) return fail('subject must not be blank');\n  if (item.addBlockedBy !== undefined || item.removeBlockedBy !== undefined) {\n    return fail('addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy');\n  }\n  // A task created as a tombstone is invisible to every view and can never\n  // leave `deleted`, so it would be a write-only black hole.\n  if (item.status === DELETED_STATUS) {\n    return fail('cannot create a task with status deleted; create it, then use action delete');\n  }\n\n  const taskCount = context.tasks.filter((task) => task.status !== DELETED_STATUS).length;\n  if (taskCount >= context.maxTasks) {\n    return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);\n  }\n\n  const blockedBy: number[] = [];\n  for (const token of item.blockedBy ?? []) {\n    const resolved = resolveDep(context, 'blockedBy', token);\n    if (!resolved.ok) return fail(resolved.message);\n    const dep = context.tasks.find((task) => task.id === resolved.id);\n    if (!dep) return fail(`blockedBy: #${resolved.id} not found`);\n    if (dep.status === DELETED_STATUS) return fail(`blockedBy: #${resolved.id} is deleted`);\n    if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);\n  }\n\n  // No cycle check is needed: the id is freshly allocated, so nothing already\n  // in the document can point at it yet.\n  const created: Task = {\n    id: context.nextId,\n    subject: item.subject,\n    status: item.status ?? 'pending',\n    createdAt: now,\n    updatedAt: now,\n  };\n  assignScalars(created, item);\n  if (blockedBy.length) created.blockedBy = blockedBy;\n\n  context.nextId += 1;\n  context.tasks.push(created);\n  if (item.ref) context.refIds.set(item.ref, created.id);\n\n  return {\n    ok: true,\n    outcome: {\n      index,\n      kind: 'created',\n      id: created.id,\n      subject: created.subject,\n      status: created.status,\n      ...(item.ref ? { ref: item.ref } : {}),\n      ...(blockedBy.length ? { blockedBy } : {}),\n    },\n  };\n}\n\nfunction applyUpdateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n  const id = item.id as number;\n  const at = context.tasks.findIndex((task) => task.id === id);\n  if (at === -1) return fail(`#${id} not found`);\n  if (item.blockedBy !== undefined) {\n    return fail('blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id');\n  }\n\n  const hasMutation =\n    item.subject !== undefined ||\n    item.description !== undefined ||\n    item.activeForm !== undefined ||\n    item.status !== undefined ||\n    item.owner !== undefined ||\n    item.metadata !== undefined ||\n    Boolean(item.addBlockedBy?.length) ||\n    Boolean(item.removeBlockedBy?.length);\n  if (!hasMutation) {\n    return fail(\n      'nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy',\n    );\n  }\n\n  const current = context.tasks[at];\n\n  // The Task Space overlay commits free text from an inline editor, so a blank\n  // subject reaches the reducer as a real update rather than as a missing\n  // field. Persisting it would leave an unidentifiable row.\n  if (item.subject !== undefined && !item.subject.trim()) return fail('subject must not be blank');\n\n  let newStatus = current.status;\n  if (item.status !== undefined) {\n    if (!isTransitionValid(current.status, item.status)) {\n      return fail(`illegal transition ${current.status} -> ${item.status}`);\n    }\n    newStatus = item.status;\n  }\n\n  let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];\n  for (const token of item.removeBlockedBy ?? []) {\n    const resolved = resolveDep(context, 'removeBlockedBy', token);\n    if (!resolved.ok) return fail(resolved.message);\n    // Removing an id that is not there is a well-defined no-op, so unlike the\n    // add path this deliberately skips the existence check.\n    newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);\n  }\n  for (const token of item.addBlockedBy ?? []) {\n    const resolved = resolveDep(context, 'addBlockedBy', token);\n    if (!resolved.ok) return fail(resolved.message);\n    if (resolved.id === id) return fail(`cannot block #${id} on itself`);\n    const dep = context.tasks.find((task) => task.id === resolved.id);\n    if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);\n    if (dep.status === DELETED_STATUS) return fail(`addBlockedBy: #${resolved.id} is deleted`);\n    if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);\n  }\n\n  const updated: Task = { ...current, status: newStatus };\n  assignScalars(updated, item);\n  if (newBlockedBy.length) updated.blockedBy = newBlockedBy;\n  else delete updated.blockedBy;\n\n  // The candidate is written before the check because `detectCycle` unions the\n  // node's stored edges with the ones passed in: checking against the old array\n  // would resurrect an edge `removeBlockedBy` just stripped and reject a\n  // remove+add that legitimately breaks a cycle.\n  const candidate = [...context.tasks];\n  candidate[at] = updated;\n  if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) {\n    return fail('addBlockedBy would create a cycle in the blockedBy graph');\n  }\n\n  const changed = taskChanged(current, updated);\n  if (changed) updated.updatedAt = now;\n  context.tasks = candidate;\n\n  return {\n    ok: true,\n    outcome: changed\n      ? { index, kind: 'updated', id, fromStatus: current.status, toStatus: newStatus }\n      : { index, kind: 'unchanged', id, status: newStatus },\n  };\n}\n\n/**\n * Apply every entry in request order, threading the document.\n *\n * Each entry lands completely or not at all: a create whose dependencies fail\n * is not kept dependency-free, because handing back an unblocked task the\n * caller asked to be blocked is a lie it may immediately act on.\n */\nfunction applyUpsert(document: TaskDocument, items: TaskItemMutation[], now: string, maxTasks: number): ApplyResult {\n  const context: UpsertContext = {\n    tasks: [...document.tasks],\n    nextId: document.nextId,\n    maxTasks,\n    refIds: new Map(),\n    failedRefs: new Map(),\n  };\n  const outcomes: UpsertItemOutcome[] = [];\n  let applied = 0;\n\n  for (const [index, item] of items.entries()) {\n    const shapeError = checkShape(context, item);\n    const result = shapeError\n      ? fail(shapeError)\n      : item.id === undefined\n        ? applyCreateItem(context, item, index, now)\n        : applyUpdateItem(context, item, index, now);\n\n    if (result.ok) {\n      outcomes.push(result.outcome);\n      applied += 1;\n      continue;\n    }\n    // A ref whose owner failed must not read as a typo to the entries that\n    // depend on it, so the dead ref is recorded rather than left unknown.\n    if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) {\n      context.failedRefs.set(item.ref, index);\n    }\n    outcomes.push({\n      index,\n      kind: 'failed',\n      message: result.message,\n      ...(item.id === undefined ? {} : { id: item.id }),\n      ...(item.ref ? { ref: item.ref } : {}),\n    });\n  }\n\n  return {\n    // Nothing applied means nothing to write: returning the original object by\n    // reference keeps the caller's write-skip path identical to a hard error.\n    document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,\n    op: { kind: 'upsert', items: outcomes, applied, failed: outcomes.length - applied },\n  };\n}\n\n/**\n * Pure reducer: (document, action, params) -> (document, op).\n *\n * All validation is in-line: structural guards plus state-aware checks\n * (transition legality, dangling or deleted blockedBy, self-block, cycles,\n * in-flight delegations). The caller owns persistence and formatting.\n */\nexport function applyTaskMutation(\n  document: TaskDocument,\n  action: ReducerAction,\n  params: TaskMutationParams,\n  now: string = new Date().toISOString(),\n  maxTasks = DEFAULT_REDUCER_MAX_TASKS,\n): ApplyResult {\n  switch (action) {\n    case 'upsert': {\n      const items = params.tasks;\n      if (!Array.isArray(items) || items.length === 0) {\n        return errorResult(\n          document,\n          'upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}',\n        );\n      }\n      if (items.length > MAX_UPSERT_ITEMS) {\n        return errorResult(\n          document,\n          `upsert accepts at most ${MAX_UPSERT_ITEMS} entries per call (received ${items.length})`,\n        );\n      }\n      return applyUpsert(document, items, now, maxTasks);\n    }\n\n    case 'list': {\n      return {\n        document,\n        op: {\n          kind: 'list',\n          includeDeleted: params.includeDeleted === true,\n          ...(params.status !== undefined ? { statusFilter: params.status } : {}),\n        },\n      };\n    }\n\n    case 'get': {\n      if (params.id === undefined) return errorResult(document, 'id required for get');\n      const task = document.tasks.find((candidate) => candidate.id === params.id);\n      if (!task) return errorResult(document, `#${params.id} not found`);\n      return { document, op: { kind: 'get', task } };\n    }\n\n    case 'delete': {\n      if (params.id === undefined) return errorResult(document, 'id required for delete');\n      const index = document.tasks.findIndex((task) => task.id === params.id);\n      if (index === -1) return errorResult(document, `#${params.id} not found`);\n      const current = document.tasks[index];\n      if (current.status === DELETED_STATUS) return errorResult(document, `#${current.id} is already deleted`);\n      if (isDelegationActive(current)) {\n        return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);\n      }\n\n      const tasks = [...document.tasks];\n      tasks[index] = { ...current, status: DELETED_STATUS, updatedAt: now };\n      return {\n        document: withTasks(document, tasks),\n        op: { kind: 'delete', id: current.id, subject: current.subject },\n      };\n    }\n\n    case 'clear': {\n      const active = document.tasks.filter(isDelegationActive);\n      if (active.length > 0) {\n        const ids = active.map((task) => `#${task.id}`).join(', ');\n        return errorResult(document, `cannot clear while delegations are running (${ids}) — cancel them first`);\n      }\n      const count = document.tasks.length;\n      return {\n        document: withTasks(document, [], 1),\n        op: { kind: 'clear', count },\n      };\n    }\n  }\n}\n","import type {\n  AssignmentSummary,\n  Task,\n  TaskAction,\n  TaskDetails,\n  TaskDocument,\n  TaskMutationParams,\n  UpsertItemOutcome,\n} from '../../models/task';\nimport { deriveBlocks, isTaskListComplete } from '../../models/taskGraph';\nimport type { Op } from '../reducer';\n\nexport const MSG_ALL_COMPLETE_CLEAR =\n  'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.';\n\n/**\n * Steering for a mixed batch. Unlike a batch of spawned subagents, a failed\n * entry here had no side effect at all, so retrying the failures is the safe\n * move and the model must be told so or it will do nothing. The hazard is the\n * other half: resending an applied create would make a second task.\n */\nexport const MSG_UPSERT_PARTIAL =\n  'The applied entries are committed. Resend only the failed entries, corrected — a failed entry changed nothing, so a corrected retry is safe. Do not resend an entry that already applied: an entry without an id creates a second task.';\n\nexport const MSG_UPSERT_NONE_APPLIED = 'No task changed, so the whole call can be resent once corrected.';\n\nexport const MSG_ASSIGN_PARTIAL =\n  'Successful assignments are already running. Retry only the failed entries after correcting their task state or arguments; do not resend successful entries.';\n\nexport interface AssignmentItemResult {\n  index: number;\n  id: number;\n  agent: string;\n  ok: boolean;\n  message: string;\n}\n\n/** LLM-facing report for a native assignment batch. */\nexport function formatAssignmentResults(items: readonly AssignmentItemResult[]): string {\n  if (items.length === 1) return items[0].message;\n\n  const succeeded = items.filter((item) => item.ok).length;\n  const failed = items.length - succeeded;\n  const lines = [\n    `Assigned ${succeeded}/${items.length} tasks${failed > 0 ? `; ${failed} failed` : ''}.`,\n    ...items.map((item) =>\n      item.ok\n        ? `- [${item.index}] Delegated #${item.id} to ${item.agent}`\n        : `- [${item.index}] Failed #${item.id} → ${item.agent}: ${item.message}`,\n    ),\n  ];\n\n  if (failed > 0 && succeeded > 0) lines.push('', MSG_ASSIGN_PARTIAL);\n  if (failed === 0) {\n    lines.push(\n      '',\n      'All assignments are running independently in the background. Continue non-overlapping work, or end your turn.',\n    );\n  }\n  return lines.join('\\n');\n}\n\n/** `[status] #id subject (activeForm) [agent] ⛓ #dep` — the `list` line format. */\nfunction formatListLine(task: Task): string {\n  const block = task.blockedBy?.length ? ` ⛓ ${task.blockedBy.map((id) => `#${id}`).join(',')}` : '';\n  const form = task.status === 'in_progress' && task.activeForm ? ` (${task.activeForm})` : '';\n  const delegated = task.delegation && task.delegation.state !== 'cancelled' ? ` [${task.delegation.agent}]` : '';\n  return `[${task.status}] #${task.id} ${task.subject}${form}${delegated}${block}`;\n}\n\nfunction formatDelegationLines(task: Task): string[] {\n  const delegation = task.delegation;\n  if (!delegation) return [];\n\n  const lines = [`  delegated to: ${delegation.agent} (${delegation.state})`];\n  if (delegation.model) lines.push(`  model: ${delegation.model}`);\n  if (delegation.result?.error) lines.push(`  error: ${delegation.result.error}`);\n  if (delegation.result?.outputPath) lines.push(`  output file: ${delegation.result.outputPath}`);\n  if (delegation.result?.output) lines.push(`  output: ${delegation.result.output}`);\n  return lines;\n}\n\nfunction formatGetLines(task: Task, document: TaskDocument): string {\n  const blocks = deriveBlocks(document.tasks).get(task.id) ?? [];\n  const lines = [`#${task.id} [${task.status}] ${task.subject}`];\n  if (task.description) lines.push(`  description: ${task.description}`);\n  if (task.activeForm) lines.push(`  activeForm: ${task.activeForm}`);\n  if (task.blockedBy?.length) lines.push(`  blockedBy: ${task.blockedBy.map((id) => `#${id}`).join(', ')}`);\n  if (blocks.length) lines.push(`  blocks: ${blocks.map((id) => `#${id}`).join(', ')}`);\n  if (task.owner) lines.push(`  owner: ${task.owner}`);\n  lines.push(...formatDelegationLines(task));\n  return lines.join('\\n');\n}\n\n/** One entry's outcome. Batch lines prefix this with `- [n] `. */\nfunction formatUpsertItem(item: UpsertItemOutcome): string {\n  switch (item.kind) {\n    case 'created': {\n      const ref = item.ref ? ` (ref \"${item.ref}\")` : '';\n      const deps = item.blockedBy?.length ? ` — blocked by ${item.blockedBy.map((id) => `#${id}`).join(', ')}` : '';\n      return `Created #${item.id}${ref}: ${item.subject} (${item.status})${deps}`;\n    }\n    case 'updated': {\n      const transition = item.fromStatus === item.toStatus ? '' : ` (${item.fromStatus} -> ${item.toStatus})`;\n      return `Updated #${item.id}${transition}`;\n    }\n    case 'unchanged':\n      return `No change: #${item.id} already matches the requested values (status: ${item.status})`;\n    case 'failed':\n      return `Failed${item.id === undefined ? '' : ` #${item.id}`}: ${item.message}`;\n  }\n}\n\n/**\n * The thrown message when an upsert applied nothing. Kept separate from\n * `formatContent` because the caller wraps it in the actionable Options block\n * rather than returning it as a successful result.\n */\nexport function formatUpsertFailureText(op: Extract<Op, { kind: 'upsert' }>): string {\n  if (op.items.length === 1) return op.items[0].kind === 'failed' ? op.items[0].message : 'no entry was applied';\n  return [\n    'no entry was applied.',\n    ...op.items.map((item) => `- [${item.index}] ${formatUpsertItem(item)}`),\n    MSG_UPSERT_NONE_APPLIED,\n  ].join('\\n');\n}\n\n/**\n * Pure formatter: `(op, document) -> string`. The switch is closed over `Op`,\n * so a new reducer variant fails to compile until it is handled here.\n */\nexport function formatContent(op: Op, document: TaskDocument): string {\n  switch (op.kind) {\n    case 'upsert': {\n      // A batch of one is the common case and must not read like a bulk\n      // report, so it keeps the exact single-line shape it has always had.\n      const lines =\n        op.items.length === 1\n          ? [formatUpsertItem(op.items[0])]\n          : [\n              `Upsert applied ${op.applied}/${op.items.length} entries${op.failed > 0 ? `; ${op.failed} failed` : ''}.`,\n              ...op.items.map((item) => `- [${item.index}] ${formatUpsertItem(item)}`),\n              ...(op.failed > 0 ? ['', MSG_UPSERT_PARTIAL] : []),\n            ];\n      // Once, last, and only when something landed: emitting it per entry\n      // would repeat it for every completion in a batch.\n      if (op.applied > 0 && isTaskListComplete(document.tasks)) lines.push(MSG_ALL_COMPLETE_CLEAR);\n      return lines.join('\\n');\n    }\n    case 'delete':\n      return `Deleted #${op.id}: ${op.subject}`;\n    case 'clear':\n      return `Closed task list (cleared ${op.count} tasks)`;\n    case 'list': {\n      let view = document.tasks;\n      if (!op.includeDeleted) view = view.filter((task) => task.status !== 'deleted');\n      if (op.statusFilter) view = view.filter((task) => task.status === op.statusFilter);\n      return view.length === 0 ? 'No tasks' : view.map(formatListLine).join('\\n');\n    }\n    case 'get':\n      return formatGetLines(op.task, document);\n    case 'error':\n      return `Error: ${op.message}`;\n  }\n}\n\nexport interface ToolResult {\n  content: Array<{ type: 'text'; text: string }>;\n  details: TaskDetails;\n}\n\n/** Build the LLM-facing envelope. `details` carries the post-mutation snapshot. */\nexport function buildToolResult(\n  action: TaskAction,\n  params: TaskMutationParams,\n  document: TaskDocument,\n  op: Op,\n): ToolResult {\n  return {\n    content: [{ type: 'text', text: formatContent(op, document) }],\n    details: {\n      action,\n      params: params as Record<string, unknown>,\n      tasks: document.tasks,\n      nextId: document.nextId,\n      rev: document.rev,\n      ...(op.kind === 'error' ? { error: op.message } : {}),\n      // Deliberately no `error` on a partial success: renderResult treats\n      // `details.error` as total failure and would hide the rows for the\n      // entries that did land.\n      ...(op.kind === 'upsert'\n        ? {\n            upsert: {\n              applied: op.items.flatMap((item) => (item.kind === 'failed' ? [] : [item.id])),\n              failed: op.failed,\n            },\n          }\n        : {}),\n    },\n  };\n}\n\n/** Envelope for a native assignment batch, including ids used by the consolidated TUI result. */\nexport function buildAssignmentResult(\n  params: TaskMutationParams,\n  document: TaskDocument,\n  text: string,\n  assignment: AssignmentSummary,\n): ToolResult {\n  return {\n    content: [{ type: 'text', text }],\n    details: {\n      action: 'assign',\n      params: params as Record<string, unknown>,\n      tasks: document.tasks,\n      nextId: document.nextId,\n      rev: document.rev,\n      assignment,\n    },\n  };\n}\n\n/** Envelope for delegation actions, which do not flow through the reducer. */\nexport function buildTextResult(\n  action: TaskAction,\n  params: TaskMutationParams,\n  document: TaskDocument,\n  text: string,\n  error?: string,\n): ToolResult {\n  return {\n    content: [{ type: 'text', text: error ? `Error: ${error}` : text }],\n    details: {\n      action,\n      params: params as Record<string, unknown>,\n      tasks: document.tasks,\n      nextId: document.nextId,\n      rev: document.rev,\n      ...(error ? { error } : {}),\n    },\n  };\n}\n","import type { DoomHeadlessTool, DoomHeadlessToolResult } from '@agimon-ai/doompi-core/headless';\nimport { Check } from 'typebox/value';\n\nimport type { TaskMutationParams } from '../../models/task';\nimport { TaskParamsSchema, type TaskParams, type TaskAssignmentParams } from '../../schemas/task';\nimport type { DelegationManager } from '../delegation';\nimport { applyTaskMutation, isCommittingOp, type ReducerAction } from '../reducer';\nimport { buildAssignmentResult, buildTextResult, buildToolResult, formatAssignmentResults } from '../taskResult';\nimport type { TaskStore } from '../taskStore';\n\nfunction output(value: unknown): DoomHeadlessToolResult {\n  if (typeof value === 'object' && value !== null && 'content' in value) return value as DoomHeadlessToolResult;\n  const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);\n  return { content: [{ type: 'text', text }], details: value };\n}\n\nfunction failure(error: unknown): DoomHeadlessToolResult {\n  return { content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], isError: true };\n}\n\nexport async function reducerAction(\n  store: TaskStore,\n  action: ReducerAction,\n  params: TaskMutationParams,\n  maxTasks: number,\n): Promise<DoomHeadlessToolResult> {\n  const { document, value } = await store.mutate((current) => {\n    const result = applyTaskMutation(current, action, params, undefined, maxTasks);\n    return { ...(isCommittingOp(result.op) ? { document: result.document } : {}), value: result };\n  });\n  if (value.op.kind === 'error') throw new Error(value.op.message);\n  return buildToolResult(action, params, document, value.op);\n}\n\ninterface AssignmentItemResult {\n  index: number;\n  id: number;\n  agent: string;\n  ok: boolean;\n  message: string;\n}\n\nasync function assignmentBatch(\n  manager: DelegationManager,\n  assignments: readonly TaskAssignmentParams[],\n  signal?: AbortSignal,\n): Promise<AssignmentItemResult[]> {\n  const result: AssignmentItemResult[] = [];\n  for (const [index, assignment] of assignments.entries()) {\n    try {\n      const outcome = await manager.assign(assignment.id, {\n        agent: assignment.agent,\n        inlineAgent: assignment.inlineAgent,\n        instructions: assignment.instructions,\n        relevantFiles: assignment.relevantFiles,\n        priorFindings: assignment.priorFindings,\n        model: assignment.model,\n        ...(assignment.context === 'fork' || assignment.context === 'fresh' ? { context: assignment.context } : {}),\n        signal,\n      });\n      result.push({ index, id: assignment.id, agent: assignment.agent, ...outcome });\n    } catch (error) {\n      result.push({ index, id: assignment.id, agent: assignment.agent, ok: false, message: String(error) });\n    }\n  }\n  return result;\n}\n\nexport function createHeadlessTaskTool(\n  store: TaskStore,\n  manager: DelegationManager,\n  maxTasks: number,\n): DoomHeadlessTool<typeof TaskParamsSchema> {\n  return {\n    name: 'task',\n    label: 'Task',\n    description: 'Maintain a persistent task graph and delegate ready tasks to background agents.',\n    parameters: TaskParamsSchema,\n    promptSnippet: 'Track complex work persistently and delegate ready tasks',\n    executionMode: 'serial',\n    async execute(_toolCallId, rawParams, signal, onUpdate) {\n      if (!Check(TaskParamsSchema, rawParams)) return failure('Invalid task parameters.');\n      const params = rawParams as TaskParams;\n      try {\n        if (params.action === 'assign') {\n          if (!params.assignments?.length) throw new Error('assign requires a non-empty assignments[] array');\n          onUpdate?.(\n            output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? '' : 's'}...`),\n          );\n          const items = await assignmentBatch(manager, params.assignments, signal);\n          const assigned = items.filter((item) => item.ok).map((item) => item.id);\n          const text = formatAssignmentResults(items);\n          if (assigned.length === 0) throw new Error(text);\n          return buildAssignmentResult(params as TaskMutationParams, store.snapshot, text, {\n            assigned,\n            failed: items.length - assigned.length,\n          });\n        }\n        if (params.action === 'cancel') {\n          const outcome = await manager.cancel(params.id ?? Number.NaN);\n          if (!outcome.ok) throw new Error(outcome.message);\n          return buildTextResult('cancel', params as TaskMutationParams, store.snapshot, outcome.message);\n        }\n        return reducerAction(store, params.action as ReducerAction, params as TaskMutationParams, maxTasks);\n      } catch (error) {\n        return failure(error);\n      }\n    },\n  };\n}\n","import type { DoomMcpPluginContext } from '@agimon-ai/doompi-core/mcp-facet';\nimport { defineMcpTool } from '@agimon-ai/doompi-core/mcp-facet';\n\nimport { getDelegationTimeoutMs, getMaxTasks } from '../../../../../services/config';\nimport { DelegationManager } from '../../../../../services/delegation';\nimport { createNodeDelegationPlatform } from '../../../../../services/delegationPlatform';\nimport { resolveSessionKey } from '../../../../../services/paths';\nimport { TaskStore } from '../../../../../services/taskStore';\nimport { createHeadlessTaskTool } from '../../../../../services/taskTool';\n\nexport default defineMcpTool(({ execution }: DoomMcpPluginContext) => {\n  const store = new TaskStore({ cwd: execution.cwd, env: execution.environment });\n  store.configureSession(resolveSessionKey(execution.sessionId, execution.environment));\n  const manager = new DelegationManager({\n    store,\n    cwd: execution.cwd,\n    platform: createNodeDelegationPlatform(execution.environment),\n    getSessionId: () => execution.sessionId,\n    runTimeoutMs: getDelegationTimeoutMs(execution.environment),\n    onNotifyError: (error) => void execution.client.notify({ body: String(error), level: 'warning' }),\n  });\n  const tool = createHeadlessTaskTool(store, manager, getMaxTasks(execution.environment));\n  let initialized: Promise<void> | undefined;\n  return {\n    ...tool,\n    async execute(...args) {\n      initialized ??= store.readAsync().then(async () => {\n        await manager.reconcile();\n      });\n      await initialized;\n      return tool.execute(...args);\n    },\n  };\n});\n","// Generated by @agimon-ai/doompi-build. Do not edit by hand.\nimport { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcp-facet';\n\nimport toolTask from '../src/extensions/workspaces/sessions/(backend)/tool/task.mcp';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n  typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T => ({ ...identity, ...(value as object) }) as T;\n\nexport const mcp = defineMcpPlugin({\n  name: '@agimon-ai/doompi-task',\n  session: (context) => ({\n    get tools(): DoomMcpSessionPlugin['tools'] { return [via({ name: 'task' }, at(toolTask, context))]; },\n  }) satisfies DoomMcpSessionPlugin,\n});\n\nexport default mcp;\n"],"mappings":";;;;;;;;;;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