@rucher/carnet 0.2.0-beta.8 → 0.2.0-beta.9

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-xzr8iVWn.mjs","names":["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/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/purge.ts","../src/status/render.ts","../src/table.ts","../src/turn.ts","../src/status/view.ts","../src/subagents.ts","../src/carnet.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 | '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 | 'INVALID_TARGET'\n | 'INVALID_BLOCKER'\n | 'INVALID_KIND'\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\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 analyze: 'an',\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|an|im|rv)\\]/;\n\nexport const KIND_LEGEND = '[rs] research · [an] analyze · [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 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', 'analyze', 'implement', 'review'] as const;\n\nexport type AgentKind = (typeof AGENT_KINDS)[number];\n\n// A kind-less agent writes no code until it is promoted.\nexport const DEFAULT_AGENT_KIND: AgentKind = 'analyze';\n\nexport const FINAL_ACTIONS = {\n research: 'inject',\n analyze: 'validate',\n implement: 'apply',\n review: 'triage',\n} as const satisfies Record<AgentKind, string>;\n\nexport type FinalAction = (typeof FINAL_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 queueOrder: number | null;\n hostAgentId: string | null;\n pendingStatus: AgentStatus | null;\n doneAt: string | null;\n startedAt: string;\n updatedAt: string;\n}\n\nexport interface StartAgentInput {\n name: string;\n task: string;\n kind?: AgentKind | undefined;\n target?: string | undefined;\n baseCommit?: string | undefined;\n worktree?: string | undefined;\n}\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 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}\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 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 };\n}\n\nexport const REPORTING_NOTE = 'reporting';\nexport const PUBLISH_FALLBACK_MILLISECONDS = 120_000;\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, updated_at = ? WHERE session = ? AND name = ?',\n )\n .run(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 <= ?',\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 ?? DEFAULT_AGENT_KIND;\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 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 started_at, updated_at)\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 at,\n at,\n );\n logEvent(ctx, session, { type: 'started', agent: name, note: input.task });\n return requireAgent(ctx, session, name);\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 = ?, status = ?, report_path = COALESCE(?, report_path), blocked_on = ?, updated_at = ? WHERE session = ? AND name = ?',\n )\n .run(note, input.status, input.reportPath ?? null, blockedOn, nowIso(ctx), session, name);\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, an analyze 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(\n \"UPDATE agents SET status = 'closed', pending_status = NULL, queue_order = NULL, blocked_on = NULL, updated_at = ? WHERE session = ? AND name = ?\",\n )\n .run(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\nexport interface PromoteAgentInput {\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 if (agent.kind !== 'analyze') {\n throw new CarnetError(\n 'INVALID_KIND',\n `Only an analyze agent is promoted; ${name} is ${agent.kind}`,\n );\n }\n ctx.db\n .prepare(\n `UPDATE agents SET kind = 'implement', promoted_from = 'analyze', status = 'running',\n pending_status = NULL, note = NULL, blocked_on = NULL, worktree = COALESCE(?, worktree),\n base_commit = COALESCE(?, base_commit), updated_at = ?\n WHERE session = ? AND name = ?`,\n )\n .run(input.worktree ?? null, input.baseCommit ?? null, nowIso(ctx), session, name);\n logEvent(ctx, session, { type: 'promoted', agent: name, note: 'analyze to implement' });\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';\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\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\nexport function migrate(db: DatabaseSync): void {\n const current = schemaVersion(db);\n if (current >= 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 (const [version, migration] of migrations.entries()) {\n if (version < current) continue;\n db.exec('BEGIN');\n try {\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\nexport function openDatabase(path: string): DatabaseSync {\n const db = new DatabaseSync(path);\n if (path !== MEMORY_DB) {\n db.exec('PRAGMA journal_mode = WAL');\n }\n db.exec('PRAGMA foreign_keys = ON');\n db.exec('PRAGMA busy_timeout = 5000');\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 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 { 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`,\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 ctx.db\n .prepare(\n \"UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'\",\n )\n .run(at, id);\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 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`,\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 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`,\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, triggers their final 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 final action, 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 {\n closeSync,\n existsSync,\n fstatSync,\n openSync,\n readdirSync,\n readFileSync,\n readSync,\n rmdirSync,\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} from './host.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 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\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 };\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 = join(projectsDirectory(env), session.cwd.replace(/[^a-zA-Z0-9]/g, '-'));\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 = join(projectsDirectory(env), parent.cwd.replace(/[^a-zA-Z0-9]/g, '-'));\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};\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';\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}\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 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}\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';\n\nfunction inTransaction<T>(db: DatabaseSync, run: () => T): T {\n db.exec('BEGIN');\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 db.prepare(\n `UPDATE agents SET status = 'closed', updated_at = ?\n WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE workspace = ?)`,\n ).run(at, name);\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","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`,\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 { 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 ctx.db\n .prepare(\n \"UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'\",\n )\n .run(at, fromId);\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 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}. ${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, FINAL_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}\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// Questions and plans unblock forks, so they come first; the human's own steps come after every handover.\nconst ACTION_RANK: Record<string, number> = {\n validate: 1,\n triage: 2,\n inject: 3,\n apply: 4,\n test: 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 === 'analyze' ? 'validate' : 'answer';\n if (status === 'review' && kind !== 'implement') return FINAL_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 0;\n return ACTION_RANK[actionWord(agent)] ?? Object.keys(ACTION_RANK).length + 1;\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 rankOf(left) - rankOf(right) || left.startedAt.localeCompare(right.startedAt);\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 };\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 const blocked = handed.filter(isBlocked).map((agent) => toLine(agent, `→ ${agent.blockedOn}`));\n const running = agents\n .filter((agent) => agent.status === 'running')\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, 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\n// SubagentStart carries no name, so this pairing is provisional: the stop corrects it by name.\nexport function pairSubagent(ctx: Ctx, session: string, hostAgentId: string): Agent | undefined {\n const paired = byHostAgentId(ctx, session, hostAgentId);\n if (paired) return paired;\n const since = new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS).toISOString();\n const row = ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND started_at >= ?\n ORDER BY started_at ASC, rowid ASC LIMIT 1`,\n )\n .get(session, since) as AgentRow | undefined;\n if (!row) return undefined;\n ctx.db\n .prepare('UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?')\n .run(hostAgentId, session, row.name);\n return byHostAgentId(ctx, session, 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 ctx.db\n .prepare(\n \"UPDATE agents SET status = 'review', note = ?, updated_at = ? WHERE session = ? AND name = ?\",\n )\n .run(STOPPED_NOTE, nowIso(ctx), session, agent.name);\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 AgentKind,\n closeAgent,\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 {\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 { byHostAgentId, pairSubagent, stopSubagent } 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 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) => mergeSessions(this.ctx, fromId, intoId),\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) => dropSession(this.ctx, id),\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 readonly agents = {\n get: (session: string, name: string) => getAgent(this.ctx, session, name),\n start: (session: string, input: StartAgentInput) => startAgent(this.ctx, session, input),\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 dropAgent(this.ctx, session, name, reason),\n close: (session: string, name: string, event: Omit<LogEventInput, 'agent'>) =>\n closeAgent(this.ctx, session, name, event),\n promote: (session: string, name: string, input: PromoteAgentInput) =>\n promoteAgent(this.ctx, session, name, input),\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: (session: string, hostAgentId: string) =>\n pairSubagent(this.ctx, session, hostAgentId),\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 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 { 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 carnet.agents.drop(session, name, `committed ${commit}`);\n clearTableOf(carnet, session, name);\n return `✅ ${name} committed ${commit}, closed`;\n }\n case 'dropped':\n carnet.agents.drop(session, name, note);\n clearTableOf(carnet, session, name);\n return `${name} dropped, closed`;\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 if (next === 'running') clearTableOf(carnet, session, name);\n else if (step !== 'answered') {\n // Tested is optional and keeps the agent on test: only the commit is left.\n const left = step === 'tested' ? 'commit' : next;\n carnet.table.set(session, { text: `${name} ${step}, ${left} next`, status: next });\n }\n return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;\n }\n }\n}\n"],"mappings":";;;;;;AASA,SAAgB,O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