@rucher/carnet 0.2.0-beta.4 → 0.2.0-beta.5
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-DptiZiz8.d.mts → carnet-v6FelCYZ.d.mts} +46 -48
- package/dist/carnet-v6FelCYZ.d.mts.map +1 -0
- package/dist/index.d.mts +24 -25
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +20 -20
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +2 -2
- package/dist/mcp.mjs +15 -15
- package/dist/mcp.mjs.map +1 -1
- package/dist/{steps-BeTGxQk4.mjs → steps-CzJOqsBI.mjs} +247 -258
- package/dist/steps-CzJOqsBI.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/carnet-DptiZiz8.d.mts.map +0 -1
- package/dist/steps-BeTGxQk4.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"steps-BeTGxQk4.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/paths.ts","../src/group/group.ts","../src/sessions.ts","../src/prompt/core-rules.ts","../src/prompt/prompt.ts","../src/workspace-files.ts","../src/hosts/claude-code.ts","../src/hosts/host.ts","../src/group-rows.ts","../src/group/locate.ts","../src/notes.ts","../src/memory.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","../src/steps.ts"],"sourcesContent":["import type { DatabaseSync } from 'node:sqlite';\n\nexport interface Ctx {\n db: DatabaseSync;\n now: () => Date;\n // null: sessions without a group, which hold no notes.\n group: string | null;\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 | 'GROUP_NOT_FOUND'\n | 'GROUP_NAME_INVALID'\n | 'REPO_NOT_FOUND'\n | 'REPO_NAME_TAKEN'\n | 'NOTE_NOT_FOUND'\n | 'INVALID_NOTE'\n | 'UNKNOWN_HOST'\n | 'NO_SESSION'\n | 'SESSION_NOT_FOUND'\n | 'SESSION_AMBIGUOUS'\n | 'SESSION_NAME_TAKEN'\n | 'SESSION_NAME_REQUIRED'\n | 'SESSION_RUNNING'\n | 'SESSION_KIND_INVALID'\n | 'SESSION_MERGE_INVALID'\n | 'SESSION_EXISTS'\n | 'SESSION_MOVE_INVALID'\n | 'SESSION_CWD_MISSING'\n | 'WORKSPACE_FILE_CONFLICT'\n | 'GROUP_INSTRUCTIONS_CONFLICT'\n | 'AGENT_EXISTS'\n | 'AGENT_NOT_FOUND'\n | 'INVALID_STATUS'\n | 'INVALID_EVENT_TYPE'\n | 'COMMIT_REQUIRED'\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 at DESC, id DESC LIMIT ?) ORDER BY at, id`,\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 // Rows from before v9 get the placeholder group '' until the move to one database assigns them.\n `\nCREATE TABLE sessions_new (\n id TEXT PRIMARY KEY,\n group_name TEXT,\n name TEXT,\n purpose TEXT,\n kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),\n status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),\n cwd TEXT,\n repo TEXT,\n host TEXT NOT NULL DEFAULT 'claude-code',\n host_pid INTEGER,\n hooked_at TEXT,\n last_title TEXT,\n parent_id TEXT REFERENCES sessions(id),\n prompt_version TEXT,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL,\n ended_at TEXT,\n CHECK (kind = 'temp' OR name IS NOT NULL)\n);\nINSERT INTO sessions_new (id, group_name, name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)\nSELECT id, '', name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at\nFROM sessions;\nDROP TABLE sessions;\nALTER TABLE sessions_new RENAME TO sessions;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\nCREATE INDEX sessions_group_status ON sessions(group_name, status, last_active_at);\nCREATE UNIQUE INDEX sessions_group_name ON sessions(group_name, name)\n WHERE group_name IS NOT NULL AND name IS NOT NULL;\nCREATE UNIQUE INDEX sessions_free_name ON sessions(name)\n WHERE group_name IS NULL AND name IS NOT NULL;\n\nALTER TABLE notes ADD COLUMN group_name TEXT NOT NULL DEFAULT '';\nALTER TABLE notes ADD COLUMN number INTEGER NOT NULL DEFAULT 0;\nUPDATE notes SET number = id;\nDROP INDEX notes_active;\nCREATE INDEX notes_active ON notes(group_name, dropped_at, kind);\nCREATE UNIQUE INDEX notes_group_number ON notes(group_name, number);\n\nCREATE TABLE active_days_new (\n group_name TEXT NOT NULL,\n day TEXT NOT NULL,\n PRIMARY KEY (group_name, day)\n);\nINSERT INTO active_days_new (group_name, day) SELECT '', day FROM active_days;\nDROP TABLE active_days;\nALTER TABLE active_days_new RENAME TO active_days;\n`,\n];\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 { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport type { Group } from './group/group.ts';\n\nexport interface RucherPaths {\n config: string;\n data: string;\n state: string;\n run: string;\n}\n\n// The XDG spec says relative values must be ignored.\nfunction xdgDirectory(value: string | undefined, fallback: string): string {\n return value && isAbsolute(value) ? value : fallback;\n}\n\nexport function rucherPaths(env: NodeJS.ProcessEnv = process.env): RucherPaths {\n if (env.RUCHER_HOME) {\n const home = env.RUCHER_HOME;\n return {\n config: join(home, 'config'),\n data: join(home, 'data'),\n state: join(home, 'state'),\n run: join(home, 'run'),\n };\n }\n const home = env.HOME || homedir();\n const state = join(xdgDirectory(env.XDG_STATE_HOME, join(home, '.local', 'state')), 'rucher');\n return {\n config: join(xdgDirectory(env.XDG_CONFIG_HOME, join(home, '.config')), 'rucher'),\n data: join(xdgDirectory(env.XDG_DATA_HOME, join(home, '.local', 'share')), 'rucher'),\n state,\n run:\n env.XDG_RUNTIME_DIR && isAbsolute(env.XDG_RUNTIME_DIR)\n ? join(env.XDG_RUNTIME_DIR, 'rucher')\n : join(state, 'run'),\n };\n}\n\nexport function databasePath(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).data, 'carnet.db');\n}\n\nexport function groupsDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).config, 'groups');\n}\n\nexport function groupSource(name: string, env?: NodeJS.ProcessEnv): string {\n return join(groupsDirectory(env), name);\n}\n\nexport function defaultWorkspace(name: string, env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).data, 'workspaces', name);\n}\n\nexport function promptsDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).state, 'prompts');\n}\n\nexport function corePromptPath(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).config, 'prompt.md');\n}\n\nexport function reportsDirectory(group: Group): string {\n return join(group.workspace, 'reports');\n}\n\nexport function reportPath(group: Group, agentName: string): string {\n return join(reportsDirectory(group), `${agentName}.md`);\n}\n","import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, join, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { DEFAULT_HOST } from '../hosts/host.ts';\nimport { defaultWorkspace, groupsDirectory, groupSource } from '../paths.ts';\n\nexport interface GroupRepo {\n path: string;\n name: string;\n}\n\nexport interface Group {\n name: string;\n source: string;\n workspace: string;\n repos: GroupRepo[];\n backends: Record<string, { settings?: Record<string, unknown> }>;\n}\n\nexport interface GroupFile {\n name?: string | undefined;\n workspace?: string | undefined;\n repos?: { path: string; name?: string | undefined }[] | undefined;\n backends?: Group['backends'] | undefined;\n}\n\nexport const GROUP_FILE = 'group.json';\nexport const INSTRUCTIONS_FILE = 'CLAUDE.md';\nexport const AGENTS_FILE = 'AGENTS.md';\nconst GROUP_NAME = /^[a-z0-9-]+$/;\n\nexport function isGroupName(name: string): boolean {\n return GROUP_NAME.test(name);\n}\n\nfunction requireGroupName(name: string): void {\n if (!isGroupName(name)) {\n throw new CarnetError(\n 'GROUP_NAME_INVALID',\n `Invalid group name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`,\n );\n }\n}\n\nexport function expandHome(path: string, env: NodeJS.ProcessEnv = process.env): string {\n if (path !== '~' && !path.startsWith('~/')) return path;\n return join(env.HOME || homedir(), path.slice(1));\n}\n\nfunction groupFilePath(name: string, env?: NodeJS.ProcessEnv): string {\n return join(groupSource(name, env), GROUP_FILE);\n}\n\nexport function groupExists(name: string, env?: NodeJS.ProcessEnv): boolean {\n return isGroupName(name) && existsSync(groupFilePath(name, env));\n}\n\nfunction readGroupFile(name: string, env?: NodeJS.ProcessEnv): GroupFile {\n if (!groupExists(name, env)) {\n throw new CarnetError('GROUP_NOT_FOUND', `No group named ${name}: see \"rucher groups list\"`);\n }\n return JSON.parse(readFileSync(groupFilePath(name, env), 'utf8')) as GroupFile;\n}\n\nfunction writeGroupFile(name: string, file: GroupFile, env?: NodeJS.ProcessEnv): void {\n writeFileSync(groupFilePath(name, env), `${JSON.stringify(file, null, 2)}\\n`);\n}\n\nexport function loadGroup(name: string, env: NodeJS.ProcessEnv = process.env): Group {\n const file = readGroupFile(name, env);\n return {\n name,\n source: groupSource(name, env),\n workspace: resolve(expandHome(file.workspace ?? defaultWorkspace(name, env), env)),\n repos: (file.repos ?? []).map((repo) => {\n const path = resolve(expandHome(repo.path, env));\n return { path, name: repo.name ?? basename(path) };\n }),\n backends: file.backends ?? {},\n };\n}\n\nexport function listGroups(env: NodeJS.ProcessEnv = process.env): Group[] {\n const directory = groupsDirectory(env);\n if (!existsSync(directory)) return [];\n return readdirSync(directory)\n .filter((name) => groupExists(name, env))\n .sort()\n .map((name) => loadGroup(name, env));\n}\n\nexport function groupHosts(group: Group): string[] {\n const hosts = Object.keys(group.backends);\n return hosts.length ? hosts : [DEFAULT_HOST];\n}\n\nfunction checkedRepo(path: string, env?: NodeJS.ProcessEnv): string {\n const absolute = resolve(expandHome(path, env));\n if (!existsSync(absolute))\n throw new CarnetError('REPO_NOT_FOUND', `Repo path does not exist: ${absolute}`);\n return absolute;\n}\n\n// Notes reference repos by name, so two repos cannot share one.\nfunction requireDistinctNames(group: string, repos: readonly GroupRepo[]): void {\n const names = repos.map((repo) => repo.name);\n const shared = names.find((name, index) => names.indexOf(name) !== index);\n if (shared) {\n throw new CarnetError(\n 'REPO_NAME_TAKEN',\n `${group} would have two repos named ${shared}: give them distinct names`,\n );\n }\n}\n\nexport interface CreateGroupOptions {\n repos?: readonly string[] | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nexport function createGroup(name: string, options: CreateGroupOptions = {}): Group {\n const { env } = options;\n requireGroupName(name);\n if (groupExists(name, env)) throw new CarnetError('GROUP_EXISTS', `Group ${name} already exists`);\n const paths = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))];\n const repos = paths.map((path) => ({ path, name: basename(path) }));\n requireDistinctNames(name, repos);\n const source = groupSource(name, env);\n const workspace = defaultWorkspace(name, env);\n mkdirSync(source, { recursive: true });\n mkdirSync(workspace, { recursive: true });\n writeGroupFile(name, { name, workspace, repos, backends: {} }, env);\n const instructions = join(source, INSTRUCTIONS_FILE);\n if (!existsSync(instructions)) writeFileSync(instructions, '');\n return loadGroup(name, env);\n}\n\nexport function sourceInstructions(group: Group): string {\n const agents = existsSync(join(group.source, AGENTS_FILE));\n if (agents && existsSync(join(group.source, INSTRUCTIONS_FILE))) {\n throw new CarnetError(\n 'GROUP_INSTRUCTIONS_CONFLICT',\n `Group ${group.name} has both ${AGENTS_FILE} and ${INSTRUCTIONS_FILE} in ${group.source}: remove ${INSTRUCTIONS_FILE}`,\n );\n }\n return agents ? AGENTS_FILE : INSTRUCTIONS_FILE;\n}\n\nexport function addGroupRepo(name: string, repo: string, env?: NodeJS.ProcessEnv): Group {\n const file = readGroupFile(name, env);\n const group = loadGroup(name, env);\n const path = checkedRepo(repo, env);\n if (group.repos.some((existing) => existing.path === path)) return group;\n requireDistinctNames(name, [...group.repos, { path, name: basename(path) }]);\n writeGroupFile(\n name,\n { ...file, repos: [...(file.repos ?? []), { path, name: basename(path) }] },\n env,\n );\n return loadGroup(name, env);\n}\n\nexport function removeGroupRepo(name: string, repo: string, env?: NodeJS.ProcessEnv): Group {\n const file = readGroupFile(name, env);\n const group = loadGroup(name, env);\n const path = resolve(expandHome(repo, env));\n const index = group.repos.findIndex(\n (existing) => existing.path === path || existing.name === repo,\n );\n if (index === -1) throw new CarnetError('REPO_NOT_FOUND', `${repo} is not a repo of ${name}`);\n writeGroupFile(\n name,\n { ...file, repos: (file.repos ?? []).filter((_, position) => position !== index) },\n env,\n );\n return loadGroup(name, env);\n}\n\n// The workspace stays where it is: Claude Code files transcripts by cwd.\nexport function renameGroup(from: string, to: string, env?: NodeJS.ProcessEnv): Group {\n const file = readGroupFile(from, env);\n requireGroupName(to);\n if (existsSync(groupSource(to, env)))\n throw new CarnetError('GROUP_EXISTS', `Group ${to} already exists`);\n const workspace = loadGroup(from, env).workspace;\n renameSync(groupSource(from, env), groupSource(to, env));\n writeGroupFile(to, { ...file, name: to, workspace }, env);\n return loadGroup(to, env);\n}\n\nexport interface DropGroupOptions {\n purge?: boolean | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nexport function dropGroup(name: string, options: DropGroupOptions = {}): Group {\n const group = loadGroup(name, options.env);\n rmSync(group.source, { recursive: true, force: true });\n if (options.purge) rmSync(group.workspace, { recursive: true, force: true });\n return group;\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 groupName: string | null;\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 group_name: string | null;\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, group_name, 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 groupName: row.group_name,\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 | null): 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, group_name, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?, ?)',\n )\n .run(id, ctx.group, 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, group_name, name, kind, status, cwd, repo, host, last_title,\n created_at, last_active_at)\n VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n input.id,\n ctx.group,\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 | null,\n payload: HookSessionPayload,\n env: HookEnv = {},\n): Session {\n const at = nowIso(ctx);\n const host = env.host ?? DEFAULT_HOST;\n const hostPid = env.processId ?? null;\n const repo = group ? repoNameFor(group, payload.cwd) : null;\n const existing = getSession(ctx, payload.session_id);\n if (!existing) {\n ctx.db\n .prepare(\n `INSERT INTO sessions (id, group_name, cwd, repo, host, host_pid, hooked_at, created_at,\n last_active_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(payload.session_id, ctx.group, 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 // Claude Code keeps transcripts under the launch cwd; the hook's cwd follows every `cd`.\n existing.cwd ?? payload.cwd ?? null,\n existing.cwd ? existing.repo : (repo ?? existing.repo),\n host,\n hostPid ?? existing.hostPid,\n payload.session_id,\n );\n }\n return adoptTitle(ctx, payload.session_id, payload.session_title);\n}\n\nexport function touchSession(ctx: Ctx, id: string): void {\n ctx.db.prepare('UPDATE sessions SET last_active_at = ? WHERE id = ?').run(nowIso(ctx), id);\n}\n\nexport function nameSession(ctx: Ctx, id: string, name: string, purpose?: string): Session {\n requireSession(ctx, id);\n try {\n ctx.db\n .prepare(\n `UPDATE sessions\n SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,\n kind = 'active'\n WHERE id = ?`,\n )\n .run(name, purpose ?? null, nowIso(ctx), id);\n } catch (error) {\n if (error instanceof Error && error.message.includes('UNIQUE')) {\n throw new CarnetError('SESSION_NAME_TAKEN', `A session named \"${name}\" already exists`);\n }\n throw error;\n }\n return requireSession(ctx, id);\n}\n\nexport function listSessions(ctx: Ctx, options: ListSessionsOptions = {}): Session[] {\n const conditions: string[] = ['group_name IS ?'];\n if (!options.includeTemp) conditions.push(\"kind != 'temp'\");\n if (!options.includeArchived) conditions.push(\"status != 'archived'\");\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(' AND ')} ORDER BY last_active_at DESC`,\n )\n .all(ctx.group) 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 group_name IS ? AND status != 'archived'\n ORDER BY last_active_at DESC LIMIT 1`,\n )\n .get(ctx.group) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport function sessionByName(ctx: Ctx, name: string): Session | undefined {\n const row = ctx.db\n .prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND name = ?`)\n .get(ctx.group, name) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport const MINIMUM_ID_PREFIX = 4;\n\nexport function shortId(id: string): string {\n return id.slice(0, 8);\n}\n\nexport function findSession(ctx: Ctx, reference: string): Session {\n const byName = sessionByName(ctx, reference);\n if (byName) return byName;\n const byId = getSession(ctx, reference);\n if (byId) return byId;\n const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);\n if (isIdPrefix && reference.length >= MINIMUM_ID_PREFIX) {\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND id LIKE ?\n ORDER BY last_active_at DESC`,\n )\n .all(ctx.group, `${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 group_name IS ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?\n ORDER BY last_active_at ASC`,\n )\n .all(ctx.group, before) as unknown as SessionRow[];\n return rows.map(toSession);\n}\n\nexport function resetDeadSessions(ctx: Ctx, isAlive: (processId: number) => boolean): Session[] {\n const running = (\n ctx.db\n .prepare(`SELECT ${COLUMNS} FROM sessions WHERE status = 'running'`)\n .all() as unknown as SessionRow[]\n ).map(toSession);\n const dead = running.filter((session) => session.hostPid === null || !isAlive(session.hostPid));\n return dead.map((session) => endSession(ctx, session.id));\n}\n","// Generated from docs/workflow.md by pnpm run build. Do not edit.\nexport const CORE_RULES = `- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the \"On the table\" line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When a fork finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that fork's report, even when answering about something else.\n- Forks never commit, push, stash or record notes. A fork writes its report to a file, ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.`;\n","import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Group } from '../group/group.ts';\nimport { corePromptPath, promptsDirectory } from '../paths.ts';\nimport { shortId, type SessionKind } from '../sessions.ts';\nimport { CORE_RULES } from './core-rules.ts';\n\nexport const PROMPT_FILE = 'prompt.md';\n\nexport interface PromptSession {\n id: string;\n name: string | null;\n kind: SessionKind;\n}\n\nexport interface AssembledPrompt {\n text: string;\n version: string;\n}\n\nexport interface AppendPromptFile {\n path: string;\n version: string;\n}\n\nfunction readIfPresent(path: string): string | undefined {\n if (!existsSync(path)) return undefined;\n const content = readFileSync(path, 'utf8').trim();\n return content || undefined;\n}\n\nexport function baseRules(env: NodeJS.ProcessEnv = process.env): string {\n return readIfPresent(corePromptPath(env)) ?? CORE_RULES;\n}\n\nexport function groupRules(group: Group | null): string | undefined {\n return group ? readIfPresent(join(group.source, PROMPT_FILE)) : undefined;\n}\n\nexport function rulesText(group: Group | null, env: NodeJS.ProcessEnv = process.env): string {\n const extra = groupRules(group);\n const base = `Rucher rules, always follow them:\\n${baseRules(env)}`;\n return extra && group ? `${base}\\n\\nRules of the ${group.name} group:\\n${extra}` : base;\n}\n\n// The identity block is left out so that renaming a session doesn't read as a rules change.\nexport function rulesVersion(group: Group | null, env: NodeJS.ProcessEnv = process.env): string {\n return createHash('sha256').update(rulesText(group, env)).digest('hex').slice(0, 12);\n}\n\nexport function assemblePrompt(\n group: Group | null,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AssembledPrompt {\n const label = session.name ?? shortId(session.id);\n const identity = group\n ? `This is the Rucher session ${label} (${session.kind}) of the ${group.name} group.`\n : `This is the Rucher session ${label} (${session.kind}), outside any group.`;\n return { text: `${rulesText(group, env)}\\n\\n${identity}\\n`, version: rulesVersion(group, env) };\n}\n\nexport function appendPromptFile(\n group: Group | null,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AppendPromptFile {\n const { text, version } = assemblePrompt(group, session, env);\n const directory = promptsDirectory(env);\n mkdirSync(directory, { recursive: true });\n const path = join(directory, `${session.id}.md`);\n writeFileSync(path, text);\n return { path, version };\n}\n\nexport function compactReminder(group: Group | null, env: NodeJS.ProcessEnv = process.env): string {\n return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${rulesText(group, env)}`;\n}\n\nexport function outsideRucherContext(\n group: Group | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return `This session was started without rucher, so its system prompt does not hold the Rucher rules. ${rulesText(group, env)}`;\n}\n\nexport const OUTSIDE_RUCHER_NOTICE =\n 'rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)';\n\nexport const RULES_UPDATED_NOTICE =\n 'rucher: rules updated, will apply after the next compaction or in a new session';\n\nexport const SUBAGENT_RULES =\n 'Rucher rules for sub-agents: never commit, push or stash. When your task asks for a report, write it to the file it names. If your prompt names you as a Carnet agent, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.';\n","import { lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CarnetError } from './errors.ts';\n\nexport const GENERATED_MARKER = 'generated by rucher, do not edit';\n\nfunction refuse(path: string): never {\n throw new CarnetError(\n 'WORKSPACE_FILE_CONFLICT',\n `${path} was not written by rucher: move its content to the group source, then remove it`,\n );\n}\n\nfunction entry(path: string): ReturnType<typeof lstatSync> | undefined {\n try {\n return lstatSync(path);\n } catch {\n return undefined;\n }\n}\n\n// Claude Code strips HTML block comments from instruction files, so the marker costs no tokens.\nexport const MARKDOWN_MARKER = `<!-- ${GENERATED_MARKER} -->\\n`;\n\nexport function markdownCopy(content: string): string {\n return `${MARKDOWN_MARKER}${content}`;\n}\n\nfunction isMarkdownCopy(path: string): boolean {\n const current = entry(path);\n if (!current?.isFile()) return false;\n return readFileSync(path, 'utf8').startsWith(MARKDOWN_MARKER);\n}\n\n// Copies whose source is gone, at the top level of the directory; hand-written files stay.\nexport function removeStaleCopies(directory: string, keep: ReadonlySet<string>): string[] {\n const removed: string[] = [];\n if (!entry(directory)) return removed;\n for (const name of readdirSync(directory)) {\n if (!name.endsWith('.md') || keep.has(name)) continue;\n const path = join(directory, name);\n if (!isMarkdownCopy(path)) continue;\n rmSync(path, { force: true });\n removed.push(name);\n }\n return removed;\n}\n\nexport function writeGenerated(path: string, content: string): boolean {\n const current = entry(path);\n if (current?.isSymbolicLink()) rmSync(path, { force: true });\n else if (current) {\n const existing = readFileSync(path, 'utf8');\n if (existing === content) return false;\n if (!existing.includes(GENERATED_MARKER)) refuse(path);\n }\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content);\n return true;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function mergeSettings(\n base: Record<string, unknown>,\n extra: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(extra)) {\n const current = merged[key];\n if (Array.isArray(current) && Array.isArray(value)) {\n const seen = new Set(current.map((item) => JSON.stringify(item)));\n merged[key] = [...current, ...value.filter((item) => !seen.has(JSON.stringify(item)))];\n } else if (isObject(current) && isObject(value)) {\n merged[key] = mergeSettings(current, value);\n } else {\n merged[key] = value;\n }\n }\n return merged;\n}\n","import {\n closeSync,\n existsSync,\n fstatSync,\n openSync,\n readdirSync,\n readFileSync,\n readSync,\n rmdirSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { AGENTS_FILE, type Group, INSTRUCTIONS_FILE, sourceInstructions } from '../group/group.ts';\nimport { PROMPT_FILE } from '../prompt/prompt.ts';\nimport {\n GENERATED_MARKER,\n markdownCopy,\n mergeSettings,\n removeStaleCopies,\n writeGenerated,\n} from '../workspace-files.ts';\nimport type {\n Host,\n HostRender,\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\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\nconst SETTINGS_FILE = join('.claude', 'settings.json');\nconst BACKEND_NOTES = 'backends/claude.md';\n\n// Instruction files are copied, not linked: an @ import inside a link resolves next to its target,\n// outside the workspace, where Claude Code skips it without approval.\nexport function instructionFiles(group: Group): string[] {\n if (!existsSync(group.source)) return [];\n return readdirSync(group.source, { withFileTypes: true })\n .filter((item) => item.isFile() && item.name.endsWith('.md') && item.name !== PROMPT_FILE)\n .map((item) => item.name)\n .sort();\n}\n\nfunction repoAgentsImports(group: Group): string[] {\n return group.repos\n .filter(\n (repo) =>\n existsSync(join(repo.path, AGENTS_FILE)) &&\n !existsSync(join(repo.path, INSTRUCTIONS_FILE)) &&\n !existsSync(join(repo.path, '.claude', INSTRUCTIONS_FILE)),\n )\n .map((repo) => `@${join(repo.path, AGENTS_FILE)}`);\n}\n\n// Claude Code has no reliable native AGENTS.md loading, so a generated CLAUDE.md imports it.\nfunction workspaceCopies(group: Group): Map<string, string> {\n const agents = sourceInstructions(group) === AGENTS_FILE;\n const read = (name: string) => readFileSync(join(group.source, name), 'utf8');\n const copies = new Map(instructionFiles(group).map((name) => [name, markdownCopy(read(name))]));\n if (!agents) return copies;\n const imports = [`@${AGENTS_FILE}`];\n if (existsSync(join(group.source, BACKEND_NOTES))) {\n copies.set(BACKEND_NOTES, markdownCopy(read(BACKEND_NOTES)));\n imports.push(`@${BACKEND_NOTES}`);\n }\n imports.push(...repoAgentsImports(group));\n copies.set(INSTRUCTIONS_FILE, markdownCopy(`${imports.join('\\n')}\\n`));\n return copies;\n}\n\nexport function groupSettings(group: Group): Record<string, unknown> {\n return mergeSettings(\n {\n '//': GENERATED_MARKER,\n permissions: {\n additionalDirectories: group.repos.map((repo) => repo.path),\n // The copies are rewritten on every render: instructions are edited in the source.\n deny: [...workspaceCopies(group).keys()].sort().map((name) => `Edit(/${name})`),\n },\n },\n group.backends['claude-code']?.settings ?? {},\n );\n}\n\nfunction removeStaleBackendNotes(group: Group, keep: ReadonlySet<string>): string[] {\n const directory = join(group.workspace, dirname(BACKEND_NOTES));\n const removed = removeStaleCopies(\n directory,\n new Set(\n [...keep]\n .filter((name) => dirname(name) === dirname(BACKEND_NOTES))\n .map((name) => basename(name)),\n ),\n );\n if (existsSync(directory) && readdirSync(directory).length === 0) rmdirSync(directory);\n return removed.map((name) => join(dirname(BACKEND_NOTES), name));\n}\n\nfunction renderClaudeWorkspace(group: Group): HostRender {\n const rendered: HostRender = { written: [], removed: [] };\n const copies = workspaceCopies(group);\n for (const [name, content] of [...copies].sort(([a], [b]) => a.localeCompare(b))) {\n if (writeGenerated(join(group.workspace, name), content)) rendered.written.push(name);\n }\n const names = new Set(copies.keys());\n rendered.removed.push(...removeStaleCopies(group.workspace, names));\n rendered.removed.push(...removeStaleBackendNotes(group, names));\n const settings = `${JSON.stringify(groupSettings(group), null, 2)}\\n`;\n if (writeGenerated(join(group.workspace, SETTINGS_FILE), settings)) {\n rendered.written.push(SETTINGS_FILE);\n }\n return rendered;\n}\n\nfunction launchArguments(options: LaunchOptions = {}): string[] {\n return [\n ...(options.name ? ['--name', options.name] : []),\n ...(options.appendPromptFile ? ['--append-system-prompt-file', options.appendPromptFile] : []),\n ...(options.directories ?? []).flatMap((directory) => ['--add-dir', directory]),\n ...(options.passthrough ?? []),\n ];\n}\n\nconst RENDERING_SOURCES = new Set(['startup', 'clear', 'compact', 'fork']);\n\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 renderWorkspace: renderClaudeWorkspace,\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 directories?: readonly string[] | undefined;\n}\n\nexport interface HostRender {\n written: string[];\n removed: string[];\n}\n\nexport interface Host {\n id: string;\n displayName: string;\n processId(env: NodeJS.ProcessEnv): number | null;\n sessionIdFromEnvironment(env: NodeJS.ProcessEnv): string | undefined;\n projectDirectory(env: NodeJS.ProcessEnv): string | undefined;\n parseSessionPayload(json: string): HostSessionPayload;\n 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 renderWorkspace(group: Group): HostRender;\n}\n\nexport const DEFAULT_HOST = 'claude-code';\n\nconst HOSTS: Readonly<Record<string, Host>> = { [claudeCode.id]: claudeCode };\n\nexport function allHosts(): Host[] {\n return Object.values(HOSTS);\n}\n\nexport function hostById(id: string): Host {\n const host = HOSTS[id];\n if (!host) {\n throw new CarnetError(\n 'UNKNOWN_HOST',\n `Unknown host \"${id}\" (available: ${Object.keys(HOSTS).join(', ')})`,\n );\n }\n return host;\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nfunction inTransaction<T>(db: DatabaseSync, run: () => T): T {\n db.exec('BEGIN');\n try {\n const result = run();\n db.exec('COMMIT');\n return result;\n } catch (error) {\n db.exec('ROLLBACK');\n throw error;\n }\n}\n\n// undefined: no such session; null: a session without a group.\nexport function sessionGroupName(db: DatabaseSync, sessionId: string): string | null | undefined {\n const row = db.prepare('SELECT group_name FROM sessions WHERE id = ?').get(sessionId) as\n | { group_name: string | null }\n | undefined;\n return row ? row.group_name : undefined;\n}\n\nexport function renameGroupRows(db: DatabaseSync, from: string, to: string): void {\n inTransaction(db, () => {\n for (const table of ['sessions', 'notes', 'active_days']) {\n db.prepare(`UPDATE ${table} SET group_name = ? WHERE group_name = ?`).run(to, from);\n }\n });\n}\n\nexport function archiveGroupSessions(db: DatabaseSync, name: string, at: string): number {\n return inTransaction(db, () => {\n db.prepare(\n `UPDATE agents SET status = 'closed', updated_at = ?\n WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE group_name = ?)`,\n ).run(at, name);\n return Number(\n db\n .prepare(\n `UPDATE sessions SET status = 'archived', last_active_at = ?\n WHERE group_name = ? AND status != 'archived'`,\n )\n .run(at, name).changes,\n );\n });\n}\n\nexport function deleteGroupNotes(db: DatabaseSync, name: string): number {\n return Number(db.prepare('DELETE FROM notes WHERE group_name = ?').run(name).changes);\n}\n\nexport function groupSessionCounts(db: DatabaseSync): Map<string, number> {\n const rows = db\n .prepare(\n `SELECT group_name, COUNT(*) AS count FROM sessions\n WHERE group_name IS NOT NULL AND status != 'archived' GROUP BY group_name`,\n )\n .all() as { group_name: string; count: number }[];\n return new Map(rows.map((row) => [row.group_name, Number(row.count)]));\n}\n","import type { DatabaseSync } from 'node:sqlite';\nimport { join, relative, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { allHosts } from '../hosts/host.ts';\nimport { sessionGroupName } from '../group-rows.ts';\nimport { type Group, type GroupRepo, groupExists, listGroups, loadGroup } from './group.ts';\n\nexport type { Group, GroupRepo } from './group.ts';\n\nexport function isInside(directory: string, path: string): boolean {\n const relativePath = relative(directory, path);\n return (\n relativePath === '' ||\n (!relativePath.startsWith('..') && !resolve(relativePath).startsWith(relativePath))\n );\n}\n\nfunction repoOf(group: Group | null, path: string): GroupRepo | undefined {\n const absolutePath = resolve(path);\n return group?.repos.find((repo) => isInside(repo.path, absolutePath));\n}\n\nexport function repoNameFor(group: Group | null, path: string | undefined): string | null {\n return path ? (repoOf(group, path)?.name ?? null) : null;\n}\n\nexport function repoPathFor(group: Group | null, path: string | undefined | null): string | null {\n if (!path) return null;\n const repo = repoOf(group, path);\n if (!repo) return null;\n const relativePath = relative(repo.path, resolve(path));\n return relativePath ? join(repo.name, relativePath) : repo.name;\n}\n\nexport type GroupOrigin = 'session' | 'option' | 'env' | 'workspace' | 'repo' | 'none';\n\nexport interface GroupResolution {\n group: Group | null;\n origin: GroupOrigin;\n repo?: GroupRepo | undefined;\n}\n\nexport interface ResolveGroupOptions {\n db?: DatabaseSync | undefined;\n sessionId?: string | undefined;\n group?: string | undefined;\n cwd?: string | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nfunction namedGroup(name: string, env: NodeJS.ProcessEnv): Group {\n if (!groupExists(name, env)) {\n throw new CarnetError('GROUP_NOT_FOUND', `No group named ${name}: see \"rucher groups list\"`);\n }\n return loadGroup(name, env);\n}\n\nfunction byWorkspace(groups: readonly Group[], directories: readonly string[]): Group | undefined {\n return groups.find((group) =>\n directories.some((directory) => isInside(group.workspace, directory)),\n );\n}\n\nfunction byRepo(\n groups: readonly Group[],\n directory: string,\n): { group: Group; repo: GroupRepo } | undefined {\n let best: { group: Group; repo: GroupRepo }[] = [];\n for (const group of groups) {\n for (const repo of group.repos) {\n if (!isInside(repo.path, directory)) continue;\n const length = best[0]?.repo.path.length ?? -1;\n if (repo.path.length > length) best = [{ group, repo }];\n else if (repo.path.length === length) best.push({ group, repo });\n }\n }\n const names = [...new Set(best.map((match) => match.group.name))];\n if (names.length > 1) {\n throw new CarnetError(\n 'GROUP_AMBIGUOUS',\n `${directory} is in repos of several groups (${names.join(', ')}): pass --group`,\n );\n }\n return best[0];\n}\n\nexport function resolveGroup({\n db,\n sessionId,\n group,\n cwd = process.cwd(),\n env = process.env,\n}: ResolveGroupOptions = {}): GroupResolution {\n if (db && sessionId) {\n const name = sessionGroupName(db, sessionId);\n if (name === null) return { group: null, origin: 'session' };\n if (name !== undefined && groupExists(name, env)) {\n return { group: loadGroup(name, env), origin: 'session' };\n }\n }\n if (group) return { group: namedGroup(group, env), origin: 'option' };\n if (env.RUCHER_GROUP) return { group: namedGroup(env.RUCHER_GROUP, env), origin: 'env' };\n const projectDirectories = allHosts()\n .map((host) => host.projectDirectory(env))\n .filter((directory): directory is string => directory !== undefined);\n const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];\n const groups = listGroups(env);\n const workspaceGroup = byWorkspace(groups, directories);\n if (workspaceGroup) return { group: workspaceGroup, origin: 'workspace' };\n for (const directory of directories) {\n const match = byRepo(groups, directory);\n if (match) return { group: match.group, origin: 'repo', repo: match.repo };\n }\n return { group: null, origin: 'none' };\n}\n\nexport function groupLabel(group: Group | null): string {\n return group?.name ?? 'no group';\n}\n\nexport function requireGroup(group: Group | null): Group {\n if (group) return group;\n throw new CarnetError(\n 'NO_GROUP',\n 'No Rucher group here: pass --group, or run this from a repo or workspace of a group',\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 { 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 number: number;\n kind: NoteKind;\n text: string;\n session: string | null;\n agent: string | null;\n similar_notes: string | null;\n created_at: string;\n dropped_at: string | null;\n dropped_reason: string | null;\n dropped_session: string | null;\n replaced_number: number | null;\n}\n\n// Notes are shown and referenced by their number in the group; the id stays internal.\nconst NOTE_COLUMNS = `notes.id, notes.number, notes.kind, notes.text, notes.session, notes.agent,\n notes.similar_notes, notes.created_at, notes.dropped_at, notes.dropped_reason,\n notes.dropped_session,\n (SELECT replaced.number FROM notes AS replaced WHERE replaced.id = notes.replaced_by)\n AS replaced_number`;\n\nconst MARKDOWN = /\\*\\*|__|\\[[^\\]]*\\]\\([^)]*\\)|^#{1,6}\\s|^[-*+]\\s/;\n\nfunction cleanText(value: string, label: string): string {\n const text = value.trim().replace(/[ \\t]+/g, ' ');\n if (!text) throw new CarnetError('INVALID_NOTE', `${label} is empty`);\n if (text.length >= NOTE_TEXT_LIMIT) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `${label} must stay under ${NOTE_TEXT_LIMIT} characters (${text.length})`,\n );\n }\n if (/[\\r\\n]/.test(text)) throw new CarnetError('INVALID_NOTE', `${label} must be one line`);\n if (text.includes('`')) throw new CarnetError('INVALID_NOTE', `${label} must not use backticks`);\n if (MARKDOWN.test(text)) throw new CarnetError('INVALID_NOTE', `${label} must not use markdown`);\n return text;\n}\n\nexport function groupRepoNames(group: Group): string[] {\n return group.repos.map((repo) => repo.name);\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 if (ctx.group === null) return;\n ctx.db\n .prepare('INSERT OR IGNORE INTO active_days (group_name, day) VALUES (?, ?)')\n .run(ctx.group, localDay(ctx.now()));\n}\n\nfunction activeDays(ctx: Ctx): string[] {\n const rows = ctx.db\n .prepare('SELECT day FROM active_days WHERE group_name IS ? ORDER BY day')\n .all(ctx.group) as unknown as { day: string }[];\n return rows.map((row) => row.day);\n}\n\nfunction activeDaysSince(days: string[], at: string): number {\n const since = localDay(new Date(at));\n return days.filter((day) => day > since).length;\n}\n\nfunction reposOf(ctx: Ctx, noteId: number): string[] {\n const rows = ctx.db\n .prepare('SELECT repo FROM note_repos WHERE note = ? ORDER BY repo')\n .all(noteId) as unknown as { repo: string }[];\n return rows.map((row) => row.repo);\n}\n\nfunction toNote(ctx: Ctx, row: NoteRow): Note {\n return {\n id: row.number,\n kind: row.kind,\n text: row.text,\n repos: reposOf(ctx, row.id),\n session: row.session,\n agent: row.agent,\n similarNotes: row.similar_notes ? (JSON.parse(row.similar_notes) as number[]) : [],\n createdAt: row.created_at,\n droppedAt: row.dropped_at,\n droppedReason: row.dropped_reason,\n droppedSession: row.dropped_session,\n replacedBy: row.replaced_number,\n };\n}\n\nfunction noteRow(ctx: Ctx, number: number): NoteRow | undefined {\n return ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND number = ?`)\n .get(ctx.group, number) as NoteRow | undefined;\n}\n\nfunction noteId(ctx: Ctx, number: number): number {\n const row = noteRow(ctx, number);\n if (!row) throw new CarnetError('NOTE_NOT_FOUND', `Unknown note #${number}`);\n return row.id;\n}\n\nexport function getNote(ctx: Ctx, id: number): Note | null {\n const row = noteRow(ctx, id);\n return row ? toNote(ctx, row) : null;\n}\n\nexport function requireNote(ctx: Ctx, id: number): Note {\n const note = getNote(ctx, id);\n if (!note) throw new CarnetError('NOTE_NOT_FOUND', `Unknown note #${id}`);\n return note;\n}\n\nfunction requireActiveNote(ctx: Ctx, id: number): Note {\n const note = requireNote(ctx, id);\n if (note.droppedAt) throw new CarnetError('INVALID_NOTE', `Note #${id} is dropped`);\n return note;\n}\n\nconst CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citations.session,\n note_citations.agent, note_citations.why, note_citations.at`;\n\nfunction citationsOf(ctx: Ctx, number: number): NoteCitation[] {\n return ctx.db\n .prepare(\n `SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE notes.group_name IS ? AND notes.number = ? ORDER BY note_citations.at`,\n )\n .all(ctx.group, number) as unknown as NoteCitation[];\n}\n\n// Several citations in one session count once: the latest stands for that session.\nfunction weightOf(citations: NoteCitation[], days: string[], halfLifeDays: number): number {\n const latest = new Map<string, string>();\n for (const citation of citations) {\n const key = citation.session ?? `citation-${citation.id}`;\n const previous = latest.get(key);\n if (!previous || citation.at > previous) latest.set(key, citation.at);\n }\n let weight = 0;\n for (const at of latest.values()) weight += 0.5 ** (activeDaysSince(days, at) / halfLifeDays);\n return weight;\n}\n\nfunction weigh(ctx: Ctx, note: Note, days: string[], halfLifeDays: number): WeightedNote {\n const citations = citationsOf(ctx, note.id);\n return {\n ...note,\n weight: weightOf(citations, days, halfLifeDays),\n citationCount: citations.length,\n };\n}\n\nexport function compareNotes(first: WeightedNote, second: WeightedNote): number {\n const kind = NOTE_KINDS.indexOf(first.kind) - NOTE_KINDS.indexOf(second.kind);\n if (kind !== 0) return kind;\n if (first.weight !== second.weight) return second.weight - first.weight;\n return second.id - first.id;\n}\n\nfunction activeNotesOfKind(ctx: Ctx, kind: NoteKind): Note[] {\n const rows = ctx.db\n .prepare(\n `SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND kind = ? AND dropped_at IS NULL`,\n )\n .all(ctx.group, kind) as unknown as NoteRow[];\n return rows.map((row) => toNote(ctx, row));\n}\n\nexport function addNote(ctx: Ctx, group: Group | null, input: AddNoteInput): AddNoteResult {\n if (group === null || ctx.group === null) {\n throw new CarnetError('NO_GROUP', 'Notes belong to a group: this session has none');\n }\n if (!isNoteKind(input.kind)) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `Invalid note kind \"${input.kind}\" (use ${NOTE_KINDS.join(', ')})`,\n );\n }\n const kind = input.kind;\n const text = cleanText(input.text, 'Note text');\n const repos = cleanRepos(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 next = ctx.db\n .prepare('SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE group_name = ?')\n .get(ctx.group) as { number: number };\n const result = ctx.db\n .prepare(\n `INSERT INTO notes (group_name, number, kind, text, session, agent, similar_notes, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n ctx.group,\n next.number,\n kind,\n text,\n input.session ?? null,\n input.agent ?? null,\n similar.length ? JSON.stringify(similar.map((note) => note.id)) : null,\n nowIso(ctx),\n );\n const id = Number(result.lastInsertRowid);\n const addRepo = ctx.db.prepare('INSERT INTO note_repos (note, repo) VALUES (?, ?)');\n for (const repo of repos) addRepo.run(id, repo);\n ctx.db.exec('COMMIT');\n return { note: requireNote(ctx, next.number), similar };\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n\nexport function listNotes(ctx: Ctx, options: ListNotesOptions = {}): WeightedNote[] {\n if (options.kind !== undefined && !isNoteKind(options.kind)) {\n throw new CarnetError('INVALID_NOTE', `Invalid note kind \"${options.kind}\"`);\n }\n const conditions: string[] = ['group_name IS ?'];\n const parameters: (string | null)[] = [ctx.group];\n if (!options.includeDropped) conditions.push('dropped_at IS NULL');\n if (options.kind) {\n conditions.push('kind = ?');\n parameters.push(options.kind);\n }\n if (options.repo) {\n conditions.push('id IN (SELECT note FROM note_repos WHERE repo = ?)');\n parameters.push(options.repo);\n }\n if (options.general) conditions.push('id NOT IN (SELECT note FROM note_repos)');\n if (options.query) {\n conditions.push(\"LOWER(text) LIKE ? ESCAPE '\\\\'\");\n parameters.push(`%${options.query.toLowerCase().replace(/[\\\\%_]/g, '\\\\$&')}%`);\n }\n const rows = ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE ${conditions.join(' AND ')}`)\n .all(...parameters) as unknown as NoteRow[];\n const days = activeDays(ctx);\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n return rows.map((row) => weigh(ctx, toNote(ctx, row), days, halfLifeDays)).sort(compareNotes);\n}\n\nexport function noteDetail(\n ctx: Ctx,\n id: number,\n halfLifeDays = DEFAULT_HALF_LIFE_DAYS,\n): NoteDetail {\n const note = requireNote(ctx, id);\n const citations = citationsOf(ctx, id);\n return {\n ...note,\n weight: weightOf(citations, activeDays(ctx), halfLifeDays),\n citationCount: citations.length,\n citations,\n };\n}\n\nexport function staleNotes(ctx: Ctx, halfLifeDays = DEFAULT_HALF_LIFE_DAYS): WeightedNote[] {\n const days = activeDays(ctx);\n return listNotes(ctx, { halfLifeDays }).filter(\n (note) =>\n activeDaysSince(days, note.createdAt) > STALE_AFTER_ACTIVE_DAYS &&\n (note.citationCount === 0 || note.weight < STALE_WEIGHT),\n );\n}\n\nexport function dropNote(ctx: Ctx, id: number, input: DropNoteInput): Note {\n requireActiveNote(ctx, id);\n const reason = cleanText(input.reason, 'Drop reason');\n if (input.replacedBy !== undefined) {\n if (input.replacedBy === id) {\n throw new CarnetError('INVALID_NOTE', `Note #${id} cannot replace itself`);\n }\n requireActiveNote(ctx, input.replacedBy);\n }\n const replacedBy = input.replacedBy === undefined ? null : noteId(ctx, input.replacedBy);\n ctx.db\n .prepare(\n 'UPDATE notes SET dropped_at = ?, dropped_reason = ?, dropped_session = ?, replaced_by = ? WHERE id = ?',\n )\n .run(nowIso(ctx), reason, input.session ?? null, replacedBy, noteId(ctx, id));\n return requireNote(ctx, id);\n}\n\nexport function citeNote(ctx: Ctx, id: number, input: CiteNoteInput): NoteCitation {\n requireActiveNote(ctx, id);\n const why = cleanText(input.why, 'Citation reason');\n const result = ctx.db\n .prepare('INSERT INTO note_citations (note, session, agent, why, at) VALUES (?, ?, ?, ?, ?)')\n .run(noteId(ctx, id), input.session ?? null, input.agent ?? null, why, nowIso(ctx));\n return ctx.db\n .prepare(\n `SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE note_citations.id = ?`,\n )\n .get(Number(result.lastInsertRowid)) as unknown as NoteCitation;\n}\n\nexport type NoteActivityKind = 'added' | 'cited' | 'dropped';\n\nexport interface NoteActivity {\n activity: NoteActivityKind;\n note: number;\n kind: NoteKind;\n text: string;\n similarNotes: number[];\n replacedBy: number | null;\n at: string;\n}\n\nconst ACTIVITY_ORDER: Record<NoteActivityKind, number> = { dropped: 0, cited: 1, added: 2 };\n\nfunction activeIds(ctx: Ctx, json: string | null): number[] {\n if (!json) return [];\n const active = ctx.db.prepare(\n 'SELECT 1 FROM notes WHERE group_name IS ? AND number = ? AND dropped_at IS NULL',\n );\n return (JSON.parse(json) as number[]).filter(\n (number) => active.get(ctx.group, number) !== undefined,\n );\n}\n\nexport function sessionNoteActivity(ctx: Ctx, session: string): NoteActivity[] {\n const added = ctx.db\n .prepare(\n `SELECT number, kind, text, similar_notes, created_at FROM notes\n WHERE group_name IS ? AND session = ?`,\n )\n .all(ctx.group, session) as unknown as Pick<\n NoteRow,\n 'number' | 'kind' | 'text' | 'similar_notes' | 'created_at'\n >[];\n const cited = ctx.db\n .prepare(\n `SELECT notes.number AS note, notes.kind, note_citations.why, note_citations.at\n FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE notes.group_name IS ? AND note_citations.session = ?`,\n )\n .all(ctx.group, session) as unknown as {\n note: number;\n kind: NoteKind;\n why: string;\n at: string;\n }[];\n const dropped = ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND dropped_session = ?`)\n .all(ctx.group, session) as unknown as NoteRow[];\n const activity: NoteActivity[] = [\n ...added.map((row) => ({\n activity: 'added' as const,\n note: row.number,\n kind: row.kind,\n text: row.text,\n similarNotes: activeIds(ctx, row.similar_notes),\n replacedBy: null,\n at: row.created_at,\n })),\n ...cited.map((row) => ({\n activity: 'cited' as const,\n note: row.note,\n kind: row.kind,\n text: row.why,\n similarNotes: [],\n replacedBy: null,\n at: row.at,\n })),\n ...dropped.map((row) => ({\n activity: 'dropped' as const,\n note: row.number,\n kind: row.kind,\n text: row.dropped_reason ?? '',\n similarNotes: [],\n replacedBy: row.replaced_number,\n at: row.dropped_at ?? '',\n })),\n ];\n return activity.sort(\n (first, second) =>\n second.at.localeCompare(first.at) ||\n ACTIVITY_ORDER[first.activity] - ACTIVITY_ORDER[second.activity] ||\n second.note - first.note,\n );\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport type { 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 | null): string {\n return group ? `Rucher memory of the ${group.name} group` : 'Rucher memory';\n}\n\nexport function sessionStartMemory(\n ctx: Ctx,\n group: Group | null,\n session: { id: string; repo: string | null },\n options: MemoryOptions = {},\n): string | undefined {\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n const repos = session.repo ? [session.repo] : [];\n const notes = notesFor(ctx, repos, true, halfLifeDays);\n if (!notes.length) return undefined;\n for (const repo of repos) {\n if (notes.some((note) => note.repos.includes(repo))) recordRepo(ctx, session.id, repo);\n }\n return renderMemory({ title: groupTitle(group), notes }, options.maxCharacters);\n}\n\nexport function sessionMemory(\n ctx: Ctx,\n group: Group | null,\n session: { id: string },\n options: MemoryOptions = {},\n): string | undefined {\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n const notes = notesFor(ctx, injectedRepos(ctx, session.id), true, halfLifeDays);\n if (!notes.length) return undefined;\n return renderMemory({ title: 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 { 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 group_name IS ? AND id != ? AND last_active_at < ?\n AND NOT EXISTS (\n SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'\n )\n AND (\n status = 'archived'\n OR (kind = 'temp' AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id))\n )`;\n\nexport function purgeSessions(ctx: Ctx, keepId: string, days: number): string[] {\n const cutoff = new Date(ctx.now().getTime() - days * DAY_MILLISECONDS).toISOString();\n ctx.db.exec('BEGIN');\n try {\n const rows = ctx.db\n .prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`)\n .all(ctx.group, 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 // Omitted: false with a status, else the current value.\n mainWorking?: boolean | undefined;\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 const mainWorking =\n input.mainWorking ?? (input.status ? false : (getTable(ctx, session)?.mainWorking ?? false));\n if (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(session, sanitizeNote(input.text), input.status ?? null, mainWorking ? 1 : 0, nowIso(ctx));\n return getTable(ctx, session) as TableItem;\n}\n\nexport function clearTable(ctx: Ctx, session: string): void {\n ctx.db.prepare('DELETE FROM table_items WHERE session = ?').run(session);\n}\n","import { type 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 { mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport 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 { MEMORY_DB, openDatabase } from './db/open.ts';\nimport { databasePath } from './paths.ts';\nimport { logEvent, type LogEventInput, readEvents } from './events.ts';\nimport { type Group, type GroupResolution, requireGroup, resolveGroup } 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 db: DatabaseSync,\n readonly group: Group | null,\n options: CarnetOptions = {},\n ) {\n this.db = db;\n this.ctx = { db, now: options.now ?? (() => new Date()), group: group?.name ?? null };\n }\n\n requireGroup(): Group {\n return requireGroup(this.group);\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 ?? undefined),\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 CarnetOptions {\n group?: string | undefined;\n sessionId?: string | undefined;\n cwd?: string | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n dbPath?: string | undefined;\n}\n\nfunction openStore(options: OpenCarnetOptions): DatabaseSync {\n const path = options.dbPath ?? databasePath(options.env);\n if (path !== MEMORY_DB) mkdirSync(dirname(path), { recursive: true });\n return openDatabase(path);\n}\n\nexport function openCarnet(options: OpenCarnetOptions = {}): Carnet {\n return openResolvedCarnet(options).carnet;\n}\n\nexport interface ResolvedCarnet {\n carnet: Carnet;\n resolution: GroupResolution;\n}\n\nexport function openResolvedCarnet(options: OpenCarnetOptions = {}): ResolvedCarnet {\n const db = openStore(options);\n try {\n const resolution = resolveGroup({ ...options, db });\n return { carnet: new Carnet(db, resolution.group, options), resolution };\n } catch (error) {\n db.close();\n throw error;\n }\n}\n\nexport function openGroupCarnet(group: Group | null, options: OpenCarnetOptions = {}): Carnet {\n return new Carnet(openStore(options), group, options);\n}\n","import type { Carnet } from './carnet.ts';\nimport type { CarnetEvent } from './events.ts';\nimport type { Session } from './sessions.ts';\nimport { formatClock } from './status/view.ts';\n\nexport const RESUME_EVENTS = 20;\nexport const RESUME_MAX_CHARACTERS = 2000;\n\nexport interface ResumeContextOptions {\n events?: number;\n maxCharacters?: number;\n}\n\nexport function formatEventLine(event: CarnetEvent): string {\n return [\n formatClock(new Date(event.at)),\n event.type,\n event.agent,\n event.link ?? event.note,\n event.commit?.slice(0, 7),\n ]\n .filter(Boolean)\n .join(' ');\n}\n\nexport function sessionLabel(session: Session): string {\n const name = session.name ?? session.id;\n return session.purpose ? `${name} (${session.purpose})` : name;\n}\n\nexport function resumeContext(\n carnet: Carnet,\n session: Session,\n { events = RESUME_EVENTS, maxCharacters = RESUME_MAX_CHARACTERS }: ResumeContextOptions = {},\n): string {\n const head = `Rucher session ${sessionLabel(session)}, state when resumed:\\n\\n${carnet.status.render(session, { notes: 'summary' })}`;\n const lines = carnet.events.read(session.id, events, true).map(formatEventLine);\n const build = () =>\n lines.length ? `${head}\\n\\nLast events\\n${lines.map((line) => ` ${line}`).join('\\n')}` : head;\n let text = build();\n // Drop the oldest events first: the latest steps matter most when picking up work.\n while (text.length > maxCharacters && lines.length > 0) {\n lines.shift();\n text = build();\n }\n return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;\n}\n","import type { Carnet } from './carnet.ts';\nimport { CarnetError } from './errors.ts';\nimport { EMOJI, OPEN_AGENT_STATUSES } from './status/model.ts';\n\ntype OpenAgentStatus = (typeof OPEN_AGENT_STATUSES)[number];\n\nexport const AGENT_STEPS = [\n 'answered',\n 'applying',\n 'applied',\n 'tested',\n 'committed',\n 'dropped',\n] as const;\nexport type AgentStep = (typeof AGENT_STEPS)[number];\n\nexport interface StepAgentInput {\n name: string;\n step: AgentStep;\n commit?: string | undefined;\n note?: string | undefined;\n next?: OpenAgentStatus | undefined;\n}\n\nconst DEFAULT_NEXT: Partial<Record<AgentStep, OpenAgentStatus>> = {\n answered: 'apply',\n applied: 'test',\n tested: 'commit',\n};\n\nfunction tableIsAbout(carnet: Carnet, session: string, name: string): boolean {\n const text = carnet.table.get(session)?.text;\n return text?.startsWith(name) === true && !/[\\w-]/.test(text.charAt(name.length));\n}\n\nfunction clearTableOf(carnet: Carnet, session: string, name: string): void {\n if (tableIsAbout(carnet, session, name)) carnet.table.clear(session);\n}\n\nexport function stepAgent(carnet: Carnet, session: string, input: StepAgentInput): string {\n const { name, step, commit, note } = input;\n if (!carnet.agents.get(session, name)) {\n throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n }\n switch (step) {\n case 'applying':\n carnet.table.set(session, { text: `${name} applying`, mainWorking: true });\n return `⚙️ ${name} applying`;\n case 'committed': {\n if (!commit) throw new CarnetError('COMMIT_REQUIRED', 'The committed step needs the commit');\n carnet.events.log(session, { type: 'committed', agent: name, commit, note });\n carnet.agents.drop(session, name, `committed ${commit}`);\n clearTableOf(carnet, session, name);\n return `${EMOJI.commit} ${name} committed ${commit}, closed`;\n }\n case 'dropped':\n carnet.agents.drop(session, name, note);\n clearTableOf(carnet, session, name);\n return `${name} dropped, closed`;\n default: {\n const next = input.next ?? (DEFAULT_NEXT[step] as OpenAgentStatus);\n carnet.events.log(session, { type: step, agent: name, note });\n carnet.agents.update(session, name, { status: next });\n if (next === 'running') clearTableOf(carnet, session, name);\n else if (step !== 'answered') {\n carnet.table.set(session, { text: `${name} ${step}, ${next} next`, status: next });\n }\n return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;\n }\n }\n}\n"],"mappings":";;;;;;AASA,SAAgB,OAAO,KAAkB;CACvC,OAAO,IAAI,IAAI,CAAC,CAAC,YAAY;AAC/B;;ACoBA,IAAa,cAAb,cAAiC,MAAM;CAE1B;CADX,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;;ACpCA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;AACF;AAMA,MAAM,kBAAqC,CAAC,GAAG,aAAa,GAAG,mBAAmB;AAsClF,SAAgB,YAAY,OAAoC;CAC9D,OAAO,OAAO,UAAU,YAAY,gBAAgB,SAAS,KAAK;AACpE;AAEA,SAAS,QAAQ,KAA4B;CAC3C,OAAO;EACL,IAAI,IAAI;EACR,SAAS,IAAI;EACb,IAAI,IAAI;EACR,MAAM,IAAI;EACV,OAAO,IAAI;EACX,QAAQ,IAAI;EACZ,MAAM,IAAI;EACV,MAAM,IAAI;CACZ;AACF;AAEA,SAAgB,SAAS,KAAU,SAAiB,OA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