@rucher/carnet 0.2.0-beta.1 → 0.2.0-beta.3
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.
- package/README.md +2 -2
- package/dist/{carnet--axAq8FF.d.mts → carnet-Du3xigg-.d.mts} +80 -36
- package/dist/carnet-Du3xigg-.d.mts.map +1 -0
- package/dist/index.d.mts +59 -35
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +46 -190
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +2 -3
- package/dist/mcp.d.mts.map +1 -1
- package/dist/mcp.mjs +82 -132
- package/dist/mcp.mjs.map +1 -1
- package/dist/{resume-D2FFakCl.mjs → steps-U_Ge5YFh.mjs} +871 -429
- package/dist/steps-U_Ge5YFh.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/carnet--axAq8FF.d.mts.map +0 -1
- package/dist/resume-D2FFakCl.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"resume-D2FFakCl.mjs","names":[],"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/hosts/claude-code.ts","../src/hosts/host.ts","../src/group/registry.ts","../src/group/locate.ts","../src/notes.ts","../src/memory.ts","../src/sessions.ts","../src/merge.ts","../src/purge.ts","../src/status/render.ts","../src/table.ts","../src/status/view.ts","../src/subagents.ts","../src/carnet.ts","../src/resume.ts"],"sourcesContent":["import type { DatabaseSync } from 'node:sqlite';\n\nexport interface Ctx {\n db: DatabaseSync;\n now: () => Date;\n}\n\nexport function nowIso(ctx: Ctx): string {\n return ctx.now().toISOString();\n}\n","export type CarnetErrorCode =\n | 'NO_GROUP'\n | 'GROUP_AMBIGUOUS'\n | 'GROUP_EXISTS'\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 | 'AGENT_EXISTS'\n | 'AGENT_NOT_FOUND'\n | 'INVALID_STATUS'\n | 'INVALID_EVENT_TYPE'\n | 'TABLE_STATUS_WITH_MAIN_WORKING';\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 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] 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}\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 }: ReadEventsOptions,\n): CarnetEvent[] {\n const filter = agentOnly ? \"AND type NOT LIKE 'session.%'\" : '';\n const rows = ctx.db\n .prepare(\n `SELECT * FROM (SELECT * FROM events WHERE session = ? ${filter} ORDER BY id DESC LIMIT ?) ORDER BY id ASC`,\n )\n .all(session, 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 'commit',\n 'branch',\n 'closed',\n] as const;\n\nexport type AgentStatus = (typeof AGENT_STATUSES)[number];\n\nexport const USER_ACTION_STATUSES = [\n 'discussing',\n 'answer',\n 'review',\n 'apply',\n 'test',\n 'commit',\n 'branch',\n] 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 commit: '✅',\n branch: '🌿',\n};\n\nexport const MAIN_WORKING_EMOJI = '⚙️';\n\nexport const LEGEND =\n '⚙️ main working · 💬 discussing · ❓ answer · 👀 review · 📥 apply · 🧪 test · ✅ commit · 🌿 branch · ⏳ running';\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 } from './events.ts';\nimport { type AgentStatus, isAgentStatus } from './status/model.ts';\nimport { sanitizeNote } from './status/note.ts';\n\nexport interface Agent {\n session: string;\n name: string;\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 baseCommit?: string | undefined;\n worktree?: string | undefined;\n}\n\nexport interface UpdateAgentInput {\n status: AgentStatus;\n note?: string | undefined;\n reportPath?: string | 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 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 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\nfunction 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\nexport function startAgent(ctx: Ctx, session: string, input: StartAgentInput): Agent {\n const name = sanitizeNote(input.name);\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, task, status, base_commit, worktree, started_at, updated_at)\n VALUES (?, ?, ?, 'running', ?, ?, ?, ?)`,\n )\n .run(session, name, input.task, input.baseCommit ?? null, input.worktree ?? null, at, at);\n logEvent(ctx, session, { type: 'started', agent: name, note: input.task });\n return requireAgent(ctx, session, name);\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 const note = input.note === undefined ? null : sanitizeNote(input.note);\n if (current.pendingStatus) publishPending(ctx, session, name);\n ctx.db\n .prepare(\n \"UPDATE agents SET note = COALESCE(?, CASE WHEN status = 'running' AND ? <> 'running' THEN NULL ELSE note END), status = ?, report_path = COALESCE(?, report_path), updated_at = ? WHERE session = ? AND name = ?\",\n )\n .run(note, input.status, input.status, input.reportPath ?? null, nowIso(ctx), session, name);\n return requireAgent(ctx, session, name);\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: AgentStatus = input.hasQuestions ? 'answer' : 'review';\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\nexport function dropAgent(ctx: Ctx, session: string, name: string, reason?: string): Agent {\n requireAgent(ctx, session, name);\n ctx.db\n .prepare(\n \"UPDATE agents SET status = 'closed', queue_order = NULL, updated_at = ? WHERE session = ? AND name = ?\",\n )\n .run(nowIso(ctx), session, name);\n logEvent(ctx, session, { type: 'dropped', agent: name, note: reason });\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\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];\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 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 {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport type { Group } from '../group/locate.ts';\nimport type {\n ContextFile,\n ContextFileResult,\n Host,\n HostPromptPayload,\n HostSessionEndPayload,\n HostToolPayload,\n HostSessionPayload,\n HostSubagentPayload,\n LaunchOptions,\n} from './host.ts';\n\nconst TRANSCRIPT_TAIL_BYTES = 256 * 1024;\nconst TITLE_PATTERN = /\"type\":\"custom-title\",\"customTitle\":(\"(?:[^\"\\\\]|\\\\.)*\")/g;\nconst FORK_NAME_PATTERN = /You are fork `([^`]+)`/;\n\nexport const REPOS_START = '<!-- rucher:repos start -->';\nexport const REPOS_END = '<!-- rucher:repos end -->';\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\nexport function transcriptTitle(path: string): 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, TRANSCRIPT_TAIL_BYTES);\n const buffer = Buffer.alloc(length);\n readSync(descriptor, buffer, 0, length, size - length);\n const matches = [...buffer.toString('utf8').matchAll(TITLE_PATTERN)];\n const last = matches.at(-1)?.[1];\n return last === undefined ? undefined : (JSON.parse(last) as string);\n } catch {\n return undefined;\n } finally {\n if (descriptor !== undefined) closeSync(descriptor);\n }\n}\n\nexport function reposBlock(group: Group): string {\n const repos = group.repos.length\n ? group.repos.map((repo) => `- \\`${basename(repo)}\\`: ${repo}`).join('\\n')\n : '- (none yet: `rucher group add <path>`)';\n return `${REPOS_START}\\n## Repos\\n\\n${repos}\\n${REPOS_END}`;\n}\n\nexport function replaceReposBlock(content: string, group: Group): string | null {\n const start = content.indexOf(REPOS_START);\n const end = content.indexOf(REPOS_END);\n if (start === -1 || end === -1 || end < start) return null;\n return content.slice(0, start) + reposBlock(group) + content.slice(end + REPOS_END.length);\n}\n\nexport function groupInstructions(group: Group): string {\n return `# ${group.name}\n\nMeta directory of the ${group.name} group: context only, the repos live at their own paths below and are reachable through \\`.claude/settings.json\\`. Start Claude Code sessions here.\n\n${reposBlock(group)}\n\n## Multi-agent work\n\nUse the rucher tools (Carnet) for agent statuses and the journal, and the rucher skill for the workflow.\n\n## Shared instructions\n\n(what every session of this group should know)\n`;\n}\n\nexport function groupSettings(group: Group): string {\n return `${JSON.stringify({ permissions: { additionalDirectories: group.repos } }, null, 2)}\\n`;\n}\n\ninterface Settings {\n permissions?: { additionalDirectories?: string[] } & Record<string, unknown>;\n [key: string]: unknown;\n}\n\nconst instructionsFile: ContextFile = {\n path: 'CLAUDE.md',\n sync(group): ContextFileResult {\n const path = join(group.root, 'CLAUDE.md');\n if (!existsSync(path)) {\n writeFileSync(path, groupInstructions(group));\n return 'written';\n }\n const content = readFileSync(path, 'utf8');\n const next = replaceReposBlock(content, group);\n if (next === null) return 'no-markers';\n if (next === content) return 'unchanged';\n writeFileSync(path, next);\n return 'updated';\n },\n};\n\nconst settingsFile: ContextFile = {\n path: '.claude/settings.json',\n sync(group, mode): ContextFileResult {\n const path = join(group.root, '.claude', 'settings.json');\n if (!existsSync(path)) {\n if (group.repos.length === 0) return 'unchanged';\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, groupSettings(group));\n return 'written';\n }\n const settings = JSON.parse(readFileSync(path, 'utf8')) as Settings;\n const current = settings.permissions?.additionalDirectories ?? [];\n const next =\n mode === 'exact'\n ? group.repos\n : [...current, ...group.repos.filter((repo) => !current.includes(repo))];\n if (next.length === current.length && next.every((repo, index) => repo === current[index])) {\n return 'unchanged';\n }\n settings.permissions = { ...settings.permissions, additionalDirectories: next };\n writeFileSync(path, `${JSON.stringify(settings, null, 2)}\\n`);\n return 'updated';\n },\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.passthrough ?? []),\n ];\n}\n\nconst RENDERING_SOURCES = new Set(['startup', 'clear', 'compact', 'fork']);\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 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 return {\n session_id: data.session_id as string,\n cwd,\n tool_name: toolName,\n agent_id: text(data, 'agent_id'),\n path: touchedPath(toolName, data.tool_input, cwd),\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 root = env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');\n const project = join(root, 'projects', 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 renameInstruction(name) {\n return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;\n },\n contextFiles: [settingsFile, instructionsFile],\n};\n","import { CarnetError } from '../errors.ts';\nimport type { Group } from '../group/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 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 path?: 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}\n\nexport interface ContextFile {\n path: string;\n sync(group: Group, mode: 'merge' | 'exact'): ContextFileResult;\n}\n\nexport type ContextFileResult = 'written' | 'updated' | 'unchanged' | 'no-markers';\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 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 contextFiles: readonly ContextFile[];\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 { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface GroupReference {\n name: string;\n path: string;\n}\n\ninterface RegistryFile {\n groups: GroupReference[];\n}\n\nexport function rucherHome(env: NodeJS.ProcessEnv = process.env): string {\n return env.RUCHER_HOME ?? join(homedir(), '.rucher');\n}\n\nfunction registryPath(env?: NodeJS.ProcessEnv): string {\n return join(rucherHome(env), 'groups.json');\n}\n\nexport function readRegistry(env?: NodeJS.ProcessEnv): GroupReference[] {\n const file = registryPath(env);\n if (!existsSync(file)) return [];\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RegistryFile>;\n return parsed.groups ?? [];\n}\n\nfunction writeRegistry(groups: GroupReference[], env?: NodeJS.ProcessEnv): GroupReference[] {\n groups.sort(\n (left, right) => left.name.localeCompare(right.name) || left.path.localeCompare(right.path),\n );\n mkdirSync(rucherHome(env), { recursive: true });\n writeFileSync(\n registryPath(env),\n `${JSON.stringify({ groups } satisfies RegistryFile, null, 2)}\\n`,\n );\n return groups;\n}\n\nexport function registerGroup(\n reference: GroupReference,\n env?: NodeJS.ProcessEnv,\n): GroupReference[] {\n return writeRegistry(\n [...readRegistry(env).filter((group) => group.path !== reference.path), reference],\n env,\n );\n}\n\nexport function unregisterGroups(paths: string[], env?: NodeJS.ProcessEnv): GroupReference[] {\n return writeRegistry(\n readRegistry(env).filter((group) => !paths.includes(group.path)),\n env,\n );\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { DatabaseSync } from 'node:sqlite';\nimport { basename, dirname, join, relative, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { allHosts, DEFAULT_HOST } from '../hosts/host.ts';\nimport { readRegistry } from './registry.ts';\n\nexport const GROUP_DIRECTORY = '.rucher';\nexport const REPORTS_DIRECTORY = 'reports';\nexport const GROUP_FILE = 'group.json';\nexport const DB_FILE = 'carnet.db';\n\nexport interface Group {\n root: string;\n name: string;\n repos: string[];\n hosts: string[];\n dbPath: string;\n}\n\nexport interface GroupFile {\n name: string;\n repos: string[];\n hosts?: string[] | undefined;\n}\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\nexport function repoNameFor(group: Group, path: string | undefined): string | null {\n if (!path) return null;\n const repo = group.repos.find((repo) => isInside(repo, resolve(path)));\n return repo ? basename(repo) : null;\n}\n\nexport function repoPathFor(group: Group, path: string | undefined | null): string | null {\n if (!path) return null;\n const absolutePath = resolve(path);\n const repo = group.repos.find((candidate) => isInside(candidate, absolutePath));\n if (!repo) return null;\n const relativePath = relative(repo, absolutePath);\n return relativePath ? join(basename(repo), relativePath) : basename(repo);\n}\n\nexport function findGroupRoot(from: string): string | null {\n let directory = resolve(from);\n for (;;) {\n // The registry home is also named .rucher, only group.json marks a group.\n if (isGroupRoot(directory)) return directory;\n const parent = dirname(directory);\n if (parent === directory) return null;\n directory = parent;\n }\n}\n\nexport function reportsDirectoryOf(group: Group): string {\n return join(group.root, GROUP_DIRECTORY, REPORTS_DIRECTORY);\n}\n\nexport function reportPathFor(group: Group, agentName: string): string {\n return join(reportsDirectoryOf(group), `${agentName}.md`);\n}\n\nexport function isGroupRoot(directory: string): boolean {\n return existsSync(join(directory, GROUP_DIRECTORY, GROUP_FILE));\n}\n\nexport function loadGroup(root: string): Group {\n const file = JSON.parse(\n readFileSync(join(root, GROUP_DIRECTORY, GROUP_FILE), 'utf8'),\n ) as GroupFile;\n return {\n root,\n name: file.name,\n repos: (file.repos ?? []).map((repo) => resolve(root, repo)),\n hosts: file.hosts?.length ? file.hosts : [DEFAULT_HOST],\n dbPath: join(root, GROUP_DIRECTORY, DB_FILE),\n };\n}\n\nexport interface LocateOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n sessionId?: string | undefined;\n}\n\nfunction groupsWithRepo(paths: readonly string[], env?: NodeJS.ProcessEnv): Group[] {\n const groups: Group[] = [];\n for (const reference of readRegistry(env)) {\n if (!isGroupRoot(reference.path)) continue;\n const group = loadGroup(reference.path);\n if (paths.some((path) => group.repos.some((repo) => isInside(repo, path)))) groups.push(group);\n }\n return groups;\n}\n\nfunction knowsSession(group: Group, sessionId: string): boolean {\n if (!existsSync(group.dbPath)) return false;\n const db = new DatabaseSync(group.dbPath, { readOnly: true });\n try {\n return db.prepare('SELECT 1 FROM sessions WHERE id = ?').get(sessionId) !== undefined;\n } catch {\n return false;\n } finally {\n db.close();\n }\n}\n\nexport function pinnedGroup(env: NodeJS.ProcessEnv): Group | null {\n const root = env.RUCHER_GROUP_ROOT;\n return root && isGroupRoot(resolve(root)) ? loadGroup(resolve(root)) : null;\n}\n\nexport function locateGroup({\n cwd = process.cwd(),\n env = process.env,\n sessionId,\n}: LocateOptions = {}): Group {\n const pinned = pinnedGroup(env);\n if (pinned) return pinned;\n const projectDirectories = allHosts()\n .map((host) => host.projectDirectory(env))\n .filter((directory): directory is string => directory !== undefined);\n const candidates = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];\n for (const directory of candidates) {\n const root = findGroupRoot(directory);\n if (root) return loadGroup(root);\n }\n const matches = groupsWithRepo(candidates, env);\n const [only] = matches;\n if (matches.length === 1 && only) return only;\n if (matches.length > 1) {\n const owners = sessionId ? matches.filter((group) => knowsSession(group, sessionId)) : [];\n const [owner] = owners;\n if (owners.length === 1 && owner) return owner;\n throw new CarnetError(\n 'GROUP_AMBIGUOUS',\n `${cwd} is in repos of several groups (${matches.map((group) => group.name).join(', ')}): launch with \"rucher new\" or \"rucher resume\", or start from the group's meta directory`,\n );\n }\n throw new CarnetError(\n 'NO_GROUP',\n `No Rucher group for ${cwd}: run \"rucher init\" in a meta directory, or \"rucher group add <this repo>\" there`,\n );\n}\n\nexport function ambiguousGroupContext(reason: string): string {\n return `Rucher could not tell which group this session belongs to, so Carnet records nothing for it: ${reason}.`;\n}\n","import { basename } from 'node:path';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport type { Group } from './group/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 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_by: number | null;\n}\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 groupRepoNames(group: Group): string[] {\n return group.repos.map((repo) => basename(repo));\n}\n\nfunction cleanRepos(group: Group, repos: string[] | undefined): string[] {\n const known = groupRepoNames(group);\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(', ')} (group 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 ctx.db.prepare('INSERT OR IGNORE INTO active_days (day) VALUES (?)').run(localDay(ctx.now()));\n}\n\nfunction activeDays(ctx: Ctx): string[] {\n const rows = ctx.db.prepare('SELECT day FROM active_days ORDER BY day').all() as unknown as {\n day: string;\n }[];\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, note: number): string[] {\n const rows = ctx.db\n .prepare('SELECT repo FROM note_repos WHERE note = ? ORDER BY repo')\n .all(note) 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.id,\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_by,\n };\n}\n\nexport function getNote(ctx: Ctx, id: number): Note | null {\n const row = ctx.db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as NoteRow | undefined;\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\nfunction citationsOf(ctx: Ctx, note: number): NoteCitation[] {\n return ctx.db\n .prepare(\n 'SELECT id, note, session, agent, why, at FROM note_citations WHERE note = ? ORDER BY at',\n )\n .all(note) 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('SELECT * FROM notes WHERE kind = ? AND dropped_at IS NULL')\n .all(kind) as unknown as NoteRow[];\n return rows.map((row) => toNote(ctx, row));\n}\n\nexport function addNote(ctx: Ctx, group: Group, input: AddNoteInput): AddNoteResult {\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(group, 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 result = ctx.db\n .prepare(\n 'INSERT INTO notes (kind, text, session, agent, similar_notes, created_at) VALUES (?, ?, ?, ?, ?, ?)',\n )\n .run(\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, id), 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[] = [];\n const parameters: string[] = [];\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 where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';\n const rows = ctx.db\n .prepare(`SELECT * FROM notes ${where}`)\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 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, input.replacedBy ?? null, 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(id, input.session ?? null, input.agent ?? null, why, nowIso(ctx));\n return ctx.db\n .prepare('SELECT id, note, session, agent, why, at FROM note_citations WHERE id = ?')\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('SELECT 1 FROM notes WHERE id = ? AND dropped_at IS NULL');\n return (JSON.parse(json) as number[]).filter((id) => active.get(id) !== undefined);\n}\n\nexport function sessionNoteActivity(ctx: Ctx, session: string): NoteActivity[] {\n const added = ctx.db\n .prepare('SELECT id, kind, text, similar_notes, created_at FROM notes WHERE session = ?')\n .all(session) as unknown as Pick<\n NoteRow,\n 'id' | 'kind' | 'text' | 'similar_notes' | 'created_at'\n >[];\n const cited = ctx.db\n .prepare(\n `SELECT note_citations.note, notes.kind, note_citations.why, note_citations.at\n FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE note_citations.session = ?`,\n )\n .all(session) as unknown as { note: number; kind: NoteKind; why: string; at: string }[];\n const dropped = ctx.db\n .prepare(\n 'SELECT id, kind, dropped_reason, replaced_by, dropped_at FROM notes WHERE dropped_session = ?',\n )\n .all(session) as unknown as Pick<\n NoteRow,\n 'id' | 'kind' | 'dropped_reason' | 'replaced_by' | 'dropped_at'\n >[];\n const activity: NoteActivity[] = [\n ...added.map((row) => ({\n activity: 'added' as const,\n note: row.id,\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.id,\n kind: row.kind,\n text: row.dropped_reason ?? '',\n similarNotes: [],\n replacedBy: row.replaced_by,\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 { Group } from './group/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 groupTitle(group: Group): string {\n return `Rucher memory of the ${group.name} group`;\n}\n\nexport function sessionStartMemory(\n ctx: Ctx,\n group: Group,\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: groupTitle(group), notes }, options.maxCharacters);\n}\n\nexport function sessionMemory(\n ctx: Ctx,\n group: Group,\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: groupTitle(group), 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 { logEvent } from './events.ts';\nimport { type Group, repoNameFor } from './group/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 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 createdAt: string;\n lastActiveAt: string;\n endedAt: string | null;\n}\n\ninterface SessionRow {\n id: 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 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}\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, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,\n parent_id, prompt_version, created_at, last_active_at, ended_at`;\n\nfunction toSession(row: SessionRow): Session {\n return {\n id: row.id,\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 createdAt: row.created_at,\n lastActiveAt: row.last_active_at,\n endedAt: row.ended_at,\n };\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(ctx: Ctx, id: string, cwd?: string, group?: Group): 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, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?)',\n )\n .run(id, cwd ?? null, group ? repoNameFor(group, 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, name, kind, status, cwd, repo, host, last_title,\n created_at, last_active_at)\n VALUES (?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n input.id,\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 group: Group,\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 = repoNameFor(group, payload.cwd);\n const existing = getSession(ctx, payload.session_id);\n if (!existing) {\n ctx.db\n .prepare(\n `INSERT INTO sessions (id, cwd, repo, host, host_pid, hooked_at, created_at, last_active_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(payload.session_id, payload.cwd ?? null, repo, host, hostPid, at, at, at);\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 payload.cwd ?? existing.cwd,\n 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[] = [];\n if (!options.includeTemp) conditions.push(\"kind != 'temp'\");\n if (!options.includeArchived) conditions.push(\"status != 'archived'\");\n const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';\n const rows = ctx.db\n .prepare(`SELECT ${COLUMNS} FROM sessions ${where} ORDER BY last_active_at DESC`)\n .all() 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 status != 'archived' ORDER BY last_active_at DESC LIMIT 1`,\n )\n .get() as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport function sessionByName(ctx: Ctx, name: string): Session | undefined {\n const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE name = ?`).get(name) as\n | SessionRow\n | 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(`SELECT ${COLUMNS} FROM sessions WHERE id LIKE ? ORDER BY last_active_at DESC`)\n .all(`${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 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 kind = 'temp' AND status = 'idle' AND last_active_at < ?\n ORDER BY last_active_at ASC`,\n )\n .all(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","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, 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 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(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 { EMOJI, LEGEND, MAIN_WORKING_EMOJI } from './model.ts';\nimport type { StatusLine, StatusView } from './view.ts';\n\nexport const MAIN_WORKING_SUFFIX = '(main working, not ready)';\n\nexport function renderTableLine(item: TableItem): string {\n if (item.mainWorking) return `${MAIN_WORKING_EMOJI} ${item.text} ${MAIN_WORKING_SUFFIX}`;\n return `${EMOJI[item.status ?? 'discussing']} ${item.text}`;\n}\n\nexport function renderAgentLine(line: StatusLine): string {\n return line.note ? `${line.emoji} ${line.name} — ${line.note}` : `${line.emoji} ${line.name}`;\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 if (view.table) {\n out.push('On the table', ` ${renderTableLine(view.table)}`, '');\n }\n out.push('Waiting on you');\n if (view.waiting.length === 0) out.push(' nothing');\n view.waiting.forEach((line, index) => {\n out.push(` ${index + 1}. ${renderAgentLine(line)}`);\n });\n out.push('', 'Running');\n if (view.running.length === 0) out.push(' nothing');\n for (const line of view.running) out.push(` ${renderAgentLine(line)}`);\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), '', 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 mainWorking: boolean;\n updatedAt: string;\n}\n\nexport interface SetTableInput {\n text: string;\n mainWorking: boolean;\n status?: UserActionStatus | undefined;\n}\n\ninterface TableRow {\n session: string;\n text: string;\n status: UserActionStatus | null;\n main_working: number;\n updated_at: string;\n}\n\nfunction toItem(row: TableRow): TableItem {\n return {\n session: row.session,\n text: row.text,\n status: row.status,\n mainWorking: row.main_working === 1,\n updatedAt: row.updated_at,\n };\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.mainWorking && input.status) {\n throw new CarnetError(\n 'TABLE_STATUS_WITH_MAIN_WORKING',\n 'A user-action status cannot be set while main is working',\n );\n }\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, main_working, updated_at) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(session) DO UPDATE SET text = excluded.text, status = excluded.status,\n main_working = excluded.main_working, updated_at = excluded.updated_at`,\n )\n .run(\n session,\n sanitizeNote(input.text),\n input.status ?? null,\n input.mainWorking ? 1 : 0,\n nowIso(ctx),\n );\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 Agent, listAgents } from '../agents.ts';\nimport type { Ctx } from '../context.ts';\nimport { type NoteActivity, sessionNoteActivity } from '../notes.ts';\nimport type { Session } from '../sessions.ts';\nimport { getTable, type TableItem } from '../table.ts';\nimport { type AgentStatus, EMOJI, isUserActionStatus } from './model.ts';\n\nexport interface StatusLine {\n name: string;\n status: AgentStatus;\n emoji: string;\n note: string | null;\n}\n\nexport interface StatusView {\n time: string;\n sessionName: string | null;\n table: TableItem | null;\n waiting: StatusLine[];\n running: StatusLine[];\n notes: NoteActivity[];\n}\n\nconst BUCKET: Partial<Record<AgentStatus, number>> = { answer: 0, review: 1 };\n\nfunction bucketOf(status: AgentStatus): number {\n return BUCKET[status] ?? 2;\n}\n\nfunction compareWaiting(left: Agent, right: Agent): number {\n if (left.queueOrder !== null || right.queueOrder !== null) {\n if (left.queueOrder === null) return 1;\n if (right.queueOrder === null) return -1;\n return left.queueOrder - right.queueOrder;\n }\n return (\n bucketOf(left.status) - bucketOf(right.status) || left.startedAt.localeCompare(right.startedAt)\n );\n}\n\nfunction toLine(agent: Agent): StatusLine {\n return {\n name: agent.name,\n status: agent.status,\n emoji: agent.status === 'closed' ? '' : EMOJI[agent.status],\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(ctx: Ctx, session: Session): StatusView {\n const agents = listAgents(ctx, session.id);\n const waiting = agents\n .filter((agent) => isUserActionStatus(agent.status))\n .sort(compareWaiting)\n .map(toLine);\n const running = agents.filter((agent) => agent.status === 'running').map(toLine);\n return {\n time: formatClock(ctx.now()),\n sessionName: session.name,\n table: getTable(ctx, session.id) ?? null,\n waiting,\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\nfunction 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 type { DatabaseSync } from 'node:sqlite';\nimport {\n dropAgent,\n finishAgent,\n type FinishAgentInput,\n getAgent,\n listAgents,\n type ListAgentsOptions,\n reorderQueue,\n startAgent,\n type StartAgentInput,\n updateAgent,\n type UpdateAgentInput,\n} from './agents.ts';\nimport type { Ctx } from './context.ts';\nimport { openDatabase } from './db/open.ts';\nimport { logEvent, type LogEventInput, readEvents } from './events.ts';\nimport { type Group, type LocateOptions, locateGroup } from './group/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 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 } from './status/view.ts';\nimport { pairSubagent, stopSubagent } from './subagents.ts';\nimport { clearTable, getTable, setTable, type SetTableInput } from './table.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 readonly group: Group,\n db: DatabaseSync,\n options: CarnetOptions = {},\n ) {\n this.db = db;\n this.ctx = { db, now: options.now ?? (() => new Date()) };\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) => ensureSession(this.ctx, id, cwd, this.group),\n upsertFromHook: (payload: HookSessionPayload, env?: HookEnv) =>\n upsertFromHook(this.ctx, this.group, 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 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 list: (session: string, options?: ListAgentsOptions) => listAgents(this.ctx, session, options),\n reorderQueue: (session: string, names: string[]) => reorderQueue(this.ctx, session, names),\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 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 events = {\n log: (session: string, input: LogEventInput) => logEvent(this.ctx, session, input),\n read: (session: string, limit?: number, agentOnly?: boolean) =>\n readEvents(this.ctx, { session, limit, agentOnly }),\n };\n\n readonly notes = {\n add: (input: AddNoteInput) => addNote(this.ctx, this.group, 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.group, session, options),\n ofSession: (session: Session, options?: MemoryOptions) =>\n sessionMemory(this.ctx, this.group, 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) => buildStatusView(this.ctx, session),\n render: (session: Session, options?: RenderOptions) =>\n renderStatus(buildStatusView(this.ctx, session), 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 LocateOptions, CarnetOptions {\n dbPath?: string;\n}\n\nexport function openCarnet(options: OpenCarnetOptions = {}): Carnet {\n return openGroupCarnet(locateGroup(options), options);\n}\n\nexport function openGroupCarnet(group: Group, options: OpenCarnetOptions = {}): Carnet {\n return new Carnet(group, openDatabase(options.dbPath ?? group.dbPath), 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 > maxChar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