@rucher/carnet 0.3.0-beta.0 → 0.3.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"steps-j8vhVj8h.mjs","names":["requireAgent","plural"],"sources":["../src/context.ts","../src/errors.ts","../src/events.ts","../src/status/model.ts","../src/status/note.ts","../src/agents.ts","../src/db/schema.ts","../src/db/open.ts","../src/paths.ts","../src/findings.ts","../src/questions.ts","../src/workspace/workspace.ts","../src/sessions.ts","../src/prompt/core-rules.ts","../src/prompt/prompt.ts","../src/run-directory-files.ts","../src/workspace/undo.ts","../src/hosts/claude-code.ts","../src/hosts/host.ts","../src/workspace-rows.ts","../src/workspace/locate.ts","../src/notes.ts","../src/memory.ts","../src/merge.ts","../src/sandbox.ts","../src/purge.ts","../src/status/render.ts","../src/table.ts","../src/turn.ts","../src/status/view.ts","../src/subagents.ts","../src/carnet.ts","../src/report.ts","../src/kinds.ts","../src/resume.ts","../src/steps.ts"],"sourcesContent":["import type { DatabaseSync } from 'node:sqlite';\n\nexport interface Ctx {\n db: DatabaseSync;\n now: () => Date;\n // null: no workspace resolved, so nothing can be written for a session.\n workspace: string | null;\n}\n\nexport function nowIso(ctx: Ctx): string {\n return ctx.now().toISOString();\n}\n","export type CarnetErrorCode =\n | 'NO_WORKSPACE'\n | 'WORKSPACE_EXISTS'\n | 'WORKSPACE_NOT_FOUND'\n | 'WORKSPACE_NAME_INVALID'\n | 'WORKSPACE_BUSY'\n | 'WORKSPACE_RELOCATE_FAILED'\n | 'REPO_NOT_FOUND'\n | 'REPO_NAME_TAKEN'\n | 'NOTE_NOT_FOUND'\n | 'INVALID_NOTE'\n | 'UNKNOWN_HOST'\n | 'NO_SESSION'\n | 'SESSION_NOT_FOUND'\n | 'SESSION_AMBIGUOUS'\n | 'SESSION_NAME_TAKEN'\n | 'SESSION_NAME_REQUIRED'\n | 'SESSION_RUNNING'\n | 'SESSION_KIND_INVALID'\n | 'SESSION_MERGE_INVALID'\n | 'SESSION_EXISTS'\n | 'SESSION_MOVE_INVALID'\n | 'SESSION_CWD_MISSING'\n | 'RUN_DIRECTORY_FILE_CONFLICT'\n | 'WORKSPACE_INSTRUCTIONS_CONFLICT'\n | 'AGENT_EXISTS'\n | 'AGENT_NOT_FOUND'\n | 'AGENT_AMBIGUOUS'\n | 'INVALID_TARGET'\n | 'INVALID_BLOCKER'\n | 'INVALID_KIND'\n | 'INVALID_SANDBOX'\n | 'INVALID_QUESTIONS'\n | 'QUESTION_NOT_FOUND'\n | 'FINDING_NOT_FOUND'\n | 'REASON_REQUIRED'\n | 'SECTION_NOT_FOUND'\n | 'REPORT_MISSING'\n | 'INVALID_STATUS'\n | 'INVALID_EVENT_TYPE'\n | 'COMMIT_REQUIRED'\n | 'SCHEMA_TOO_NEW';\n\nexport class CarnetError extends Error {\n constructor(\n readonly code: CarnetErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'CarnetError';\n }\n}\n","import type { AgentKind } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\n\nexport const EVENT_TYPES = [\n 'started',\n 'finished',\n 'answered',\n 'applied',\n 'tested',\n 'committed',\n 'dropped',\n 'injected',\n 'promoted',\n 'triaged',\n] as const;\n\nexport const SESSION_EVENT_TYPES = [\n 'session.started',\n 'session.resumed',\n 'session.ended',\n 'session.forked',\n] as const;\n\nexport type AgentEventType = (typeof EVENT_TYPES)[number];\nexport type SessionEventType = (typeof SESSION_EVENT_TYPES)[number];\nexport type EventType = AgentEventType | SessionEventType;\n\nconst ALL_EVENT_TYPES: readonly string[] = [...EVENT_TYPES, ...SESSION_EVENT_TYPES];\n\nexport interface CarnetEvent {\n id: number;\n session: string;\n at: string;\n type: EventType;\n agent: string | null;\n commit: string | null;\n link: string | null;\n note: string | null;\n}\n\nexport interface LogEventInput {\n type: EventType;\n agent?: string | undefined;\n commit?: string | undefined;\n link?: string | undefined;\n note?: string | undefined;\n}\n\nexport interface ReadEventsOptions {\n session: string;\n limit?: number | undefined;\n agentOnly?: boolean | undefined;\n kind?: AgentKind | undefined;\n}\n\ninterface EventRow {\n id: number;\n session: string;\n at: string;\n type: EventType;\n agent: string | null;\n commit_sha: string | null;\n link: string | null;\n note: string | null;\n}\n\nexport function isEventType(value: unknown): value is EventType {\n return typeof value === 'string' && ALL_EVENT_TYPES.includes(value);\n}\n\nfunction toEvent(row: EventRow): CarnetEvent {\n return {\n id: row.id,\n session: row.session,\n at: row.at,\n type: row.type,\n agent: row.agent,\n commit: row.commit_sha,\n link: row.link,\n note: row.note,\n };\n}\n\nexport function logEvent(ctx: Ctx, session: string, input: LogEventInput): CarnetEvent {\n if (!isEventType(input.type)) {\n throw new CarnetError('INVALID_EVENT_TYPE', `Unknown event type \"${String(input.type)}\"`);\n }\n const result = ctx.db\n .prepare(\n 'INSERT INTO events (session, at, type, agent, commit_sha, link, note) VALUES (?, ?, ?, ?, ?, ?, ?)',\n )\n .run(\n session,\n nowIso(ctx),\n input.type,\n input.agent ?? null,\n input.commit ?? null,\n input.link ?? null,\n input.note ?? null,\n );\n const row = ctx.db\n .prepare('SELECT * FROM events WHERE id = ?')\n .get(result.lastInsertRowid) as unknown as EventRow;\n return toEvent(row);\n}\n\nexport function readEvents(\n ctx: Ctx,\n { session, limit = 20, agentOnly = false, kind }: ReadEventsOptions,\n): CarnetEvent[] {\n const filters = [\n agentOnly ? \"AND type NOT LIKE 'session.%'\" : '',\n kind\n ? 'AND agent IN (SELECT name FROM agents WHERE session = events.session AND kind = ?)'\n : '',\n ].join(' ');\n const parameters: string[] = kind ? [session, kind] : [session];\n const rows = ctx.db\n .prepare(\n `SELECT * FROM (SELECT * FROM events WHERE session = ? ${filters} ORDER BY at DESC, id DESC LIMIT ?) ORDER BY at, id`,\n )\n .all(...parameters, limit) as unknown as EventRow[];\n return rows.map(toEvent);\n}\n","export const AGENT_STATUSES = [\n 'running',\n 'discussing',\n 'answer',\n 'review',\n 'apply',\n 'test',\n 'closed',\n] as const;\n\nexport type AgentStatus = (typeof AGENT_STATUSES)[number];\n\nexport const USER_ACTION_STATUSES = ['discussing', 'answer', 'review', 'apply', 'test'] as const;\n\nexport type UserActionStatus = (typeof USER_ACTION_STATUSES)[number];\n\nexport const EMOJI: Record<Exclude<AgentStatus, 'closed'>, string> = {\n running: '⏳',\n discussing: '💬',\n answer: '❓',\n review: '👀',\n apply: '📥',\n test: '🧪',\n};\n\nexport const MAIN_WORKING_EMOJI = '⚙️';\nexport const MAIN_WAITING_EMOJI = '⏸';\nexport const MAIN_FAILED_EMOJI = '⚠';\n\nexport const LEGEND =\n '⚙️ main working · ⏸ waiting on you · ⚠ turn failed · 💬 discussing · ❓ answer · 👀 review · 📥 apply · 🧪 test · ⏳ running';\n\nexport const KIND_ABBREVIATIONS = {\n research: 'rs',\n plan: 'pl',\n implement: 'im',\n review: 'rv',\n} as const;\n\n// Brackets keep the kind apart from the agent's name even where there is no colour.\nexport function kindTag(kind: keyof typeof KIND_ABBREVIATIONS): string {\n return `[${KIND_ABBREVIATIONS[kind]}]`;\n}\n\nexport const KIND_TAG_PATTERN = /\\[(?:rs|pl|im|rv)\\]/;\n\nexport const KIND_LEGEND = '[rs] research · [pl] plan · [im] implement · [rv] review';\n\nexport function isAgentStatus(value: unknown): value is AgentStatus {\n return typeof value === 'string' && (AGENT_STATUSES as readonly string[]).includes(value);\n}\n\nexport function isUserActionStatus(value: unknown): value is UserActionStatus {\n return typeof value === 'string' && (USER_ACTION_STATUSES as readonly string[]).includes(value);\n}\n\nexport const OPEN_AGENT_STATUSES = ['running', ...USER_ACTION_STATUSES] as const;\n","export const NOTE_MAX = 60;\n\nconst PATH_PREFIX = /^(\\/|\\.\\.?\\/|~\\/)/;\nconst FILE_AFTER_SLASH = /\\/[^/\\s]+\\.[A-Za-z0-9]+$/;\n\nfunction looksLikePath(token: string): boolean {\n if (PATH_PREFIX.test(token)) return true;\n const slashes = token.split('/').length - 1;\n return slashes >= 2 || (slashes === 1 && FILE_AFTER_SLASH.test(token));\n}\n\nexport function sanitizeNote(text: string): string {\n const cleaned = text\n .replaceAll('`', '')\n .split(/\\s+/)\n .filter((token) => token && !looksLikePath(token))\n .join(' ')\n .trim();\n if (cleaned.length <= NOTE_MAX) return cleaned;\n return `${cleaned.slice(0, NOTE_MAX - 1).trimEnd()}…`;\n}\n","import type { DatabaseSync, SQLInputValue } from 'node:sqlite';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { logEvent, type LogEventInput } from './events.ts';\nimport { type AgentStatus, isAgentStatus } from './status/model.ts';\nimport { sanitizeNote } from './status/note.ts';\n\nexport const AGENT_KINDS = ['research', 'plan', 'implement', 'review'] as const;\n\nexport type AgentKind = (typeof AGENT_KINDS)[number];\n\nexport const KIND_REQUIRED = 'kind is required: research, plan, implement or review';\n\nexport const KIND_ACTIONS = {\n research: 'inject',\n plan: 'validate',\n implement: 'apply',\n review: 'triage',\n} as const satisfies Record<AgentKind, string>;\n\nexport type KindAction = (typeof KIND_ACTIONS)[AgentKind];\n\nexport function isAgentKind(value: unknown): value is AgentKind {\n return typeof value === 'string' && (AGENT_KINDS as readonly string[]).includes(value);\n}\n\nconst MAIN_TARGET = /^main(?::(.+))?$/;\n\nexport function mainTargetRange(target: string): string | null | undefined {\n const match = MAIN_TARGET.exec(target);\n return match ? (match[1]?.trim() ?? null) : undefined;\n}\n\nexport interface Agent {\n session: string;\n name: string;\n kind: AgentKind;\n promotedFrom: AgentKind | null;\n // A review's target: an implement agent name, or main[:<range>].\n target: string | null;\n // Another open agent of the session this one waits on; the view derives Waiting on agents from it.\n blockedOn: string | null;\n task: string | null;\n status: AgentStatus;\n note: string | null;\n reportPath: string | null;\n baseCommit: string | null;\n worktree: string | null;\n sandbox: string | null;\n queueOrder: number | null;\n hostAgentId: string | null;\n pendingStatus: AgentStatus | null;\n doneAt: string | null;\n startedAt: string;\n updatedAt: string;\n // When the status last changed, so Waiting on you can put the longest waiting first.\n statusSince: string;\n}\n\nexport interface StartAgentInput {\n name: string;\n task: string;\n kind: AgentKind;\n target?: string | undefined;\n baseCommit?: string | undefined;\n worktree?: string | undefined;\n // Absolute, under the run directory's sandboxes folder.\n sandbox?: string | undefined;\n}\n\nexport const SANDBOX_KINDS: readonly AgentKind[] = ['research', 'plan'];\n\nexport interface UpdateAgentInput {\n status: AgentStatus;\n // Undefined keeps the current note; null clears it.\n note?: string | null | undefined;\n reportPath?: string | undefined;\n // Undefined keeps the current blocker; null clears it.\n blockedOn?: string | null | undefined;\n}\n\nexport interface FinishAgentInput {\n reportPath: string;\n hasQuestions: boolean;\n}\n\nexport interface ListAgentsOptions {\n includeClosed?: boolean;\n}\n\nexport interface AgentRow {\n session: string;\n name: string;\n kind: AgentKind;\n promoted_from: AgentKind | null;\n target: string | null;\n blocked_on: string | null;\n task: string | null;\n status: AgentStatus;\n note: string | null;\n report_path: string | null;\n base_commit: string | null;\n worktree: string | null;\n sandbox: string | null;\n queue_order: number | null;\n host_agent_id: string | null;\n pending_status: AgentStatus | null;\n done_at: string | null;\n started_at: string;\n updated_at: string;\n status_since: string | null;\n}\n\nexport function toAgent(row: AgentRow): Agent {\n return {\n session: row.session,\n name: row.name,\n kind: row.kind,\n promotedFrom: row.promoted_from,\n target: row.target,\n blockedOn: row.blocked_on,\n task: row.task,\n status: row.status,\n note: row.note,\n reportPath: row.report_path,\n baseCommit: row.base_commit,\n worktree: row.worktree,\n sandbox: row.sandbox,\n queueOrder: row.queue_order,\n hostAgentId: row.host_agent_id,\n pendingStatus: row.pending_status,\n doneAt: row.done_at,\n startedAt: row.started_at,\n updatedAt: row.updated_at,\n statusSince: row.status_since ?? row.updated_at,\n };\n}\n\nexport const REPORTING_NOTE = 'reporting';\nexport const PUBLISH_FALLBACK_MILLISECONDS = 120_000;\n\n// A pin and a waiting age belong to one status: both reset when it changes.\nfunction statusChangeSql(next: string): string {\n return `status_since = CASE WHEN status = ${next} THEN status_since ELSE ? END,\n queue_order = CASE WHEN status = ${next} THEN queue_order ELSE NULL END`;\n}\n\nfunction statusChangeArgs(next: string, at: string): string[] {\n return [next, at, next];\n}\n\n// Closing ends every pending step too: a stray pending_status would reopen the agent on the next read.\nconst CLOSE_SET = `status = 'closed', pending_status = NULL, queue_order = NULL, blocked_on = NULL,\n status_since = ?, updated_at = ?`;\n\n// `where` is a constant SQL clause; its values are bound through `params`, never inlined.\nexport function closeAgentsWhere(\n db: DatabaseSync,\n where: string,\n params: SQLInputValue[],\n at: string,\n): number {\n return Number(\n db\n .prepare(`UPDATE agents SET ${CLOSE_SET} WHERE status != 'closed' AND (${where})`)\n .run(at, at, ...params).changes,\n );\n}\n\nexport function moveAgentStatus(\n ctx: Ctx,\n session: string,\n name: string,\n status: AgentStatus,\n note: string | null,\n): void {\n const at = nowIso(ctx);\n ctx.db\n .prepare(\n `UPDATE agents SET status = ?, note = ?, ${statusChangeSql('?')}, updated_at = ?\n WHERE session = ? AND name = ?`,\n )\n .run(status, note, ...statusChangeArgs(status, at), at, session, name);\n}\n\nexport function publishPending(ctx: Ctx, session: string, name: string): void {\n const row = ctx.db\n .prepare('SELECT pending_status, report_path FROM agents WHERE session = ? AND name = ?')\n .get(session, name) as Pick<AgentRow, 'pending_status' | 'report_path'> | undefined;\n if (!row?.pending_status) return;\n ctx.db\n .prepare(\n `UPDATE agents SET status = pending_status, pending_status = NULL, note = NULL,\n ${statusChangeSql('pending_status')}, updated_at = ?\n WHERE session = ? AND name = ? AND status != 'closed'`,\n )\n .run(nowIso(ctx), nowIso(ctx), session, name);\n logEvent(ctx, session, { type: 'finished', agent: name, link: row.report_path ?? undefined });\n}\n\n// Covers a paired fork whose SubagentStop never arrives (crash, hook timeout).\nfunction publishOverdue(ctx: Ctx, session: string): void {\n const before = new Date(ctx.now().getTime() - PUBLISH_FALLBACK_MILLISECONDS).toISOString();\n const rows = ctx.db\n .prepare(\n \"SELECT name FROM agents WHERE session = ? AND pending_status IS NOT NULL AND done_at <= ? AND status != 'closed'\",\n )\n .all(session, before) as unknown as Pick<AgentRow, 'name'>[];\n for (const row of rows) publishPending(ctx, session, row.name);\n}\n\nexport function getAgent(ctx: Ctx, session: string, name: string): Agent | undefined {\n publishOverdue(ctx, session);\n const row = ctx.db\n .prepare('SELECT * FROM agents WHERE session = ? AND name = ?')\n .get(session, name) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nexport function requireAgent(ctx: Ctx, session: string, name: string): Agent {\n const agent = getAgent(ctx, session, name);\n if (!agent) throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n return agent;\n}\n\n// A review reads a finished diff: a running target is still moving, a closed one is already in main.\nfunction checkReviewTarget(ctx: Ctx, session: string, target: string): void {\n if (mainTargetRange(target) !== undefined) return;\n const agent = getAgent(ctx, session, target);\n if (!agent || agent.kind !== 'implement') {\n throw new CarnetError(\n 'INVALID_TARGET',\n `Target \"${target}\" is not an implement agent of this session; use its name, or main[:<range>]`,\n );\n }\n if (agent.status === 'running') {\n throw new CarnetError('INVALID_TARGET', `Target \"${target}\" is still running`);\n }\n if (agent.status === 'closed') {\n throw new CarnetError(\n 'INVALID_TARGET',\n `Target \"${target}\" is closed; review main[:<range>] instead`,\n );\n }\n}\n\nexport function startAgent(ctx: Ctx, session: string, input: StartAgentInput): Agent {\n const name = sanitizeNote(input.name);\n const kind = input.kind;\n if (!isAgentKind(kind)) throw new CarnetError('INVALID_KIND', KIND_REQUIRED);\n if (input.worktree && kind !== 'implement') {\n throw new CarnetError(\n 'INVALID_KIND',\n `A worktree means an implement agent: start ${name} with kind implement, or promote a research or plan agent with agent_promote`,\n );\n }\n const target = input.target?.trim() || null;\n if (kind === 'review' && !target) {\n throw new CarnetError(\n 'INVALID_TARGET',\n 'A review needs a target: an implement agent name, or main[:<range>]',\n );\n }\n if (kind !== 'review' && target) {\n throw new CarnetError('INVALID_TARGET', 'Only a review agent takes a target');\n }\n if (target) checkReviewTarget(ctx, session, target);\n if (input.sandbox) checkSandbox(ctx, session, name, kind, input.sandbox);\n const existing = getAgent(ctx, session, name);\n if (existing && existing.status !== 'closed') {\n throw new CarnetError('AGENT_EXISTS', `Agent \"${name}\" is already open in this session`);\n }\n if (existing) {\n ctx.db.prepare('DELETE FROM agents WHERE session = ? AND name = ?').run(session, name);\n }\n const at = nowIso(ctx);\n ctx.db\n .prepare(\n `INSERT INTO agents (session, name, kind, target, task, status, base_commit, worktree,\n sandbox, started_at, updated_at, status_since)\n VALUES (?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n session,\n name,\n kind,\n target,\n input.task,\n input.baseCommit ?? null,\n input.worktree ?? null,\n input.sandbox ?? null,\n at,\n at,\n at,\n );\n logEvent(ctx, session, { type: 'started', agent: name, note: input.task });\n return requireAgent(ctx, session, name);\n}\n\nfunction checkSandbox(\n ctx: Ctx,\n session: string,\n name: string,\n kind: AgentKind,\n sandbox: string,\n): void {\n if (!SANDBOX_KINDS.includes(kind)) {\n throw new CarnetError(\n 'INVALID_KIND',\n `Only a research or plan agent gets a sandbox; ${name} is ${kind}`,\n );\n }\n const holder = ctx.db\n .prepare(\n `SELECT agents.name FROM agents JOIN sessions ON sessions.id = agents.session\n WHERE agents.sandbox = ? AND sessions.workspace = (SELECT workspace FROM sessions WHERE id = ?)\n AND NOT (agents.session = ? AND agents.name = ?)`,\n )\n .get(sandbox, session, session, name) as { name: string } | undefined;\n if (holder) {\n throw new CarnetError('INVALID_SANDBOX', `${sandbox} is already the sandbox of ${holder.name}`);\n }\n}\n\n// Cleared once the folder is gone, so a later agent may take the same path.\nexport function clearSandbox(ctx: Ctx, session: string, name: string): void {\n ctx.db\n .prepare('UPDATE agents SET sandbox = NULL WHERE session = ? AND name = ?')\n .run(session, name);\n}\n\n// Without a session: every session of the workspace.\nexport function closedSandboxes(\n ctx: Ctx,\n session?: string,\n): { session: string; name: string; sandbox: string }[] {\n const where = session\n ? 'agents.session = ?'\n : 'agents.session IN (SELECT id FROM sessions WHERE workspace = ?)';\n return ctx.db\n .prepare(\n `SELECT session, name, sandbox FROM agents\n WHERE ${where} AND status = 'closed' AND sandbox IS NOT NULL`,\n )\n .all(session ?? ctx.workspace) as unknown as {\n session: string;\n name: string;\n sandbox: string;\n }[];\n}\n\nfunction checkBlocker(ctx: Ctx, session: string, name: string, blocker: string): void {\n if (blocker === name) {\n throw new CarnetError('INVALID_BLOCKER', `Agent \"${name}\" can't wait on itself`);\n }\n const seen = new Set([name]);\n let current = getAgent(ctx, session, blocker);\n if (!current || current.status === 'closed') {\n throw new CarnetError('INVALID_BLOCKER', `\"${blocker}\" is not an open agent of this session`);\n }\n while (current?.blockedOn && current.status !== 'closed') {\n if (seen.has(current.blockedOn)) {\n throw new CarnetError(\n 'INVALID_BLOCKER',\n `\"${blocker}\" already waits on \"${name}\", directly or through another agent`,\n );\n }\n seen.add(current.name);\n current = getAgent(ctx, session, current.blockedOn);\n }\n}\n\nexport function updateAgent(\n ctx: Ctx,\n session: string,\n name: string,\n input: UpdateAgentInput,\n): Agent {\n const current = requireAgent(ctx, session, name);\n if (!isAgentStatus(input.status) || input.status === 'closed') {\n throw new CarnetError(\n 'INVALID_STATUS',\n `Invalid agent status \"${input.status}\"; use agent_drop to close`,\n );\n }\n let note: string | null;\n if (input.note !== undefined) note = input.note === null ? null : sanitizeNote(input.note);\n else note = current.status === 'running' && input.status !== 'running' ? null : current.note;\n let blockedOn = current.blockedOn;\n if (input.blockedOn !== undefined) {\n blockedOn = input.blockedOn === null ? null : sanitizeNote(input.blockedOn);\n if (blockedOn) checkBlocker(ctx, session, name, blockedOn);\n }\n if (current.pendingStatus) publishPending(ctx, session, name);\n ctx.db\n .prepare(\n `UPDATE agents SET note = ?, ${statusChangeSql('?')}, status = ?,\n report_path = COALESCE(?, report_path), blocked_on = ?, updated_at = ? WHERE session = ? AND name = ?`,\n )\n .run(\n note,\n ...statusChangeArgs(input.status, nowIso(ctx)),\n input.status,\n input.reportPath ?? null,\n blockedOn,\n nowIso(ctx),\n session,\n name,\n );\n return requireAgent(ctx, session, name);\n}\n\n// A review's findings wait in 👀 review for triage.\nexport function statusWhenDone(kind: AgentKind, hasQuestions: boolean): AgentStatus {\n if (hasQuestions) return 'answer';\n return kind === 'implement' ? 'apply' : 'review';\n}\n\nexport function finishAgent(\n ctx: Ctx,\n session: string,\n name: string,\n input: FinishAgentInput,\n): Agent {\n const agent = requireAgent(ctx, session, name);\n const status = statusWhenDone(agent.kind, input.hasQuestions);\n const at = nowIso(ctx);\n // A paired fork keeps writing its final message after agent_done; SubagentStop marks the real end.\n ctx.db\n .prepare(\n 'UPDATE agents SET pending_status = ?, note = ?, report_path = ?, done_at = ?, updated_at = ? WHERE session = ? AND name = ?',\n )\n .run(status, REPORTING_NOTE, input.reportPath, at, at, session, name);\n if (!agent.hostAgentId) publishPending(ctx, session, name);\n return requireAgent(ctx, session, name);\n}\n\n// Once the questions are answered, a plan agent's plan still waits for validation.\nexport function statusAfterAnswers(kind: AgentKind): 'apply' | 'review' {\n return kind === 'implement' ? 'apply' : 'review';\n}\n\nexport function closeAgent(\n ctx: Ctx,\n session: string,\n name: string,\n event: Omit<LogEventInput, 'agent'>,\n): Agent {\n requireAgent(ctx, session, name);\n ctx.db\n .prepare(`UPDATE agents SET ${CLOSE_SET} WHERE session = ? AND name = ?`)\n .run(nowIso(ctx), nowIso(ctx), session, name);\n logEvent(ctx, session, { ...event, agent: name });\n return requireAgent(ctx, session, name);\n}\n\nexport function dropAgent(ctx: Ctx, session: string, name: string, reason?: string): Agent {\n return closeAgent(ctx, session, name, { type: 'dropped', note: reason });\n}\n\nconst PROMOTIONS: Readonly<Partial<Record<AgentKind, readonly AgentKind[]>>> = {\n research: ['plan', 'implement'],\n plan: ['implement'],\n};\n\nexport const PROMOTE_KIND_REQUIRED =\n 'kind is required: plan or implement for a research agent, implement for a plan one';\n\nexport interface PromoteAgentInput {\n kind: AgentKind | undefined;\n worktree?: string | undefined;\n baseCommit?: string | undefined;\n}\n\nexport function promoteAgent(\n ctx: Ctx,\n session: string,\n name: string,\n input: PromoteAgentInput,\n): Agent {\n const agent = requireAgent(ctx, session, name);\n const target = input.kind;\n if (!isAgentKind(target)) throw new CarnetError('INVALID_KIND', PROMOTE_KIND_REQUIRED);\n const allowed = PROMOTIONS[agent.kind] ?? [];\n if (!allowed.includes(target)) {\n throw new CarnetError(\n 'INVALID_KIND',\n allowed.length === 0\n ? `A ${agent.kind} agent is never promoted; only research and plan are`\n : `${name} is ${agent.kind}: it is promoted to ${allowed.join(' or ')}, not ${target}`,\n );\n }\n if (input.worktree && target !== 'implement') {\n throw new CarnetError(\n 'INVALID_KIND',\n `A worktree means an implement agent: promote ${name} with kind implement`,\n );\n }\n ctx.db\n .prepare(\n `UPDATE agents SET kind = ?, promoted_from = ?, status = 'running',\n pending_status = NULL, note = NULL, blocked_on = NULL, worktree = COALESCE(?, worktree),\n base_commit = COALESCE(?, base_commit), queue_order = NULL, status_since = ?, updated_at = ?\n WHERE session = ? AND name = ?`,\n )\n .run(\n target,\n agent.kind,\n input.worktree ?? null,\n input.baseCommit ?? null,\n nowIso(ctx),\n nowIso(ctx),\n session,\n name,\n );\n logEvent(ctx, session, { type: 'promoted', agent: name, note: `${agent.kind} to ${target}` });\n return requireAgent(ctx, session, name);\n}\n\nexport function listAgents(ctx: Ctx, session: string, options: ListAgentsOptions = {}): Agent[] {\n publishOverdue(ctx, session);\n const where = options.includeClosed ? '' : \"AND status != 'closed'\";\n const rows = ctx.db\n .prepare(`SELECT * FROM agents WHERE session = ? ${where} ORDER BY started_at ASC, name ASC`)\n .all(session) as unknown as unknown as AgentRow[];\n return rows.map(toAgent);\n}\n\nexport function reorderQueue(ctx: Ctx, session: string, names: string[]): Agent[] {\n const at = nowIso(ctx);\n ctx.db.prepare('UPDATE agents SET queue_order = NULL WHERE session = ?').run(session);\n const update = ctx.db.prepare(\n 'UPDATE agents SET queue_order = ?, updated_at = ? WHERE session = ? AND name = ?',\n );\n names.forEach((name, index) => {\n update.run(index + 1, at, session, sanitizeNote(name));\n });\n return listAgents(ctx, session);\n}\n","import type { DatabaseSync } from 'node:sqlite';\nimport { CarnetError } from '../errors.ts';\n\n// Before v11, sessions started outside any workspace had none. Those that hold no work go;\n// the others stop the migration, since their workspace can't be guessed.\nconst DISPOSABLE_SESSION = `workspace IS NULL\n AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id)\n AND NOT EXISTS (\n SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'\n )\n AND NOT EXISTS (SELECT 1 FROM notes WHERE notes.session = sessions.id OR notes.dropped_session = sessions.id)\n AND NOT EXISTS (SELECT 1 FROM note_citations WHERE note_citations.session = sessions.id)\n AND NOT EXISTS (SELECT 1 FROM sessions AS child WHERE child.parent_id = sessions.id)`;\n\nexport const migrations: readonly string[] = [\n `\nCREATE TABLE sessions (\n id TEXT PRIMARY KEY,\n name TEXT UNIQUE,\n purpose TEXT,\n status TEXT NOT NULL DEFAULT 'temporary'\n CHECK (status IN ('temporary', 'active', 'dropped')),\n cwd TEXT,\n repo TEXT,\n claude_pid INTEGER,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL\n);\n\nCREATE TABLE agents (\n session TEXT NOT NULL REFERENCES sessions(id),\n name TEXT NOT NULL,\n task TEXT,\n status TEXT NOT NULL\n CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'commit', 'branch', 'closed')),\n note TEXT,\n report_path TEXT,\n base_commit TEXT,\n worktree TEXT,\n queue_order INTEGER,\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session, name)\n);\n\nCREATE TABLE table_items (\n session TEXT PRIMARY KEY REFERENCES sessions(id),\n text TEXT NOT NULL,\n status TEXT,\n main_working INTEGER NOT NULL DEFAULT 0,\n updated_at TEXT NOT NULL\n);\n\nCREATE TABLE events (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id),\n at TEXT NOT NULL,\n type TEXT NOT NULL\n CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped')),\n agent TEXT,\n commit_sha TEXT,\n link TEXT,\n note TEXT\n);\n\nCREATE INDEX events_session_at ON events(session, at);\nCREATE INDEX agents_session_status ON agents(session, status);\n`,\n `\nALTER TABLE agents ADD COLUMN claude_agent_id TEXT;\n`,\n `\nALTER TABLE sessions ADD COLUMN hooked_at TEXT;\nCREATE INDEX sessions_claude_pid ON sessions(claude_pid, hooked_at);\n`,\n `\nALTER TABLE agents ADD COLUMN pending_status TEXT;\nALTER TABLE agents ADD COLUMN done_at TEXT;\n`,\n `\nUPDATE sessions SET status = 'active' WHERE status = 'paused';\n`,\n `\nALTER TABLE sessions RENAME COLUMN claude_pid TO host_pid;\nALTER TABLE sessions ADD COLUMN host TEXT NOT NULL DEFAULT 'claude-code';\nALTER TABLE agents RENAME COLUMN claude_agent_id TO host_agent_id;\nDROP INDEX sessions_claude_pid;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\n`,\n `\nCREATE TABLE sessions_new (\n id TEXT PRIMARY KEY,\n name TEXT UNIQUE,\n purpose TEXT,\n kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),\n status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),\n cwd TEXT,\n repo TEXT,\n host TEXT NOT NULL DEFAULT 'claude-code',\n host_pid INTEGER,\n hooked_at TEXT,\n last_title TEXT,\n parent_id TEXT REFERENCES sessions(id),\n prompt_version TEXT,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL,\n ended_at TEXT,\n CHECK (kind = 'temp' OR name IS NOT NULL)\n);\nINSERT INTO sessions_new (id, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at,\n last_title, created_at, last_active_at)\nSELECT id, name, purpose,\n CASE WHEN status = 'active' AND name IS NOT NULL THEN 'active'\n WHEN status = 'dropped' AND name IS NOT NULL THEN 'active'\n ELSE 'temp' END,\n CASE WHEN status = 'dropped' THEN 'archived' ELSE 'idle' END,\n cwd, repo, host, host_pid, hooked_at, name, created_at, last_active_at\nFROM sessions;\nDROP TABLE sessions;\nALTER TABLE sessions_new RENAME TO sessions;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\n\nCREATE TABLE events_new (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id),\n at TEXT NOT NULL,\n type TEXT NOT NULL\n CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped',\n 'session.started', 'session.resumed', 'session.ended', 'session.forked')),\n agent TEXT,\n commit_sha TEXT,\n link TEXT,\n note TEXT\n);\nINSERT INTO events_new SELECT id, session, at, type, agent, commit_sha, link, note FROM events;\nDROP TABLE events;\nALTER TABLE events_new RENAME TO events;\nCREATE INDEX events_session_at ON events(session, at);\n`,\n `\nCREATE TABLE notes (\n id INTEGER PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('learning', 'dead_end', 'decision')),\n text TEXT NOT NULL,\n session TEXT REFERENCES sessions(id) ON DELETE SET NULL,\n agent TEXT,\n similar_notes TEXT,\n created_at TEXT NOT NULL,\n dropped_at TEXT,\n dropped_reason TEXT,\n dropped_session TEXT REFERENCES sessions(id) ON DELETE SET NULL,\n replaced_by INTEGER REFERENCES notes(id)\n);\n\nCREATE INDEX notes_active ON notes(dropped_at, kind);\nCREATE INDEX notes_session ON notes(session);\n\nCREATE TABLE note_repos (\n note INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,\n repo TEXT NOT NULL,\n PRIMARY KEY (note, repo)\n);\n\nCREATE INDEX note_repos_repo ON note_repos(repo);\n\nCREATE TABLE note_citations (\n id INTEGER PRIMARY KEY,\n note INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,\n session TEXT REFERENCES sessions(id) ON DELETE SET NULL,\n agent TEXT,\n why TEXT NOT NULL,\n at TEXT NOT NULL\n);\n\nCREATE INDEX note_citations_note_at ON note_citations(note, at);\nCREATE INDEX note_citations_session ON note_citations(session);\n\nCREATE TABLE active_days (\n day TEXT PRIMARY KEY\n);\n\nCREATE TABLE session_repos (\n session TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,\n repo TEXT NOT NULL,\n injected_at TEXT NOT NULL,\n PRIMARY KEY (session, repo)\n);\n`,\n // Rows from before v9 get the placeholder group '' until the move to one database assigns them.\n `\nCREATE TABLE sessions_new (\n id TEXT PRIMARY KEY,\n group_name TEXT,\n name TEXT,\n purpose TEXT,\n kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),\n status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),\n cwd TEXT,\n repo TEXT,\n host TEXT NOT NULL DEFAULT 'claude-code',\n host_pid INTEGER,\n hooked_at TEXT,\n last_title TEXT,\n parent_id TEXT REFERENCES sessions(id),\n prompt_version TEXT,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL,\n ended_at TEXT,\n CHECK (kind = 'temp' OR name IS NOT NULL)\n);\nINSERT INTO sessions_new (id, group_name, name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)\nSELECT id, '', name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at\nFROM sessions;\nDROP TABLE sessions;\nALTER TABLE sessions_new RENAME TO sessions;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\nCREATE INDEX sessions_group_status ON sessions(group_name, status, last_active_at);\nCREATE UNIQUE INDEX sessions_group_name ON sessions(group_name, name)\n WHERE group_name IS NOT NULL AND name IS NOT NULL;\nCREATE UNIQUE INDEX sessions_free_name ON sessions(name)\n WHERE group_name IS NULL AND name IS NOT NULL;\n\nALTER TABLE notes ADD COLUMN group_name TEXT NOT NULL DEFAULT '';\nALTER TABLE notes ADD COLUMN number INTEGER NOT NULL DEFAULT 0;\nUPDATE notes SET number = id;\nDROP INDEX notes_active;\nCREATE INDEX notes_active ON notes(group_name, dropped_at, kind);\nCREATE UNIQUE INDEX notes_group_number ON notes(group_name, number);\n\nCREATE TABLE active_days_new (\n group_name TEXT NOT NULL,\n day TEXT NOT NULL,\n PRIMARY KEY (group_name, day)\n);\nINSERT INTO active_days_new (group_name, day) SELECT '', day FROM active_days;\nDROP TABLE active_days;\nALTER TABLE active_days_new RENAME TO active_days;\n`,\n `\nALTER TABLE sessions RENAME COLUMN group_name TO workspace;\nALTER TABLE notes RENAME COLUMN group_name TO workspace;\nALTER TABLE active_days RENAME COLUMN group_name TO workspace;\nDROP INDEX sessions_group_status;\nDROP INDEX sessions_group_name;\nDROP INDEX notes_group_number;\nCREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_active_at);\nCREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name)\n WHERE workspace IS NOT NULL AND name IS NOT NULL;\nCREATE UNIQUE INDEX notes_workspace_number ON notes(workspace, number);\n`,\n `\nDELETE FROM events WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});\nDELETE FROM table_items WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});\nDELETE FROM session_repos WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});\nDELETE FROM sessions WHERE ${DISPOSABLE_SESSION};\n\nCREATE TABLE sessions_new (\n id TEXT PRIMARY KEY,\n workspace TEXT NOT NULL,\n name TEXT,\n purpose TEXT,\n kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),\n status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),\n cwd TEXT,\n repo TEXT,\n host TEXT NOT NULL DEFAULT 'claude-code',\n host_pid INTEGER,\n hooked_at TEXT,\n last_title TEXT,\n parent_id TEXT REFERENCES sessions(id),\n prompt_version TEXT,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL,\n ended_at TEXT,\n turn TEXT CHECK (turn IN ('working', 'waiting', 'failed')),\n turn_started_at TEXT,\n CHECK (kind = 'temp' OR name IS NOT NULL)\n);\nINSERT INTO sessions_new (id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)\nSELECT id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at\nFROM sessions;\nDROP TABLE sessions;\nALTER TABLE sessions_new RENAME TO sessions;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\nCREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_active_at);\nCREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name) WHERE name IS NOT NULL;\n\nALTER TABLE table_items DROP COLUMN main_working;\n\nALTER TABLE agents ADD COLUMN kind TEXT NOT NULL DEFAULT 'analyze'\n CHECK (kind IN ('research', 'analyze', 'implement', 'review'));\nALTER TABLE agents ADD COLUMN promoted_from TEXT\n CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review'));\nALTER TABLE agents ADD COLUMN target TEXT;\n-- Older agents waiting on code steps, or given a worktree, wrote code.\nUPDATE agents SET kind = 'implement'\nWHERE (status IN ('apply', 'test', 'commit')) OR worktree IS NOT NULL;\n\nCREATE TABLE agent_questions (\n session TEXT NOT NULL,\n agent TEXT NOT NULL,\n n INTEGER NOT NULL CHECK (n >= 1),\n text TEXT NOT NULL,\n context TEXT,\n recommendation TEXT NOT NULL,\n alternatives TEXT NOT NULL DEFAULT '[]',\n answer TEXT,\n answered_at TEXT,\n PRIMARY KEY (session, agent, n),\n FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE\n);\n\nCREATE TABLE review_findings (\n session TEXT NOT NULL,\n agent TEXT NOT NULL,\n n INTEGER NOT NULL CHECK (n >= 1),\n severity TEXT NOT NULL CHECK (severity IN ('blocking', 'to_fix', 'suggestion')),\n location TEXT,\n text TEXT NOT NULL,\n fix TEXT,\n decision TEXT CHECK (decision IN ('sent', 'fixed', 'ignored')),\n reason TEXT,\n decided_at TEXT,\n PRIMARY KEY (session, agent, n),\n FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE\n);\n\nCREATE TABLE events_new (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id),\n at TEXT NOT NULL,\n type TEXT NOT NULL\n CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped',\n 'injected', 'promoted', 'triaged',\n 'session.started', 'session.resumed', 'session.ended', 'session.forked')),\n agent TEXT,\n commit_sha TEXT,\n link TEXT,\n note TEXT\n);\nINSERT INTO events_new SELECT id, session, at, type, agent, commit_sha, link, note FROM events;\nDROP TABLE events;\nALTER TABLE events_new RENAME TO events;\nCREATE INDEX events_session_at ON events(session, at);\n`,\n `\n-- Testing and committing are one human step, and no step ever led to branch.\nUPDATE agents SET status = 'test' WHERE status IN ('commit', 'branch');\nUPDATE agents SET pending_status = 'test' WHERE pending_status IN ('commit', 'branch');\nUPDATE table_items SET status = 'test' WHERE status IN ('commit', 'branch');\nCREATE TABLE agents_new (\n session TEXT NOT NULL REFERENCES sessions(id),\n name TEXT NOT NULL,\n task TEXT,\n status TEXT NOT NULL\n CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),\n note TEXT,\n report_path TEXT,\n base_commit TEXT,\n worktree TEXT,\n queue_order INTEGER,\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n host_agent_id TEXT,\n pending_status TEXT,\n done_at TEXT,\n kind TEXT NOT NULL DEFAULT 'analyze'\n CHECK (kind IN ('research', 'analyze', 'implement', 'review')),\n promoted_from TEXT CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review')),\n target TEXT,\n blocked_on TEXT,\n PRIMARY KEY (session, name)\n);\nINSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target)\nSELECT session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target\nFROM agents;\nDROP TABLE agents;\nALTER TABLE agents_new RENAME TO agents;\nCREATE INDEX agents_session_status ON agents(session, status);\n-- The CLI and the plugin update separately; the pane warns when the hooks lag behind.\nALTER TABLE sessions ADD COLUMN plugin_version TEXT;\n`,\n `\n-- A research or analyze agent's throwaway folder under the run directory, writable through the guard.\nALTER TABLE agents ADD COLUMN sandbox TEXT;\n`,\n `\n-- The analyze kind is now plan. launch_requested_at marks the Agent call that launches an agent,\n-- so the next subagent pairs with it rather than with an older registered one.\nCREATE TABLE agents_new (\n session TEXT NOT NULL REFERENCES sessions(id),\n name TEXT NOT NULL,\n task TEXT,\n status TEXT NOT NULL\n CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),\n note TEXT,\n report_path TEXT,\n base_commit TEXT,\n worktree TEXT,\n queue_order INTEGER,\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n host_agent_id TEXT,\n pending_status TEXT,\n done_at TEXT,\n kind TEXT NOT NULL CHECK (kind IN ('research', 'plan', 'implement', 'review')),\n promoted_from TEXT CHECK (promoted_from IN ('research', 'plan', 'implement', 'review')),\n target TEXT,\n blocked_on TEXT,\n sandbox TEXT,\n launch_requested_at TEXT,\n PRIMARY KEY (session, name)\n);\nINSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from,\n target, blocked_on, sandbox)\nSELECT session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at,\n CASE kind WHEN 'analyze' THEN 'plan' ELSE kind END,\n CASE promoted_from WHEN 'analyze' THEN 'plan' ELSE promoted_from END,\n target, blocked_on, sandbox\nFROM agents;\nDROP TABLE agents;\nALTER TABLE agents_new RENAME TO agents;\nCREATE INDEX agents_session_status ON agents(session, status);\n`,\n `\n-- When the status last changed; rows from before it start from their last update.\nALTER TABLE agents ADD COLUMN status_since TEXT;\nUPDATE agents SET status_since = updated_at;\n`,\n];\n\nconst preconditions: Readonly<Record<number, (db: DatabaseSync) => void>> = {\n 11: (db) => {\n const kept = db\n .prepare(\n `SELECT id, name FROM sessions WHERE workspace IS NULL AND NOT (${DISPOSABLE_SESSION})`,\n )\n .all() as { id: string; name: string | null }[];\n if (kept.length === 0) return;\n const list = kept.map((row) => row.name ?? row.id).join(', ');\n throw new Error(\n `Every session now needs a workspace, and these sessions without one hold agents, notes or forks: ${list}. ` +\n \"Give each one a workspace with the previous rucher (rucher sessions move), or in SQL: UPDATE sessions SET workspace = '<name>' WHERE id = '<id>'\",\n );\n },\n};\n\nexport function schemaVersion(db: DatabaseSync): number {\n const row = db.prepare('PRAGMA user_version').get() as { user_version: number };\n return row.user_version;\n}\n\nfunction foreignKeyViolations(db: DatabaseSync): number {\n return db.prepare('PRAGMA foreign_key_check').all().length;\n}\n\nfunction knownVersion(db: DatabaseSync): number {\n const version = schemaVersion(db);\n if (version > migrations.length) {\n throw new CarnetError(\n 'SCHEMA_TOO_NEW',\n `The Carnet database is at schema v${version}, newer than this rucher (v${migrations.length}). ` +\n 'Update rucher and its plugin; sessions started before the update run the old version until they are restarted.',\n );\n }\n return version;\n}\n\nexport function migrate(db: DatabaseSync): void {\n if (knownVersion(db) >= migrations.length) return;\n const foreignKeys = db.prepare('PRAGMA foreign_keys').get() as { foreign_keys: number };\n // Table rebuilds need foreign keys off, and SQLite ignores that pragma inside a transaction.\n db.exec('PRAGMA foreign_keys = OFF');\n try {\n for (;;) {\n // Several processes open the database at once after an update: reading the version under\n // the write lock keeps a step another process already applied from running twice.\n db.exec('BEGIN IMMEDIATE');\n try {\n const version = knownVersion(db);\n const migration = migrations[version];\n if (migration === undefined) {\n db.exec('COMMIT');\n return;\n }\n preconditions[version + 1]?.(db);\n db.exec(migration);\n if (foreignKeyViolations(db) > 0) {\n throw new Error(`Migration ${version + 1} broke foreign keys`);\n }\n db.exec(`PRAGMA user_version = ${version + 1}`);\n db.exec('COMMIT');\n } catch (error) {\n db.exec('ROLLBACK');\n throw error;\n }\n }\n } finally {\n db.exec(`PRAGMA foreign_keys = ${foreignKeys.foreign_keys ? 'ON' : 'OFF'}`);\n }\n}\n","import { DatabaseSync } from 'node:sqlite';\nimport { migrate } from './schema.ts';\n\nexport const MEMORY_DB = ':memory:';\n\n// WAL persists in the file, so only a new database switches. SQLite skips the busy handler for\n// that switch, so processes creating the file together retry it briefly.\nfunction useWal(db: DatabaseSync): void {\n const mode = db.prepare('PRAGMA journal_mode').get() as { journal_mode: string };\n if (mode.journal_mode === 'wal') return;\n for (let attempt = 1; ; attempt += 1) {\n try {\n db.exec('PRAGMA journal_mode = WAL');\n return;\n } catch (error) {\n if (attempt >= 50 || !String(error).includes('database is locked')) throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);\n }\n }\n}\n\nexport function openDatabase(path: string): DatabaseSync {\n const db = new DatabaseSync(path);\n db.exec('PRAGMA busy_timeout = 5000');\n if (path !== MEMORY_DB) useWal(db);\n db.exec('PRAGMA foreign_keys = ON');\n migrate(db);\n return db;\n}\n","import { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport type { Workspace } from './workspace/workspace.ts';\n\nexport interface RucherPaths {\n config: string;\n data: string;\n state: string;\n run: string;\n}\n\n// The XDG spec says relative values must be ignored.\nfunction xdgDirectory(value: string | undefined, fallback: string): string {\n return value && isAbsolute(value) ? value : fallback;\n}\n\nexport function rucherPaths(env: NodeJS.ProcessEnv = process.env): RucherPaths {\n if (env.RUCHER_HOME) {\n const home = env.RUCHER_HOME;\n return {\n config: join(home, 'config'),\n data: join(home, 'data'),\n state: join(home, 'state'),\n run: join(home, 'run'),\n };\n }\n const home = env.HOME || homedir();\n const state = join(xdgDirectory(env.XDG_STATE_HOME, join(home, '.local', 'state')), 'rucher');\n return {\n config: join(xdgDirectory(env.XDG_CONFIG_HOME, join(home, '.config')), 'rucher'),\n data: join(xdgDirectory(env.XDG_DATA_HOME, join(home, '.local', 'share')), 'rucher'),\n state,\n run:\n env.XDG_RUNTIME_DIR && isAbsolute(env.XDG_RUNTIME_DIR)\n ? join(env.XDG_RUNTIME_DIR, 'rucher')\n : join(state, 'run'),\n };\n}\n\nexport function databasePath(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).data, 'carnet.db');\n}\n\nexport function workspacesDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).config, 'workspaces');\n}\n\nexport function workspaceDefinition(name: string, env?: NodeJS.ProcessEnv): string {\n return join(workspacesDirectory(env), name);\n}\n\nexport function defaultRunDirectory(name: string, env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).data, 'workspaces', name);\n}\n\nexport function promptsDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).state, 'prompts');\n}\n\nexport function corePromptPath(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).config, 'prompt.md');\n}\n\nexport function reportsDirectory(workspace: Workspace): string {\n return join(workspace.runDirectory, 'reports');\n}\n\nexport function sandboxesDirectory(workspace: Workspace): string {\n return join(workspace.runDirectory, 'sandboxes');\n}\n\nexport function reportPath(workspace: Workspace, agentName: string): string {\n return join(reportsDirectory(workspace), `${agentName}.md`);\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\n\nexport const FINDING_SEVERITIES = ['blocking', 'to_fix', 'suggestion'] as const;\nexport type FindingSeverity = (typeof FINDING_SEVERITIES)[number];\n\nexport const FINDING_DECISIONS = ['sent', 'fixed', 'ignored'] as const;\nexport type FindingDecision = (typeof FINDING_DECISIONS)[number];\n\nexport interface FindingInput {\n severity: FindingSeverity;\n location?: string | undefined;\n text: string;\n fix?: string | undefined;\n}\n\nexport interface Finding {\n n: number;\n total: number;\n severity: FindingSeverity;\n location: string | null;\n text: string;\n fix: string | null;\n decision: FindingDecision | null;\n reason: string | null;\n}\n\nexport interface DecisionInput {\n n: number;\n decision: FindingDecision;\n reason?: string | undefined;\n}\n\ninterface FindingRow {\n n: number;\n severity: FindingSeverity;\n location: string | null;\n text: string;\n fix: string | null;\n decision: FindingDecision | null;\n reason: string | null;\n}\n\nexport function listFindings(\n ctx: Ctx,\n session: string,\n agent: string,\n pendingOnly = false,\n): Finding[] {\n const rows = ctx.db\n .prepare('SELECT * FROM review_findings WHERE session = ? AND agent = ? ORDER BY n')\n .all(session, agent) as unknown as FindingRow[];\n const total = rows.length;\n return rows\n .filter((row) => !pendingOnly || row.decision === null)\n .map((row) => ({ ...row, total }));\n}\n\n// Numbered blocking first, so the order findings are handled in is their numbering.\nexport function replaceFindings(\n ctx: Ctx,\n session: string,\n agent: string,\n inputs: readonly FindingInput[],\n): Finding[] {\n const sorted = [...inputs].sort(\n (a, b) => FINDING_SEVERITIES.indexOf(a.severity) - FINDING_SEVERITIES.indexOf(b.severity),\n );\n ctx.db.prepare('DELETE FROM review_findings WHERE session = ? AND agent = ?').run(session, agent);\n const insert = ctx.db.prepare(\n `INSERT INTO review_findings (session, agent, n, severity, location, text, fix)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n );\n sorted.forEach((input, index) => {\n insert.run(\n session,\n agent,\n index + 1,\n input.severity,\n input.location?.trim() || null,\n input.text.trim(),\n input.fix?.trim() || null,\n );\n });\n return listFindings(ctx, session, agent);\n}\n\nexport function decideFindings(\n ctx: Ctx,\n session: string,\n agent: string,\n decisions: readonly DecisionInput[],\n): Finding[] {\n const known = new Set(listFindings(ctx, session, agent).map((finding) => finding.n));\n const missing = decisions.filter((item) => !known.has(item.n)).map((item) => item.n);\n if (missing.length) {\n throw new CarnetError(\n 'FINDING_NOT_FOUND',\n `No finding ${missing.join(', ')} for ${agent}; review_findings lists them`,\n );\n }\n const unexplained = decisions.filter(\n (item) => item.decision === 'ignored' && !item.reason?.trim(),\n );\n if (unexplained.length) {\n throw new CarnetError(\n 'REASON_REQUIRED',\n `Ignoring finding ${unexplained.map((item) => item.n).join(', ')} needs a short reason`,\n );\n }\n const at = nowIso(ctx);\n const update = ctx.db.prepare(\n 'UPDATE review_findings SET decision = ?, reason = ?, decided_at = ? WHERE session = ? AND agent = ? AND n = ?',\n );\n for (const item of decisions) {\n update.run(item.decision, item.reason?.trim() || null, at, session, agent, item.n);\n }\n return listFindings(ctx, session, agent);\n}\n\nexport function formatFinding(finding: Finding): string {\n const location = finding.location ? ` ${finding.location}` : '';\n const fix = finding.fix ? ` (fix: ${finding.fix})` : '';\n return `${finding.n}/${finding.total} [${finding.severity}]${location} — ${finding.text}${fix}`;\n}\n\nexport function renderFindings(findings: readonly Finding[]): string {\n const lines = findings.map((finding) => {\n const location = finding.location ? ` \\`${finding.location}\\`` : '';\n const fix = finding.fix ? `\\n Fix: ${finding.fix}` : '';\n return `${finding.n}. **${finding.severity}**${location}: ${finding.text}${fix}`;\n });\n return `## Findings\\n\\n${lines.join('\\n')}`;\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\n\nexport const MAX_ALTERNATIVES = 3;\n\nexport interface QuestionInput {\n text: string;\n context?: string | undefined;\n recommendation: string;\n alternatives?: readonly string[] | undefined;\n}\n\nexport interface Question {\n n: number;\n total: number;\n text: string;\n context: string | null;\n recommendation: string;\n alternatives: string[];\n answer: string | null;\n answeredAt: string | null;\n}\n\nexport interface AnswerInput {\n n: number;\n answer: string;\n}\n\ninterface QuestionRow {\n n: number;\n text: string;\n context: string | null;\n recommendation: string;\n alternatives: string;\n answer: string | null;\n answered_at: string | null;\n}\n\nexport function listQuestions(\n ctx: Ctx,\n session: string,\n agent: string,\n openOnly = false,\n): Question[] {\n const rows = ctx.db\n .prepare('SELECT * FROM agent_questions WHERE session = ? AND agent = ? ORDER BY n')\n .all(session, agent) as unknown as QuestionRow[];\n const total = rows.length;\n return rows\n .filter((row) => !openOnly || row.answer === null)\n .map((row) => ({\n n: row.n,\n total,\n text: row.text,\n context: row.context,\n recommendation: row.recommendation,\n alternatives: JSON.parse(row.alternatives) as string[],\n answer: row.answer,\n answeredAt: row.answered_at,\n }));\n}\n\n// A revised plan replaces the questions still open; answered ones stay, so numbering goes on.\nexport function addQuestions(\n ctx: Ctx,\n session: string,\n agent: string,\n inputs: readonly QuestionInput[],\n): Question[] {\n for (const input of inputs) {\n if ((input.alternatives?.length ?? 0) > MAX_ALTERNATIVES) {\n throw new CarnetError(\n 'INVALID_QUESTIONS',\n `A question takes at most ${MAX_ALTERNATIVES} alternatives; list more in its text`,\n );\n }\n }\n ctx.db\n .prepare('DELETE FROM agent_questions WHERE session = ? AND agent = ? AND answer IS NULL')\n .run(session, agent);\n const last = ctx.db\n .prepare('SELECT COALESCE(MAX(n), 0) AS n FROM agent_questions WHERE session = ? AND agent = ?')\n .get(session, agent) as { n: number };\n const insert = ctx.db.prepare(\n `INSERT INTO agent_questions (session, agent, n, text, context, recommendation, alternatives)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n );\n inputs.forEach((input, index) => {\n insert.run(\n session,\n agent,\n last.n + index + 1,\n input.text.trim(),\n input.context?.trim() || null,\n input.recommendation.trim(),\n JSON.stringify(input.alternatives ?? []),\n );\n });\n return listQuestions(ctx, session, agent);\n}\n\nexport function answerQuestions(\n ctx: Ctx,\n session: string,\n agent: string,\n answers: readonly AnswerInput[],\n): Question[] {\n const known = new Set(listQuestions(ctx, session, agent).map((question) => question.n));\n const missing = answers.filter((answer) => !known.has(answer.n)).map((answer) => answer.n);\n if (missing.length) {\n throw new CarnetError(\n 'QUESTION_NOT_FOUND',\n `No question ${missing.join(', ')} for ${agent}; agent_questions lists them`,\n );\n }\n const at = nowIso(ctx);\n const update = ctx.db.prepare(\n 'UPDATE agent_questions SET answer = ?, answered_at = ? WHERE session = ? AND agent = ? AND n = ?',\n );\n for (const answer of answers) update.run(answer.answer.trim(), at, session, agent, answer.n);\n return listQuestions(ctx, session, agent);\n}\n\nexport function renderQuestions(questions: readonly Question[]): string {\n const blocks = questions.map((question) => {\n const lines = [`${question.n}. ${question.text}`];\n if (question.context) lines.push(` Context: ${question.context}`);\n lines.push(` Recommendation: ${question.recommendation}`);\n if (question.alternatives.length) {\n lines.push(` Alternatives: ${question.alternatives.join(' · ')}`);\n }\n return lines.join('\\n');\n });\n return `## Questions\\n\\n${blocks.join('\\n')}`;\n}\n","import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, join, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { DEFAULT_HOST } from '../hosts/host.ts';\nimport { defaultRunDirectory, workspacesDirectory, workspaceDefinition } from '../paths.ts';\n\nexport interface WorkspaceRepo {\n path: string;\n name: string;\n}\n\nexport interface Workspace {\n name: string;\n definition: string;\n runDirectory: string;\n repos: WorkspaceRepo[];\n backends: Record<string, { settings?: Record<string, unknown> }>;\n}\n\nexport interface WorkspaceFile {\n name?: string | undefined;\n repos?: { path: string; name?: string | undefined }[] | undefined;\n backends?: Workspace['backends'] | undefined;\n}\n\nexport const WORKSPACE_FILE = 'workspace.json';\nexport const INSTRUCTIONS_FILE = 'CLAUDE.md';\nexport const AGENTS_FILE = 'AGENTS.md';\nconst WORKSPACE_NAME = /^[a-z0-9-]+$/;\n\nexport function isWorkspaceName(name: string): boolean {\n return WORKSPACE_NAME.test(name);\n}\n\nfunction requireWorkspaceName(name: string): void {\n if (!isWorkspaceName(name)) {\n throw new CarnetError(\n 'WORKSPACE_NAME_INVALID',\n `Invalid workspace name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`,\n );\n }\n}\n\nexport function expandHome(path: string, env: NodeJS.ProcessEnv = process.env): string {\n if (path !== '~' && !path.startsWith('~/')) return path;\n return join(env.HOME || homedir(), path.slice(1));\n}\n\nfunction workspaceFilePath(name: string, env?: NodeJS.ProcessEnv): string {\n return join(workspaceDefinition(name, env), WORKSPACE_FILE);\n}\n\nexport function workspaceExists(name: string, env?: NodeJS.ProcessEnv): boolean {\n return isWorkspaceName(name) && existsSync(workspaceFilePath(name, env));\n}\n\nfunction readWorkspaceFile(name: string, env?: NodeJS.ProcessEnv): WorkspaceFile {\n if (!workspaceExists(name, env)) {\n throw new CarnetError(\n 'WORKSPACE_NOT_FOUND',\n `No workspace named ${name}: see \"rucher ws list\"`,\n );\n }\n return JSON.parse(readFileSync(workspaceFilePath(name, env), 'utf8')) as WorkspaceFile;\n}\n\nfunction writeWorkspaceFile(name: string, file: WorkspaceFile, env?: NodeJS.ProcessEnv): void {\n writeFileSync(workspaceFilePath(name, env), `${JSON.stringify(file, null, 2)}\\n`);\n}\n\nexport function loadWorkspace(name: string, env: NodeJS.ProcessEnv = process.env): Workspace {\n const file = readWorkspaceFile(name, env);\n return {\n name,\n definition: workspaceDefinition(name, env),\n runDirectory: defaultRunDirectory(name, env),\n repos: (file.repos ?? []).map((repo) => {\n const path = resolve(expandHome(repo.path, env));\n return { path, name: repo.name ?? basename(path) };\n }),\n backends: file.backends ?? {},\n };\n}\n\nexport function listWorkspaces(env: NodeJS.ProcessEnv = process.env): Workspace[] {\n const directory = workspacesDirectory(env);\n if (!existsSync(directory)) return [];\n return readdirSync(directory)\n .filter((name) => workspaceExists(name, env))\n .sort()\n .map((name) => loadWorkspace(name, env));\n}\n\nexport function workspaceHosts(workspace: Workspace): string[] {\n const hosts = Object.keys(workspace.backends);\n return hosts.length ? hosts : [DEFAULT_HOST];\n}\n\nfunction checkedRepo(path: string, env?: NodeJS.ProcessEnv): string {\n const absolute = resolve(expandHome(path, env));\n if (!existsSync(absolute))\n throw new CarnetError('REPO_NOT_FOUND', `Repo path does not exist: ${absolute}`);\n return absolute;\n}\n\n// Notes reference repos by name, so two repos cannot share one.\nfunction requireDistinctNames(workspace: string, repos: readonly WorkspaceRepo[]): void {\n const names = repos.map((repo) => repo.name);\n const shared = names.find((name, index) => names.indexOf(name) !== index);\n if (shared) {\n throw new CarnetError(\n 'REPO_NAME_TAKEN',\n `${workspace} would have two repos named ${shared}: give them distinct names`,\n );\n }\n}\n\nexport interface CreateWorkspaceOptions {\n repos?: readonly string[] | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nexport function createWorkspace(name: string, options: CreateWorkspaceOptions = {}): Workspace {\n const { env } = options;\n requireWorkspaceName(name);\n if (workspaceExists(name, env))\n throw new CarnetError('WORKSPACE_EXISTS', `Workspace ${name} already exists`);\n const paths = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))];\n const repos = paths.map((path) => ({ path, name: basename(path) }));\n requireDistinctNames(name, repos);\n const definition = workspaceDefinition(name, env);\n const runDirectory = defaultRunDirectory(name, env);\n mkdirSync(definition, { recursive: true });\n mkdirSync(runDirectory, { recursive: true });\n writeWorkspaceFile(name, { name, repos, backends: {} }, env);\n const instructions = join(definition, INSTRUCTIONS_FILE);\n if (!existsSync(instructions)) writeFileSync(instructions, '');\n return loadWorkspace(name, env);\n}\n\nexport function definitionInstructions(workspace: Workspace): string {\n const agents = existsSync(join(workspace.definition, AGENTS_FILE));\n if (agents && existsSync(join(workspace.definition, INSTRUCTIONS_FILE))) {\n throw new CarnetError(\n 'WORKSPACE_INSTRUCTIONS_CONFLICT',\n `Workspace ${workspace.name} has both ${AGENTS_FILE} and ${INSTRUCTIONS_FILE} in ${workspace.definition}: remove ${INSTRUCTIONS_FILE}`,\n );\n }\n return agents ? AGENTS_FILE : INSTRUCTIONS_FILE;\n}\n\nexport function addWorkspaceRepo(name: string, repo: string, env?: NodeJS.ProcessEnv): Workspace {\n const file = readWorkspaceFile(name, env);\n const workspace = loadWorkspace(name, env);\n const path = checkedRepo(repo, env);\n if (workspace.repos.some((existing) => existing.path === path)) return workspace;\n requireDistinctNames(name, [...workspace.repos, { path, name: basename(path) }]);\n writeWorkspaceFile(\n name,\n { ...file, repos: [...(file.repos ?? []), { path, name: basename(path) }] },\n env,\n );\n return loadWorkspace(name, env);\n}\n\nexport function removeWorkspaceRepo(\n name: string,\n repo: string,\n env?: NodeJS.ProcessEnv,\n): Workspace {\n const file = readWorkspaceFile(name, env);\n const workspace = loadWorkspace(name, env);\n const path = resolve(expandHome(repo, env));\n const index = workspace.repos.findIndex(\n (existing) => existing.path === path || existing.name === repo,\n );\n if (index === -1) throw new CarnetError('REPO_NOT_FOUND', `${repo} is not a repo of ${name}`);\n writeWorkspaceFile(\n name,\n { ...file, repos: (file.repos ?? []).filter((_, position) => position !== index) },\n env,\n );\n return loadWorkspace(name, env);\n}\n\nexport interface DropWorkspaceOptions {\n purge?: boolean | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nexport function dropWorkspace(name: string, options: DropWorkspaceOptions = {}): Workspace {\n const workspace = loadWorkspace(name, options.env);\n rmSync(workspace.definition, { recursive: true, force: true });\n if (options.purge) rmSync(workspace.runDirectory, { recursive: true, force: true });\n return workspace;\n}\n","import { closeAgentsWhere } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { logEvent } from './events.ts';\nimport { type Workspace, repoNameFor } from './workspace/locate.ts';\nimport { DEFAULT_HOST, type HostSessionPayload } from './hosts/host.ts';\n\nexport type SessionKind = 'active' | 'temp';\nexport type SessionStatus = 'running' | 'idle' | 'archived';\n\nexport interface Session {\n id: string;\n workspace: string;\n name: string | null;\n purpose: string | null;\n kind: SessionKind;\n status: SessionStatus;\n cwd: string | null;\n repo: string | null;\n host: string;\n hostPid: number | null;\n hookedAt: string | null;\n lastTitle: string | null;\n parentId: string | null;\n promptVersion: string | null;\n pluginVersion: string | null;\n createdAt: string;\n lastActiveAt: string;\n endedAt: string | null;\n}\n\ninterface SessionRow {\n id: string;\n workspace: string;\n name: string | null;\n purpose: string | null;\n kind: SessionKind;\n status: SessionStatus;\n cwd: string | null;\n repo: string | null;\n host: string;\n host_pid: number | null;\n hooked_at: string | null;\n last_title: string | null;\n parent_id: string | null;\n prompt_version: string | null;\n plugin_version: string | null;\n created_at: string;\n last_active_at: string;\n ended_at: string | null;\n}\n\nexport type HookSessionPayload = HostSessionPayload;\n\nexport interface HookEnv {\n host?: string | undefined;\n processId?: number | null | undefined;\n RUCHER_PURGE_DAYS?: string | undefined;\n RUCHER_HOME?: string | undefined;\n RUCHER_SESSION_ID?: string | undefined;\n RUCHER_SESSION_KIND?: string | undefined;\n RUCHER_SESSION_NAME?: string | undefined;\n RUCHER_PROMPT_VERSION?: string | undefined;\n RUCHER_MEMORY_MAX_CHARACTERS?: string | undefined;\n RUCHER_MEMORY_HALF_LIFE_DAYS?: string | undefined;\n CLAUDE_CONFIG_DIR?: string | undefined;\n}\n\nexport interface CreateSessionInput {\n id: string;\n kind: SessionKind;\n name?: string | null | undefined;\n cwd: string;\n repo?: string | null | undefined;\n host?: string | undefined;\n}\n\nexport interface ListSessionsOptions {\n includeTemp?: boolean | undefined;\n includeArchived?: boolean | undefined;\n}\n\nconst COLUMNS = `id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,\n parent_id, prompt_version, plugin_version, created_at, last_active_at, ended_at`;\n\nfunction toSession(row: SessionRow): Session {\n return {\n id: row.id,\n workspace: row.workspace,\n name: row.name,\n purpose: row.purpose,\n kind: row.kind,\n status: row.status,\n cwd: row.cwd,\n repo: row.repo,\n host: row.host,\n hostPid: row.host_pid,\n hookedAt: row.hooked_at,\n lastTitle: row.last_title,\n parentId: row.parent_id,\n promptVersion: row.prompt_version,\n pluginVersion: row.plugin_version,\n createdAt: row.created_at,\n lastActiveAt: row.last_active_at,\n endedAt: row.ended_at,\n };\n}\n\nfunction workspaceOf(ctx: Ctx): string {\n if (ctx.workspace !== null) return ctx.workspace;\n throw new CarnetError('NO_WORKSPACE', 'A session belongs to a workspace: there is none here');\n}\n\nexport function getSession(ctx: Ctx, id: string): Session | undefined {\n const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id) as\n | SessionRow\n | undefined;\n return row && toSession(row);\n}\n\nexport function requireSession(ctx: Ctx, id: string): Session {\n const session = getSession(ctx, id);\n if (!session) throw new CarnetError('SESSION_NOT_FOUND', `Unknown session ${id}`);\n return session;\n}\n\nexport function ensureSession(\n ctx: Ctx,\n id: string,\n cwd?: string,\n workspace?: Workspace | null,\n): Session {\n const existing = getSession(ctx, id);\n if (existing) return existing;\n const at = nowIso(ctx);\n ctx.db\n .prepare(\n 'INSERT INTO sessions (id, workspace, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?, ?)',\n )\n .run(id, workspaceOf(ctx), cwd ?? null, workspace ? repoNameFor(workspace, cwd) : null, at, at);\n return requireSession(ctx, id);\n}\n\nfunction nameTaken(error: unknown, name: string | null | undefined): never {\n if (name && error instanceof Error && error.message.includes('UNIQUE')) {\n throw new CarnetError('SESSION_NAME_TAKEN', `A session named \"${name}\" already exists`);\n }\n throw error;\n}\n\nexport function createSession(ctx: Ctx, input: CreateSessionInput): Session {\n if (input.kind === 'active' && !input.name) {\n throw new CarnetError('SESSION_NAME_REQUIRED', 'An active session needs a name');\n }\n const at = nowIso(ctx);\n try {\n ctx.db\n .prepare(\n `INSERT INTO sessions (id, workspace, name, kind, status, cwd, repo, host, last_title,\n created_at, last_active_at)\n VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n input.id,\n workspaceOf(ctx),\n input.name ?? null,\n input.kind,\n input.cwd,\n input.repo ?? null,\n input.host ?? DEFAULT_HOST,\n input.name ?? null,\n at,\n at,\n );\n } catch (error) {\n nameTaken(error, input.name);\n }\n return requireSession(ctx, input.id);\n}\n\nexport function setSessionKind(\n ctx: Ctx,\n id: string,\n kind: SessionKind,\n name?: string | null,\n): Session {\n const session = requireSession(ctx, id);\n const nextName = name ?? session.name;\n if (kind === 'active' && !nextName) {\n throw new CarnetError('SESSION_NAME_REQUIRED', 'An active session needs a name');\n }\n try {\n ctx.db\n .prepare('UPDATE sessions SET kind = ?, name = ?, last_title = ? WHERE id = ?')\n .run(kind, nextName, nextName ?? session.lastTitle, id);\n } catch (error) {\n nameTaken(error, nextName);\n }\n return requireSession(ctx, id);\n}\n\n// Both the launching process and the SessionEnd hook report the end: only the first one counts.\nexport function endSession(ctx: Ctx, id: string): Session {\n const session = requireSession(ctx, id);\n if (session.status !== 'running') return session;\n const ended = setSessionStatus(ctx, id, 'idle');\n logEvent(ctx, id, { type: 'session.ended' });\n return ended;\n}\n\nfunction titleAvailable(ctx: Ctx, id: string, title: string): boolean {\n const owner = sessionByName(ctx, title);\n return !owner || owner.id === id;\n}\n\n// The Rucher name is canonical: a host title only renames the session when the title itself\n// changed since it was last seen, so a rename made in Rucher survives the next prompt.\nexport function adoptTitle(ctx: Ctx, id: string, rawTitle: string | undefined): Session {\n const session = requireSession(ctx, id);\n const title = rawTitle?.trim() || null;\n if (title === null || title === session.lastTitle) return session;\n ctx.db.prepare('UPDATE sessions SET last_title = ? WHERE id = ?').run(title, id);\n if (title === session.name || !titleAvailable(ctx, id, title)) return requireSession(ctx, id);\n ctx.db\n .prepare(\n `UPDATE sessions\n SET name = ?, kind = CASE WHEN name IS NULL THEN 'active' ELSE kind END\n WHERE id = ?`,\n )\n .run(title, id);\n return requireSession(ctx, id);\n}\n\nexport function upsertFromHook(\n ctx: Ctx,\n workspace: Workspace | null,\n payload: HookSessionPayload,\n env: HookEnv = {},\n): Session {\n const at = nowIso(ctx);\n const host = env.host ?? DEFAULT_HOST;\n const hostPid = env.processId ?? null;\n const repo = workspace ? repoNameFor(workspace, payload.cwd) : null;\n const existing = getSession(ctx, payload.session_id);\n if (!existing) {\n ctx.db\n .prepare(\n `INSERT INTO sessions (id, workspace, cwd, repo, host, host_pid, hooked_at, created_at,\n last_active_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n payload.session_id,\n workspaceOf(ctx),\n payload.cwd ?? null,\n repo,\n host,\n hostPid,\n at,\n at,\n at,\n );\n } else {\n ctx.db\n .prepare(\n `UPDATE sessions\n SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?\n WHERE id = ?`,\n )\n .run(\n at,\n at,\n // Claude Code keeps transcripts under the launch cwd; the hook's cwd follows every `cd`.\n existing.cwd ?? payload.cwd ?? null,\n existing.cwd ? existing.repo : (repo ?? existing.repo),\n host,\n hostPid ?? existing.hostPid,\n payload.session_id,\n );\n }\n return adoptTitle(ctx, payload.session_id, payload.session_title);\n}\n\nexport function touchSession(ctx: Ctx, id: string): void {\n ctx.db.prepare('UPDATE sessions SET last_active_at = ? WHERE id = ?').run(nowIso(ctx), id);\n}\n\nexport function nameSession(ctx: Ctx, id: string, name: string, purpose?: string): Session {\n requireSession(ctx, id);\n try {\n ctx.db\n .prepare(\n `UPDATE sessions\n SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,\n kind = 'active'\n WHERE id = ?`,\n )\n .run(name, purpose ?? null, nowIso(ctx), id);\n } catch (error) {\n if (error instanceof Error && error.message.includes('UNIQUE')) {\n throw new CarnetError('SESSION_NAME_TAKEN', `A session named \"${name}\" already exists`);\n }\n throw error;\n }\n return requireSession(ctx, id);\n}\n\nexport function listSessions(ctx: Ctx, options: ListSessionsOptions = {}): Session[] {\n const conditions: string[] = ['workspace = ?'];\n if (!options.includeTemp) conditions.push(\"kind != 'temp'\");\n if (!options.includeArchived) conditions.push(\"status != 'archived'\");\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(' AND ')} ORDER BY last_active_at DESC, rowid DESC`,\n )\n .all(ctx.workspace) as unknown as SessionRow[];\n return rows.map(toSession);\n}\n\nexport function dropSession(ctx: Ctx, id: string): Session {\n requireSession(ctx, id);\n const at = nowIso(ctx);\n closeAgentsWhere(ctx.db, 'session = ?', [id], at);\n ctx.db\n .prepare(\"UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?\")\n .run(at, id);\n return requireSession(ctx, id);\n}\n\nexport function defaultSession(ctx: Ctx): Session | undefined {\n const row = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND status != 'archived'\n ORDER BY last_active_at DESC, rowid DESC LIMIT 1`,\n )\n .get(ctx.workspace) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport function sessionByName(ctx: Ctx, name: string): Session | undefined {\n const row = ctx.db\n .prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND name = ?`)\n .get(ctx.workspace, name) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport const MINIMUM_ID_PREFIX = 4;\n\nexport function shortId(id: string): string {\n return id.slice(0, 8);\n}\n\nexport function findSession(ctx: Ctx, reference: string): Session {\n const byName = sessionByName(ctx, reference);\n if (byName) return byName;\n const byId = getSession(ctx, reference);\n if (byId) return byId;\n const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);\n if (isIdPrefix && reference.length >= MINIMUM_ID_PREFIX) {\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND id LIKE ?\n ORDER BY last_active_at DESC, rowid DESC`,\n )\n .all(ctx.workspace, `${reference.toLowerCase()}%`) as unknown as SessionRow[];\n const [only, ...others] = rows;\n if (only && others.length === 0) return toSession(only);\n if (only) {\n const matches = rows.map((row) => shortId(row.id)).join(', ');\n throw new CarnetError(\n 'SESSION_AMBIGUOUS',\n `Session id \"${reference}\" matches several sessions: ${matches}`,\n );\n }\n }\n const hint =\n isIdPrefix && reference.length < MINIMUM_ID_PREFIX\n ? ` (an id prefix needs at least ${MINIMUM_ID_PREFIX} characters)`\n : '';\n throw new CarnetError('SESSION_NOT_FOUND', `Unknown session \"${reference}\"${hint}`);\n}\n\nexport function sessionByHostProcess(\n ctx: Ctx,\n host: string,\n processId: number,\n): Session | undefined {\n const row = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions\n WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL\n ORDER BY hooked_at DESC, rowid DESC LIMIT 1`,\n )\n .get(host, processId) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport function recordPluginVersion(ctx: Ctx, id: string, version: string | null): void {\n ctx.db.prepare('UPDATE sessions SET plugin_version = ? WHERE id = ?').run(version, id);\n}\n\nexport function recordPromptVersion(ctx: Ctx, id: string, version: string | null): Session {\n requireSession(ctx, id);\n ctx.db.prepare('UPDATE sessions SET prompt_version = ? WHERE id = ?').run(version, id);\n return requireSession(ctx, id);\n}\n\nexport function setParent(ctx: Ctx, id: string, parentId: string): Session {\n requireSession(ctx, id);\n requireSession(ctx, parentId);\n ctx.db.prepare('UPDATE sessions SET parent_id = ? WHERE id = ?').run(parentId, id);\n return requireSession(ctx, id);\n}\n\nexport function setSessionStatus(ctx: Ctx, id: string, status: SessionStatus): Session {\n requireSession(ctx, id);\n const at = nowIso(ctx);\n ctx.db\n .prepare(\n `UPDATE sessions\n SET status = ?, last_active_at = ?,\n ended_at = CASE WHEN ? = 'running' THEN NULL WHEN ? = 'idle' THEN ? ELSE ended_at END\n WHERE id = ?`,\n )\n .run(status, at, status, status, at, id);\n return requireSession(ctx, id);\n}\n\nfunction refuseWhileRunning(session: Session, action: string): void {\n if (session.status === 'running') {\n throw new CarnetError(\n 'SESSION_RUNNING',\n `Session ${session.name ?? shortId(session.id)} is running: ${action} it once it has ended`,\n );\n }\n}\n\n// last_title keeps the host title last seen: the old title then matches it and doesn't undo the rename.\nexport function renameSession(ctx: Ctx, id: string, name: string): Session {\n const session = requireSession(ctx, id);\n refuseWhileRunning(session, 'rename');\n try {\n ctx.db.prepare('UPDATE sessions SET name = ? WHERE id = ?').run(name, id);\n } catch (error) {\n nameTaken(error, name);\n }\n return requireSession(ctx, id);\n}\n\nexport function promoteSession(ctx: Ctx, id: string, name?: string): Session {\n const session = requireSession(ctx, id);\n if (session.kind === 'active') {\n throw new CarnetError('SESSION_KIND_INVALID', `Session ${session.name} is already active`);\n }\n const nextName = name ?? session.name;\n if (!nextName) {\n throw new CarnetError('SESSION_NAME_REQUIRED', 'An active session needs a name');\n }\n if (nextName !== session.name) refuseWhileRunning(session, 'rename');\n try {\n ctx.db.prepare(\"UPDATE sessions SET kind = 'active', name = ? WHERE id = ?\").run(nextName, id);\n } catch (error) {\n nameTaken(error, nextName);\n }\n return requireSession(ctx, id);\n}\n\nexport function demoteSession(ctx: Ctx, id: string): Session {\n const session = requireSession(ctx, id);\n if (session.kind === 'temp') {\n throw new CarnetError(\n 'SESSION_KIND_INVALID',\n `Session ${session.name ?? shortId(session.id)} is already temp`,\n );\n }\n ctx.db.prepare(\"UPDATE sessions SET kind = 'temp' WHERE id = ?\").run(id);\n return requireSession(ctx, id);\n}\n\nexport function staleTempSessions(ctx: Ctx, olderThanMilliseconds: number): Session[] {\n const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions\n WHERE workspace = ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?\n ORDER BY last_active_at ASC, rowid ASC`,\n )\n .all(ctx.workspace, before) as unknown as SessionRow[];\n return rows.map(toSession);\n}\n\nexport function resetDeadSessions(ctx: Ctx, isAlive: (processId: number) => boolean): Session[] {\n const running = (\n ctx.db\n .prepare(`SELECT ${COLUMNS} FROM sessions WHERE status = 'running'`)\n .all() as unknown as SessionRow[]\n ).map(toSession);\n const dead = running.filter((session) => session.hostPid === null || !isAlive(session.hostPid));\n return dead.map((session) => endSession(ctx, session.id));\n}\n","// Generated from docs/workflow.md by pnpm run build. Do not edit.\nexport const CORE_RULES = `- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches agents, asks for their report and its next action (inject, validate, apply, triage), applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the Main line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When an agent finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that report or its next action (/rucher:next), even when answering about something else.\n- Agents never commit, push, stash or record notes. An agent follows its kind's contract, writes its report to a file ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- To launch agents or handle their results, load the rucher skill: it holds the full workflow.`;\n","import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Workspace } from '../workspace/workspace.ts';\nimport { corePromptPath, promptsDirectory } from '../paths.ts';\nimport { shortId, type SessionKind } from '../sessions.ts';\nimport { CORE_RULES } from './core-rules.ts';\n\nexport const PROMPT_FILE = 'prompt.md';\n\nexport interface PromptSession {\n id: string;\n name: string | null;\n kind: SessionKind;\n}\n\nexport interface AssembledPrompt {\n text: string;\n version: string;\n}\n\nexport interface AppendPromptFile {\n path: string;\n version: string;\n}\n\nfunction readIfPresent(path: string): string | undefined {\n if (!existsSync(path)) return undefined;\n const content = readFileSync(path, 'utf8').trim();\n return content || undefined;\n}\n\nexport function baseRules(env: NodeJS.ProcessEnv = process.env): string {\n return readIfPresent(corePromptPath(env)) ?? CORE_RULES;\n}\n\nexport function workspaceRules(workspace: Workspace | null): string | undefined {\n return workspace ? readIfPresent(join(workspace.definition, PROMPT_FILE)) : undefined;\n}\n\nexport function rulesText(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n const extra = workspaceRules(workspace);\n const base = `Rucher rules, always follow them:\\n${baseRules(env)}`;\n return extra && workspace\n ? `${base}\\n\\nRules of the ${workspace.name} workspace:\\n${extra}`\n : base;\n}\n\n// The identity block is left out so that renaming a session doesn't read as a rules change.\nexport function rulesVersion(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return createHash('sha256').update(rulesText(workspace, env)).digest('hex').slice(0, 12);\n}\n\nexport function assemblePrompt(\n workspace: Workspace | null,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AssembledPrompt {\n const label = session.name ?? shortId(session.id);\n const identity = workspace\n ? `This is the Rucher session ${label} (${session.kind}) of the ${workspace.name} workspace.`\n : `This is the Rucher session ${label} (${session.kind}), outside any workspace.`;\n return {\n text: `${rulesText(workspace, env)}\\n\\n${identity}\\n`,\n version: rulesVersion(workspace, env),\n };\n}\n\nexport function appendPromptFile(\n workspace: Workspace | null,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AppendPromptFile {\n const { text, version } = assemblePrompt(workspace, session, env);\n const directory = promptsDirectory(env);\n mkdirSync(directory, { recursive: true });\n const path = join(directory, `${session.id}.md`);\n writeFileSync(path, text);\n return { path, version };\n}\n\nexport function compactReminder(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${rulesText(workspace, env)}`;\n}\n\nexport function outsideRucherContext(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return `This session was started without rucher, so its system prompt does not hold the Rucher rules. ${rulesText(workspace, env)}`;\n}\n\nexport const OUTSIDE_RUCHER_NOTICE =\n 'rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)';\n\nexport const RULES_UPDATED_NOTICE =\n 'rucher: rules updated, will apply after the next compaction or in a new session';\n\nexport const SUBAGENT_RULES =\n 'Rucher rules for sub-agents: never commit, push or stash. When your task asks for a report, write it to the file it names. If your prompt names you as a Carnet agent, follow the contract of its kind, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.';\n","import { lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CarnetError } from './errors.ts';\n\nexport const GENERATED_MARKER = 'generated by rucher, do not edit';\n\nfunction refuse(path: string): never {\n throw new CarnetError(\n 'RUN_DIRECTORY_FILE_CONFLICT',\n `${path} was not written by rucher: move its content to the workspace definition, then remove it`,\n );\n}\n\nfunction entry(path: string): ReturnType<typeof lstatSync> | undefined {\n try {\n return lstatSync(path);\n } catch {\n return undefined;\n }\n}\n\n// Claude Code strips HTML block comments from instruction files, so the marker costs no tokens.\nexport const MARKDOWN_MARKER = `<!-- ${GENERATED_MARKER} -->\\n`;\n\nexport function markdownCopy(content: string): string {\n return `${MARKDOWN_MARKER}${content}`;\n}\n\nfunction isMarkdownCopy(path: string): boolean {\n const current = entry(path);\n if (!current?.isFile()) return false;\n return readFileSync(path, 'utf8').startsWith(MARKDOWN_MARKER);\n}\n\n// Copies whose definition file is gone, at the top level of the directory; hand-written files stay.\nexport function removeStaleCopies(directory: string, keep: ReadonlySet<string>): string[] {\n const removed: string[] = [];\n if (!entry(directory)) return removed;\n for (const name of readdirSync(directory)) {\n if (!name.endsWith('.md') || keep.has(name)) continue;\n const path = join(directory, name);\n if (!isMarkdownCopy(path)) continue;\n rmSync(path, { force: true });\n removed.push(name);\n }\n return removed;\n}\n\nexport function writeGenerated(path: string, content: string): boolean {\n const current = entry(path);\n if (current?.isSymbolicLink()) rmSync(path, { force: true });\n else if (current) {\n const existing = readFileSync(path, 'utf8');\n if (existing === content) return false;\n if (!existing.includes(GENERATED_MARKER)) refuse(path);\n }\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content);\n return true;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function mergeSettings(\n base: Record<string, unknown>,\n extra: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(extra)) {\n const current = merged[key];\n if (Array.isArray(current) && Array.isArray(value)) {\n const seen = new Set(current.map((item) => JSON.stringify(item)));\n merged[key] = [...current, ...value.filter((item) => !seen.has(JSON.stringify(item)))];\n } else if (isObject(current) && isObject(value)) {\n merged[key] = mergeSettings(current, value);\n } else {\n merged[key] = value;\n }\n }\n return merged;\n}\n","import { renameSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { CarnetError } from '../errors.ts';\n\nexport interface UndoStep {\n // The shell command that does the same by hand, printed when the step itself fails.\n command: string;\n run: () => void;\n}\n\nexport interface UndoOutcome {\n undone: string[];\n left: string[];\n}\n\nexport class UndoList {\n private readonly steps: UndoStep[] = [];\n\n push(step: UndoStep): void {\n this.steps.push(step);\n }\n\n // Once one step fails, the later ones would act on a half-restored tree, so they are only listed.\n undo(): UndoOutcome {\n const outcome: UndoOutcome = { undone: [], left: [] };\n for (const step of [...this.steps].reverse()) {\n if (outcome.left.length) {\n outcome.left.push(step.command);\n continue;\n }\n try {\n step.run();\n outcome.undone.push(step.command);\n } catch {\n outcome.left.push(step.command);\n }\n }\n this.steps.length = 0;\n return outcome;\n }\n}\n\nexport function shellQuote(path: string): string {\n return `'${path.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nexport function moveTracked(undo: UndoList, move: { from: string; to: string }): void {\n renameSync(move.from, move.to);\n undo.push({\n command: `mv ${shellQuote(move.to)} ${shellQuote(move.from)}`,\n run: () => renameSync(move.to, move.from),\n });\n}\n\nexport function relocateFailed(error: unknown, undo: UndoList, backup: string): never {\n const outcome = undo.undo();\n const cause = error instanceof Error ? error.message : String(error);\n if (outcome.left.length === 0) {\n if (error instanceof CarnetError) throw error;\n throw new CarnetError('WORKSPACE_RELOCATE_FAILED', `${cause}; nothing was changed`);\n }\n throw new CarnetError(\n 'WORKSPACE_RELOCATE_FAILED',\n `${cause}; undo stopped, run by hand:\\n${outcome.left.join('\\n')}\\nDatabase backup: ${join(backup, 'carnet.db')}`,\n );\n}\n","import {\n closeSync,\n existsSync,\n fstatSync,\n openSync,\n readdirSync,\n readFileSync,\n mkdirSync,\n readSync,\n renameSync,\n rmdirSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport {\n AGENTS_FILE,\n type Workspace,\n INSTRUCTIONS_FILE,\n definitionInstructions,\n} from '../workspace/workspace.ts';\nimport { PROMPT_FILE } from '../prompt/prompt.ts';\nimport {\n GENERATED_MARKER,\n markdownCopy,\n mergeSettings,\n removeStaleCopies,\n writeGenerated,\n} from '../run-directory-files.ts';\nimport type {\n Host,\n HostRender,\n HostPromptPayload,\n HostSessionEndPayload,\n HostStopPayload,\n HostToolPayload,\n HostSessionPayload,\n HostSubagentPayload,\n LaunchOptions,\n ProjectRelocation,\n} from './host.ts';\nimport { CarnetError } from '../errors.ts';\nimport { shellQuote, type UndoStep } from '../workspace/undo.ts';\n\nconst TRANSCRIPT_TAIL_BYTES = 256 * 1024;\nconst TRANSCRIPT_HEAD_BYTES = 64 * 1024;\nconst TITLE_PATTERN = /\"type\":\"custom-title\",\"customTitle\":(\"(?:[^\"\\\\]|\\\\.)*\")/g;\nconst FORK_NAME_PATTERN = /You are (?:agent|fork) `([^`]+)`/;\n\nfunction payloadObject(json: string): Record<string, unknown> {\n const data = JSON.parse(json) as Record<string, unknown>;\n if (typeof data.session_id !== 'string' || !data.session_id) {\n throw new TypeError('Hook payload has no session_id');\n }\n return data;\n}\n\nfunction text(data: Record<string, unknown>, key: string): string | undefined {\n const value = data[key];\n return typeof value === 'string' ? value : undefined;\n}\n\n// Bash commands are not parsed: their cwd is the only reliable path.\nfunction touchedPath(\n toolName: string | undefined,\n input: unknown,\n cwd: string | undefined,\n): string | undefined {\n const fields =\n typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {};\n if (toolName === 'Read' || toolName === 'Edit' || toolName === 'Write') {\n return text(fields, 'file_path');\n }\n if (toolName === 'Grep' || toolName === 'Glob') return text(fields, 'path') ?? cwd;\n if (toolName === 'Bash') return cwd;\n return undefined;\n}\n\nfunction ownTaskDescription(data: Record<string, unknown>, agentId: string): string | undefined {\n const tasks = data.background_tasks;\n if (!Array.isArray(tasks)) return undefined;\n const own = tasks.find(\n (task): task is Record<string, unknown> =>\n typeof task === 'object' && task !== null && (task as Record<string, unknown>).id === agentId,\n );\n return own ? text(own, 'description') : undefined;\n}\n\nfunction subagentMetadataDescription(transcriptPath: string): string | undefined {\n try {\n const metadata = JSON.parse(\n readFileSync(transcriptPath.replace(/\\.jsonl$/, '.meta.json'), 'utf8'),\n ) as Record<string, unknown>;\n return text(metadata, 'description');\n } catch {\n return undefined;\n }\n}\n\nfunction launchedNames(toolInput: Record<string, unknown>): string[] | undefined {\n const prompt = text(toolInput, 'prompt');\n const names = [text(toolInput, 'description'), prompt && FORK_NAME_PATTERN.exec(prompt)?.[1]];\n const found = names.filter((name): name is string => Boolean(name));\n return found.length > 0 ? [...new Set(found)] : undefined;\n}\n\nfunction subagentPromptName(transcriptPath: string): string | undefined {\n try {\n const firstLine = readFileSync(transcriptPath, 'utf8').split('\\n', 1)[0] ?? '';\n return FORK_NAME_PATTERN.exec(firstLine)?.[1];\n } catch {\n return undefined;\n }\n}\n\n// A slice of the file, so a long transcript is never read whole.\nfunction readSlice(path: string, from: 'start' | 'end', bytes: number): string | undefined {\n let descriptor: number | undefined;\n try {\n descriptor = openSync(path, 'r');\n const size = fstatSync(descriptor).size;\n const length = Math.min(size, bytes);\n const buffer = Buffer.alloc(length);\n readSync(descriptor, buffer, 0, length, from === 'end' ? size - length : 0);\n return buffer.toString('utf8');\n } catch {\n return undefined;\n } finally {\n if (descriptor !== undefined) closeSync(descriptor);\n }\n}\n\nexport function transcriptTitle(path: string): string | undefined {\n const tail = readSlice(path, 'end', TRANSCRIPT_TAIL_BYTES);\n if (tail === undefined) return undefined;\n const last = [...tail.matchAll(TITLE_PATTERN)].at(-1)?.[1];\n return last === undefined ? undefined : (JSON.parse(last) as string);\n}\n\nfunction records(text: string | undefined): Record<string, unknown>[] {\n return (text ?? '').split('\\n').flatMap((line) => {\n try {\n const value = JSON.parse(line) as unknown;\n return value && typeof value === 'object' ? [value as Record<string, unknown>] : [];\n } catch {\n return [];\n }\n });\n}\n\n// Claude Code hands a conversation over to a new id (Remote Control, its daemon) by forking it:\n// the old transcript ends with continued-in, the new one opens with derived-from.\nfunction continuesConversation(\n parentFile: string,\n childFile: string,\n parentId: string,\n childId: string,\n): boolean {\n const handedOver = records(readSlice(parentFile, 'end', TRANSCRIPT_TAIL_BYTES)).some(\n (record) => record.type === 'continued-in' && record.continuedInSessionId === childId,\n );\n if (handedOver) return true;\n return records(readSlice(childFile, 'start', TRANSCRIPT_HEAD_BYTES)).some(\n (record) =>\n record.type === 'derived-from' &&\n Array.isArray(record.sessions) &&\n record.sessions.some(\n (source: unknown) =>\n !!source &&\n typeof source === 'object' &&\n (source as Record<string, unknown>).id === parentId &&\n (source as Record<string, unknown>).via === 'resume',\n ),\n );\n}\n\nconst SETTINGS_FILE = join('.claude', 'settings.json');\nconst BACKEND_NOTES = 'backends/claude.md';\n\n// Instruction files are copied, not linked: an @ import inside a link resolves next to its target,\n// outside the run directory, where Claude Code skips it without approval.\nexport function instructionFiles(workspace: Workspace): string[] {\n if (!existsSync(workspace.definition)) return [];\n return readdirSync(workspace.definition, { withFileTypes: true })\n .filter((item) => item.isFile() && item.name.endsWith('.md') && item.name !== PROMPT_FILE)\n .map((item) => item.name)\n .sort();\n}\n\nfunction repoAgentsImports(workspace: Workspace): string[] {\n return workspace.repos\n .filter(\n (repo) =>\n existsSync(join(repo.path, AGENTS_FILE)) &&\n !existsSync(join(repo.path, INSTRUCTIONS_FILE)) &&\n !existsSync(join(repo.path, '.claude', INSTRUCTIONS_FILE)),\n )\n .map((repo) => `@${join(repo.path, AGENTS_FILE)}`);\n}\n\n// Claude Code has no reliable native AGENTS.md loading, so a generated CLAUDE.md imports it.\nfunction runDirectoryCopies(workspace: Workspace): Map<string, string> {\n const agents = definitionInstructions(workspace) === AGENTS_FILE;\n const read = (name: string) => readFileSync(join(workspace.definition, name), 'utf8');\n const copies = new Map(\n instructionFiles(workspace).map((name) => [name, markdownCopy(read(name))]),\n );\n if (!agents) return copies;\n const imports = [`@${AGENTS_FILE}`];\n if (existsSync(join(workspace.definition, BACKEND_NOTES))) {\n copies.set(BACKEND_NOTES, markdownCopy(read(BACKEND_NOTES)));\n imports.push(`@${BACKEND_NOTES}`);\n }\n imports.push(...repoAgentsImports(workspace));\n copies.set(INSTRUCTIONS_FILE, markdownCopy(`${imports.join('\\n')}\\n`));\n return copies;\n}\n\nexport function workspaceSettings(workspace: Workspace): Record<string, unknown> {\n return mergeSettings(\n {\n '//': GENERATED_MARKER,\n permissions: {\n additionalDirectories: workspace.repos.map((repo) => repo.path),\n // The copies are rewritten on every render: instructions are edited in the definition.\n deny: [...runDirectoryCopies(workspace).keys()].sort().map((name) => `Edit(/${name})`),\n },\n },\n workspace.backends['claude-code']?.settings ?? {},\n );\n}\n\nfunction removeStaleBackendNotes(workspace: Workspace, keep: ReadonlySet<string>): string[] {\n const directory = join(workspace.runDirectory, dirname(BACKEND_NOTES));\n const removed = removeStaleCopies(\n directory,\n new Set(\n [...keep]\n .filter((name) => dirname(name) === dirname(BACKEND_NOTES))\n .map((name) => basename(name)),\n ),\n );\n if (existsSync(directory) && readdirSync(directory).length === 0) rmdirSync(directory);\n return removed.map((name) => join(dirname(BACKEND_NOTES), name));\n}\n\nfunction renderClaudeRunDirectory(workspace: Workspace): HostRender {\n const rendered: HostRender = { written: [], removed: [] };\n const copies = runDirectoryCopies(workspace);\n for (const [name, content] of [...copies].sort(([a], [b]) => a.localeCompare(b))) {\n if (writeGenerated(join(workspace.runDirectory, name), content)) rendered.written.push(name);\n }\n const names = new Set(copies.keys());\n rendered.removed.push(...removeStaleCopies(workspace.runDirectory, names));\n rendered.removed.push(...removeStaleBackendNotes(workspace, names));\n const settings = `${JSON.stringify(workspaceSettings(workspace), null, 2)}\\n`;\n if (writeGenerated(join(workspace.runDirectory, SETTINGS_FILE), settings)) {\n rendered.written.push(SETTINGS_FILE);\n }\n return rendered;\n}\n\nfunction launchArguments(options: LaunchOptions = {}): string[] {\n return [\n ...(options.name ? ['--name', options.name] : []),\n ...(options.appendPromptFile ? ['--append-system-prompt-file', options.appendPromptFile] : []),\n ...(options.directories ?? []).flatMap((directory) => ['--add-dir', directory]),\n ...(options.passthrough ?? []),\n ];\n}\n\nconst RENDERING_SOURCES = new Set(['startup', 'clear', 'compact', 'fork']);\n\nfunction projectsDirectory(env: NodeJS.ProcessEnv): string {\n return join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');\n}\n\n// Folder names are prefixes of each other (shop, shop-web): always compute the exact one.\nexport function claudeProjectFolder(cwd: string, env: NodeJS.ProcessEnv = process.env): string {\n return join(projectsDirectory(env), cwd.replace(/[^a-zA-Z0-9]/g, '-'));\n}\n\nexport function claudeConfigFile(env: NodeJS.ProcessEnv = process.env): string {\n return env.CLAUDE_CONFIG_DIR\n ? join(env.CLAUDE_CONFIG_DIR, '.claude.json')\n : join(env.HOME || homedir(), '.claude.json');\n}\n\nfunction renameStep(from: string, to: string): UndoStep {\n return {\n command: `mv ${shellQuote(to)} ${shellQuote(from)}`,\n run: () => renameSync(to, from),\n };\n}\n\nfunction moveProject(source: string, target: string): ProjectRelocation {\n if (existsSync(target)) {\n throw new CarnetError(\n 'WORKSPACE_EXISTS',\n `Claude Code already has a project folder: ${target}`,\n );\n }\n renameSync(source, target);\n return { moves: [{ from: source, to: target }], undo: [renameStep(source, target)] };\n}\n\nconst MEMORY_INDEX = 'MEMORY.md';\n\n// Conversations are named by uuid and never collide; memory files can, so they take a prefix.\nfunction mergeProject(source: string, target: string, prefix: string): ProjectRelocation {\n const relocation: ProjectRelocation = { moves: [], undo: [] };\n const move = (from: string, to: string) => {\n if (existsSync(to)) {\n throw new CarnetError('WORKSPACE_EXISTS', `Claude Code project file already exists: ${to}`);\n }\n mkdirSync(dirname(to), { recursive: true });\n renameSync(from, to);\n relocation.moves.push({ from, to });\n relocation.undo.push(renameStep(from, to));\n };\n for (const entry of readdirSync(source)) {\n if (entry !== 'memory') move(join(source, entry), join(target, entry));\n }\n const memory = join(source, 'memory');\n if (!existsSync(memory)) return removeEmpty(relocation, [source]);\n const renamed = new Map<string, string>();\n for (const entry of readdirSync(memory)) {\n if (entry === MEMORY_INDEX) continue;\n const name = existsSync(join(target, 'memory', entry)) ? `${prefix}-${entry}` : entry;\n if (name !== entry) renamed.set(entry, name);\n move(join(memory, entry), join(target, 'memory', name));\n }\n const fromIndex = join(memory, MEMORY_INDEX);\n if (existsSync(fromIndex)) {\n const intoIndex = join(target, 'memory', MEMORY_INDEX);\n if (!existsSync(intoIndex)) move(fromIndex, intoIndex);\n else {\n const original = readFileSync(intoIndex, 'utf8');\n const added = [...renamed].reduce(\n (text, [from, to]) => text.replaceAll(`(${from})`, `(${to})`),\n readFileSync(fromIndex, 'utf8'),\n );\n const separator = original.endsWith('\\n') || original === '' ? '' : '\\n';\n writeFileSync(intoIndex, `${original}${separator}\\n## Ex-workspace ${prefix}\\n\\n${added}`);\n const fromText = readFileSync(fromIndex, 'utf8');\n unlinkSync(fromIndex);\n relocation.undo.push({\n command: `# restore ${shellQuote(intoIndex)} and ${shellQuote(fromIndex)} by hand`,\n run: () => {\n writeFileSync(fromIndex, fromText);\n writeFileSync(intoIndex, original);\n },\n });\n }\n }\n return removeEmpty(relocation, [memory, source]);\n}\n\n// The emptied folders go too; the undo recreates them before moving the files back.\nfunction removeEmpty(relocation: ProjectRelocation, folders: string[]): ProjectRelocation {\n for (const folder of folders) {\n if (readdirSync(folder).length > 0) continue;\n rmdirSync(folder);\n relocation.undo.push({\n command: `mkdir -p ${shellQuote(folder)}`,\n run: () => mkdirSync(folder, { recursive: true }),\n });\n }\n return relocation;\n}\n\nfunction relocateProject(\n from: string,\n to: string,\n env: NodeJS.ProcessEnv,\n mode: 'move' | 'merge' = 'move',\n): ProjectRelocation | null {\n const source = claudeProjectFolder(from, env);\n const target = claudeProjectFolder(to, env);\n if (!existsSync(source)) return null;\n if (mode === 'move') return moveProject(source, target);\n if (!existsSync(target)) return moveProject(source, target);\n return mergeProject(source, target, basename(from));\n}\n\n// Every running Claude session rewrites this file, so it is re-read right before the write and\n// only the trust entry changes. Without a target, the entry is dropped.\nfunction moveTrust(from: string, to: string | null, env: NodeJS.ProcessEnv): boolean {\n const file = claudeConfigFile(env);\n if (!existsSync(file)) return false;\n const config = JSON.parse(readFileSync(file, 'utf8')) as { projects?: Record<string, unknown> };\n const projects = config.projects;\n if (!projects || !(from in projects) || (to !== null && to in projects)) return false;\n config.projects = Object.fromEntries(\n Object.entries(projects).flatMap(([key, value]) =>\n key !== from ? [[key, value]] : to === null ? [] : [[to, value]],\n ),\n );\n const temporary = `${file}.rucher-${process.pid}`;\n writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\\n`, { mode: statSync(file).mode });\n renameSync(temporary, file);\n return true;\n}\n\nexport const claudeCode: Host = {\n id: 'claude-code',\n displayName: 'Claude Code',\n processId(env) {\n const processId = Number(env.CLAUDE_PID);\n return Number.isInteger(processId) && processId > 0 ? processId : null;\n },\n sessionIdFromEnvironment(env) {\n return env.CLAUDE_CODE_SESSION_ID || undefined;\n },\n projectDirectory(env) {\n return env.CLAUDE_PROJECT_DIR || undefined;\n },\n parseSessionPayload(json): HostSessionPayload {\n const data = payloadObject(json);\n return {\n session_id: data.session_id as string,\n cwd: text(data, 'cwd'),\n source: text(data, 'source'),\n session_title: text(data, 'session_title'),\n };\n },\n parseStopPayload(json): HostStopPayload {\n const data = payloadObject(json);\n return {\n session_id: data.session_id as string,\n cwd: text(data, 'cwd'),\n failed: data.hook_event_name === 'StopFailure',\n };\n },\n parsePromptPayload(json): HostPromptPayload {\n const data = payloadObject(json);\n return {\n session_id: data.session_id as string,\n cwd: text(data, 'cwd'),\n session_title: text(data, 'session_title'),\n transcript_path: text(data, 'transcript_path'),\n };\n },\n parseSubagentPayload(json): HostSubagentPayload {\n const data = payloadObject(json);\n const agentId = text(data, 'agent_id');\n if (!agentId) throw new TypeError('Hook payload has no agent_id');\n return {\n session_id: data.session_id as string,\n agent_id: agentId,\n agent_type: text(data, 'agent_type'),\n cwd: text(data, 'cwd'),\n description: ownTaskDescription(data, agentId),\n agent_transcript_path: text(data, 'agent_transcript_path'),\n };\n },\n parseSessionEndPayload(json): HostSessionEndPayload {\n const data = payloadObject(json);\n return {\n session_id: data.session_id as string,\n cwd: text(data, 'cwd'),\n reason: text(data, 'reason'),\n };\n },\n parseToolPayload(json): HostToolPayload {\n const data = payloadObject(json);\n const toolName = text(data, 'tool_name');\n const cwd = text(data, 'cwd');\n const toolInput =\n typeof data.tool_input === 'object' && data.tool_input !== null\n ? (data.tool_input as Record<string, unknown>)\n : {};\n return {\n session_id: data.session_id as string,\n cwd,\n tool_name: toolName,\n agent_id: text(data, 'agent_id'),\n agent_type: text(data, 'agent_type'),\n path: touchedPath(toolName, data.tool_input, cwd),\n file_path: text(toolInput, 'file_path') ?? text(toolInput, 'notebook_path'),\n command: text(toolInput, 'command'),\n subagent_type: text(toolInput, 'subagent_type'),\n launched_names: launchedNames(toolInput),\n };\n },\n subagentInheritsContext(payload) {\n return payload.agent_type === 'fork';\n },\n // The system prompt is rendered again on these sources and kept as is on resume.\n rendersSystemPrompt(source) {\n return RENDERING_SOURCES.has(source);\n },\n subagentNames(payload) {\n const transcript = payload.agent_transcript_path;\n const candidates = [\n payload.description,\n transcript && subagentMetadataDescription(transcript),\n transcript && subagentPromptName(transcript),\n ];\n return [...new Set(candidates.filter((name): name is string => Boolean(name)))];\n },\n // `/rename` fires no hook of its own; the next prompt carries the new title.\n promptTitle(payload) {\n return (\n payload.session_title ??\n (payload.transcript_path ? transcriptTitle(payload.transcript_path) : undefined)\n );\n },\n launchCommand(sessionId, options) {\n return { command: 'claude', args: ['--session-id', sessionId, ...launchArguments(options)] };\n },\n resumeCommand(session, options) {\n return {\n command: 'claude',\n args: ['--resume', session.id, ...launchArguments({ name: session.name, ...options })],\n };\n },\n forkCommand(parent, options) {\n return {\n command: 'claude',\n args: ['--resume', parent.id, '--fork-session', ...launchArguments(options)],\n };\n },\n // Claude Code keeps each conversation under a project directory derived from its cwd.\n transcriptFiles(session, env = process.env) {\n if (!session.cwd) return [];\n const project = claudeProjectFolder(session.cwd, env);\n return [join(project, `${session.id}.jsonl`), join(project, session.id)].filter((path) =>\n existsSync(path),\n );\n },\n // Claude Code writes no transcript before the first message. Every project directory is\n // searched, so a conversation filed under another cwd is never shadowed by a fresh one.\n hasConversation(session, env = process.env) {\n const projects = projectsDirectory(env);\n if (!existsSync(projects)) return false;\n return readdirSync(projects).some((project) =>\n existsSync(join(projects, project, `${session.id}.jsonl`)),\n );\n },\n continues(parent, childId, env = process.env) {\n if (!parent.cwd) return false;\n const project = claudeProjectFolder(parent.cwd, env);\n return continuesConversation(\n join(project, `${parent.id}.jsonl`),\n join(project, `${childId}.jsonl`),\n parent.id,\n childId,\n );\n },\n renameInstruction(name) {\n return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;\n },\n renderRunDirectory: renderClaudeRunDirectory,\n relocateProject,\n moveTrust,\n};\n","import { CarnetError } from '../errors.ts';\nimport type { Workspace } from '../workspace/locate.ts';\nimport type { Session } from '../sessions.ts';\nimport { claudeCode } from './claude-code.ts';\nimport type { UndoStep } from '../workspace/undo.ts';\n\nexport interface HostSessionPayload {\n session_id: string;\n cwd?: string | undefined;\n source?: string | undefined;\n session_title?: string | undefined;\n}\n\nexport interface HostPromptPayload {\n session_id: string;\n cwd?: string | undefined;\n session_title?: string | undefined;\n transcript_path?: string | undefined;\n}\n\nexport interface HostSubagentPayload {\n session_id: string;\n agent_id: string;\n agent_type?: string | undefined;\n cwd?: string | undefined;\n description?: string | undefined;\n agent_transcript_path?: string | undefined;\n}\n\nexport interface HostStopPayload {\n session_id: string;\n cwd?: string | undefined;\n failed: boolean;\n}\n\nexport interface HostSessionEndPayload {\n session_id: string;\n cwd?: string | undefined;\n reason?: string | undefined;\n}\n\nexport interface HostToolPayload {\n session_id: string;\n cwd?: string | undefined;\n tool_name?: string | undefined;\n agent_id?: string | undefined;\n agent_type?: string | undefined;\n path?: string | undefined;\n file_path?: string | undefined;\n command?: string | undefined;\n // An Agent call's subagent type, and the agent names it may launch: description, then prompt.\n subagent_type?: string | undefined;\n launched_names?: string[] | undefined;\n}\n\nexport interface ResumeCommand {\n command: string;\n args: string[];\n}\n\nexport interface LaunchOptions {\n name?: string | null | undefined;\n appendPromptFile?: string | undefined;\n passthrough?: readonly string[] | undefined;\n directories?: readonly string[] | undefined;\n}\n\nexport interface HostRender {\n written: string[];\n removed: string[];\n}\n\nexport interface RelocatedFolder {\n from: string;\n to: string;\n}\n\nexport interface ProjectRelocation {\n moves: RelocatedFolder[];\n // In the order applied, so they undo in reverse.\n undo: UndoStep[];\n}\n\nexport interface Host {\n id: string;\n displayName: string;\n processId(env: NodeJS.ProcessEnv): number | null;\n sessionIdFromEnvironment(env: NodeJS.ProcessEnv): string | undefined;\n projectDirectory(env: NodeJS.ProcessEnv): string | undefined;\n parseSessionPayload(json: string): HostSessionPayload;\n parseStopPayload(json: string): HostStopPayload;\n parsePromptPayload(json: string): HostPromptPayload;\n parseSubagentPayload(json: string): HostSubagentPayload;\n parseSessionEndPayload(json: string): HostSessionEndPayload;\n parseToolPayload(json: string): HostToolPayload;\n subagentNames(payload: HostSubagentPayload): string[];\n subagentInheritsContext(payload: HostSubagentPayload): boolean;\n rendersSystemPrompt(source: string): boolean;\n promptTitle(payload: HostPromptPayload): string | undefined;\n launchCommand(sessionId: string, options?: LaunchOptions): ResumeCommand;\n resumeCommand(session: Session, options?: LaunchOptions): ResumeCommand;\n forkCommand(parent: Session, options?: LaunchOptions): ResumeCommand;\n renameInstruction(name: string): string;\n transcriptFiles(session: Session, env?: NodeJS.ProcessEnv): string[];\n hasConversation(session: Session, env?: NodeJS.ProcessEnv): boolean;\n // True when the host carried the parent's conversation on under childId, rather than forking it.\n continues(parent: Session, childId: string, env?: NodeJS.ProcessEnv): boolean;\n renderRunDirectory(workspace: Workspace): HostRender;\n // The host's own files kept per run directory, moved when a workspace is renamed.\n relocateProject?(\n from: string,\n to: string,\n env: NodeJS.ProcessEnv,\n mode?: 'move' | 'merge',\n ): ProjectRelocation | null;\n moveTrust?(from: string, to: string | null, env: NodeJS.ProcessEnv): boolean;\n}\n\nexport const DEFAULT_HOST = 'claude-code';\n\nconst HOSTS: Readonly<Record<string, Host>> = { [claudeCode.id]: claudeCode };\n\nexport function allHosts(): Host[] {\n return Object.values(HOSTS);\n}\n\nexport function hostById(id: string): Host {\n const host = HOSTS[id];\n if (!host) {\n throw new CarnetError(\n 'UNKNOWN_HOST',\n `Unknown host \"${id}\" (available: ${Object.keys(HOSTS).join(', ')})`,\n );\n }\n return host;\n}\n","import type { DatabaseSync } from 'node:sqlite';\nimport { closeAgentsWhere } from './agents.ts';\n\nfunction inTransaction<T>(db: DatabaseSync, run: () => T): T {\n db.exec('BEGIN IMMEDIATE');\n try {\n const result = run();\n db.exec('COMMIT');\n return result;\n } catch (error) {\n db.exec('ROLLBACK');\n throw error;\n }\n}\n\nexport function sessionWorkspaceName(db: DatabaseSync, sessionId: string): string | undefined {\n const row = db.prepare('SELECT workspace FROM sessions WHERE id = ?').get(sessionId) as\n | { workspace: string }\n | undefined;\n return row?.workspace;\n}\n\nexport function archiveWorkspaceSessions(db: DatabaseSync, name: string, at: string): number {\n return inTransaction(db, () => {\n closeAgentsWhere(db, 'session IN (SELECT id FROM sessions WHERE workspace = ?)', [name], at);\n return Number(\n db\n .prepare(\n `UPDATE sessions SET status = 'archived', last_active_at = ?\n WHERE workspace = ? AND status != 'archived'`,\n )\n .run(at, name).changes,\n );\n });\n}\n\nexport function deleteWorkspaceNotes(db: DatabaseSync, name: string): number {\n return Number(db.prepare('DELETE FROM notes WHERE workspace = ?').run(name).changes);\n}\n\nexport function workspaceSessionCounts(db: DatabaseSync): Map<string, number> {\n const rows = db\n .prepare(\n `SELECT workspace, COUNT(*) AS count FROM sessions\n WHERE status != 'archived' GROUP BY workspace`,\n )\n .all() as { workspace: string; count: number }[];\n return new Map(rows.map((row) => [row.workspace, Number(row.count)]));\n}\n\nexport function workspaceLastActive(db: DatabaseSync): Map<string, string> {\n const rows = db\n .prepare('SELECT workspace, MAX(last_active_at) AS at FROM sessions GROUP BY workspace')\n .all() as { workspace: string; at: string }[];\n return new Map(rows.map((row) => [row.workspace, row.at]));\n}\n\n// Not LIKE: a home path can hold _ or %, and the slash keeps workspace a from matching a-b.\nfunction rewritePrefix(\n db: DatabaseSync,\n table: string,\n column: string,\n from: string,\n to: string,\n): number {\n return Number(\n db\n .prepare(\n `UPDATE ${table} SET ${column} = ? || substr(${column}, length(?) + 1)\n WHERE ${column} = ? OR substr(${column}, 1, length(?) + 1) = ? || '/'`,\n )\n .run(to, from, from, from, from).changes,\n );\n}\n\nexport function rewriteRunDirectory(db: DatabaseSync, from: string, to: string): number {\n return [\n ['sessions', 'cwd'],\n ['agents', 'report_path'],\n ['agents', 'sandbox'],\n ['events', 'link'],\n ].reduce((total, [table, column]) => total + rewritePrefix(db, table!, column!, from, to), 0);\n}\n\nexport interface WorkspaceRowCounts {\n sessions: number;\n notes: number;\n activeDays: number;\n}\n\nexport function workspaceRowCounts(db: DatabaseSync, name: string): WorkspaceRowCounts {\n const count = (table: string) =>\n Number(\n (\n db.prepare(`SELECT COUNT(*) AS total FROM ${table} WHERE workspace = ?`).get(name) as {\n total: number;\n }\n ).total,\n );\n return { sessions: count('sessions'), notes: count('notes'), activeDays: count('active_days') };\n}\n\nexport interface RunningSessionRow {\n id: string;\n name: string | null;\n hostPid: number;\n}\n\nexport function runningWorkspaceSessions(db: DatabaseSync, name: string): RunningSessionRow[] {\n const rows = db\n .prepare(\n `SELECT id, name, host_pid FROM sessions\n WHERE workspace = ? AND status = 'running' AND host_pid IS NOT NULL`,\n )\n .all(name) as { id: string; name: string | null; host_pid: number }[];\n return rows.map((row) => ({ id: row.id, name: row.name, hostPid: Number(row.host_pid) }));\n}\n\nexport function renameWorkspaceRows(\n db: DatabaseSync,\n names: { from: string; to: string },\n runDirectories: { from: string; to: string },\n): WorkspaceRowCounts & { paths: number } {\n return inTransaction(db, () => {\n const counts = workspaceRowCounts(db, names.from);\n for (const table of ['sessions', 'notes', 'active_days']) {\n db.prepare(`UPDATE ${table} SET workspace = ? WHERE workspace = ?`).run(names.to, names.from);\n }\n return { ...counts, paths: rewriteRunDirectory(db, runDirectories.from, runDirectories.to) };\n });\n}\n\nexport interface MergeRowsInput {\n names: { from: string; into: string };\n runDirectories: { from: string; into: string };\n // Exact old → new paths for files renamed on collision, applied before the prefix rewrite.\n paths: ReadonlyMap<string, string>;\n // A repo of from known under another name in into: from's name → into's name.\n repos: ReadonlyMap<string, string>;\n}\n\nexport interface MergeRowsResult extends WorkspaceRowCounts {\n firstNumber: number;\n}\n\nexport function nextNoteNumber(db: DatabaseSync, name: string): number {\n const row = db\n .prepare('SELECT COALESCE(MAX(number), 0) AS top FROM notes WHERE workspace = ?')\n .get(name) as { top: number };\n return Number(row.top) + 1;\n}\n\nexport function mergeWorkspaceRows(db: DatabaseSync, input: MergeRowsInput): MergeRowsResult {\n const { from, into } = input.names;\n return inTransaction(db, () => {\n const counts = workspaceRowCounts(db, from);\n for (const [fromName, intoName] of input.repos) {\n db.prepare(\n `UPDATE note_repos SET repo = ?\n WHERE repo = ? AND note IN (SELECT id FROM notes WHERE workspace = ?)`,\n ).run(intoName, fromName, from);\n db.prepare(\n `UPDATE session_repos SET repo = ?\n WHERE repo = ? AND session IN (SELECT id FROM sessions WHERE workspace = ?)`,\n ).run(intoName, fromName, from);\n db.prepare('UPDATE sessions SET repo = ? WHERE repo = ? AND workspace = ?').run(\n intoName,\n fromName,\n from,\n );\n }\n const firstNumber = nextNoteNumber(db, into);\n // Offset, not renumbered densely: from's order and gaps stay, and no number can clash.\n db.prepare('UPDATE notes SET workspace = ?, number = number + ? WHERE workspace = ?').run(\n into,\n firstNumber - 1,\n from,\n );\n db.prepare('UPDATE sessions SET workspace = ? WHERE workspace = ?').run(into, from);\n db.prepare(\n 'INSERT OR IGNORE INTO active_days (workspace, day) SELECT ?, day FROM active_days WHERE workspace = ?',\n ).run(into, from);\n db.prepare('DELETE FROM active_days WHERE workspace = ?').run(from);\n for (const [oldPath, newPath] of input.paths) {\n for (const [table, column] of [\n ['agents', 'report_path'],\n ['agents', 'sandbox'],\n ['events', 'link'],\n ]) {\n db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ?`).run(newPath, oldPath);\n }\n }\n rewriteRunDirectory(db, input.runDirectories.from, input.runDirectories.into);\n return { ...counts, firstNumber };\n });\n}\n","import type { DatabaseSync } from 'node:sqlite';\nimport { join, relative, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { allHosts } from '../hosts/host.ts';\nimport { sessionWorkspaceName } from '../workspace-rows.ts';\nimport {\n type Workspace,\n type WorkspaceRepo,\n workspaceExists,\n listWorkspaces,\n loadWorkspace,\n} from './workspace.ts';\n\nexport type { Workspace, WorkspaceRepo } from './workspace.ts';\n\nexport function isInside(directory: string, path: string): boolean {\n const relativePath = relative(directory, path);\n return (\n relativePath === '' ||\n (!relativePath.startsWith('..') && !resolve(relativePath).startsWith(relativePath))\n );\n}\n\nfunction repoOf(workspace: Workspace | null, path: string): WorkspaceRepo | undefined {\n const absolutePath = resolve(path);\n return workspace?.repos.find((repo) => isInside(repo.path, absolutePath));\n}\n\nexport function repoNameFor(workspace: Workspace | null, path: string | undefined): string | null {\n return path ? (repoOf(workspace, path)?.name ?? null) : null;\n}\n\nexport function repoPathFor(\n workspace: Workspace | null,\n path: string | undefined | null,\n): string | null {\n if (!path) return null;\n const repo = repoOf(workspace, path);\n if (!repo) return null;\n const relativePath = relative(repo.path, resolve(path));\n return relativePath ? join(repo.name, relativePath) : repo.name;\n}\n\nexport type WorkspaceOrigin = 'session' | 'option' | 'env' | 'run-directory' | 'none';\n\nexport interface WorkspaceResolution {\n workspace: Workspace | null;\n origin: WorkspaceOrigin;\n}\n\nexport interface ResolveWorkspaceOptions {\n db?: DatabaseSync | undefined;\n sessionId?: string | undefined;\n workspace?: string | undefined;\n cwd?: string | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nfunction namedWorkspace(name: string, env: NodeJS.ProcessEnv): Workspace {\n if (!workspaceExists(name, env)) {\n throw new CarnetError(\n 'WORKSPACE_NOT_FOUND',\n `No workspace named ${name}: see \"rucher ws list\"`,\n );\n }\n return loadWorkspace(name, env);\n}\n\nfunction byRunDirectory(\n workspaces: readonly Workspace[],\n directories: readonly string[],\n): Workspace | undefined {\n return workspaces.find((workspace) =>\n directories.some((directory) => isInside(workspace.runDirectory, directory)),\n );\n}\n\nexport function resolveWorkspace({\n db,\n sessionId,\n workspace,\n cwd = process.cwd(),\n env = process.env,\n}: ResolveWorkspaceOptions = {}): WorkspaceResolution {\n if (db && sessionId) {\n const name = sessionWorkspaceName(db, sessionId);\n if (name !== undefined && workspaceExists(name, env)) {\n return { workspace: loadWorkspace(name, env), origin: 'session' };\n }\n }\n if (workspace) return { workspace: namedWorkspace(workspace, env), origin: 'option' };\n if (env.RUCHER_WS) return { workspace: namedWorkspace(env.RUCHER_WS, env), origin: 'env' };\n const projectDirectories = allHosts()\n .map((host) => host.projectDirectory(env))\n .filter((directory): directory is string => directory !== undefined);\n const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];\n const runDirectoryWorkspace = byRunDirectory(listWorkspaces(env), directories);\n if (runDirectoryWorkspace) return { workspace: runDirectoryWorkspace, origin: 'run-directory' };\n return { workspace: null, origin: 'none' };\n}\n\nexport function workspaceLabel(workspace: Workspace | null): string {\n return workspace?.name ?? 'no workspace';\n}\n\nexport function requireWorkspace(workspace: Workspace | null): Workspace {\n if (workspace) return workspace;\n throw new CarnetError(\n 'NO_WORKSPACE',\n \"No Rucher workspace here: pass --ws <name>, or run this from a workspace's run directory\",\n );\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport type { Workspace } from './workspace/locate.ts';\n\nexport const NOTE_KINDS = ['dead_end', 'decision', 'learning'] as const;\nexport type NoteKind = (typeof NOTE_KINDS)[number];\n\nexport const NOTE_TEXT_LIMIT = 200;\nexport const DUPLICATE_SIMILARITY = 0.6;\nexport const DEFAULT_HALF_LIFE_DAYS = 20;\nexport const STALE_AFTER_ACTIVE_DAYS = 40;\nexport const STALE_WEIGHT = 0.05;\nconst SIMILAR_SHOWN = 3;\n\nexport function isNoteKind(value: string): value is NoteKind {\n return (NOTE_KINDS as readonly string[]).includes(value);\n}\n\nexport function memoryHalfLife(value: string | undefined): number {\n const days = Number(value);\n return Number.isFinite(days) && days > 0 ? days : DEFAULT_HALF_LIFE_DAYS;\n}\n\nexport interface Note {\n id: number;\n kind: NoteKind;\n text: string;\n repos: string[];\n session: string | null;\n agent: string | null;\n similarNotes: number[];\n createdAt: string;\n droppedAt: string | null;\n droppedReason: string | null;\n droppedSession: string | null;\n replacedBy: number | null;\n}\n\nexport interface NoteCitation {\n id: number;\n note: number;\n session: string | null;\n agent: string | null;\n why: string;\n at: string;\n}\n\nexport interface WeightedNote extends Note {\n weight: number;\n citationCount: number;\n}\n\nexport interface NoteDetail extends WeightedNote {\n citations: NoteCitation[];\n}\n\nexport interface AddNoteInput {\n kind: string;\n text: string;\n repos?: string[] | undefined;\n session?: string | null | undefined;\n agent?: string | null | undefined;\n}\n\nexport interface AddNoteResult {\n note: Note;\n similar: Note[];\n}\n\nexport interface ListNotesOptions {\n kind?: string | undefined;\n repo?: string | undefined;\n general?: boolean | undefined;\n query?: string | undefined;\n includeDropped?: boolean | undefined;\n halfLifeDays?: number | undefined;\n}\n\nexport interface DropNoteInput {\n reason: string;\n replacedBy?: number | undefined;\n session?: string | null | undefined;\n}\n\nexport interface CiteNoteInput {\n why: string;\n session?: string | null | undefined;\n agent?: string | null | undefined;\n}\n\ninterface NoteRow {\n id: number;\n number: number;\n kind: NoteKind;\n text: string;\n session: string | null;\n agent: string | null;\n similar_notes: string | null;\n created_at: string;\n dropped_at: string | null;\n dropped_reason: string | null;\n dropped_session: string | null;\n replaced_number: number | null;\n}\n\n// Notes are shown and referenced by their number in the workspace; the id stays internal.\nconst NOTE_COLUMNS = `notes.id, notes.number, notes.kind, notes.text, notes.session, notes.agent,\n notes.similar_notes, notes.created_at, notes.dropped_at, notes.dropped_reason,\n notes.dropped_session,\n (SELECT replaced.number FROM notes AS replaced WHERE replaced.id = notes.replaced_by)\n AS replaced_number`;\n\nconst MARKDOWN = /\\*\\*|__|\\[[^\\]]*\\]\\([^)]*\\)|^#{1,6}\\s|^[-*+]\\s/;\n\nfunction cleanText(value: string, label: string): string {\n const text = value.trim().replace(/[ \\t]+/g, ' ');\n if (!text) throw new CarnetError('INVALID_NOTE', `${label} is empty`);\n if (text.length >= NOTE_TEXT_LIMIT) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `${label} must stay under ${NOTE_TEXT_LIMIT} characters (${text.length})`,\n );\n }\n if (/[\\r\\n]/.test(text)) throw new CarnetError('INVALID_NOTE', `${label} must be one line`);\n if (text.includes('`')) throw new CarnetError('INVALID_NOTE', `${label} must not use backticks`);\n if (MARKDOWN.test(text)) throw new CarnetError('INVALID_NOTE', `${label} must not use markdown`);\n return text;\n}\n\nexport function workspaceRepoNames(workspace: Workspace): string[] {\n return workspace.repos.map((repo) => repo.name);\n}\n\nfunction cleanRepos(workspace: Workspace, repos: string[] | undefined): string[] {\n const known = workspaceRepoNames(workspace);\n const unique = [...new Set((repos ?? []).map((repo) => repo.trim()).filter(Boolean))];\n const unknown = unique.filter((repo) => !known.includes(repo));\n if (unknown.length) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `Unknown repo ${unknown.join(', ')} (workspace repos: ${known.join(', ') || 'none'})`,\n );\n }\n return unique;\n}\n\nfunction words(text: string): Set<string> {\n return new Set(text.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []);\n}\n\nexport function similarity(first: string, second: string): number {\n const left = words(first);\n const right = words(second);\n if (left.size === 0 && right.size === 0) return 0;\n let shared = 0;\n for (const word of left) if (right.has(word)) shared++;\n return shared / (left.size + right.size - shared);\n}\n\nexport function localDay(date: Date): string {\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n return `${date.getFullYear()}-${month}-${day}`;\n}\n\nexport function recordActiveDay(ctx: Ctx): void {\n if (ctx.workspace === null) return;\n ctx.db\n .prepare('INSERT OR IGNORE INTO active_days (workspace, day) VALUES (?, ?)')\n .run(ctx.workspace, localDay(ctx.now()));\n}\n\nfunction activeDays(ctx: Ctx): string[] {\n const rows = ctx.db\n .prepare('SELECT day FROM active_days WHERE workspace IS ? ORDER BY day')\n .all(ctx.workspace) as unknown as { day: string }[];\n return rows.map((row) => row.day);\n}\n\nfunction activeDaysSince(days: string[], at: string): number {\n const since = localDay(new Date(at));\n return days.filter((day) => day > since).length;\n}\n\nfunction reposOf(ctx: Ctx, noteId: number): string[] {\n const rows = ctx.db\n .prepare('SELECT repo FROM note_repos WHERE note = ? ORDER BY repo')\n .all(noteId) as unknown as { repo: string }[];\n return rows.map((row) => row.repo);\n}\n\nfunction toNote(ctx: Ctx, row: NoteRow): Note {\n return {\n id: row.number,\n kind: row.kind,\n text: row.text,\n repos: reposOf(ctx, row.id),\n session: row.session,\n agent: row.agent,\n similarNotes: row.similar_notes ? (JSON.parse(row.similar_notes) as number[]) : [],\n createdAt: row.created_at,\n droppedAt: row.dropped_at,\n droppedReason: row.dropped_reason,\n droppedSession: row.dropped_session,\n replacedBy: row.replaced_number,\n };\n}\n\nfunction noteRow(ctx: Ctx, number: number): NoteRow | undefined {\n return ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND number = ?`)\n .get(ctx.workspace, number) as NoteRow | undefined;\n}\n\nfunction noteId(ctx: Ctx, number: number): number {\n const row = noteRow(ctx, number);\n if (!row) throw new CarnetError('NOTE_NOT_FOUND', `Unknown note #${number}`);\n return row.id;\n}\n\nexport function getNote(ctx: Ctx, id: number): Note | null {\n const row = noteRow(ctx, id);\n return row ? toNote(ctx, row) : null;\n}\n\nexport function requireNote(ctx: Ctx, id: number): Note {\n const note = getNote(ctx, id);\n if (!note) throw new CarnetError('NOTE_NOT_FOUND', `Unknown note #${id}`);\n return note;\n}\n\nfunction requireActiveNote(ctx: Ctx, id: number): Note {\n const note = requireNote(ctx, id);\n if (note.droppedAt) throw new CarnetError('INVALID_NOTE', `Note #${id} is dropped`);\n return note;\n}\n\nconst CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citations.session,\n note_citations.agent, note_citations.why, note_citations.at`;\n\nfunction citationsOf(ctx: Ctx, number: number): NoteCitation[] {\n return ctx.db\n .prepare(\n `SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at, note_citations.rowid`,\n )\n .all(ctx.workspace, number) as unknown as NoteCitation[];\n}\n\n// Several citations in one session count once: the latest stands for that session.\nfunction weightOf(citations: NoteCitation[], days: string[], halfLifeDays: number): number {\n const latest = new Map<string, string>();\n for (const citation of citations) {\n const key = citation.session ?? `citation-${citation.id}`;\n const previous = latest.get(key);\n if (!previous || citation.at > previous) latest.set(key, citation.at);\n }\n let weight = 0;\n for (const at of latest.values()) weight += 0.5 ** (activeDaysSince(days, at) / halfLifeDays);\n return weight;\n}\n\nfunction weigh(ctx: Ctx, note: Note, days: string[], halfLifeDays: number): WeightedNote {\n const citations = citationsOf(ctx, note.id);\n return {\n ...note,\n weight: weightOf(citations, days, halfLifeDays),\n citationCount: citations.length,\n };\n}\n\nexport function compareNotes(first: WeightedNote, second: WeightedNote): number {\n const kind = NOTE_KINDS.indexOf(first.kind) - NOTE_KINDS.indexOf(second.kind);\n if (kind !== 0) return kind;\n if (first.weight !== second.weight) return second.weight - first.weight;\n return second.id - first.id;\n}\n\nfunction activeNotesOfKind(ctx: Ctx, kind: NoteKind): Note[] {\n const rows = ctx.db\n .prepare(\n `SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND kind = ? AND dropped_at IS NULL`,\n )\n .all(ctx.workspace, kind) as unknown as NoteRow[];\n return rows.map((row) => toNote(ctx, row));\n}\n\nexport function addNote(ctx: Ctx, workspace: Workspace | null, input: AddNoteInput): AddNoteResult {\n if (workspace === null || ctx.workspace === null) {\n throw new CarnetError('NO_WORKSPACE', 'Notes belong to a workspace: this session has none');\n }\n if (!isNoteKind(input.kind)) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `Invalid note kind \"${input.kind}\" (use ${NOTE_KINDS.join(', ')})`,\n );\n }\n const kind = input.kind;\n const text = cleanText(input.text, 'Note text');\n const repos = cleanRepos(workspace, input.repos);\n const similar = activeNotesOfKind(ctx, kind)\n .map((note) => ({ note, score: similarity(text, note.text) }))\n .filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY)\n .sort((first, second) => second.score - first.score)\n .slice(0, SIMILAR_SHOWN)\n .map((candidate) => candidate.note);\n ctx.db.exec('BEGIN');\n try {\n const next = ctx.db\n .prepare('SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE workspace = ?')\n .get(ctx.workspace) as { number: number };\n const result = ctx.db\n .prepare(\n `INSERT INTO notes (workspace, number, kind, text, session, agent, similar_notes, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n ctx.workspace,\n next.number,\n kind,\n text,\n input.session ?? null,\n input.agent ?? null,\n similar.length ? JSON.stringify(similar.map((note) => note.id)) : null,\n nowIso(ctx),\n );\n const id = Number(result.lastInsertRowid);\n const addRepo = ctx.db.prepare('INSERT INTO note_repos (note, repo) VALUES (?, ?)');\n for (const repo of repos) addRepo.run(id, repo);\n ctx.db.exec('COMMIT');\n return { note: requireNote(ctx, next.number), similar };\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n\nexport function listNotes(ctx: Ctx, options: ListNotesOptions = {}): WeightedNote[] {\n if (options.kind !== undefined && !isNoteKind(options.kind)) {\n throw new CarnetError('INVALID_NOTE', `Invalid note kind \"${options.kind}\"`);\n }\n const conditions: string[] = ['workspace IS ?'];\n const parameters: (string | null)[] = [ctx.workspace];\n if (!options.includeDropped) conditions.push('dropped_at IS NULL');\n if (options.kind) {\n conditions.push('kind = ?');\n parameters.push(options.kind);\n }\n if (options.repo) {\n conditions.push('id IN (SELECT note FROM note_repos WHERE repo = ?)');\n parameters.push(options.repo);\n }\n if (options.general) conditions.push('id NOT IN (SELECT note FROM note_repos)');\n if (options.query) {\n conditions.push(\"LOWER(text) LIKE ? ESCAPE '\\\\'\");\n parameters.push(`%${options.query.toLowerCase().replace(/[\\\\%_]/g, '\\\\$&')}%`);\n }\n const rows = ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE ${conditions.join(' AND ')}`)\n .all(...parameters) as unknown as NoteRow[];\n const days = activeDays(ctx);\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n return rows.map((row) => weigh(ctx, toNote(ctx, row), days, halfLifeDays)).sort(compareNotes);\n}\n\nexport function noteDetail(\n ctx: Ctx,\n id: number,\n halfLifeDays = DEFAULT_HALF_LIFE_DAYS,\n): NoteDetail {\n const note = requireNote(ctx, id);\n const citations = citationsOf(ctx, id);\n return {\n ...note,\n weight: weightOf(citations, activeDays(ctx), halfLifeDays),\n citationCount: citations.length,\n citations,\n };\n}\n\nexport function staleNotes(ctx: Ctx, halfLifeDays = DEFAULT_HALF_LIFE_DAYS): WeightedNote[] {\n const days = activeDays(ctx);\n return listNotes(ctx, { halfLifeDays }).filter(\n (note) =>\n activeDaysSince(days, note.createdAt) > STALE_AFTER_ACTIVE_DAYS &&\n (note.citationCount === 0 || note.weight < STALE_WEIGHT),\n );\n}\n\nexport function dropNote(ctx: Ctx, id: number, input: DropNoteInput): Note {\n requireActiveNote(ctx, id);\n const reason = cleanText(input.reason, 'Drop reason');\n if (input.replacedBy !== undefined) {\n if (input.replacedBy === id) {\n throw new CarnetError('INVALID_NOTE', `Note #${id} cannot replace itself`);\n }\n requireActiveNote(ctx, input.replacedBy);\n }\n const replacedBy = input.replacedBy === undefined ? null : noteId(ctx, input.replacedBy);\n ctx.db\n .prepare(\n 'UPDATE notes SET dropped_at = ?, dropped_reason = ?, dropped_session = ?, replaced_by = ? WHERE id = ?',\n )\n .run(nowIso(ctx), reason, input.session ?? null, replacedBy, noteId(ctx, id));\n return requireNote(ctx, id);\n}\n\nexport function citeNote(ctx: Ctx, id: number, input: CiteNoteInput): NoteCitation {\n requireActiveNote(ctx, id);\n const why = cleanText(input.why, 'Citation reason');\n const result = ctx.db\n .prepare('INSERT INTO note_citations (note, session, agent, why, at) VALUES (?, ?, ?, ?, ?)')\n .run(noteId(ctx, id), input.session ?? null, input.agent ?? null, why, nowIso(ctx));\n return ctx.db\n .prepare(\n `SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE note_citations.id = ?`,\n )\n .get(Number(result.lastInsertRowid)) as unknown as NoteCitation;\n}\n\nexport type NoteActivityKind = 'added' | 'cited' | 'dropped';\n\nexport interface NoteActivity {\n activity: NoteActivityKind;\n note: number;\n kind: NoteKind;\n text: string;\n similarNotes: number[];\n replacedBy: number | null;\n at: string;\n}\n\nconst ACTIVITY_ORDER: Record<NoteActivityKind, number> = { dropped: 0, cited: 1, added: 2 };\n\nfunction activeIds(ctx: Ctx, json: string | null): number[] {\n if (!json) return [];\n const active = ctx.db.prepare(\n 'SELECT 1 FROM notes WHERE workspace IS ? AND number = ? AND dropped_at IS NULL',\n );\n return (JSON.parse(json) as number[]).filter(\n (number) => active.get(ctx.workspace, number) !== undefined,\n );\n}\n\nexport function sessionNoteActivity(ctx: Ctx, session: string): NoteActivity[] {\n const added = ctx.db\n .prepare(\n `SELECT number, kind, text, similar_notes, created_at FROM notes\n WHERE workspace IS ? AND session = ?`,\n )\n .all(ctx.workspace, session) as unknown as Pick<\n NoteRow,\n 'number' | 'kind' | 'text' | 'similar_notes' | 'created_at'\n >[];\n const cited = ctx.db\n .prepare(\n `SELECT notes.number AS note, notes.kind, note_citations.why, note_citations.at\n FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE notes.workspace IS ? AND note_citations.session = ?`,\n )\n .all(ctx.workspace, session) as unknown as {\n note: number;\n kind: NoteKind;\n why: string;\n at: string;\n }[];\n const dropped = ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND dropped_session = ?`)\n .all(ctx.workspace, session) as unknown as NoteRow[];\n const activity: NoteActivity[] = [\n ...added.map((row) => ({\n activity: 'added' as const,\n note: row.number,\n kind: row.kind,\n text: row.text,\n similarNotes: activeIds(ctx, row.similar_notes),\n replacedBy: null,\n at: row.created_at,\n })),\n ...cited.map((row) => ({\n activity: 'cited' as const,\n note: row.note,\n kind: row.kind,\n text: row.why,\n similarNotes: [],\n replacedBy: null,\n at: row.at,\n })),\n ...dropped.map((row) => ({\n activity: 'dropped' as const,\n note: row.number,\n kind: row.kind,\n text: row.dropped_reason ?? '',\n similarNotes: [],\n replacedBy: row.replaced_number,\n at: row.dropped_at ?? '',\n })),\n ];\n return activity.sort(\n (first, second) =>\n second.at.localeCompare(first.at) ||\n ACTIVITY_ORDER[first.activity] - ACTIVITY_ORDER[second.activity] ||\n second.note - first.note,\n );\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport type { Workspace } from './workspace/locate.ts';\nimport {\n compareNotes,\n DEFAULT_HALF_LIFE_DAYS,\n listNotes,\n NOTE_KINDS,\n type NoteKind,\n type WeightedNote,\n} from './notes.ts';\n\nexport const MEMORY_MAX_CHARACTERS = 2000;\n\nconst KIND_TITLES: Readonly<Record<NoteKind, string>> = {\n dead_end: 'Dead ends',\n decision: 'Decisions',\n learning: 'Learnings',\n};\n\n// Cut first what loses least: learnings, then decisions; dead ends go last.\nconst CUT_ORDER: readonly NoteKind[] = ['learning', 'decision', 'dead_end'];\n\nexport function memoryMaxCharacters(value: string | undefined): number {\n const characters = Number(value);\n return Number.isInteger(characters) && characters > 0 ? characters : MEMORY_MAX_CHARACTERS;\n}\n\nexport interface MemoryOptions {\n maxCharacters?: number | undefined;\n halfLifeDays?: number | undefined;\n}\n\ninterface MemoryScope {\n title: string;\n notes: WeightedNote[];\n}\n\nfunction noteLine(note: WeightedNote): string {\n const repos = note.repos.length ? `[${note.repos.join(', ')}] ` : '';\n return ` #${String(note.id).padEnd(4)}${repos}${note.text}`;\n}\n\nfunction render(scope: MemoryScope, kept: WeightedNote[]): string {\n const total = scope.notes.length;\n const leftOut = total - kept.length;\n const count = `${total} note${total > 1 ? 's' : ''}`;\n const pointer = leftOut ? `${leftOut} left out, note_list for the rest` : 'note_list for details';\n const lines = [`${scope.title} (${count}, ${pointer}):`];\n for (const kind of NOTE_KINDS) {\n const ofKind = kept.filter((note) => note.kind === kind);\n if (!ofKind.length) continue;\n lines.push('', KIND_TITLES[kind], ...ofKind.map(noteLine));\n }\n return lines.join('\\n');\n}\n\nexport function renderMemory(scope: MemoryScope, maxCharacters = MEMORY_MAX_CHARACTERS): string {\n const kept = [...scope.notes];\n let text = render(scope, kept);\n while (text.length > maxCharacters && kept.length) {\n const kind = CUT_ORDER.find((candidate) => kept.some((note) => note.kind === candidate));\n const lowest = kept.findLastIndex((note) => note.kind === kind);\n kept.splice(lowest, 1);\n text = render(scope, kept);\n }\n return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;\n}\n\nfunction injectedRepos(ctx: Ctx, session: string): string[] {\n const rows = ctx.db\n .prepare('SELECT repo FROM session_repos WHERE session = ? ORDER BY injected_at, repo')\n .all(session) as unknown as { repo: string }[];\n return rows.map((row) => row.repo);\n}\n\nfunction recordRepo(ctx: Ctx, session: string, repo: string): void {\n ctx.db\n .prepare('INSERT OR IGNORE INTO session_repos (session, repo, injected_at) VALUES (?, ?, ?)')\n .run(session, repo, nowIso(ctx));\n}\n\nfunction notesFor(ctx: Ctx, repos: string[], general: boolean, halfLifeDays: number) {\n const byId = new Map<number, WeightedNote>();\n const add = (notes: WeightedNote[]) => notes.forEach((note) => byId.set(note.id, note));\n if (general) add(listNotes(ctx, { general: true, halfLifeDays }));\n for (const repo of repos) add(listNotes(ctx, { repo, halfLifeDays }));\n return [...byId.values()].sort(compareNotes);\n}\n\nfunction workspaceTitle(workspace: Workspace | null): string {\n return workspace ? `Rucher memory of the ${workspace.name} workspace` : 'Rucher memory';\n}\n\nexport function sessionStartMemory(\n ctx: Ctx,\n workspace: Workspace | null,\n session: { id: string; repo: string | null },\n options: MemoryOptions = {},\n): string | undefined {\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n const repos = session.repo ? [session.repo] : [];\n const notes = notesFor(ctx, repos, true, halfLifeDays);\n if (!notes.length) return undefined;\n for (const repo of repos) {\n if (notes.some((note) => note.repos.includes(repo))) recordRepo(ctx, session.id, repo);\n }\n return renderMemory({ title: workspaceTitle(workspace), notes }, options.maxCharacters);\n}\n\nexport function sessionMemory(\n ctx: Ctx,\n workspace: Workspace | null,\n session: { id: string },\n options: MemoryOptions = {},\n): string | undefined {\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n const notes = notesFor(ctx, injectedRepos(ctx, session.id), true, halfLifeDays);\n if (!notes.length) return undefined;\n return renderMemory({ title: workspaceTitle(workspace), notes }, options.maxCharacters);\n}\n\nexport function repoMemory(\n ctx: Ctx,\n session: { id: string },\n repo: string,\n options: MemoryOptions = {},\n): string | undefined {\n const injected = injectedRepos(ctx, session.id);\n if (injected.includes(repo)) return undefined;\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n // A note shared with a repo already injected is already in context.\n const notes = listNotes(ctx, { repo, halfLifeDays }).filter(\n (note) => !note.repos.some((other) => injected.includes(other)),\n );\n if (!notes.length) return undefined;\n recordRepo(ctx, session.id, repo);\n return renderMemory({ title: `Rucher memory, repo ${repo}`, notes }, options.maxCharacters);\n}\n\nexport function copyInjectedRepos(ctx: Ctx, from: string, into: string): void {\n for (const repo of injectedRepos(ctx, from)) recordRepo(ctx, into, repo);\n}\n","import { closeAgentsWhere } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { requireSession, type Session } from './sessions.ts';\n\nexport interface MergeResult {\n session: Session;\n movedAgents: string[];\n closedAgents: string[];\n movedEvents: number;\n movedTable: boolean;\n}\n\nfunction namesOf(ctx: Ctx, session: string): string[] {\n const rows = ctx.db\n .prepare('SELECT name FROM agents WHERE session = ?')\n .all(session) as unknown as {\n name: string;\n }[];\n return rows.map((row) => row.name);\n}\n\nexport function mergeSessions(ctx: Ctx, fromId: string, intoId: string): MergeResult {\n if (fromId === intoId) {\n throw new CarnetError('SESSION_MERGE_INVALID', 'Cannot merge a session into itself');\n }\n const from = requireSession(ctx, fromId);\n const into = requireSession(ctx, intoId);\n const at = nowIso(ctx);\n const taken = new Set(namesOf(ctx, intoId));\n const fromNames = namesOf(ctx, fromId);\n const movedAgents = fromNames.filter((name) => !taken.has(name));\n const closedAgents = fromNames.filter((name) => taken.has(name));\n ctx.db.exec('BEGIN');\n try {\n const moveAgent = ctx.db.prepare(\n 'UPDATE agents SET session = ?, updated_at = ? WHERE session = ? AND name = ?',\n );\n for (const name of movedAgents) moveAgent.run(intoId, at, fromId, name);\n closeAgentsWhere(ctx.db, 'session = ?', [fromId], at);\n const movedEvents = Number(\n ctx.db.prepare('UPDATE events SET session = ? WHERE session = ?').run(intoId, fromId).changes,\n );\n const intoHasTable =\n ctx.db.prepare('SELECT 1 FROM table_items WHERE session = ?').get(intoId) !== undefined;\n const movedTable =\n !intoHasTable &&\n Number(\n ctx.db.prepare('UPDATE table_items SET session = ? WHERE session = ?').run(intoId, fromId)\n .changes,\n ) > 0;\n ctx.db.prepare('DELETE FROM table_items WHERE session = ?').run(fromId);\n const keepName = into.name === null && from.name !== null;\n ctx.db\n .prepare(\n \"UPDATE sessions SET status = 'archived', kind = 'temp', name = NULL, turn = NULL, turn_started_at = NULL, last_active_at = ? WHERE id = ?\",\n )\n .run(at, fromId);\n ctx.db\n .prepare(\n `UPDATE sessions\n SET name = COALESCE(?, name), purpose = COALESCE(purpose, ?), last_active_at = ?,\n kind = CASE WHEN ? THEN ? ELSE kind END\n WHERE id = ?`,\n )\n .run(keepName ? from.name : null, from.purpose, at, keepName ? 1 : 0, from.kind, intoId);\n ctx.db.exec('COMMIT');\n return {\n session: requireSession(ctx, intoId),\n movedAgents,\n closedAgents,\n movedEvents,\n movedTable,\n };\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n","import { existsSync, lstatSync, mkdirSync, readdirSync, rmSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { CarnetError } from './errors.ts';\nimport { sandboxesDirectory } from './paths.ts';\nimport type { Workspace } from './workspace/workspace.ts';\n\nfunction strictlyInside(path: string, folder: string): boolean {\n const rest = relative(folder, path);\n return rest !== '' && !rest.startsWith('..') && !isAbsolute(rest);\n}\n\n// A sandbox lives only in the run directory's sandboxes folder, so removing it can never reach\n// a repo or the human's files.\nexport function resolveSandbox(workspace: Workspace | null, path: string): string {\n if (!workspace) {\n throw new CarnetError('INVALID_SANDBOX', 'A sandbox needs a workspace: none is resolved');\n }\n const root = sandboxesDirectory(workspace);\n const expanded = path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;\n const resolved = resolve(workspace.runDirectory, expanded);\n if (!strictlyInside(resolved, root)) {\n throw new CarnetError(\n 'INVALID_SANDBOX',\n `${path} is not a folder under ${root}: a sandbox lives in the workspace's sandboxes folder`,\n );\n }\n if (existsSync(resolved)) {\n if (!lstatSync(resolved).isDirectory() || readdirSync(resolved).length > 0) {\n throw new CarnetError('INVALID_SANDBOX', `${resolved} already exists and is not empty`);\n }\n }\n return resolved;\n}\n\nexport function sandboxRemovedSuffix(removed: boolean): string {\n return removed ? ', sandbox removed' : '';\n}\n\nexport function createSandbox(path: string): void {\n mkdirSync(path, { recursive: true });\n}\n\nexport function removeSandbox(workspace: Workspace | null, path: string | null): boolean {\n if (!workspace || !path) return false;\n const resolved = resolve(path);\n if (!strictlyInside(resolved, sandboxesDirectory(workspace)) || !existsSync(resolved)) {\n return false;\n }\n rmSync(resolved, { recursive: true, force: true });\n return true;\n}\n","import type { Ctx } from './context.ts';\n\nexport const DEFAULT_PURGE_DAYS = 3;\nconst DAY_MILLISECONDS = 24 * 60 * 60 * 1000;\n\nexport function purgeDays(value: string | undefined): number {\n const days = Number(value);\n return Number.isFinite(days) && days > 0 ? days : DEFAULT_PURGE_DAYS;\n}\n\n// Only sessions without agent events go: the agent journal is never deleted, lifecycle events are.\nconst PURGEABLE = `\n workspace = ? AND id != ? AND last_active_at < ?\n AND NOT EXISTS (\n SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'\n )\n AND (\n status = 'archived'\n OR (kind = 'temp' AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id))\n )`;\n\nexport function purgeSessions(ctx: Ctx, keepId: string, days: number): string[] {\n const cutoff = new Date(ctx.now().getTime() - days * DAY_MILLISECONDS).toISOString();\n ctx.db.exec('BEGIN');\n try {\n const rows = ctx.db\n .prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`)\n .all(ctx.workspace, keepId, cutoff) as unknown as { id: string }[];\n const ids = rows.map((row) => row.id);\n for (const table of ['table_items', 'agents', 'events']) {\n const statement = ctx.db.prepare(`DELETE FROM ${table} WHERE session = ?`);\n for (const id of ids) statement.run(id);\n }\n const deleteSession = ctx.db.prepare('DELETE FROM sessions WHERE id = ?');\n for (const id of ids) deleteSession.run(id);\n ctx.db.exec('COMMIT');\n return ids;\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n","import type { NoteActivity } from '../notes.ts';\nimport type { TableItem } from '../table.ts';\nimport type { Turn } from '../turn.ts';\nimport {\n EMOJI,\n KIND_LEGEND,\n kindTag,\n LEGEND,\n MAIN_FAILED_EMOJI,\n MAIN_WAITING_EMOJI,\n MAIN_WORKING_EMOJI,\n} from './model.ts';\nimport type { StatusLine, StatusView } from './view.ts';\n\nexport const MAIN_HEADER = 'Main';\nexport const MAIN_WORKING_SUFFIX = '(main working)';\nexport const BLOCKED_HEADER = 'Waiting on agents';\nexport const MAIN_WAITING_SUFFIX = '(waiting on you)';\nexport const MAIN_FAILED_SUFFIX = '(turn failed)';\n\nexport function renderTableLine(item: TableItem): string {\n return `${EMOJI[item.status ?? 'discussing']} ${item.text}`;\n}\n\nconst TURN_MARKS = {\n working: { emoji: MAIN_WORKING_EMOJI, suffix: MAIN_WORKING_SUFFIX, alone: 'main working' },\n waiting: { emoji: MAIN_WAITING_EMOJI, suffix: MAIN_WAITING_SUFFIX, alone: 'waiting on you' },\n failed: { emoji: MAIN_FAILED_EMOJI, suffix: MAIN_FAILED_SUFFIX, alone: 'turn failed' },\n} as const;\n\nexport const MAIN_IDLE = 'idle';\n\nexport function renderMainLine(item: TableItem | null, turn: Turn | null): string {\n if (!turn) return item ? renderTableLine(item) : MAIN_IDLE;\n const mark = TURN_MARKS[turn];\n return item ? `${mark.emoji} ${item.text} ${mark.suffix}` : `${mark.emoji} ${mark.alone}`;\n}\n\nexport function renderAgentLine(line: StatusLine, nameWidth = 0): string {\n const head = `${line.emoji} ${kindTag(line.kind)} ${line.name}`;\n const action = line.action\n ? ` ${' '.repeat(Math.max(nameWidth - line.name.length, 0))} ${line.action}`\n : '';\n return line.note ? `${head}${action} — ${line.note}` : `${head}${action}`;\n}\n\n// Aligns the actions of one section, so the eye reads them as a column.\nfunction nameWidth(lines: readonly StatusLine[]): number {\n return Math.max(0, ...lines.map((line) => line.name.length));\n}\n\nexport const NOTES_HEADER = 'Notes';\nexport const NOTES_FOLD_LINES = 5;\nconst ACTIVITY_MARK = { added: '+', cited: '★', dropped: '−' } as const;\nconst LABEL_WIDTH = 'dead_end'.length;\nexport const SIMILAR_PREFIX = 'similar to ';\n\nexport type NotesMode = 'full' | 'summary' | 'expanded';\n\nexport interface RenderOptions {\n notes?: NotesMode | undefined;\n}\n\nfunction plural(count: number, word: string): string {\n return `${count} ${word}${count > 1 ? 's' : ''}`;\n}\n\nexport function renderNotesSummary(notes: NoteActivity[]): string {\n const count = (activity: NoteActivity['activity']) =>\n notes.filter((item) => item.activity === activity).length;\n const duplicates = notes.filter(\n (item) => item.activity === 'added' && item.similarNotes.length > 0,\n ).length;\n const parts = [\n count('added') && `${count('added')} added`,\n count('cited') && `${count('cited')} cited`,\n count('dropped') && `${count('dropped')} dropped`,\n duplicates && plural(duplicates, 'possible duplicate'),\n ].filter(Boolean);\n return `${NOTES_HEADER} ${parts.join(' · ')}`;\n}\n\nexport function renderNoteLine(item: NoteActivity, idWidth: number): string {\n const id = `#${item.note}`.padEnd(idWidth);\n const label = (item.activity === 'added' ? item.kind : item.activity).padEnd(LABEL_WIDTH);\n let text = item.text;\n // Before the text, so a narrow terminal cuts the note rather than the duplicate warning.\n if (item.activity === 'added' && item.similarNotes.length > 0) {\n text = `${SIMILAR_PREFIX}${item.similarNotes.map((note) => `#${note}`).join(', ')} · ${text}`;\n }\n if (item.activity === 'dropped' && item.replacedBy !== null)\n text = `replaced by #${item.replacedBy}`;\n return `${ACTIVITY_MARK[item.activity]} ${id} ${label} ${text}`;\n}\n\nexport function renderNotes(notes: NoteActivity[], mode: NotesMode = 'full'): string[] {\n if (notes.length === 0) return [];\n if (mode === 'summary' || (mode === 'full' && notes.length > NOTES_FOLD_LINES)) {\n return [renderNotesSummary(notes)];\n }\n const idWidth = Math.max(...notes.map((item) => `#${item.note}`.length));\n return [NOTES_HEADER, ...notes.map((item) => ` ${renderNoteLine(item, idWidth)}`)];\n}\n\nexport function renderSections(view: StatusView, options: RenderOptions = {}): string {\n const out: string[] = [];\n // Always shown, so the sections below never jump when a turn starts or ends.\n out.push(MAIN_HEADER, ` ${renderMainLine(view.table, view.turn)}`, '');\n out.push('Waiting on you');\n if (view.waiting.length === 0) out.push(' nothing');\n const waitingWidth = nameWidth(view.waiting);\n view.waiting.forEach((line, index) => {\n out.push(` ${index + 1}.${line.pinned ? '📌' : ''} ${renderAgentLine(line, waitingWidth)}`);\n });\n if (view.blocked.length > 0) {\n out.push('', BLOCKED_HEADER);\n const blockedWidth = nameWidth(view.blocked);\n for (const line of view.blocked) out.push(` ${renderAgentLine(line, blockedWidth)}`);\n }\n out.push('', 'Running');\n if (view.running.length === 0) out.push(' nothing');\n const runningWidth = nameWidth(view.running);\n for (const line of view.running) out.push(` ${renderAgentLine(line, runningWidth)}`);\n const notes = renderNotes(view.notes, options.notes);\n if (notes.length > 0) out.push('', ...notes);\n return out.join('\\n');\n}\n\nexport function renderStatus(view: StatusView, options?: RenderOptions): string {\n return [view.time, '', renderSections(view, options), '', KIND_LEGEND, LEGEND].join('\\n');\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { type UserActionStatus, isUserActionStatus } from './status/model.ts';\nimport { sanitizeNote } from './status/note.ts';\n\nexport interface TableItem {\n session: string;\n text: string;\n status: UserActionStatus | null;\n updatedAt: string;\n}\n\nexport interface SetTableInput {\n text: string;\n status?: UserActionStatus | undefined;\n}\n\ninterface TableRow {\n session: string;\n text: string;\n status: UserActionStatus | null;\n updated_at: string;\n}\n\nfunction toItem(row: TableRow): TableItem {\n return { session: row.session, text: row.text, status: row.status, updatedAt: row.updated_at };\n}\n\nexport function tableIsAbout(item: TableItem | undefined | null, name: string): boolean {\n const text = item?.text;\n return text?.startsWith(name) === true && !/[\\w-]/.test(text.charAt(name.length));\n}\n\nexport function getTable(ctx: Ctx, session: string): TableItem | undefined {\n const row = ctx.db.prepare('SELECT * FROM table_items WHERE session = ?').get(session) as\n | TableRow\n | undefined;\n return row && toItem(row);\n}\n\nexport function setTable(ctx: Ctx, session: string, input: SetTableInput): TableItem {\n if (input.status !== undefined && !isUserActionStatus(input.status)) {\n throw new CarnetError('INVALID_STATUS', `Invalid table status \"${String(input.status)}\"`);\n }\n ctx.db\n .prepare(\n `INSERT INTO table_items (session, text, status, updated_at) VALUES (?, ?, ?, ?)\n ON CONFLICT(session) DO UPDATE SET text = excluded.text, status = excluded.status,\n updated_at = excluded.updated_at`,\n )\n .run(session, sanitizeNote(input.text), input.status ?? null, nowIso(ctx));\n return getTable(ctx, session) as TableItem;\n}\n\nexport function clearTable(ctx: Ctx, session: string): void {\n ctx.db.prepare('DELETE FROM table_items WHERE session = ?').run(session);\n}\n","import { type Ctx, nowIso } from './context.ts';\n\nexport const TURNS = ['working', 'waiting', 'failed'] as const;\nexport type Turn = (typeof TURNS)[number];\n\nexport interface TurnOptions {\n // Off when the installed hooks cannot end a turn, so the Main line never shows a turn stuck on.\n trackTurn?: boolean | undefined;\n}\n\nexport function getTurn(ctx: Ctx, session: string): Turn | null {\n const row = ctx.db.prepare('SELECT turn FROM sessions WHERE id = ?').get(session) as\n | { turn: Turn | null }\n | undefined;\n return row?.turn ?? null;\n}\n\n// The UPDATE matches no row when the state already holds, so repeating a call writes nothing.\n// A running turn keeps its start time when it moves between working and waiting.\nfunction setTurn(ctx: Ctx, session: string, turn: Turn | null): void {\n ctx.db\n .prepare(\n `UPDATE sessions SET turn = ?1,\n turn_started_at = CASE\n WHEN ?1 IS NULL THEN NULL\n WHEN ?1 <> 'failed' AND turn IN ('working', 'waiting') THEN turn_started_at\n ELSE ?2 END\n WHERE id = ?3 AND turn IS NOT ?1`,\n )\n .run(turn, nowIso(ctx), session);\n}\n\nexport function startTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, 'working');\n}\n\nexport function waitTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, 'waiting');\n}\n\nexport function failTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, 'failed');\n}\n\nexport function endTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, null);\n}\n","import { type Agent, type AgentKind, KIND_ACTIONS, listAgents } from '../agents.ts';\nimport type { Ctx } from '../context.ts';\nimport { listFindings } from '../findings.ts';\nimport { type NoteActivity, sessionNoteActivity } from '../notes.ts';\nimport { listQuestions } from '../questions.ts';\nimport type { Session } from '../sessions.ts';\nimport { getTable, type TableItem, tableIsAbout } from '../table.ts';\nimport { getTurn, type Turn } from '../turn.ts';\nimport { type AgentStatus, EMOJI, isUserActionStatus } from './model.ts';\n\nexport interface StatusLine {\n name: string;\n kind: AgentKind;\n status: AgentStatus;\n emoji: string;\n // What the human does next, or what a running agent is, with its detail.\n action: string | null;\n note: string | null;\n pinned: boolean;\n}\n\nexport interface StatusView {\n time: string;\n sessionName: string | null;\n table: TableItem | null;\n turn: Turn | null;\n waiting: StatusLine[];\n blocked: StatusLine[];\n running: StatusLine[];\n notes: NoteActivity[];\n}\n\nexport interface StatusViewOptions {\n kind?: AgentKind | undefined;\n}\n\n// A test ties the main repo up, so it comes first; then what resumes a fork; then new main-repo work;\n// then what nothing waits on.\nconst ACTION_RANK: Record<string, number> = {\n test: 0,\n answer: 1,\n validate: 2,\n triage: 3,\n apply: 4,\n inject: 5,\n};\n\nfunction plural(count: number, word: string): string {\n return `${count} ${word}${count === 1 ? '' : 's'}`;\n}\n\nfunction actionWord(agent: Agent): string {\n const { kind, status } = agent;\n if (status === 'answer') return kind === 'plan' ? 'validate' : 'answer';\n if (status === 'review' && kind !== 'implement') return KIND_ACTIONS[kind];\n if (status === 'apply' && kind === 'implement') return 'apply';\n if (status === 'test') return status;\n return status === 'discussing' ? 'discuss' : status;\n}\n\nfunction actionDetail(ctx: Ctx, agent: Agent, word: string): string | null {\n if (word === 'validate' || word === 'answer') {\n const open = listQuestions(ctx, agent.session, agent.name, true).length;\n if (open > 0) return plural(open, 'question');\n // Questions asked only in the report prose have no count to show.\n if (agent.status === 'answer') return 'questions';\n return 'plan';\n }\n if (word === 'triage') {\n const pending = listFindings(ctx, agent.session, agent.name, true);\n const blocking = pending.filter((finding) => finding.severity === 'blocking').length;\n const parts = [\n pending.length > 0 ? plural(pending.length, 'finding') : null,\n blocking > 0 ? `(${blocking} blocking)` : null,\n agent.target ? `→ ${agent.target}` : null,\n ].filter(Boolean);\n return parts.length > 0 ? parts.join(' ') : null;\n }\n return null;\n}\n\nfunction waitingAction(ctx: Ctx, agent: Agent): string {\n const word = actionWord(agent);\n const detail = actionDetail(ctx, agent, word);\n return detail ? `${word} · ${detail}` : word;\n}\n\nfunction runningAction(agent: Agent): string | null {\n return agent.promotedFrom ? `promoted from ${agent.promotedFrom}` : null;\n}\n\nfunction rankOf(agent: Agent): number {\n if (agent.status === 'answer') return ACTION_RANK.answer as number;\n return ACTION_RANK[actionWord(agent)] ?? Object.keys(ACTION_RANK).length;\n}\n\nfunction compareWaiting(left: Agent, right: Agent): number {\n if (left.queueOrder !== null || right.queueOrder !== null) {\n if (left.queueOrder === null) return 1;\n if (right.queueOrder === null) return -1;\n return left.queueOrder - right.queueOrder;\n }\n return (\n rankOf(left) - rankOf(right) ||\n left.statusSince.localeCompare(right.statusSince) ||\n left.name.localeCompare(right.name)\n );\n}\n\nfunction toLine(agent: Agent, action: string | null): StatusLine {\n return {\n name: agent.name,\n kind: agent.kind,\n status: agent.status,\n emoji: agent.status === 'closed' ? '' : EMOJI[agent.status],\n action,\n note: agent.note,\n pinned: agent.queueOrder !== null,\n };\n}\n\nexport function formatClock(date: Date): string {\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n return `${hours}:${minutes}`;\n}\n\nexport function buildStatusView(\n ctx: Ctx,\n session: Session,\n options: StatusViewOptions = {},\n): StatusView {\n const all = listAgents(ctx, session.id);\n const open = new Set(all.map((agent) => agent.name));\n // Nothing releases a blocked agent: it waits only while its blocker is still open.\n const isBlocked = (agent: Agent) => agent.blockedOn !== null && open.has(agent.blockedOn);\n const agents = all.filter((agent) => !options.kind || agent.kind === options.kind);\n const table = getTable(ctx, session.id) ?? null;\n const handed = agents.filter((agent) => isUserActionStatus(agent.status));\n // An agent named on the Main line is the main agent's business, not waiting on the human.\n const waiting = handed\n .filter((agent) => !isBlocked(agent) && !tableIsAbout(table, agent.name))\n .sort(compareWaiting)\n .map((agent) => toLine(agent, waitingAction(ctx, agent)));\n // Whatever its status, even one registered as running before its launch.\n const blocked = agents.filter(isBlocked).map((agent) => toLine(agent, `→ ${agent.blockedOn}`));\n const running = agents\n .filter((agent) => agent.status === 'running' && !isBlocked(agent))\n .map((agent) => toLine(agent, runningAction(agent)));\n return {\n time: formatClock(ctx.now()),\n sessionName: session.name,\n table,\n turn: getTurn(ctx, session.id),\n waiting,\n blocked,\n running,\n notes: sessionNoteActivity(ctx, session.id),\n };\n}\n","import { type Agent, type AgentRow, moveAgentStatus, publishPending, toAgent } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { logEvent } from './events.ts';\n\nexport const PAIRING_WINDOW_MILLISECONDS = 60_000;\nexport const STOPPED_NOTE = 'stopped without agent_done';\n\nexport function byHostAgentId(ctx: Ctx, session: string, hostAgentId: string): Agent | undefined {\n const row = ctx.db\n .prepare('SELECT * FROM agents WHERE session = ? AND host_agent_id = ?')\n .get(session, hostAgentId) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nfunction unpairedByName(ctx: Ctx, session: string, names: readonly string[]): AgentRow | undefined {\n for (const name of names) {\n const row = ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND name = ? AND status != 'closed' AND host_agent_id IS NULL`,\n )\n .get(session, name) as AgentRow | undefined;\n if (row) return row;\n }\n return undefined;\n}\n\nexport function unpairedAgent(\n ctx: Ctx,\n session: string,\n names: readonly string[],\n): Agent | undefined {\n const row = unpairedByName(ctx, session, names);\n return row && toAgent(row);\n}\n\nexport function pendingPlanAgent(ctx: Ctx, session: string): Agent | undefined {\n const row = ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND kind = 'plan' AND status = 'running' AND host_agent_id IS NULL\n ORDER BY started_at ASC, rowid ASC LIMIT 1`,\n )\n .get(session) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nexport function requestLaunch(ctx: Ctx, session: string, name: string): void {\n ctx.db\n .prepare('UPDATE agents SET launch_requested_at = ? WHERE session = ? AND name = ?')\n .run(nowIso(ctx), session, name);\n}\n\n// Helpers (Explore, general-purpose) never stand in: only a fork or a Rucher cold agent can be\n// the launch an agent waits for. No type at all keeps the fallbacks for hosts that send none.\nexport function pairsByFallback(agentType: string | undefined): boolean {\n return agentType === undefined || agentType === 'fork' || /^rucher[\\w-]*:/.test(agentType);\n}\n\nfunction openByName(ctx: Ctx, session: string, names: readonly string[]): AgentRow | undefined {\n for (const name of names) {\n const row = ctx.db\n .prepare(`SELECT * FROM agents WHERE session = ? AND name = ? AND status != 'closed'`)\n .get(session, name) as AgentRow | undefined;\n if (row) return row;\n }\n return undefined;\n}\n\nfunction pairWith(ctx: Ctx, session: string, name: string, hostAgentId: string): Agent | undefined {\n ctx.db\n .prepare(\n 'UPDATE agents SET host_agent_id = ?, launch_requested_at = NULL WHERE session = ? AND name = ?',\n )\n .run(hostAgentId, session, name);\n return byHostAgentId(ctx, session, hostAgentId);\n}\n\n// A name from the subagent pairs exactly, taking the agent back from a fallback holder since two\n// subagents never carry one name. Then the agent an Agent call announced; only then does the oldest\n// unpaired, unblocked agent of the last minute stand in, and the stop corrects it by name.\nexport function pairSubagent(\n ctx: Ctx,\n session: string,\n hostAgentId: string,\n names: readonly string[] = [],\n agentType?: string,\n): Agent | undefined {\n const paired = byHostAgentId(ctx, session, hostAgentId);\n if (paired) return paired;\n const named = openByName(ctx, session, names);\n if (named) return pairWith(ctx, session, named.name, hostAgentId);\n if (!pairsByFallback(agentType)) return undefined;\n const since = new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS).toISOString();\n const row =\n (ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND status != 'closed' AND host_agent_id IS NULL\n AND launch_requested_at >= ?\n ORDER BY launch_requested_at ASC, rowid ASC LIMIT 1`,\n )\n .get(session, since) as AgentRow | undefined) ??\n (ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND blocked_on IS NULL\n AND started_at >= ?\n ORDER BY started_at ASC, rowid ASC LIMIT 1`,\n )\n .get(session, since) as AgentRow | undefined);\n return row && pairWith(ctx, session, row.name, hostAgentId);\n}\n\nfunction byName(ctx: Ctx, session: string, name: string): Agent | undefined {\n const row = ctx.db\n .prepare('SELECT * FROM agents WHERE session = ? AND name = ?')\n .get(session, name) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nfunction setHostAgentId(ctx: Ctx, session: string, name: string, hostAgentId: string | null) {\n ctx.db\n .prepare('UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?')\n .run(hostAgentId, session, name);\n}\n\n// A name only overrides the provisional pair when it designates an existing agent, so a\n// free-text Agent description never unpairs the right fork.\nfunction repairByName(ctx: Ctx, session: string, hostAgentId: string, names: string[]) {\n const named = names.map((name) => byName(ctx, session, name)).find(Boolean);\n if (!named || named.hostAgentId === hostAgentId) return;\n const holder = byHostAgentId(ctx, session, hostAgentId);\n if (holder) setHostAgentId(ctx, session, holder.name, named.hostAgentId);\n setHostAgentId(ctx, session, named.name, hostAgentId);\n}\n\nexport function stopSubagent(\n ctx: Ctx,\n session: string,\n hostAgentId: string,\n names: string[] = [],\n): Agent | undefined {\n repairByName(ctx, session, hostAgentId, names);\n const agent = byHostAgentId(ctx, session, hostAgentId);\n if (!agent || agent.status !== 'running') return undefined;\n if (agent.pendingStatus) {\n publishPending(ctx, session, agent.name);\n return byHostAgentId(ctx, session, hostAgentId);\n }\n moveAgentStatus(ctx, session, agent.name, 'review', STOPPED_NOTE);\n logEvent(ctx, session, { type: 'finished', agent: agent.name, note: STOPPED_NOTE });\n return byHostAgentId(ctx, session, hostAgentId);\n}\n","import { mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync } from 'node:sqlite';\nimport {\n type Agent,\n type AgentKind,\n clearSandbox,\n closeAgent,\n closedSandboxes,\n dropAgent,\n finishAgent,\n type FinishAgentInput,\n getAgent,\n listAgents,\n type ListAgentsOptions,\n promoteAgent,\n type PromoteAgentInput,\n reorderQueue,\n startAgent,\n type StartAgentInput,\n updateAgent,\n type UpdateAgentInput,\n} from './agents.ts';\nimport type { Ctx } from './context.ts';\nimport { MEMORY_DB, openDatabase } from './db/open.ts';\nimport { databasePath } from './paths.ts';\nimport { logEvent, type LogEventInput, readEvents } from './events.ts';\nimport {\n type DecisionInput,\n decideFindings,\n type FindingInput,\n listFindings,\n replaceFindings,\n} from './findings.ts';\nimport {\n type AnswerInput,\n addQuestions,\n answerQuestions,\n listQuestions,\n type QuestionInput,\n} from './questions.ts';\nimport {\n type Workspace,\n type WorkspaceResolution,\n requireWorkspace,\n resolveWorkspace,\n} from './workspace/locate.ts';\nimport {\n copyInjectedRepos,\n type MemoryOptions,\n repoMemory,\n sessionMemory,\n sessionStartMemory,\n} from './memory.ts';\nimport { mergeSessions } from './merge.ts';\nimport { createSandbox, removeSandbox, resolveSandbox } from './sandbox.ts';\nimport {\n type AddNoteInput,\n addNote,\n type CiteNoteInput,\n citeNote,\n type DropNoteInput,\n dropNote,\n getNote,\n listNotes,\n type ListNotesOptions,\n noteDetail,\n recordActiveDay,\n staleNotes,\n sessionNoteActivity,\n} from './notes.ts';\nimport { purgeSessions } from './purge.ts';\nimport {\n createSession,\n type CreateSessionInput,\n defaultSession,\n dropSession,\n endSession,\n ensureSession,\n getSession,\n type HookEnv,\n type HookSessionPayload,\n listSessions,\n type ListSessionsOptions,\n nameSession,\n adoptTitle,\n requireSession,\n findSession,\n recordPluginVersion,\n recordPromptVersion,\n type Session,\n type SessionKind,\n type SessionStatus,\n setParent,\n setSessionKind,\n setSessionStatus,\n demoteSession,\n promoteSession,\n renameSession,\n resetDeadSessions,\n staleTempSessions,\n sessionByHostProcess,\n sessionByName,\n touchSession,\n upsertFromHook,\n} from './sessions.ts';\nimport { type RenderOptions, renderSections, renderStatus } from './status/render.ts';\nimport { buildStatusView, type StatusViewOptions } from './status/view.ts';\nimport {\n byHostAgentId,\n pairSubagent,\n pendingPlanAgent,\n requestLaunch,\n stopSubagent,\n unpairedAgent,\n} from './subagents.ts';\nimport { clearTable, getTable, setTable, type SetTableInput } from './table.ts';\nimport { endTurn, failTurn, getTurn, startTurn, waitTurn } from './turn.ts';\n\nexport interface CarnetOptions {\n now?: () => Date;\n}\n\nexport interface ClosedAgent extends Agent {\n sandboxRemoved: boolean;\n}\n\nexport class Carnet {\n readonly db: DatabaseSync;\n private readonly ctx: Ctx;\n\n constructor(\n db: DatabaseSync,\n readonly workspace: Workspace | null,\n options: CarnetOptions = {},\n ) {\n this.db = db;\n this.ctx = { db, now: options.now ?? (() => new Date()), workspace: workspace?.name ?? null };\n }\n\n now(): Date {\n return this.ctx.now();\n }\n\n requireWorkspace(): Workspace {\n return requireWorkspace(this.workspace);\n }\n\n readonly sessions = {\n get: (id: string) => getSession(this.ctx, id),\n find: (reference: string) => findSession(this.ctx, reference),\n require: (id: string) => requireSession(this.ctx, id),\n ensure: (id: string, cwd?: string) =>\n ensureSession(this.ctx, id, cwd, this.workspace ?? undefined),\n upsertFromHook: (payload: HookSessionPayload, env?: HookEnv) =>\n upsertFromHook(this.ctx, this.workspace, payload, env),\n touch: (id: string) => touchSession(this.ctx, id),\n merge: (fromId: string, intoId: string) => {\n const result = mergeSessions(this.ctx, fromId, intoId);\n this.releaseClosedSandboxes(fromId);\n this.releaseClosedSandboxes(intoId);\n return result;\n },\n purge: (keepId: string, days: number) => purgeSessions(this.ctx, keepId, days),\n name: (id: string, name: string, purpose?: string) => nameSession(this.ctx, id, name, purpose),\n adoptTitle: (id: string, title: string | undefined) => adoptTitle(this.ctx, id, title),\n list: (options?: ListSessionsOptions) => listSessions(this.ctx, options),\n drop: (id: string) => {\n const session = dropSession(this.ctx, id);\n this.releaseClosedSandboxes(id);\n return session;\n },\n default: () => defaultSession(this.ctx),\n byName: (name: string) => sessionByName(this.ctx, name),\n byHostProcess: (host: string, processId: number) =>\n sessionByHostProcess(this.ctx, host, processId),\n recordPluginVersion: (id: string, version: string | null) =>\n recordPluginVersion(this.ctx, id, version),\n recordPromptVersion: (id: string, version: string | null) =>\n recordPromptVersion(this.ctx, id, version),\n setParent: (id: string, parentId: string) => setParent(this.ctx, id, parentId),\n setStatus: (id: string, status: SessionStatus) => setSessionStatus(this.ctx, id, status),\n create: (input: CreateSessionInput) => createSession(this.ctx, input),\n setKind: (id: string, kind: SessionKind, name?: string | null) =>\n setSessionKind(this.ctx, id, kind, name),\n end: (id: string) => endSession(this.ctx, id),\n rename: (id: string, name: string) => renameSession(this.ctx, id, name),\n promote: (id: string, name?: string) => promoteSession(this.ctx, id, name),\n demote: (id: string) => demoteSession(this.ctx, id),\n staleTemp: (olderThanMilliseconds: number) =>\n staleTempSessions(this.ctx, olderThanMilliseconds),\n resetDead: (isAlive: (processId: number) => boolean) => resetDeadSessions(this.ctx, isAlive),\n };\n\n private releaseSandbox(agent: Agent): ClosedAgent {\n if (!agent.sandbox) return { ...agent, sandboxRemoved: false };\n const sandboxRemoved = removeSandbox(this.workspace, agent.sandbox);\n clearSandbox(this.ctx, agent.session, agent.name);\n return { ...agent, sandbox: null, sandboxRemoved };\n }\n\n releaseClosedSandboxes(session?: string): number {\n let removed = 0;\n for (const row of closedSandboxes(this.ctx, session)) {\n if (removeSandbox(this.workspace, row.sandbox)) removed += 1;\n clearSandbox(this.ctx, row.session, row.name);\n }\n return removed;\n }\n\n readonly agents = {\n get: (session: string, name: string) => getAgent(this.ctx, session, name),\n start: (session: string, input: StartAgentInput) => {\n const sandbox = input.sandbox ? resolveSandbox(this.workspace, input.sandbox) : undefined;\n const agent = startAgent(this.ctx, session, { ...input, sandbox });\n if (sandbox) createSandbox(sandbox);\n return agent;\n },\n update: (session: string, name: string, input: UpdateAgentInput) =>\n updateAgent(this.ctx, session, name, input),\n finish: (session: string, name: string, input: FinishAgentInput) =>\n finishAgent(this.ctx, session, name, input),\n drop: (session: string, name: string, reason?: string) =>\n this.releaseSandbox(dropAgent(this.ctx, session, name, reason)),\n close: (session: string, name: string, event: Omit<LogEventInput, 'agent'>) =>\n this.releaseSandbox(closeAgent(this.ctx, session, name, event)),\n promote: (session: string, name: string, input: PromoteAgentInput) => {\n const agent = promoteAgent(this.ctx, session, name, input);\n return agent.kind === 'implement'\n ? this.releaseSandbox(agent)\n : { ...agent, sandboxRemoved: false };\n },\n list: (session: string, options?: ListAgentsOptions) => listAgents(this.ctx, session, options),\n reorderQueue: (session: string, names: string[]) => reorderQueue(this.ctx, session, names),\n byHostAgentId: (session: string, hostAgentId: string) =>\n byHostAgentId(this.ctx, session, hostAgentId),\n pairSubagent: (\n session: string,\n hostAgentId: string,\n names?: readonly string[],\n agentType?: string,\n ) => pairSubagent(this.ctx, session, hostAgentId, names, agentType),\n unpaired: (session: string, names: readonly string[]) =>\n unpairedAgent(this.ctx, session, names),\n pendingPlan: (session: string) => pendingPlanAgent(this.ctx, session),\n requestLaunch: (session: string, name: string) => requestLaunch(this.ctx, session, name),\n stopSubagent: (session: string, hostAgentId: string, names?: string[]) =>\n stopSubagent(this.ctx, session, hostAgentId, names),\n };\n\n readonly questions = {\n list: (session: string, agent: string, openOnly?: boolean) =>\n listQuestions(this.ctx, session, agent, openOnly),\n add: (session: string, agent: string, inputs: readonly QuestionInput[]) =>\n addQuestions(this.ctx, session, agent, inputs),\n answer: (session: string, agent: string, answers: readonly AnswerInput[]) =>\n answerQuestions(this.ctx, session, agent, answers),\n };\n\n readonly findings = {\n list: (session: string, agent: string, pendingOnly?: boolean) =>\n listFindings(this.ctx, session, agent, pendingOnly),\n replace: (session: string, agent: string, inputs: readonly FindingInput[]) =>\n replaceFindings(this.ctx, session, agent, inputs),\n decide: (session: string, agent: string, decisions: readonly DecisionInput[]) =>\n decideFindings(this.ctx, session, agent, decisions),\n };\n\n readonly table = {\n get: (session: string) => getTable(this.ctx, session),\n set: (session: string, input: SetTableInput) => setTable(this.ctx, session, input),\n clear: (session: string) => clearTable(this.ctx, session),\n };\n\n readonly turn = {\n get: (session: string) => getTurn(this.ctx, session),\n start: (session: string) => startTurn(this.ctx, session),\n wait: (session: string) => waitTurn(this.ctx, session),\n fail: (session: string) => failTurn(this.ctx, session),\n end: (session: string) => endTurn(this.ctx, session),\n };\n\n readonly events = {\n log: (session: string, input: LogEventInput) => logEvent(this.ctx, session, input),\n read: (session: string, limit?: number, agentOnly?: boolean, kind?: AgentKind) =>\n readEvents(this.ctx, { session, limit, agentOnly, kind }),\n };\n\n readonly notes = {\n add: (input: AddNoteInput) => addNote(this.ctx, this.workspace, input),\n get: (id: number) => getNote(this.ctx, id),\n show: (id: number, halfLifeDays?: number) => noteDetail(this.ctx, id, halfLifeDays),\n list: (options?: ListNotesOptions) => listNotes(this.ctx, options),\n stale: (halfLifeDays?: number) => staleNotes(this.ctx, halfLifeDays),\n drop: (id: number, input: DropNoteInput) => dropNote(this.ctx, id, input),\n cite: (id: number, input: CiteNoteInput) => citeNote(this.ctx, id, input),\n recordActiveDay: () => recordActiveDay(this.ctx),\n activity: (session: string) => sessionNoteActivity(this.ctx, session),\n };\n\n readonly memory = {\n atStart: (session: Session, options?: MemoryOptions) =>\n sessionStartMemory(this.ctx, this.workspace, session, options),\n ofSession: (session: Session, options?: MemoryOptions) =>\n sessionMemory(this.ctx, this.workspace, session, options),\n forRepo: (session: Session, repo: string, options?: MemoryOptions) =>\n repoMemory(this.ctx, session, repo, options),\n copyRepos: (from: string, into: string) => copyInjectedRepos(this.ctx, from, into),\n };\n\n readonly status = {\n view: (session: Session, options?: StatusViewOptions) =>\n buildStatusView(this.ctx, session, options),\n render: (session: Session, options?: RenderOptions & StatusViewOptions) =>\n renderStatus(buildStatusView(this.ctx, session, options), options),\n sections: (session: Session) => renderSections(buildStatusView(this.ctx, session)),\n };\n\n close(): void {\n this.db.close();\n }\n}\n\nexport interface OpenCarnetOptions extends CarnetOptions {\n workspace?: string | undefined;\n sessionId?: string | undefined;\n cwd?: string | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n dbPath?: string | undefined;\n}\n\nfunction openStore(options: OpenCarnetOptions): DatabaseSync {\n const path = options.dbPath ?? databasePath(options.env);\n if (path !== MEMORY_DB) mkdirSync(dirname(path), { recursive: true });\n return openDatabase(path);\n}\n\nexport function openCarnet(options: OpenCarnetOptions = {}): Carnet {\n return openResolvedCarnet(options).carnet;\n}\n\nexport interface ResolvedCarnet {\n carnet: Carnet;\n resolution: WorkspaceResolution;\n}\n\nexport function openResolvedCarnet(options: OpenCarnetOptions = {}): ResolvedCarnet {\n const db = openStore(options);\n try {\n const resolution = resolveWorkspace({ ...options, db });\n return { carnet: new Carnet(db, resolution.workspace, options), resolution };\n } catch (error) {\n db.close();\n throw error;\n }\n}\n\nexport function openWorkspaceCarnet(\n workspace: Workspace | null,\n options: OpenCarnetOptions = {},\n): Carnet {\n return new Carnet(openStore(options), workspace, options);\n}\n","import { appendFileSync, existsSync, readFileSync } from 'node:fs';\n\nconst HEADING = /^##\\s+(.+?)\\s*$/;\nconst FENCE = /^\\s*(```|~~~)/;\n\nfunction normalize(text: string): string {\n return text\n .toLowerCase()\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '');\n}\n\nexport function hasSection(markdown: string, names: readonly string[]): boolean {\n return extractSection(markdown, names) !== undefined;\n}\n\n// A `## ` line inside a code fence is an example, not a section of the report.\nfunction headings(lines: readonly string[]): (string | undefined)[] {\n let fenced = false;\n return lines.map((line) => {\n if (FENCE.test(line)) fenced = !fenced;\n return fenced ? undefined : HEADING.exec(line)?.[1];\n });\n}\n\nfunction headingTitle(heading: string): string {\n const [title = ''] = normalize(heading)\n .replace(/^\\d+[.)]\\s*/, '')\n .replace(/[*_`]/g, '')\n .split(/[:(]/);\n return title.trim();\n}\n\nfunction escape(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction matchRank(heading: string, names: readonly string[]): number {\n const title = headingTitle(heading);\n if (names.some((name) => title === name || title === `${name}s`)) return 1;\n const word = names.some((name) =>\n new RegExp(`(^|[^a-z0-9])${escape(name)}s?($|[^a-z0-9])`).test(title),\n );\n return word ? 2 : 0;\n}\n\nexport function extractSection(markdown: string, names: readonly string[]): string | undefined {\n const wanted = names.map(normalize);\n const lines = markdown.split('\\n');\n const titles = headings(lines);\n const ranks = titles.map((heading) => (heading === undefined ? 0 : matchRank(heading, wanted)));\n // An exact heading wins over one that only contains the name: `## Done` over `## Verification done`.\n const exact = ranks.indexOf(1);\n const start = exact !== -1 ? exact : ranks.indexOf(2);\n if (start === -1) return undefined;\n const end = titles.findIndex((heading, index) => index > start && heading !== undefined);\n return lines\n .slice(start + 1, end === -1 ? undefined : end)\n .join('\\n')\n .trim();\n}\n\nexport function readReport(path: string | null): string | undefined {\n return path && existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n}\n\nexport function appendToReport(path: string | null, markdown: string): void {\n const current = readReport(path);\n if (current === undefined || !path) return;\n const separator = current.endsWith('\\n\\n') ? '' : current.endsWith('\\n') ? '\\n' : '\\n\\n';\n appendFileSync(path, `${separator}${markdown.trimEnd()}\\n`);\n}\n\n// A promoted agent's next report replaces this one, and a review still needs the plan.\nexport function keptReportPath(report: string, kind: 'research' | 'plan'): string {\n return report.replace(/(\\.md)?$/, kind === 'plan' ? '.plan.md' : '.research.md');\n}\n","import { copyFileSync, existsSync } from 'node:fs';\nimport {\n type Agent,\n KIND_ACTIONS,\n type KindAction,\n mainTargetRange,\n type PromoteAgentInput,\n statusAfterAnswers,\n} from './agents.ts';\nimport type { Carnet } from './carnet.ts';\nimport { CarnetError } from './errors.ts';\nimport { sandboxRemovedSuffix } from './sandbox.ts';\nimport {\n type DecisionInput,\n type FindingInput,\n formatFinding,\n renderFindings,\n} from './findings.ts';\nimport {\n type AnswerInput,\n type Question,\n type QuestionInput,\n renderQuestions,\n} from './questions.ts';\nimport {\n appendToReport,\n extractSection,\n hasSection,\n keptReportPath,\n readReport,\n} from './report.ts';\nimport { type Session, shortId } from './sessions.ts';\nimport { EMOJI, kindTag } from './status/model.ts';\n\nexport function kindAction(agent: Pick<Agent, 'kind'>): KindAction {\n return KIND_ACTIONS[agent.kind];\n}\n\nexport interface FinishWithItemsInput {\n reportPath: string;\n hasQuestions?: boolean | undefined;\n questions?: readonly QuestionInput[] | undefined;\n findings?: readonly FindingInput[] | undefined;\n}\n\n// Structured questions and findings are the only copy the fork writes; the report gets them from here.\nexport function finishWithItems(\n carnet: Carnet,\n session: string,\n name: string,\n input: FinishWithItemsInput,\n): Agent {\n const agent = requireAgent(carnet, session, name);\n if (input.findings?.length && agent.kind !== 'review') {\n throw new CarnetError(\n 'INVALID_KIND',\n `Only a review agent reports findings; ${name} is ${agent.kind}`,\n );\n }\n const report = readReport(input.reportPath);\n if (input.questions?.length) {\n const open = carnet.questions\n .add(session, name, input.questions)\n .filter((question) => question.answer === null);\n if (report !== undefined && !hasSection(report, ['questions'])) {\n appendToReport(input.reportPath, renderQuestions(open));\n }\n }\n if (input.findings?.length) {\n const findings = carnet.findings.replace(session, name, input.findings);\n if (report !== undefined && !hasSection(report, ['findings'])) {\n appendToReport(input.reportPath, renderFindings(findings));\n }\n }\n const openQuestions = carnet.questions.list(session, name, true).length;\n return carnet.agents.finish(session, name, {\n reportPath: input.reportPath,\n hasQuestions: openQuestions > 0 || input.hasQuestions === true,\n });\n}\n\nfunction requireAgent(carnet: Carnet, session: string, name: string): Agent {\n const agent = carnet.agents.get(session, name);\n if (!agent) throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n return agent;\n}\n\n// The human reads a report from another terminal, so the asking session isn't always the most\n// recently active one: every open session is searched, and an open agent wins over a closed homonym.\nexport function locateAgent(carnet: Carnet, name: string): { session: Session; agent: Agent } {\n const found = carnet.sessions.list({ includeTemp: true }).flatMap((session) => {\n const agent = carnet.agents.get(session.id, name);\n return agent ? [{ session, agent }] : [];\n });\n const open = found.filter((entry) => entry.agent.status !== 'closed');\n const only = found.length === 1 ? found[0] : open.length === 1 ? open[0] : undefined;\n if (only) return only;\n if (found.length === 0) {\n throw new CarnetError(\n 'AGENT_NOT_FOUND',\n `No agent \"${name}\" in the open sessions of this workspace`,\n );\n }\n const labels = found.map((entry) => entry.session.name ?? shortId(entry.session.id));\n throw new CarnetError(\n 'AGENT_AMBIGUOUS',\n `\"${name}\" is in several sessions: ${labels.join(', ')}; pass --session`,\n );\n}\n\n// The named agent (or the only one starting with it), else the first of Waiting on you, so the\n// model never sorts the queue itself.\nexport function nextAgent(carnet: Carnet, session: string, prefix?: string): string | undefined {\n if (!prefix) {\n return carnet.status.view(carnet.sessions.require(session)).waiting[0]?.name;\n }\n if (carnet.agents.get(session, prefix)) return prefix;\n const matches = carnet.agents\n .list(session, { includeClosed: true })\n .filter((agent) => agent.name.startsWith(prefix))\n .map((agent) => agent.name);\n if (matches.length === 1) return matches[0];\n if (matches.length === 0) {\n throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${prefix}\" in this session`);\n }\n throw new CarnetError('AGENT_AMBIGUOUS', `\"${prefix}\" matches ${matches.join(', ')}: which one?`);\n}\n\nfunction formatQuestion(question: Question): string {\n const lines = [`${question.n}/${question.total} ${question.text}`];\n if (question.context) lines.push(` context: ${question.context}`);\n lines.push(` recommended: ${question.recommendation}`);\n if (question.alternatives.length) {\n lines.push(` alternatives: ${question.alternatives.join(' | ')}`);\n }\n return lines.join('\\n');\n}\n\nexport function openQuestionsText(carnet: Carnet, session: string, name: string): string {\n requireAgent(carnet, session, name);\n const open = carnet.questions.list(session, name, true);\n if (!open.length) return `${name}: no open questions`;\n const total = open[0]?.total ?? open.length;\n return [`${name}: ${open.length} of ${total} open`, ...open.map(formatQuestion)].join('\\n');\n}\n\nfunction today(carnet: Carnet): string {\n return carnet.now().toISOString().slice(0, 10);\n}\n\nexport function answerQuestionsText(\n carnet: Carnet,\n session: string,\n name: string,\n answers: readonly AnswerInput[],\n): string {\n const agent = requireAgent(carnet, session, name);\n const questions = carnet.questions.answer(session, name, answers);\n const lines = [...answers]\n .sort((a, b) => a.n - b.n)\n .map((answer) => `${answer.n}. ${answer.answer.trim()}`);\n appendToReport(agent.reportPath, `## Answers (${today(carnet)})\\n\\n${lines.join('\\n')}`);\n const open = questions.filter((question) => question.answer === null).length;\n if (open) return `answered ${answers.length} · ${open} of ${questions.length} open`;\n const next = statusAfterAnswers(agent.kind);\n carnet.events.log(session, { type: 'answered', agent: name });\n carnet.agents.update(session, name, { status: next, note: null });\n return `all ${questions.length} answered · ${EMOJI[next]} ${name} ${next}`;\n}\n\nconst FOR_MAIN = ['for the main', 'pour le main'];\nconst PLAN = ['plan'];\n\nexport interface InjectInput {\n full?: boolean | undefined;\n section?: string | undefined;\n echo?: boolean | undefined;\n}\n\nexport function injectReport(\n carnet: Carnet,\n session: string,\n name: string,\n input: InjectInput,\n): string {\n const agent = requireAgent(carnet, session, name);\n const report = readReport(agent.reportPath);\n if (report === undefined) {\n throw new CarnetError('REPORT_MISSING', `${name} has no report to inject yet`);\n }\n const names = input.section\n ? [input.section]\n : agent.kind === 'plan' || agent.promotedFrom === 'plan'\n ? PLAN\n : FOR_MAIN;\n const text = input.full ? report.trim() : extractSection(report, names);\n if (text === undefined) {\n throw new CarnetError(\n 'SECTION_NOT_FOUND',\n `No \"## ${names[0]}\" section in ${name}'s report; pass section or full`,\n );\n }\n const lineCount = text.split('\\n').length;\n const note = `${input.full ? 'full report' : names[0]}, ${lineCount} lines`;\n let removed = false;\n if (agent.kind === 'research' && agent.status !== 'closed') {\n removed = carnet.agents.close(session, name, {\n type: 'injected',\n note,\n link: agent.reportPath ?? undefined,\n }).sandboxRemoved;\n } else {\n carnet.events.log(session, { type: 'injected', agent: name, note });\n }\n const confirmation = `${name} injected (${lineCount} lines)${sandboxRemovedSuffix(removed)}`;\n return input.echo === false ? confirmation : `${confirmation}\\n${text}`;\n}\n\nfunction firstLines(text: string | undefined, max: number): string[] {\n if (!text) return [];\n const lines = text.split('\\n').filter((line) => line.trim() !== '');\n return lines.length > max ? [...lines.slice(0, max), '…'] : lines;\n}\n\nfunction firstParagraph(text: string | undefined, max: number): string[] {\n return firstLines(text?.split(/\\n\\s*\\n/)[0], max);\n}\n\nconst TOP_LEVEL_ITEM = /^(-|\\*|\\d+\\.)\\s|^\\*\\*/;\n\nfunction topLevelItems(text: string | undefined, max: number): string[] {\n return firstLines(\n text\n ?.split('\\n')\n .filter((line) => TOP_LEVEL_ITEM.test(line))\n .join('\\n'),\n max,\n );\n}\n\nfunction planSteps(plan: string | undefined): string[] {\n if (!plan) return [];\n const headings = plan.split('\\n').filter((line) => /^###\\s/.test(line));\n const steps =\n headings.length > 0 ? headings : plan.split('\\n').filter((line) => /^\\d+\\.\\s/.test(line));\n return steps.map((line) => line.replace(/^###\\s+/, '').trim());\n}\n\nfunction block(title: string, lines: string[]): string[] {\n return lines.length > 0 ? [`${title}:`, ...lines] : [];\n}\n\n// A preview before the kind's action, built from the sections each contract requires, so the\n// main agent never reads a whole report into its context.\nexport function reportSummary(carnet: Carnet, session: string, name: string): string {\n const agent = requireAgent(carnet, session, name);\n const report = readReport(agent.reportPath);\n if (report === undefined) {\n throw new CarnetError('REPORT_MISSING', `${name} has no report yet`);\n }\n const section = (...names: string[]) => extractSection(report, names);\n const emoji = agent.status === 'closed' ? '' : `${EMOJI[agent.status]} `;\n const lines = [`${name} ${kindTag(agent.kind)} ${emoji}→ ${kindAction(agent)}`];\n if (agent.kind === 'research') {\n lines.push(\n ...block('For the main', firstLines(section(...FOR_MAIN), 15)),\n ...block('Gaps', firstLines(section('gaps'), 3)),\n );\n } else if (agent.kind === 'plan') {\n const plan = section(...PLAN);\n const steps = planSteps(plan);\n const open = carnet.questions.list(session, name, true).length;\n // Without steps the plan agent answered a question in Understanding, so show the answer whole.\n const understanding = section('understanding');\n lines.push(\n ...block(\n 'Understanding',\n steps.length > 0 ? firstParagraph(understanding, 5) : firstLines(understanding, 15),\n ),\n ...(steps.length > 0\n ? block(`Plan, ${steps.length} steps`, steps)\n : [`Plan: ${firstLines(plan, 1)[0] ?? 'none'}`]),\n `Questions: ${open} open`,\n );\n } else if (agent.kind === 'implement') {\n lines.push(\n ...block('Done', topLevelItems(section('done'), 8)),\n ...block('Deviations', firstLines(section('deviations'), 6)),\n ...block('Risks', firstLines(section('risks'), 6)),\n ...block('Commit message', firstLines(section('commit message')?.replace(/```\\w*/g, ''), 1)),\n );\n } else {\n const pending = carnet.findings.list(session, name, true);\n const bySeverity = ['blocking', 'to_fix', 'suggestion']\n .map((severity) => [severity, pending.filter((f) => f.severity === severity).length] as const)\n .filter(([, count]) => count > 0)\n .map(([severity, count]) => `${count} ${severity.replace('_', ' ')}`);\n lines.push(\n ...block('Verdict', firstLines(section('verdict'), 1)),\n `Findings: ${bySeverity.length > 0 ? bySeverity.join(', ') : 'none pending'}`,\n ...block('Not verified', firstLines(section('not verified'), 3)),\n );\n }\n const contractSections = [...FOR_MAIN, ...PLAN, 'understanding', 'done', 'verdict'];\n if (!hasSection(report, contractSections)) {\n lines.push(...block('Report', firstLines(report.replace(/^#[^\\n]*\\n/, ''), 10)));\n }\n lines.push(`report: ${agent.reportPath}`);\n return lines.join('\\n');\n}\n\nexport interface ReportDocument {\n text: string;\n path: string;\n}\n\nfunction decisions(questions: readonly Question[]): string[] {\n return questions.flatMap((question) => [\n `${question.n}. ${question.text}`,\n ` Recommended: ${question.recommendation}`,\n ` Answered: ${question.answer ?? 'open'}`,\n ]);\n}\n\n// What the human reads in full before validating: the plan as written, each question beside its answer.\nexport function reportDocument(carnet: Carnet, session: string, name: string): ReportDocument {\n const agent = requireAgent(carnet, session, name);\n const report = readReport(agent.reportPath);\n if (report === undefined || !agent.reportPath) {\n throw new CarnetError('REPORT_MISSING', `${name} has no report yet`);\n }\n const understanding = extractSection(report, ['understanding']);\n const plan = extractSection(report, PLAN);\n if (agent.kind !== 'plan' || plan === undefined) {\n return { text: report.trimEnd(), path: agent.reportPath };\n }\n const questions = carnet.questions.list(session, name);\n const lines = [`# ${name} ${kindTag(agent.kind)}: the plan as answered`];\n if (understanding !== undefined) lines.push('', '## Understanding', '', understanding);\n lines.push('', '## Plan', '', plan);\n if (questions.length > 0) lines.push('', '## Decisions', '', ...decisions(questions));\n return { text: lines.join('\\n'), path: agent.reportPath };\n}\n\nexport function promoteText(\n carnet: Carnet,\n session: string,\n name: string,\n input: PromoteAgentInput,\n): string {\n const current = requireAgent(carnet, session, name);\n const agent = carnet.agents.promote(session, name, input);\n const lines = [`${EMOJI.running} ${name} promoted to ${agent.kind}`];\n const from = current.kind;\n if ((from === 'research' || from === 'plan') && current.reportPath) {\n if (existsSync(current.reportPath)) {\n const kept = keptReportPath(current.reportPath, from);\n copyFileSync(current.reportPath, kept);\n lines.push(`${from === 'plan' ? 'plan' : 'research'} kept: ${kept}`);\n }\n }\n if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);\n if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);\n if (agent.sandbox) lines.push(`sandbox kept: ${agent.sandbox}`);\n if (agent.sandboxRemoved) lines.push('sandbox removed');\n return lines.join('\\n');\n}\n\nexport function reviewContext(carnet: Carnet, session: string, target: string): string {\n const range = mainTargetRange(target);\n if (range !== undefined) {\n return range\n ? `target main, commits ${range}`\n : 'target main, the uncommitted changes of the main repo';\n }\n const agent = requireAgent(carnet, session, target);\n if (agent.kind !== 'implement') {\n throw new CarnetError('INVALID_TARGET', `${target} is ${agent.kind}, not implement`);\n }\n const from = agent.promotedFrom ? `, promoted from ${agent.promotedFrom}` : '';\n const lines = [`target ${target} (implement${from}, ${agent.status})`];\n if (agent.task) lines.push(`task: ${agent.task}`);\n if (agent.reportPath) lines.push(`report: ${agent.reportPath}`);\n if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);\n if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);\n for (const kind of ['research', 'plan'] as const) {\n const kept = agent.reportPath ? keptReportPath(agent.reportPath, kind) : null;\n if (kept && existsSync(kept)) lines.push(`${kind === 'plan' ? 'plan' : 'research'}: ${kept}`);\n }\n const answered = carnet.questions.list(session, target).filter((question) => question.answer);\n if (answered.length) {\n lines.push('answers:');\n for (const question of answered) {\n lines.push(` ${question.n}. ${question.text} → ${question.answer}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function findingsText(\n carnet: Carnet,\n session: string,\n name: string,\n pendingOnly: boolean,\n): string {\n const agent = requireAgent(carnet, session, name);\n const findings = carnet.findings.list(session, name, pendingOnly);\n const all = carnet.findings.list(session, name);\n if (!findings.length) return `${name}: ${all.length ? 'no pending findings' : 'no findings'}`;\n const pending = all.filter((finding) => finding.decision === null).length;\n const target = agent.target ? ` · target ${agent.target}` : '';\n const header = `${name}: ${pending} of ${all.length} pending${target}`;\n return [\n header,\n ...findings.map((finding) => {\n const decided = finding.decision ? ` → ${finding.decision}` : '';\n return `${formatFinding(finding)}${decided}`;\n }),\n ].join('\\n');\n}\n\nexport function decideText(\n carnet: Carnet,\n session: string,\n name: string,\n decisions: readonly DecisionInput[],\n): string {\n const agent = requireAgent(carnet, session, name);\n if (agent.kind !== 'review') {\n throw new CarnetError('INVALID_KIND', `${name} is ${agent.kind}, not review`);\n }\n if (\n decisions.some((item) => item.decision === 'sent') &&\n agent.target &&\n mainTargetRange(agent.target) !== undefined\n ) {\n throw new CarnetError(\n 'INVALID_TARGET',\n `${name} reviews main: there is no agent to send findings to; fix or ignore them`,\n );\n }\n const findings = carnet.findings.decide(session, name, decisions);\n const pending = findings.filter((finding) => finding.decision === null).length;\n if (pending) return `decided ${decisions.length} · ${pending} of ${findings.length} pending`;\n const count = (decision: string) =>\n findings.filter((finding) => finding.decision === decision).length;\n const note = `${count('sent')} sent, ${count('fixed')} fixed, ${count('ignored')} ignored`;\n carnet.agents.close(session, name, {\n type: 'triaged',\n note,\n link: agent.reportPath ?? undefined,\n });\n const lines = [`${name} triaged: ${note}, closed`];\n const sent = findings.filter((finding) => finding.decision === 'sent');\n if (sent.length && agent.target) {\n lines.push(`send to ${agent.target}:`, ...sent.map(formatFinding));\n }\n return lines.join('\\n');\n}\n","import type { Carnet } from './carnet.ts';\nimport type { CarnetEvent } from './events.ts';\nimport type { Session } from './sessions.ts';\nimport { formatClock } from './status/view.ts';\n\nexport const RESUME_EVENTS = 20;\nexport const RESUME_MAX_CHARACTERS = 2000;\n\nexport interface ResumeContextOptions {\n events?: number;\n maxCharacters?: number;\n}\n\nexport function formatEventLine(event: CarnetEvent): string {\n return [\n formatClock(new Date(event.at)),\n event.type,\n event.agent,\n event.link ?? event.note,\n event.commit?.slice(0, 7),\n ]\n .filter(Boolean)\n .join(' ');\n}\n\nexport function sessionLabel(session: Session): string {\n const name = session.name ?? session.id;\n return session.purpose ? `${name} (${session.purpose})` : name;\n}\n\nexport function resumeContext(\n carnet: Carnet,\n session: Session,\n { events = RESUME_EVENTS, maxCharacters = RESUME_MAX_CHARACTERS }: ResumeContextOptions = {},\n): string {\n const head = `Rucher session ${sessionLabel(session)}, state when resumed:\\n\\n${carnet.status.render(session, { notes: 'summary' })}`;\n const lines = carnet.events.read(session.id, events, true).map(formatEventLine);\n const build = () =>\n lines.length ? `${head}\\n\\nLast events\\n${lines.map((line) => ` ${line}`).join('\\n')}` : head;\n let text = build();\n // Drop the oldest events first: the latest steps matter most when picking up work.\n while (text.length > maxCharacters && lines.length > 0) {\n lines.shift();\n text = build();\n }\n return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;\n}\n","import { statusAfterAnswers } from './agents.ts';\nimport type { Carnet } from './carnet.ts';\nimport { CarnetError } from './errors.ts';\nimport { sandboxRemovedSuffix } from './sandbox.ts';\nimport { EMOJI, OPEN_AGENT_STATUSES } from './status/model.ts';\nimport { tableIsAbout } from './table.ts';\n\ntype OpenAgentStatus = (typeof OPEN_AGENT_STATUSES)[number];\n\nexport const AGENT_STEPS = [\n 'answered',\n 'applying',\n 'applied',\n 'tested',\n 'committed',\n 'dropped',\n] as const;\nexport type AgentStep = (typeof AGENT_STEPS)[number];\n\nexport interface StepAgentInput {\n name: string;\n step: AgentStep;\n commit?: string | undefined;\n note?: string | undefined;\n next?: OpenAgentStatus | undefined;\n}\n\nconst DEFAULT_NEXT: Partial<Record<AgentStep, OpenAgentStatus>> = {\n applied: 'test',\n tested: 'test',\n};\n\nfunction clearTableOf(carnet: Carnet, session: string, name: string): void {\n if (tableIsAbout(carnet.table.get(session), name)) carnet.table.clear(session);\n}\n\nexport function stepAgent(carnet: Carnet, session: string, input: StepAgentInput): string {\n const { name, step, commit, note } = input;\n const agent = carnet.agents.get(session, name);\n if (!agent) {\n throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n }\n switch (step) {\n case 'applying': {\n if (agent.kind !== 'implement') {\n throw new CarnetError(\n 'INVALID_KIND',\n `${name} is ${agent.kind}: only an implement agent is applied`,\n );\n }\n carnet.table.set(session, { text: `${name} applying` });\n carnet.agents.update(session, name, {\n status: agent.status,\n note: note ?? null,\n blockedOn: null,\n });\n const reviews = carnet.agents\n .list(session)\n .filter((other) => other.kind === 'review' && other.target === name);\n const warning = reviews.length\n ? `\\nwarning: review ${reviews.map((review) => review.name).join(', ')} not triaged yet`\n : '';\n return `⚙️ ${name} applying${warning}`;\n }\n case 'committed': {\n if (!commit) throw new CarnetError('COMMIT_REQUIRED', 'The committed step needs the commit');\n carnet.events.log(session, { type: 'committed', agent: name, commit, note });\n const closed = carnet.agents.drop(session, name, `committed ${commit}`);\n clearTableOf(carnet, session, name);\n return `✅ ${name} committed ${commit}, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;\n }\n case 'dropped': {\n const closed = carnet.agents.drop(session, name, note);\n clearTableOf(carnet, session, name);\n return `${name} dropped, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;\n }\n default: {\n const next =\n input.next ??\n (step === 'answered'\n ? statusAfterAnswers(agent.kind)\n : (DEFAULT_NEXT[step] as OpenAgentStatus));\n carnet.events.log(session, { type: step, agent: name, note });\n // A step means the human is handling the agent, so it no longer waits on another one.\n carnet.agents.update(session, name, { status: next, note: note ?? null, blockedOn: null });\n // Once applied, the agent waits on the human under test, so the Main line lets it show there.\n if (next === 'running' || step !== 'answered') clearTableOf(carnet, session, name);\n return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;\n }\n }\n}\n"],"mappings":";;;;;;AASA,SAAgB,OAAO,KAAkB;CACvC,OAAO,IAAI,IAAI,CAAC,CAAC,YAAY;AAC/B;;ACgCA,IAAa,cAAb,cAAiC,MAAM;CA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