@rucher/carnet 0.3.0 → 0.4.0-beta.0
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/dist/carnet-B9opMp0K.d.mts +1228 -0
- package/dist/carnet-B9opMp0K.d.mts.map +1 -0
- package/dist/index.d.mts +224 -21
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +410 -110
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +4 -4
- package/dist/mcp.d.mts.map +1 -1
- package/dist/mcp.mjs +261 -154
- package/dist/mcp.mjs.map +1 -1
- package/dist/{steps-DfvHqzF0.mjs → usage-D3xjR_RF.mjs} +4657 -1993
- package/dist/usage-D3xjR_RF.mjs.map +1 -0
- package/package.json +2 -1
- package/dist/carnet-D3zpKpdn.d.mts +0 -646
- package/dist/carnet-D3zpKpdn.d.mts.map +0 -1
- package/dist/steps-DfvHqzF0.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage-D3xjR_RF.mjs","names":["attachmentsSchema","producedSchema","recommendedThenSchema","requireAgent","count","count","contextOf","inTransaction","DAY_MILLISECONDS","plural","requireAgent"],"sources":["../src/errors.ts","../src/agent-json.ts","../src/context.ts","../src/notes.ts","../src/references.ts","../src/events.ts","../src/status/model.ts","../src/status/note.ts","../src/agents.ts","../src/findings.ts","../src/memory.ts","../src/questions.ts","../src/report.ts","../src/prompt/kind-contracts.ts","../src/paths.ts","../src/config/schema.ts","../src/config/load.ts","../src/workspace/workspace.ts","../src/prompt/core-rules.ts","../src/context-files.ts","../src/prompt/prompt.ts","../src/run-directory-files.ts","../src/workspace/undo.ts","../src/hosts/claude-code-store.ts","../src/hosts/claude-code-hooks.ts","../src/hosts/claude-code-transcript.ts","../src/hosts/claude-code-usage.ts","../src/hosts/claude-code-launch.ts","../src/hosts/claude-code.ts","../src/hosts/rucher.ts","../src/hosts/host.ts","../src/workspace-rows.ts","../src/workspace/locate.ts","../src/sessions.ts","../src/brief.ts","../src/db/search-schema.ts","../src/db/schema.ts","../src/db/open.ts","../src/merge.ts","../src/sandbox.ts","../src/purge.ts","../src/status/render.ts","../src/table.ts","../src/turn.ts","../src/status/view.ts","../src/subagents.ts","../src/search.ts","../src/carnet.ts","../src/prompt/next-actions.ts","../src/kinds.ts","../src/resume.ts","../src/steps.ts","../src/config/defaults.ts","../src/frontmatter.ts","../src/layers.ts","../src/config/resolve.ts","../src/config/profiles.ts","../src/usage.ts"],"sourcesContent":["export type CarnetErrorCode =\n | 'NO_WORKSPACE'\n | 'WORKSPACE_EXISTS'\n | 'WORKSPACE_NOT_FOUND'\n | 'WORKSPACE_NAME_INVALID'\n | 'WORKSPACE_BUSY'\n | 'WORKSPACE_RELOCATE_FAILED'\n | 'REPO_NOT_FOUND'\n | 'REPO_NAME_TAKEN'\n | 'NOTE_NOT_FOUND'\n | 'INVALID_NOTE'\n | 'UNKNOWN_HOST'\n | 'HOST_WITHOUT_HOOKS'\n | 'HOST_CANNOT_LAUNCH'\n | 'NO_CONVERSATION'\n | 'NO_SESSION'\n | 'SESSION_NOT_FOUND'\n | 'SESSION_AMBIGUOUS'\n | 'SESSION_NAME_TAKEN'\n | 'SESSION_NAME_REQUIRED'\n | 'SESSION_RUNNING'\n | 'SESSION_KIND_INVALID'\n | 'SESSION_MERGE_INVALID'\n | 'SESSION_EXISTS'\n | 'SESSION_MOVE_INVALID'\n | 'SESSION_CWD_MISSING'\n | 'RUN_DIRECTORY_FILE_CONFLICT'\n | 'WORKSPACE_INSTRUCTIONS_CONFLICT'\n | 'AGENT_EXISTS'\n | 'INVALID_NAME'\n | 'AGENT_NOT_FOUND'\n | 'AGENT_AMBIGUOUS'\n | 'INVALID_TARGET'\n | 'INVALID_BLOCKER'\n | 'INVALID_KIND'\n | 'INVALID_SANDBOX'\n | 'INVALID_QUESTIONS'\n | 'QUESTION_NOT_FOUND'\n | 'FINDING_NOT_FOUND'\n | 'REASON_REQUIRED'\n | 'SECTION_NOT_FOUND'\n | 'REPORT_MISSING'\n | 'INVALID_STATUS'\n | 'INVALID_EVENT_TYPE'\n | 'COMMIT_REQUIRED'\n | 'INVALID_JSON'\n | 'INVALID_DECISION'\n | 'INVALID_ROUTE'\n | 'FINDING_DECIDED'\n | 'INVALID_ATTACHMENT'\n | 'INVALID_REFERENCE'\n | 'REFERENCE_NOT_FOUND'\n | 'MISSION_REQUIRED'\n | 'PLUGIN_OUTDATED'\n | 'SCHEMA_TOO_NEW'\n | 'CONFIG_INVALID'\n | 'RUN_FIXED'\n | 'BACKEND_UNAVAILABLE';\n\nexport class CarnetError extends Error {\n constructor(\n readonly code: CarnetErrorCode,\n message: string,\n readonly hint?: string,\n ) {\n super(message);\n this.name = 'CarnetError';\n }\n}\n","import * as z from 'zod/v4';\nimport { CarnetError } from './errors.ts';\n\nexport const DELIVERABLES = ['report', 'questions', 'plan', 'findings', 'worktree'] as const;\nexport const deliverable = z.enum(DELIVERABLES);\nexport type Deliverable = z.infer<typeof deliverable>;\n\nconst agentId = z.number().int().positive();\n\nfunction attachmentShapes<Agent extends z.ZodType>(agent: Agent) {\n return [\n z.object({ type: z.literal('ref'), id: z.number().int().positive() }),\n z.object({\n type: z.literal('deliverable'),\n agent,\n section: z.enum(['plan', 'report']),\n }),\n z.object({ type: z.literal('for_main'), agent }),\n z.object({\n type: z.literal('findings'),\n review: agent,\n n: z.array(z.number().int().min(1)).min(1),\n }),\n z\n .object({\n type: z.literal('notes'),\n ids: z.array(z.number().int().positive()).min(1).optional(),\n query: z.string().min(1).optional(),\n })\n .refine((notes) => notes.ids !== undefined || notes.query !== undefined, {\n message: 'notes needs ids or a query',\n }),\n ] as const;\n}\n\nexport const attachment = z.discriminatedUnion('type', attachmentShapes(agentId));\nexport type Attachment = z.infer<typeof attachment>;\nexport const attachments = z.array(attachment);\n\n// What a caller passes before resolution: an agent by name, or a document by path that becomes a\n// ref once stored.\nexport const attachmentInput = z.discriminatedUnion('type', [\n ...attachmentShapes(z.union([agentId, z.string().min(1)])),\n z.object({ type: z.literal('doc'), path: z.string().min(1) }),\n]);\nexport type AttachmentInput = z.infer<typeof attachmentInput>;\nexport const attachmentsInput = z.array(attachmentInput);\n\nexport const produced = z.array(deliverable).min(1);\nexport type Produced = z.infer<typeof produced>;\n\nexport const recommendedThen = z.object({ option: z.string().min(1), reason: z.string().min(1) });\nexport type RecommendedThen = z.infer<typeof recommendedThen>;\n\n// Snapshots are shaped by their owners (kinds, profiles); Carnet only keeps them as JSON objects.\nexport const snapshot = z.record(z.string(), z.unknown());\nexport type Snapshot = z.infer<typeof snapshot>;\n\nexport function toJsonColumn<T>(\n schema: z.ZodType<T>,\n value: T | null | undefined,\n field: string,\n): string | null {\n if (value === null || value === undefined) return null;\n const parsed = schema.safeParse(value);\n if (!parsed.success) {\n throw new CarnetError('INVALID_JSON', `Invalid ${field}: ${z.prettifyError(parsed.error)}`);\n }\n return JSON.stringify(parsed.data);\n}\n\n// A value written by another version may no longer fit: it reads as absent rather than failing\n// every read of the row.\nexport function fromJsonColumn<T>(schema: z.ZodType<T>, text: string | null): T | null {\n if (text === null) return null;\n try {\n const parsed = schema.safeParse(JSON.parse(text));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nexport interface Ctx {\n db: DatabaseSync;\n now: () => Date;\n // null: no workspace resolved, so nothing can be written for a session.\n workspace: string | null;\n}\n\nexport function nowIso(ctx: Ctx): string {\n return ctx.now().toISOString();\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport type { Workspace } from './workspace/locate.ts';\n\nexport const NOTE_KINDS = ['dead_end', 'decision', 'learning'] as const;\nexport type NoteKind = (typeof NOTE_KINDS)[number];\n\nexport const NOTE_TEXT_LIMIT = 200;\nexport const DUPLICATE_SIMILARITY = 0.6;\nexport const DEFAULT_HALF_LIFE_DAYS = 20;\nexport const STALE_AFTER_ACTIVE_DAYS = 40;\nexport const STALE_WEIGHT = 0.05;\nconst SIMILAR_SHOWN = 3;\n\nexport function isNoteKind(value: string): value is NoteKind {\n return (NOTE_KINDS as readonly string[]).includes(value);\n}\n\nexport function memoryHalfLife(value: string | undefined): number {\n const days = Number(value);\n return Number.isFinite(days) && days > 0 ? days : DEFAULT_HALF_LIFE_DAYS;\n}\n\nexport interface Note {\n id: number;\n kind: NoteKind;\n text: string;\n repos: string[];\n session: string | null;\n agent: string | null;\n similarNotes: number[];\n createdAt: string;\n droppedAt: string | null;\n droppedReason: string | null;\n droppedSession: string | null;\n replacedBy: number | null;\n}\n\nexport interface NoteCitation {\n id: number;\n note: number;\n session: string | null;\n agent: string | null;\n why: string;\n at: string;\n}\n\nexport interface WeightedNote extends Note {\n weight: number;\n citationCount: number;\n}\n\nexport interface NoteDetail extends WeightedNote {\n citations: NoteCitation[];\n}\n\nexport interface AddNoteInput {\n kind: string;\n text: string;\n repos?: string[] | undefined;\n session?: string | null | undefined;\n agent?: string | null | undefined;\n}\n\nexport interface AddNoteResult {\n note: Note;\n similar: Note[];\n}\n\nexport interface ListNotesOptions {\n kind?: string | undefined;\n repo?: string | undefined;\n general?: boolean | undefined;\n query?: string | undefined;\n includeDropped?: boolean | undefined;\n halfLifeDays?: number | undefined;\n}\n\nexport interface DropNoteInput {\n reason: string;\n replacedBy?: number | undefined;\n session?: string | null | undefined;\n}\n\nexport interface CiteNoteInput {\n why: string;\n session?: string | null | undefined;\n agent?: string | null | undefined;\n}\n\ninterface NoteRow {\n id: number;\n number: number;\n kind: NoteKind;\n text: string;\n session: string | null;\n agent: string | null;\n similar_notes: string | null;\n created_at: string;\n dropped_at: string | null;\n dropped_reason: string | null;\n dropped_session: string | null;\n replaced_number: number | null;\n}\n\n// Notes are shown and referenced by their number in the workspace; the id stays internal.\nconst NOTE_COLUMNS = `notes.id, notes.number, notes.kind, notes.text, notes.session, notes.agent,\n notes.similar_notes, notes.created_at, notes.dropped_at, notes.dropped_reason,\n notes.dropped_session,\n (SELECT replaced.number FROM notes AS replaced WHERE replaced.id = notes.replaced_by)\n AS replaced_number`;\n\nconst MARKDOWN = /\\*\\*|__|\\[[^\\]]*\\]\\([^)]*\\)|^#{1,6}\\s|^[-*+]\\s/;\n\nfunction cleanText(value: string, label: string): string {\n const text = value.trim().replace(/[ \\t]+/g, ' ');\n if (!text) throw new CarnetError('INVALID_NOTE', `${label} is empty`);\n if (text.length >= NOTE_TEXT_LIMIT) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `${label} must stay under ${NOTE_TEXT_LIMIT} characters (${text.length})`,\n );\n }\n if (/[\\r\\n]/.test(text)) throw new CarnetError('INVALID_NOTE', `${label} must be one line`);\n if (text.includes('`')) throw new CarnetError('INVALID_NOTE', `${label} must not use backticks`);\n if (MARKDOWN.test(text)) throw new CarnetError('INVALID_NOTE', `${label} must not use markdown`);\n return text;\n}\n\nexport function workspaceRepoNames(workspace: Workspace): string[] {\n return workspace.repos.map((repo) => repo.name);\n}\n\nfunction cleanRepos(workspace: Workspace, repos: string[] | undefined): string[] {\n const known = workspaceRepoNames(workspace);\n const unique = [...new Set((repos ?? []).map((repo) => repo.trim()).filter(Boolean))];\n const unknown = unique.filter((repo) => !known.includes(repo));\n if (unknown.length) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `Unknown repo ${unknown.join(', ')} (workspace repos: ${known.join(', ') || 'none'})`,\n );\n }\n return unique;\n}\n\nfunction words(text: string): Set<string> {\n return new Set(text.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []);\n}\n\nexport function similarity(first: string, second: string): number {\n const left = words(first);\n const right = words(second);\n if (left.size === 0 && right.size === 0) return 0;\n let shared = 0;\n for (const word of left) if (right.has(word)) shared++;\n return shared / (left.size + right.size - shared);\n}\n\nexport function localDay(date: Date): string {\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n return `${date.getFullYear()}-${month}-${day}`;\n}\n\nexport function recordActiveDay(ctx: Ctx): void {\n if (ctx.workspace === null) return;\n ctx.db\n .prepare('INSERT OR IGNORE INTO active_days (workspace, day) VALUES (?, ?)')\n .run(ctx.workspace, localDay(ctx.now()));\n}\n\nfunction activeDays(ctx: Ctx): string[] {\n const rows = ctx.db\n .prepare('SELECT day FROM active_days WHERE workspace IS ? ORDER BY day')\n .all(ctx.workspace) as unknown as { day: string }[];\n return rows.map((row) => row.day);\n}\n\nfunction activeDaysSince(days: string[], at: string): number {\n const since = localDay(new Date(at));\n return days.filter((day) => day > since).length;\n}\n\nfunction reposOf(ctx: Ctx, noteId: number): string[] {\n const rows = ctx.db\n .prepare('SELECT repo FROM note_repos WHERE note = ? ORDER BY repo')\n .all(noteId) as unknown as { repo: string }[];\n return rows.map((row) => row.repo);\n}\n\nfunction toNote(ctx: Ctx, row: NoteRow): Note {\n return {\n id: row.number,\n kind: row.kind,\n text: row.text,\n repos: reposOf(ctx, row.id),\n session: row.session,\n agent: row.agent,\n similarNotes: row.similar_notes ? (JSON.parse(row.similar_notes) as number[]) : [],\n createdAt: row.created_at,\n droppedAt: row.dropped_at,\n droppedReason: row.dropped_reason,\n droppedSession: row.dropped_session,\n replacedBy: row.replaced_number,\n };\n}\n\nfunction noteRow(ctx: Ctx, number: number): NoteRow | undefined {\n return ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND number = ?`)\n .get(ctx.workspace, number) as NoteRow | undefined;\n}\n\nfunction noteId(ctx: Ctx, number: number): number {\n const row = noteRow(ctx, number);\n if (!row) throw new CarnetError('NOTE_NOT_FOUND', `Unknown note #${number}`);\n return row.id;\n}\n\nexport function getNote(ctx: Ctx, id: number): Note | null {\n const row = noteRow(ctx, id);\n return row ? toNote(ctx, row) : null;\n}\n\nexport function requireNote(ctx: Ctx, id: number): Note {\n const note = getNote(ctx, id);\n if (!note) throw new CarnetError('NOTE_NOT_FOUND', `Unknown note #${id}`);\n return note;\n}\n\nfunction requireActiveNote(ctx: Ctx, id: number): Note {\n const note = requireNote(ctx, id);\n if (note.droppedAt) throw new CarnetError('INVALID_NOTE', `Note #${id} is dropped`);\n return note;\n}\n\nconst CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citations.session,\n note_citations.agent, note_citations.why, note_citations.at`;\n\nfunction citationsOf(ctx: Ctx, number: number): NoteCitation[] {\n return ctx.db\n .prepare(\n `SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at, note_citations.rowid`,\n )\n .all(ctx.workspace, number) as unknown as NoteCitation[];\n}\n\n// Several citations in one session count once: the latest stands for that session.\nfunction weightOf(citations: NoteCitation[], days: string[], halfLifeDays: number): number {\n const latest = new Map<string, string>();\n for (const citation of citations) {\n const key = citation.session ?? `citation-${citation.id}`;\n const previous = latest.get(key);\n if (!previous || citation.at > previous) latest.set(key, citation.at);\n }\n let weight = 0;\n for (const at of latest.values()) weight += 0.5 ** (activeDaysSince(days, at) / halfLifeDays);\n return weight;\n}\n\nfunction weigh(ctx: Ctx, note: Note, days: string[], halfLifeDays: number): WeightedNote {\n const citations = citationsOf(ctx, note.id);\n return {\n ...note,\n weight: weightOf(citations, days, halfLifeDays),\n citationCount: citations.length,\n };\n}\n\nexport function compareNotes(first: WeightedNote, second: WeightedNote): number {\n const kind = NOTE_KINDS.indexOf(first.kind) - NOTE_KINDS.indexOf(second.kind);\n if (kind !== 0) return kind;\n if (first.weight !== second.weight) return second.weight - first.weight;\n return second.id - first.id;\n}\n\nfunction activeNotesOfKind(ctx: Ctx, kind: NoteKind): Note[] {\n const rows = ctx.db\n .prepare(\n `SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND kind = ? AND dropped_at IS NULL`,\n )\n .all(ctx.workspace, kind) as unknown as NoteRow[];\n return rows.map((row) => toNote(ctx, row));\n}\n\nexport function addNote(ctx: Ctx, workspace: Workspace | null, input: AddNoteInput): AddNoteResult {\n if (workspace === null || ctx.workspace === null) {\n throw new CarnetError('NO_WORKSPACE', 'Notes belong to a workspace: this session has none');\n }\n if (!isNoteKind(input.kind)) {\n throw new CarnetError(\n 'INVALID_NOTE',\n `Invalid note kind \"${input.kind}\" (use ${NOTE_KINDS.join(', ')})`,\n );\n }\n const kind = input.kind;\n const text = cleanText(input.text, 'Note text');\n const repos = cleanRepos(workspace, input.repos);\n const similar = activeNotesOfKind(ctx, kind)\n .map((note) => ({ note, score: similarity(text, note.text) }))\n .filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY)\n .sort((first, second) => second.score - first.score)\n .slice(0, SIMILAR_SHOWN)\n .map((candidate) => candidate.note);\n ctx.db.exec('BEGIN');\n try {\n const next = ctx.db\n .prepare('SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE workspace = ?')\n .get(ctx.workspace) as { number: number };\n const result = ctx.db\n .prepare(\n `INSERT INTO notes (workspace, number, kind, text, session, agent, similar_notes, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n ctx.workspace,\n next.number,\n kind,\n text,\n input.session ?? null,\n input.agent ?? null,\n similar.length ? JSON.stringify(similar.map((note) => note.id)) : null,\n nowIso(ctx),\n );\n const id = Number(result.lastInsertRowid);\n const addRepo = ctx.db.prepare('INSERT INTO note_repos (note, repo) VALUES (?, ?)');\n for (const repo of repos) addRepo.run(id, repo);\n ctx.db.exec('COMMIT');\n return { note: requireNote(ctx, next.number), similar };\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n\nexport function listNotes(ctx: Ctx, options: ListNotesOptions = {}): WeightedNote[] {\n if (options.kind !== undefined && !isNoteKind(options.kind)) {\n throw new CarnetError('INVALID_NOTE', `Invalid note kind \"${options.kind}\"`);\n }\n const conditions: string[] = ['workspace IS ?'];\n const parameters: (string | null)[] = [ctx.workspace];\n if (!options.includeDropped) conditions.push('dropped_at IS NULL');\n if (options.kind) {\n conditions.push('kind = ?');\n parameters.push(options.kind);\n }\n if (options.repo) {\n conditions.push('id IN (SELECT note FROM note_repos WHERE repo = ?)');\n parameters.push(options.repo);\n }\n if (options.general) conditions.push('id NOT IN (SELECT note FROM note_repos)');\n if (options.query) {\n conditions.push(\"LOWER(text) LIKE ? ESCAPE '\\\\'\");\n parameters.push(`%${options.query.toLowerCase().replace(/[\\\\%_]/g, '\\\\$&')}%`);\n }\n const rows = ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE ${conditions.join(' AND ')}`)\n .all(...parameters) as unknown as NoteRow[];\n const days = activeDays(ctx);\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n return rows.map((row) => weigh(ctx, toNote(ctx, row), days, halfLifeDays)).sort(compareNotes);\n}\n\nexport function noteDetail(\n ctx: Ctx,\n id: number,\n halfLifeDays = DEFAULT_HALF_LIFE_DAYS,\n): NoteDetail {\n const note = requireNote(ctx, id);\n const citations = citationsOf(ctx, id);\n return {\n ...note,\n weight: weightOf(citations, activeDays(ctx), halfLifeDays),\n citationCount: citations.length,\n citations,\n };\n}\n\nexport function staleNotes(ctx: Ctx, halfLifeDays = DEFAULT_HALF_LIFE_DAYS): WeightedNote[] {\n const days = activeDays(ctx);\n return listNotes(ctx, { halfLifeDays }).filter(\n (note) =>\n activeDaysSince(days, note.createdAt) > STALE_AFTER_ACTIVE_DAYS &&\n (note.citationCount === 0 || note.weight < STALE_WEIGHT),\n );\n}\n\nexport function dropNote(ctx: Ctx, id: number, input: DropNoteInput): Note {\n requireActiveNote(ctx, id);\n const reason = cleanText(input.reason, 'Drop reason');\n if (input.replacedBy !== undefined) {\n if (input.replacedBy === id) {\n throw new CarnetError('INVALID_NOTE', `Note #${id} cannot replace itself`);\n }\n requireActiveNote(ctx, input.replacedBy);\n }\n const replacedBy = input.replacedBy === undefined ? null : noteId(ctx, input.replacedBy);\n ctx.db\n .prepare(\n 'UPDATE notes SET dropped_at = ?, dropped_reason = ?, dropped_session = ?, replaced_by = ? WHERE id = ?',\n )\n .run(nowIso(ctx), reason, input.session ?? null, replacedBy, noteId(ctx, id));\n return requireNote(ctx, id);\n}\n\nexport interface DropNotesResult {\n dropped: Note[];\n skipped: { id: number; reason: string }[];\n}\n\n// Unknown or already dropped ids are skipped so one stale id never blocks a cleanup.\nexport function dropNotes(\n ctx: Ctx,\n ids: number[],\n input: Omit<DropNoteInput, 'replacedBy'> & { dryRun?: boolean | undefined },\n): DropNotesResult {\n const result: DropNotesResult = { dropped: [], skipped: [] };\n const reason = cleanText(input.reason, 'Drop reason');\n ctx.db.exec('BEGIN IMMEDIATE');\n try {\n for (const id of new Set(ids)) {\n const note = getNote(ctx, id);\n if (!note) result.skipped.push({ id, reason: 'unknown' });\n else if (note.droppedAt) result.skipped.push({ id, reason: 'already dropped' });\n else result.dropped.push(input.dryRun ? note : dropNote(ctx, id, { ...input, reason }));\n }\n ctx.db.exec(input.dryRun ? 'ROLLBACK' : 'COMMIT');\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n return result;\n}\n\nexport function citeNote(ctx: Ctx, id: number, input: CiteNoteInput): NoteCitation {\n requireActiveNote(ctx, id);\n const why = cleanText(input.why, 'Citation reason');\n const result = ctx.db\n .prepare('INSERT INTO note_citations (note, session, agent, why, at) VALUES (?, ?, ?, ?, ?)')\n .run(noteId(ctx, id), input.session ?? null, input.agent ?? null, why, nowIso(ctx));\n return ctx.db\n .prepare(\n `SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE note_citations.id = ?`,\n )\n .get(Number(result.lastInsertRowid)) as unknown as NoteCitation;\n}\n\nexport type NoteActivityKind = 'added' | 'cited' | 'dropped';\n\nexport interface NoteActivity {\n activity: NoteActivityKind;\n note: number;\n kind: NoteKind;\n text: string;\n similarNotes: number[];\n replacedBy: number | null;\n at: string;\n}\n\nconst ACTIVITY_ORDER: Record<NoteActivityKind, number> = { dropped: 0, cited: 1, added: 2 };\n\nfunction activeIds(ctx: Ctx, json: string | null): number[] {\n if (!json) return [];\n const active = ctx.db.prepare(\n 'SELECT 1 FROM notes WHERE workspace IS ? AND number = ? AND dropped_at IS NULL',\n );\n return (JSON.parse(json) as number[]).filter(\n (number) => active.get(ctx.workspace, number) !== undefined,\n );\n}\n\nexport function sessionNoteActivity(ctx: Ctx, session: string): NoteActivity[] {\n const added = ctx.db\n .prepare(\n `SELECT number, kind, text, similar_notes, created_at FROM notes\n WHERE workspace IS ? AND session = ?`,\n )\n .all(ctx.workspace, session) as unknown as Pick<\n NoteRow,\n 'number' | 'kind' | 'text' | 'similar_notes' | 'created_at'\n >[];\n const cited = ctx.db\n .prepare(\n `SELECT notes.number AS note, notes.kind, note_citations.why, note_citations.at\n FROM note_citations JOIN notes ON notes.id = note_citations.note\n WHERE notes.workspace IS ? AND note_citations.session = ?`,\n )\n .all(ctx.workspace, session) as unknown as {\n note: number;\n kind: NoteKind;\n why: string;\n at: string;\n }[];\n const dropped = ctx.db\n .prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND dropped_session = ?`)\n .all(ctx.workspace, session) as unknown as NoteRow[];\n const activity: NoteActivity[] = [\n ...added.map((row) => ({\n activity: 'added' as const,\n note: row.number,\n kind: row.kind,\n text: row.text,\n similarNotes: activeIds(ctx, row.similar_notes),\n replacedBy: null,\n at: row.created_at,\n })),\n ...cited.map((row) => ({\n activity: 'cited' as const,\n note: row.note,\n kind: row.kind,\n text: row.why,\n similarNotes: [],\n replacedBy: null,\n at: row.at,\n })),\n ...dropped.map((row) => ({\n activity: 'dropped' as const,\n note: row.number,\n kind: row.kind,\n text: row.dropped_reason ?? '',\n similarNotes: [],\n replacedBy: row.replaced_number,\n at: row.dropped_at ?? '',\n })),\n ];\n return activity.sort(\n (first, second) =>\n second.at.localeCompare(first.at) ||\n ACTIVITY_ORDER[first.activity] - ACTIVITY_ORDER[second.activity] ||\n second.note - first.note,\n );\n}\n","import { closeSync, existsSync, openSync, readSync, realpathSync, statSync } from 'node:fs';\nimport { extname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\n\nexport const REFERENCE_SCOPES = ['session', 'agent'] as const;\nexport type ReferenceScope = (typeof REFERENCE_SCOPES)[number];\n\nexport interface Reference {\n id: number;\n session: string;\n scope: ReferenceScope;\n path: string;\n title: string | null;\n bytes: number | null;\n missing: boolean;\n addedAt: string;\n removedAt: string | null;\n}\n\ninterface ReferenceRow {\n id: number;\n session: string;\n scope: ReferenceScope;\n path: string;\n title: string | null;\n added_at: string;\n removed_at: string | null;\n}\n\n// The heading sits near the top; documents can be large and are read at every session start.\nconst HEADING_BYTES = 8192;\n\nfunction firstHeading(path: string): string | null {\n try {\n const fd = openSync(path, 'r');\n try {\n const buffer = Buffer.alloc(HEADING_BYTES);\n const read = readSync(fd, buffer, 0, HEADING_BYTES, 0);\n const heading = /^#\\s+(.+)$/m.exec(buffer.subarray(0, read).toString('utf8'));\n return heading?.[1]?.trim() || null;\n } finally {\n closeSync(fd);\n }\n } catch {\n return null;\n }\n}\n\n// Documents are read live: title and size come from the file as it is now.\nfunction toReference(row: ReferenceRow): Reference {\n const stats = statSync(row.path, { throwIfNoEntry: false });\n const missing = !stats;\n return {\n id: Number(row.id),\n session: row.session,\n scope: row.scope,\n path: row.path,\n title: missing ? row.title : (firstHeading(row.path) ?? row.title),\n bytes: stats ? stats.size : null,\n missing,\n addedAt: row.added_at,\n removedAt: row.removed_at,\n };\n}\n\nexport function documentPath(path: string, cwd = process.cwd(), runDirectory?: string): string {\n const absolute = resolve(cwd, path);\n if (!existsSync(absolute) || !statSync(absolute).isFile()) {\n throw new CarnetError('INVALID_REFERENCE', `No file ${absolute}`);\n }\n if (extname(absolute).toLowerCase() !== '.md') {\n throw new CarnetError('INVALID_REFERENCE', `A reference is a markdown file, not ${absolute}`);\n }\n // One spelling per file, so adding it again finds its row. Under the run directory it is that\n // directory's spelling, the string a rename or merge rewrites.\n return runDirectory ? underRunDirectory(absolute, runDirectory) : realpathSync(absolute);\n}\n\nfunction pathKeys(idOrPath: string, runDirectory?: string): string[] {\n const absolute = resolve(idOrPath);\n const keys = [absolute];\n try {\n const real = realpathSync(absolute);\n if (real !== absolute) keys.push(real);\n if (runDirectory) keys.push(underRunDirectory(absolute, runDirectory));\n } catch {\n // The file is gone: the stored spelling is still one of the keys above.\n }\n return [...new Set(keys)];\n}\n\nfunction underRunDirectory(absolute: string, runDirectory: string): string {\n try {\n const real = realpathSync(absolute);\n const rest = relative(realpathSync(runDirectory), real);\n if (rest.startsWith('..') || isAbsolute(rest)) return real;\n return rest === '' ? runDirectory : join(runDirectory, rest);\n } catch {\n return absolute;\n }\n}\n\nexport interface AddReferenceInput {\n path: string;\n scope?: ReferenceScope | undefined;\n cwd?: string | undefined;\n runDirectory?: string | undefined;\n}\n\n// Adding a document already there gives the same row back.\nexport function addReference(ctx: Ctx, session: string, input: AddReferenceInput): Reference {\n const path = documentPath(input.path, input.cwd, input.runDirectory);\n const scope = input.scope ?? 'session';\n const existing = ctx.db\n .prepare(\n `SELECT * FROM reference_docs\n WHERE session = ? AND scope = ? AND path = ? AND removed_at IS NULL ORDER BY id LIMIT 1`,\n )\n .get(session, scope, path) as ReferenceRow | undefined;\n if (existing) return toReference(existing);\n const result = ctx.db\n .prepare(\n 'INSERT INTO reference_docs (session, scope, path, title, added_at) VALUES (?, ?, ?, ?, ?)',\n )\n .run(session, scope, path, firstHeading(path), nowIso(ctx));\n return requireReference(ctx, Number(result.lastInsertRowid));\n}\n\nexport function getReference(ctx: Ctx, id: number): Reference | undefined {\n const row = ctx.db.prepare('SELECT * FROM reference_docs WHERE id = ?').get(id) as\n | ReferenceRow\n | undefined;\n return row && toReference(row);\n}\n\nexport function requireReference(ctx: Ctx, id: number): Reference {\n const reference = getReference(ctx, id);\n if (!reference) throw new CarnetError('REFERENCE_NOT_FOUND', `No reference ${id}`);\n return reference;\n}\n\nexport interface ListReferencesOptions {\n ids?: readonly number[] | undefined;\n all?: boolean | undefined;\n}\n\n// The session's documents, then the given ones (an agent's ref attachments) not already listed.\nexport function listReferences(\n ctx: Ctx,\n session: string,\n options: ListReferencesOptions = {},\n): Reference[] {\n const removed = options.all ? '' : ' AND removed_at IS NULL';\n const rows = ctx.db\n .prepare(\n `SELECT * FROM reference_docs WHERE session = ? AND scope = 'session'${removed} ORDER BY id`,\n )\n .all(session) as unknown as ReferenceRow[];\n const references = rows.map(toReference);\n for (const id of options.ids ?? []) {\n if (references.some((reference) => reference.id === id)) continue;\n const reference = getReference(ctx, id);\n if (reference && reference.session === session) references.push(reference);\n }\n return references;\n}\n\nexport function removeReference(\n ctx: Ctx,\n session: string,\n idOrPath: string,\n runDirectory?: string,\n): Reference {\n const id = /^\\d+$/.test(idOrPath) ? Number(idOrPath) : undefined;\n const paths = id === undefined ? pathKeys(idOrPath, runDirectory) : [];\n const row = (\n id === undefined\n ? ctx.db\n .prepare(\n `SELECT * FROM reference_docs WHERE session = ? AND path IN (${paths.map(() => '?').join(', ')})\n AND removed_at IS NULL\n ORDER BY scope = 'agent', id LIMIT 1`,\n )\n .get(session, ...paths)\n : ctx.db\n .prepare(\n 'SELECT * FROM reference_docs WHERE session = ? AND id = ? AND removed_at IS NULL',\n )\n .get(session, id)\n ) as ReferenceRow | undefined;\n if (!row) {\n throw new CarnetError('REFERENCE_NOT_FOUND', `No reference ${idOrPath} in this session`);\n }\n ctx.db.prepare('UPDATE reference_docs SET removed_at = ? WHERE id = ?').run(nowIso(ctx), row.id);\n return requireReference(ctx, Number(row.id));\n}\n\n// A session merged into another brings its documents; a session document the other already has is\n// kept once. Agent documents all move: their agents' attachments point to them.\nexport function mergeReferences(ctx: Ctx, fromId: string, intoId: string, at: string): void {\n ctx.db\n .prepare(\n `UPDATE reference_docs SET removed_at = ?\n WHERE session = ? AND scope = 'session' AND removed_at IS NULL AND EXISTS (\n SELECT 1 FROM reference_docs AS other\n WHERE other.session = ? AND other.scope = 'session'\n AND other.path = reference_docs.path AND other.removed_at IS NULL)`,\n )\n .run(at, fromId, intoId);\n ctx.db.prepare('UPDATE reference_docs SET session = ? WHERE session = ?').run(intoId, fromId);\n}\n\nexport function formatBytes(bytes: number | null): string {\n if (bytes === null) return 'missing';\n if (bytes < 1024) return `${bytes} B`;\n return `${(bytes / 1024).toFixed(bytes < 10240 ? 1 : 0)} kB`;\n}\n\nexport function referenceLine(reference: Reference): string {\n const title = reference.title ? `${reference.title} · ` : '';\n const state = reference.removedAt ? ' (removed)' : reference.missing ? ' (missing)' : '';\n return `#${reference.id} ${title}${reference.path} · ${formatBytes(reference.bytes)}${state}`;\n}\n","import type { AgentKind } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\n\nexport const EVENT_TYPES = [\n 'started',\n 'finished',\n 'answered',\n 'applied',\n 'tested',\n 'committed',\n 'dropped',\n 'injected',\n 'promoted',\n 'triaged',\n 'reopened',\n 'briefed',\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 agentId: number | null;\n commit: string | null;\n link: string | null;\n note: string | null;\n payload: unknown;\n}\n\nexport interface LogEventInput {\n type: EventType;\n agent?: string | undefined;\n // Without it, the agent of that name: the open one, else the latest closed.\n agentId?: number | undefined;\n payload?: unknown;\n commit?: string | undefined;\n link?: string | undefined;\n note?: string | undefined;\n}\n\nexport interface ReadEventsOptions {\n session: string;\n limit?: number | undefined;\n agentOnly?: boolean | undefined;\n kind?: AgentKind | undefined;\n}\n\ninterface EventRow {\n id: number;\n session: string;\n at: string;\n type: EventType;\n agent: string | null;\n agent_id: number | null;\n commit_sha: string | null;\n link: string | null;\n note: string | null;\n payload: 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 agentIdByName(ctx: Ctx, session: string, name: string): number | null {\n const row = ctx.db\n .prepare(\n `SELECT id FROM agents WHERE session = ? AND name = ?\n ORDER BY status = 'closed', id DESC LIMIT 1`,\n )\n .get(session, name) as { id: number } | undefined;\n return row ? Number(row.id) : null;\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 agentId: row.agent_id === null ? null : Number(row.agent_id),\n commit: row.commit_sha,\n link: row.link,\n note: row.note,\n payload: row.payload === null ? null : (JSON.parse(row.payload) as unknown),\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 agentId =\n input.agentId ?? (input.agent === undefined ? null : agentIdByName(ctx, session, input.agent));\n const result = ctx.db\n .prepare(\n `INSERT INTO events (session, at, type, agent, agent_id, commit_sha, link, note, payload)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n session,\n nowIso(ctx),\n input.type,\n input.agent ?? null,\n agentId,\n input.commit ?? null,\n input.link ?? null,\n input.note ?? null,\n input.payload === undefined ? null : JSON.stringify(input.payload),\n );\n const row = ctx.db\n .prepare('SELECT * FROM events WHERE id = ?')\n .get(result.lastInsertRowid) as unknown as EventRow;\n return toEvent(row);\n}\n\nexport function readEvents(\n ctx: Ctx,\n { session, limit = 20, agentOnly = false, kind }: ReadEventsOptions,\n): CarnetEvent[] {\n const filters = [\n agentOnly ? \"AND type NOT LIKE 'session.%'\" : '',\n kind\n ? 'AND agent_id IN (SELECT id FROM agents WHERE session = events.session AND kind = ?)'\n : '',\n ].join(' ');\n const parameters: string[] = kind ? [session, kind] : [session];\n const rows = ctx.db\n .prepare(\n `SELECT * FROM (SELECT * FROM events WHERE session = ? ${filters} ORDER BY at DESC, id DESC LIMIT ?) ORDER BY at, id`,\n )\n .all(...parameters, limit) as unknown as EventRow[];\n return rows.map(toEvent);\n}\n","export const AGENT_STATUSES = [\n 'running',\n 'discussing',\n 'answer',\n 'review',\n 'apply',\n 'test',\n 'closed',\n] as const;\n\nexport type AgentStatus = (typeof AGENT_STATUSES)[number];\n\nexport const USER_ACTION_STATUSES = ['discussing', 'answer', 'review', 'apply', 'test'] as const;\n\nexport type UserActionStatus = (typeof USER_ACTION_STATUSES)[number];\n\nexport const EMOJI: Record<Exclude<AgentStatus, 'closed'>, string> = {\n running: '⏳',\n discussing: '💬',\n answer: '❓',\n review: '👀',\n apply: '📥',\n test: '🧪',\n};\n\nexport const MAIN_WORKING_EMOJI = '⚙️';\nexport const MAIN_WAITING_EMOJI = '⏸';\nexport const MAIN_FAILED_EMOJI = '⚠';\n\nexport const LEGEND =\n '⚙️ main working · ⏸ waiting on you · ⚠ turn failed · 💬 discussing · ❓ answer · 👀 review · 📥 apply · 🧪 test · ⏳ running';\n\nexport const KIND_ABBREVIATIONS = {\n research: 'rs',\n plan: 'pl',\n implement: 'im',\n review: 'rv',\n} as const;\n\n// Brackets keep the kind apart from the agent's name even where there is no colour.\nexport function kindTag(kind: keyof typeof KIND_ABBREVIATIONS): string {\n return `[${KIND_ABBREVIATIONS[kind]}]`;\n}\n\nexport const KIND_TAG_PATTERN = /\\[(?:rs|pl|im|rv)\\]/;\n\nexport const KIND_LEGEND = '[rs] research · [pl] plan · [im] implement · [rv] review';\n\nexport function isAgentStatus(value: unknown): value is AgentStatus {\n return typeof value === 'string' && (AGENT_STATUSES as readonly string[]).includes(value);\n}\n\nexport function isUserActionStatus(value: unknown): value is UserActionStatus {\n return typeof value === 'string' && (USER_ACTION_STATUSES as readonly string[]).includes(value);\n}\n\nexport const OPEN_AGENT_STATUSES = ['running', ...USER_ACTION_STATUSES] as const;\n","export const NOTE_MAX = 60;\n\nconst PATH_PREFIX = /^(\\/|\\.\\.?\\/|~\\/)/;\nconst FILE_AFTER_SLASH = /\\/[^/\\s]+\\.[A-Za-z0-9]+$/;\n\nfunction looksLikePath(token: string): boolean {\n if (PATH_PREFIX.test(token)) return true;\n const slashes = token.split('/').length - 1;\n return slashes >= 2 || (slashes === 1 && FILE_AFTER_SLASH.test(token));\n}\n\nexport function sanitizeNote(text: string): string {\n const cleaned = text\n .replaceAll('`', '')\n .split(/\\s+/)\n .filter((token) => token && !looksLikePath(token))\n .join(' ')\n .trim();\n if (cleaned.length <= NOTE_MAX) return cleaned;\n return `${cleaned.slice(0, NOTE_MAX - 1).trimEnd()}…`;\n}\n","import type { DatabaseSync, SQLInputValue } from 'node:sqlite';\nimport {\n type Attachment,\n type AttachmentInput,\n attachments as attachmentsSchema,\n fromJsonColumn,\n type Produced,\n produced as producedSchema,\n type RecommendedThen,\n recommendedThen as recommendedThenSchema,\n type Snapshot,\n snapshot,\n toJsonColumn,\n} from './agent-json.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { getNote } from './notes.ts';\nimport { addReference, getReference } from './references.ts';\nimport { logEvent, type LogEventInput } from './events.ts';\nimport { type AgentStatus, isAgentStatus } from './status/model.ts';\nimport { sanitizeNote } from './status/note.ts';\n\nexport const AGENT_KINDS = ['research', 'plan', 'implement', 'review'] as const;\n\nexport type AgentKind = (typeof AGENT_KINDS)[number];\n\nexport const KIND_REQUIRED = 'kind is required: research, plan, implement or review';\n\nexport const KIND_ACTIONS = {\n research: 'inject',\n plan: 'validate',\n implement: 'apply',\n review: 'triage',\n} as const satisfies Record<AgentKind, string>;\n\nexport type KindAction = (typeof KIND_ACTIONS)[AgentKind];\n\nexport type AgentMode = 'fork' | 'cold';\n\n// The mode a kind launches in unless the launch says otherwise; a review never sees the conversation.\nexport const KIND_MODES: Readonly<Record<AgentKind, AgentMode>> = {\n research: 'fork',\n plan: 'fork',\n implement: 'fork',\n review: 'cold',\n};\n\nexport function agentMode(\n kind: AgentKind,\n choice: { cold?: boolean | undefined; fork?: boolean | undefined } = {},\n): AgentMode {\n if (choice.cold && choice.fork) {\n throw new CarnetError('INVALID_KIND', 'Pass cold or fork, not both');\n }\n if (kind === 'review') {\n if (choice.fork) throw new CarnetError('INVALID_KIND', 'A review always runs cold');\n return 'cold';\n }\n if (choice.cold) return 'cold';\n if (choice.fork) return 'fork';\n return KIND_MODES[kind];\n}\n\nexport function isAgentKind(value: unknown): value is AgentKind {\n return typeof value === 'string' && (AGENT_KINDS as readonly string[]).includes(value);\n}\n\n// An agent keeps its name when promoted, so a kind in its name would turn false.\nconst KIND_WORDS = new Set([\n ...AGENT_KINDS,\n 'rs',\n 'pl',\n 'im',\n 'rv',\n 'impl',\n 'implementation',\n 'planning',\n 'analyze',\n 'analysis',\n 'an',\n]);\n\nexport function kindWordIn(name: string): string | undefined {\n return name\n .toLowerCase()\n .split(/[-_.\\s]+/)\n .find((segment) => KIND_WORDS.has(segment));\n}\n\nexport function checkAgentName(name: string): void {\n const word = kindWordIn(name);\n if (word) throw new CarnetError('INVALID_NAME', kindInNameText(name, word));\n}\n\nfunction kindInNameText(name: string, word: string): string {\n const rest = name\n .split(/[-_.\\s]+/)\n .filter((segment) => segment.toLowerCase() !== word)\n .join('-');\n const example = rest && !kindWordIn(rest) ? rest : 'cache-ttl';\n return `Agent name \"${name}\" holds the kind word \"${word}\", but an agent keeps its name when promoted: name it after its task, like \"${example}\"`;\n}\n\nconst MAIN_TARGET = /^main(?::(.+))?$/;\n\nexport function mainTargetRange(target: string): string | null | undefined {\n const match = MAIN_TARGET.exec(target);\n return match ? (match[1]?.trim() ?? null) : undefined;\n}\n\nexport type AgentContext = 'fork' | 'cold';\n\nexport const CLAUDE_BACKEND = 'claude';\n\nexport interface Agent {\n id: number;\n session: string;\n name: string;\n kind: AgentKind;\n promotedFrom: AgentKind | null;\n // A review's target: an implement agent name, or main[:<range>].\n target: string | null;\n // Another open agent of the session this one waits on; the view derives Waiting on agents from it.\n blockedOn: string | null;\n task: string | null;\n status: AgentStatus;\n note: string | null;\n reportPath: string | null;\n baseCommit: string | null;\n worktree: string | null;\n sandbox: string | null;\n queueOrder: number | null;\n hostAgentId: string | null;\n pendingStatus: AgentStatus | null;\n doneAt: string | null;\n startedAt: string;\n updatedAt: string;\n // When the status last changed, so Waiting on you can put the longest waiting first.\n statusSince: string;\n backend: string | null;\n model: string | null;\n // The backend's own id for the agent: an SDK session, a Cursor agent.\n backendRef: string | null;\n // The resolved kind as launched or last promoted, so a kind edited later never changes it.\n kindDef: Snapshot | null;\n context: AgentContext | null;\n mission: string | null;\n attachments: Attachment[] | null;\n produced: Produced | null;\n recommendedThen: RecommendedThen | null;\n}\n\nexport interface StartAgentInput {\n name: string;\n task: string;\n kind: AgentKind;\n target?: string | undefined;\n baseCommit?: string | undefined;\n worktree?: string | undefined;\n // Absolute, under the run directory's sandboxes folder.\n sandbox?: string | undefined;\n context?: AgentContext | undefined;\n mission?: string | undefined;\n attachments?: Attachment[] | undefined;\n kindDef?: Snapshot | undefined;\n backend?: string | undefined;\n model?: string | undefined;\n}\n\nexport const SANDBOX_KINDS: readonly AgentKind[] = ['research', 'plan'];\n\nexport interface UpdateAgentInput {\n status: AgentStatus;\n // Undefined keeps the current note; null clears it.\n note?: string | null | undefined;\n reportPath?: string | undefined;\n // Undefined keeps the current blocker; null clears it.\n blockedOn?: string | null | undefined;\n}\n\nexport interface FinishAgentInput {\n reportPath: string;\n hasQuestions: boolean;\n produced?: Produced | undefined;\n recommendedThen?: RecommendedThen | undefined;\n}\n\nexport interface ListAgentsOptions {\n includeClosed?: boolean;\n}\n\nexport interface AgentRow {\n id: number;\n session: string;\n name: string;\n kind: AgentKind;\n promoted_from: AgentKind | null;\n target: string | null;\n blocked_on: string | null;\n task: string | null;\n status: AgentStatus;\n note: string | null;\n report_path: string | null;\n base_commit: string | null;\n worktree: string | null;\n sandbox: string | null;\n queue_order: number | null;\n host_agent_id: string | null;\n pending_status: AgentStatus | null;\n done_at: string | null;\n started_at: string;\n updated_at: string;\n status_since: string | null;\n backend: string | null;\n model: string | null;\n backend_ref: string | null;\n kind_def: string | null;\n context: AgentContext | null;\n mission: string | null;\n attachments: string | null;\n produced: string | null;\n recommended_then: string | null;\n}\n\nexport function toAgent(row: AgentRow): Agent {\n return {\n id: Number(row.id),\n session: row.session,\n name: row.name,\n kind: row.kind,\n promotedFrom: row.promoted_from,\n target: row.target,\n blockedOn: row.blocked_on,\n task: row.task,\n status: row.status,\n note: row.note,\n reportPath: row.report_path,\n baseCommit: row.base_commit,\n worktree: row.worktree,\n sandbox: row.sandbox,\n queueOrder: row.queue_order,\n hostAgentId: row.host_agent_id,\n pendingStatus: row.pending_status,\n doneAt: row.done_at,\n startedAt: row.started_at,\n updatedAt: row.updated_at,\n statusSince: row.status_since ?? row.updated_at,\n backend: row.backend,\n model: row.model,\n backendRef: row.backend_ref,\n kindDef: fromJsonColumn(snapshot, row.kind_def),\n context: row.context,\n mission: row.mission,\n attachments: fromJsonColumn(attachmentsSchema, row.attachments),\n produced: fromJsonColumn(producedSchema, row.produced),\n recommendedThen: fromJsonColumn(recommendedThenSchema, row.recommended_then),\n };\n}\n\nexport const REPORTING_NOTE = 'reporting';\nexport const PUBLISH_FALLBACK_MILLISECONDS = 120_000;\n\n// A pin and a waiting age belong to one status: both reset when it changes.\nfunction statusChangeSql(next: string): string {\n return `status_since = CASE WHEN status = ${next} THEN status_since ELSE ? END,\n queue_order = CASE WHEN status = ${next} THEN queue_order ELSE NULL END`;\n}\n\nfunction statusChangeArgs(next: string, at: string): string[] {\n return [next, at, next];\n}\n\n// Closing ends every pending step too: a stray pending_status would reopen the agent on the next read.\nconst CLOSE_SET = `status = 'closed', pending_status = NULL, queue_order = NULL, blocked_on = NULL,\n status_since = ?, updated_at = ?`;\n\n// `where` is a constant SQL clause; its values are bound through `params`, never inlined.\nexport function closeAgentsWhere(\n db: DatabaseSync,\n where: string,\n params: SQLInputValue[],\n at: string,\n): number {\n return Number(\n db\n .prepare(`UPDATE agents SET ${CLOSE_SET} WHERE status != 'closed' AND (${where})`)\n .run(at, at, ...params).changes,\n );\n}\n\nexport function moveAgentStatus(\n ctx: Ctx,\n id: number,\n status: AgentStatus,\n note: string | null,\n): void {\n const at = nowIso(ctx);\n ctx.db\n .prepare(\n `UPDATE agents SET status = ?, note = ?, ${statusChangeSql('?')}, updated_at = ?\n WHERE id = ?`,\n )\n .run(status, note, ...statusChangeArgs(status, at), at, id);\n}\n\nexport function publishPending(ctx: Ctx, id: number, payload?: Record<string, unknown>): void {\n const row = ctx.db\n .prepare('SELECT session, name, pending_status, report_path FROM agents WHERE id = ?')\n .get(id) as Pick<AgentRow, 'session' | 'name' | 'pending_status' | 'report_path'> | undefined;\n if (!row?.pending_status) return;\n ctx.db\n .prepare(\n `UPDATE agents SET status = pending_status, pending_status = NULL, note = NULL,\n ${statusChangeSql('pending_status')}, updated_at = ?\n WHERE id = ? AND status != 'closed'`,\n )\n .run(nowIso(ctx), nowIso(ctx), id);\n logEvent(ctx, row.session, {\n type: 'finished',\n agent: row.name,\n agentId: id,\n link: row.report_path ?? undefined,\n payload,\n });\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 id FROM agents WHERE session = ? AND pending_status IS NOT NULL AND done_at <= ? AND status != 'closed'\",\n )\n .all(session, before) as unknown as Pick<AgentRow, 'id'>[];\n for (const row of rows) publishPending(ctx, Number(row.id));\n}\n\n// Closed agents keep their rows, so a name can match several: the open one, else the latest.\nexport const AGENT_BY_NAME_SQL = `SELECT * FROM agents WHERE session = ? AND name = ?\n ORDER BY status = 'closed', id DESC LIMIT 1`;\n\nexport function getAgent(ctx: Ctx, session: string, name: string): Agent | undefined {\n publishOverdue(ctx, session);\n const row = ctx.db.prepare(AGENT_BY_NAME_SQL).get(session, name) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nexport function agentIdOf(ctx: Ctx, session: string, name: string): number | undefined {\n const row = ctx.db.prepare(AGENT_BY_NAME_SQL).get(session, name) as AgentRow | undefined;\n return row && Number(row.id);\n}\n\nexport function requireAgentId(ctx: Ctx, session: string, name: string): number {\n const id = agentIdOf(ctx, session, name);\n if (id === undefined)\n throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n return id;\n}\n\nexport function getAgentById(ctx: Ctx, id: number): Agent | undefined {\n const row = ctx.db.prepare('SELECT * FROM agents WHERE id = ?').get(id) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nfunction agentById(ctx: Ctx, id: number): Agent {\n const agent = getAgentById(ctx, id);\n if (!agent) throw new CarnetError('AGENT_NOT_FOUND', `No agent with id ${id}`);\n return agent;\n}\n\nexport function requireAgent(ctx: Ctx, session: string, name: string): Agent {\n const agent = getAgent(ctx, session, name);\n if (!agent) throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n return agent;\n}\n\n// A review reads a finished diff: a running target is still moving, a closed one is already in main.\nfunction checkReviewTarget(ctx: Ctx, session: string, target: string): void {\n if (mainTargetRange(target) !== undefined) return;\n const agent = getAgent(ctx, session, target);\n if (!agent || agent.kind !== 'implement') {\n throw new CarnetError(\n 'INVALID_TARGET',\n `Target \"${target}\" is not an implement agent of this session; use its name, or main[:<range>]`,\n );\n }\n if (agent.status === 'running') {\n throw new CarnetError('INVALID_TARGET', `Target \"${target}\" is still running`);\n }\n if (agent.status === 'closed') {\n throw new CarnetError(\n 'INVALID_TARGET',\n `Target \"${target}\" is closed; review main[:<range>] instead`,\n );\n }\n}\n\nexport function startAgent(ctx: Ctx, session: string, input: StartAgentInput): Agent {\n const name = sanitizeNote(input.name);\n checkAgentName(name);\n const kind = input.kind;\n if (!isAgentKind(kind)) throw new CarnetError('INVALID_KIND', KIND_REQUIRED);\n if (input.worktree && kind !== 'implement') {\n throw new CarnetError(\n 'INVALID_KIND',\n `A worktree means an implement agent: start ${name} with kind implement, or promote a research or plan agent with agent_promote`,\n );\n }\n const target = input.target?.trim() || null;\n if (kind === 'review' && !target) {\n throw new CarnetError(\n 'INVALID_TARGET',\n 'A review needs a target: an implement agent name, or main[:<range>]',\n );\n }\n if (kind !== 'review' && target) {\n throw new CarnetError('INVALID_TARGET', 'Only a review agent takes a target');\n }\n if (target) checkReviewTarget(ctx, session, target);\n if (input.sandbox) checkSandbox(ctx, session, name, kind, input.sandbox);\n const existing = getAgent(ctx, session, name);\n if (existing && existing.status !== 'closed') {\n throw new CarnetError('AGENT_EXISTS', `Agent \"${name}\" is already open in this session`);\n }\n const at = nowIso(ctx);\n const result = ctx.db\n .prepare(\n `INSERT INTO agents (session, name, kind, target, task, status, base_commit, worktree,\n sandbox, started_at, updated_at, status_since, backend, model, context, mission,\n attachments, kind_def)\n VALUES (?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n session,\n name,\n kind,\n target,\n input.task,\n input.baseCommit ?? null,\n input.worktree ?? null,\n input.sandbox ?? null,\n at,\n at,\n at,\n input.backend ?? CLAUDE_BACKEND,\n input.model ?? null,\n input.context ?? (kind === 'review' ? 'cold' : null),\n input.mission?.trim() || null,\n toJsonColumn(attachmentsSchema, input.attachments, 'attachments'),\n toJsonColumn(snapshot, input.kindDef, 'kind_def'),\n );\n const id = Number(result.lastInsertRowid);\n logEvent(ctx, session, { type: 'started', agent: name, agentId: id, note: input.task });\n return agentById(ctx, id);\n}\n\n// Agents named in attachments resolve in this session, a closed one included: a review is closed\n// by the triage that spawns agents for its findings.\nexport function resolveAttachments(\n ctx: Ctx,\n session: string,\n inputs: readonly AttachmentInput[],\n runDirectory?: string,\n): Attachment[] {\n const idOf = (agent: number | string): number =>\n typeof agent === 'number' ? agent : requireAgentId(ctx, session, agent);\n return inputs.map((input): Attachment => {\n switch (input.type) {\n case 'doc':\n return {\n type: 'ref',\n id: addReference(ctx, session, { path: input.path, scope: 'agent', runDirectory }).id,\n };\n case 'ref': {\n const reference = getReference(ctx, input.id);\n if (reference?.session !== session || reference.removedAt) {\n throw new CarnetError('INVALID_ATTACHMENT', `No reference ${input.id} in this session`);\n }\n return input;\n }\n case 'notes': {\n const unknown = (input.ids ?? []).filter((id) => !getNote(ctx, id));\n if (unknown.length) {\n throw new CarnetError('INVALID_ATTACHMENT', `No note ${unknown.join(', ')}`);\n }\n return input;\n }\n case 'deliverable':\n case 'for_main':\n return { ...input, agent: idOf(input.agent) };\n case 'findings': {\n const review = getAgentById(ctx, idOf(input.review));\n if (review?.kind !== 'review' || review.session !== session) {\n throw new CarnetError(\n 'INVALID_ATTACHMENT',\n `Findings come from a review agent of this session, not ${String(input.review)}`,\n );\n }\n return { ...input, review: review.id };\n }\n }\n });\n}\n\n// Adds to what an open agent starts from, skipping what it already has.\nexport function addAttachments(ctx: Ctx, id: number, added: readonly Attachment[]): Agent {\n const agent = agentById(ctx, id);\n const current = agent.attachments ?? [];\n const known = new Set(current.map((attachment) => JSON.stringify(attachment)));\n const next = [\n ...current,\n ...added.filter((attachment) => !known.has(JSON.stringify(attachment))),\n ];\n ctx.db\n .prepare('UPDATE agents SET attachments = ? WHERE id = ?')\n .run(toJsonColumn(attachmentsSchema, next, 'attachments'), id);\n return agentById(ctx, id);\n}\n\nfunction checkSandbox(\n ctx: Ctx,\n session: string,\n name: string,\n kind: AgentKind,\n sandbox: string,\n): void {\n if (!SANDBOX_KINDS.includes(kind)) {\n throw new CarnetError(\n 'INVALID_KIND',\n `Only a research or plan agent gets a sandbox; ${name} is ${kind}`,\n );\n }\n const holder = ctx.db\n .prepare(\n `SELECT agents.name FROM agents JOIN sessions ON sessions.id = agents.session\n WHERE agents.sandbox = ? AND sessions.workspace = (SELECT workspace FROM sessions WHERE id = ?)\n AND NOT (agents.session = ? AND agents.name = ? AND agents.status != 'closed')`,\n )\n .get(sandbox, session, session, name) as { name: string } | undefined;\n if (holder) {\n throw new CarnetError('INVALID_SANDBOX', `${sandbox} is already the sandbox of ${holder.name}`);\n }\n}\n\n// Cleared once the folder is gone, so a later agent may take the same path.\nexport function clearSandbox(ctx: Ctx, id: number): void {\n ctx.db.prepare('UPDATE agents SET sandbox = NULL WHERE id = ?').run(id);\n}\n\n// Without a session: every session of the workspace.\nexport function closedSandboxes(\n ctx: Ctx,\n session?: string,\n): { id: number; session: string; name: string; sandbox: string }[] {\n const where = session\n ? 'agents.session = ?'\n : 'agents.session IN (SELECT id FROM sessions WHERE workspace = ?)';\n return ctx.db\n .prepare(\n `SELECT id, session, name, sandbox FROM agents\n WHERE ${where} AND status = 'closed' AND sandbox IS NOT NULL`,\n )\n .all(session ?? ctx.workspace) as unknown as {\n id: number;\n session: string;\n name: string;\n sandbox: string;\n }[];\n}\n\nfunction checkBlocker(ctx: Ctx, session: string, name: string, blocker: string): void {\n if (blocker === name) {\n throw new CarnetError('INVALID_BLOCKER', `Agent \"${name}\" can't wait on itself`);\n }\n const seen = new Set([name]);\n let current = getAgent(ctx, session, blocker);\n if (!current || current.status === 'closed') {\n throw new CarnetError('INVALID_BLOCKER', `\"${blocker}\" is not an open agent of this session`);\n }\n while (current?.blockedOn && current.status !== 'closed') {\n if (seen.has(current.blockedOn)) {\n throw new CarnetError(\n 'INVALID_BLOCKER',\n `\"${blocker}\" already waits on \"${name}\", directly or through another agent`,\n );\n }\n seen.add(current.name);\n current = getAgent(ctx, session, current.blockedOn);\n }\n}\n\nexport function updateAgent(\n ctx: Ctx,\n session: string,\n name: string,\n input: UpdateAgentInput,\n): Agent {\n const current = requireAgent(ctx, session, name);\n if (!isAgentStatus(input.status) || input.status === 'closed') {\n throw new CarnetError(\n 'INVALID_STATUS',\n `Invalid agent status \"${input.status}\"; use agent_drop to close`,\n );\n }\n let note: string | null;\n if (input.note !== undefined) note = input.note === null ? null : sanitizeNote(input.note);\n else note = current.status === 'running' && input.status !== 'running' ? null : current.note;\n let blockedOn = current.blockedOn;\n if (input.blockedOn !== undefined) {\n blockedOn = input.blockedOn === null ? null : sanitizeNote(input.blockedOn);\n if (blockedOn) checkBlocker(ctx, session, name, blockedOn);\n }\n if (current.pendingStatus) publishPending(ctx, current.id);\n ctx.db\n .prepare(\n `UPDATE agents SET note = ?, ${statusChangeSql('?')}, status = ?,\n report_path = COALESCE(?, report_path), blocked_on = ?, updated_at = ? WHERE id = ?`,\n )\n .run(\n note,\n ...statusChangeArgs(input.status, nowIso(ctx)),\n input.status,\n input.reportPath ?? null,\n blockedOn,\n nowIso(ctx),\n current.id,\n );\n return agentById(ctx, current.id);\n}\n\n// A review's findings wait in 👀 review for triage.\nexport function statusWhenDone(kind: AgentKind, hasQuestions: boolean): AgentStatus {\n if (hasQuestions) return 'answer';\n return kind === 'implement' ? 'apply' : 'review';\n}\n\nexport function finishAgent(\n ctx: Ctx,\n session: string,\n name: string,\n input: FinishAgentInput,\n): Agent {\n const agent = requireAgent(ctx, session, name);\n const status = statusWhenDone(agent.kind, input.hasQuestions);\n const at = nowIso(ctx);\n // A paired fork keeps writing its final message after agent_done; SubagentStop marks the real end.\n ctx.db\n .prepare(\n `UPDATE agents SET pending_status = ?, note = ?, report_path = ?, done_at = ?, updated_at = ?,\n produced = COALESCE(?, produced), recommended_then = COALESCE(?, recommended_then)\n WHERE id = ?`,\n )\n .run(\n status,\n REPORTING_NOTE,\n input.reportPath,\n at,\n at,\n toJsonColumn(producedSchema, input.produced, 'produced'),\n toJsonColumn(recommendedThenSchema, input.recommendedThen, 'recommended_then'),\n agent.id,\n );\n if (!agent.hostAgentId) publishPending(ctx, agent.id);\n return agentById(ctx, agent.id);\n}\n\n// Once the questions are answered, a plan agent's plan still waits for validation.\nexport function statusAfterAnswers(kind: AgentKind): 'apply' | 'review' {\n return kind === 'implement' ? 'apply' : 'review';\n}\n\nexport function closeAgent(\n ctx: Ctx,\n session: string,\n name: string,\n event: Omit<LogEventInput, 'agent' | 'agentId'>,\n): Agent {\n const agent = requireAgent(ctx, session, name);\n ctx.db\n .prepare(`UPDATE agents SET ${CLOSE_SET} WHERE id = ?`)\n .run(nowIso(ctx), nowIso(ctx), agent.id);\n logEvent(ctx, session, { ...event, agent: agent.name, agentId: agent.id });\n return agentById(ctx, agent.id);\n}\n\nexport function dropAgent(ctx: Ctx, session: string, name: string, reason?: string): Agent {\n return closeAgent(ctx, session, name, { type: 'dropped', note: reason });\n}\n\nconst PROMOTIONS: Readonly<Partial<Record<AgentKind, readonly AgentKind[]>>> = {\n research: ['plan', 'implement'],\n plan: ['implement'],\n};\n\nexport const PROMOTE_KIND_REQUIRED =\n 'kind is required: plan or implement for a research agent, implement for a plan one';\n\nexport interface PromoteAgentInput {\n kind: AgentKind | undefined;\n worktree?: string | undefined;\n baseCommit?: string | undefined;\n // The target kind resolved; the previous snapshot goes to the promoted event.\n kindDef?: Snapshot | undefined;\n // A cold promotion is a new launch of the same agent, briefed instead of resumed.\n cold?: boolean | undefined;\n fork?: boolean | undefined;\n mission?: string | undefined;\n}\n\nexport function promoteAgent(\n ctx: Ctx,\n session: string,\n name: string,\n input: PromoteAgentInput,\n): Agent {\n const agent = requireAgent(ctx, session, name);\n const target = input.kind;\n if (!isAgentKind(target)) throw new CarnetError('INVALID_KIND', PROMOTE_KIND_REQUIRED);\n const allowed = PROMOTIONS[agent.kind] ?? [];\n if (!allowed.includes(target)) {\n throw new CarnetError(\n 'INVALID_KIND',\n allowed.length === 0\n ? `A ${agent.kind} agent is never promoted; only research and plan are`\n : `${name} is ${agent.kind}: it is promoted to ${allowed.join(' or ')}, not ${target}`,\n );\n }\n if (input.worktree && target !== 'implement') {\n throw new CarnetError(\n 'INVALID_KIND',\n `A worktree means an implement agent: promote ${name} with kind implement`,\n );\n }\n // The deliverable and the next move belonged to the previous contract.\n ctx.db\n .prepare(\n `UPDATE agents SET kind = ?, promoted_from = ?, status = 'running',\n pending_status = NULL, note = NULL, blocked_on = NULL, worktree = COALESCE(?, worktree),\n base_commit = COALESCE(?, base_commit), queue_order = NULL, status_since = ?, updated_at = ?,\n kind_def = ?, produced = NULL, recommended_then = NULL\n WHERE id = ?`,\n )\n .run(\n target,\n agent.kind,\n input.worktree ?? null,\n input.baseCommit ?? null,\n nowIso(ctx),\n nowIso(ctx),\n toJsonColumn(snapshot, input.kindDef, 'kind_def'),\n agent.id,\n );\n if (input.cold) {\n ctx.db\n .prepare(\n `UPDATE agents SET context = 'cold', host_agent_id = NULL, launch_requested_at = NULL,\n mission = COALESCE(?, mission)\n WHERE id = ?`,\n )\n .run(input.mission?.trim() || null, agent.id);\n }\n logEvent(ctx, session, {\n type: 'promoted',\n agent: agent.name,\n agentId: agent.id,\n note: `${agent.kind} to ${target}`,\n payload: {\n from: agent.kind,\n to: target,\n kind_def: agent.kindDef,\n produced: agent.produced,\n recommended_then: agent.recommendedThen,\n },\n });\n return agentById(ctx, agent.id);\n}\n\nexport interface KindStep {\n kind: string;\n kindDef: Snapshot | null;\n at: string | null;\n}\n\n// Every kind the agent held, oldest first, each with the contract it ran under.\nexport function kindHistory(ctx: Ctx, id: number): KindStep[] {\n const agent = agentById(ctx, id);\n const rows = ctx.db\n .prepare(\"SELECT at, payload FROM events WHERE agent_id = ? AND type = 'promoted' ORDER BY id\")\n .all(id) as { at: string; payload: string | null }[];\n const steps: KindStep[] = [];\n let since: string | null = agent.startedAt;\n for (const row of rows) {\n const payload = fromJsonColumn(snapshot, row.payload);\n const kind = typeof payload?.from === 'string' ? payload.from : (agent.promotedFrom ?? '');\n const kindDef = snapshot.safeParse(payload?.kind_def);\n steps.push({ kind, kindDef: kindDef.success ? kindDef.data : null, at: since });\n since = row.at;\n }\n steps.push({ kind: agent.kind, kindDef: agent.kindDef, at: since });\n return steps;\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 = ? AND status != 'closed'\",\n );\n names.forEach((name, index) => {\n update.run(index + 1, at, session, sanitizeNote(name));\n });\n return listAgents(ctx, session);\n}\n","import { agentIdOf, checkAgentName, requireAgentId } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { sanitizeNote } from './status/note.ts';\n\nexport const FINDING_SEVERITIES = ['blocking', 'to_fix', 'suggestion'] as const;\nexport type FindingSeverity = (typeof FINDING_SEVERITIES)[number];\n\nexport const FINDING_DECISIONS = [\n 'fix',\n 'sent',\n 'fixed',\n 'ignored',\n 'spawned',\n 'deferred',\n] as const;\nexport type FindingDecision = (typeof FINDING_DECISIONS)[number];\n\nexport const FINDING_ROUTES = ['send back', 'in main', 'implement', 'plan', 'research'] as const;\nexport type FindingRoute = (typeof FINDING_ROUTES)[number];\n\nexport const SPAWN_KINDS = ['implement', 'plan', 'research'] as const;\nexport type SpawnKind = (typeof SPAWN_KINDS)[number];\n\n// Unapplied work goes back to its author; once applied, a suggestion is small enough for the\n// main agent and anything heavier gets its own implement agent. The reviewer's own route wins\n// while it is still possible.\nexport function recommendedRoute(\n severity: FindingSeverity,\n canSendBack: boolean,\n proposed?: FindingRoute | null,\n): FindingRoute {\n if (proposed && (proposed !== 'send back' || canSendBack)) return proposed;\n if (canSendBack) return 'send back';\n return severity === 'suggestion' ? 'in main' : 'implement';\n}\n\nexport interface FindingInput {\n severity: FindingSeverity;\n location?: string | undefined;\n text: string;\n fix?: string | undefined;\n route?: FindingRoute | undefined;\n}\n\nexport interface Finding {\n n: number;\n total: number;\n severity: FindingSeverity;\n location: string | null;\n text: string;\n fix: string | null;\n decision: FindingDecision | null;\n reason: string | null;\n // The reviewer's proposed route.\n route: FindingRoute | null;\n spawnName: string | null;\n spawnKind: SpawnKind | null;\n spawnedAgent: number | null;\n deliveredAt: string | null;\n}\n\nexport interface DecisionInput {\n n: number;\n decision: FindingDecision;\n reason?: string | undefined;\n // Spawned only: the planned agent and its kind.\n agent?: string | undefined;\n kind?: SpawnKind | undefined;\n}\n\n// open: undecided, chosen to fix or deferred; undecided: no decision yet.\nexport type FindingFilter = 'all' | 'open' | 'undecided';\n\ninterface FindingRow {\n n: number;\n severity: FindingSeverity;\n location: string | null;\n text: string;\n fix: string | null;\n decision: FindingDecision | null;\n reason: string | null;\n route: FindingRoute | null;\n spawn_name: string | null;\n spawn_kind: SpawnKind | null;\n spawned_agent: number | null;\n delivered_at: string | null;\n}\n\nexport function isFindingDecision(value: unknown): value is FindingDecision {\n return typeof value === 'string' && (FINDING_DECISIONS as readonly string[]).includes(value);\n}\n\nexport function isFindingRoute(value: unknown): value is FindingRoute {\n return typeof value === 'string' && (FINDING_ROUTES as readonly string[]).includes(value);\n}\n\n// A deferred finding is put off, not settled: its review stays open.\nexport function isOpen(finding: { decision: FindingDecision | null }): boolean {\n return finding.decision === null || finding.decision === 'fix' || finding.decision === 'deferred';\n}\n\nconst FINDING_COLUMNS =\n 'n, severity, location, text, fix, decision, reason, route, spawn_name, spawn_kind, spawned_agent, delivered_at';\n\n// Deferred findings come after the others, so the ones never asked are asked first.\nconst OPEN_ORDER = (finding: Finding) => (finding.decision === 'deferred' ? 1 : 0);\n\nfunction toFinding(row: FindingRow, total: number): Finding {\n return {\n n: row.n,\n total,\n severity: row.severity,\n location: row.location,\n text: row.text,\n fix: row.fix,\n decision: row.decision,\n reason: row.reason,\n route: row.route,\n spawnName: row.spawn_name,\n spawnKind: row.spawn_kind,\n spawnedAgent: row.spawned_agent === null ? null : Number(row.spawned_agent),\n deliveredAt: row.delivered_at,\n };\n}\n\nexport function findingsOf(ctx: Ctx, id: number): Finding[] {\n const rows = ctx.db\n .prepare(`SELECT ${FINDING_COLUMNS} FROM review_findings WHERE agent_id = ? ORDER BY n`)\n .all(id) as unknown as FindingRow[];\n return rows.map((row) => toFinding(row, rows.length));\n}\n\nexport function listFindings(\n ctx: Ctx,\n session: string,\n agent: string,\n filter: FindingFilter = 'all',\n): Finding[] {\n const id = agentIdOf(ctx, session, agent);\n if (id === undefined) return [];\n const all = findingsOf(ctx, id);\n if (filter === 'all') return all;\n if (filter === 'undecided') return all.filter((finding) => finding.decision === null);\n return all\n .filter(isOpen)\n .sort((left, right) => OPEN_ORDER(left) - OPEN_ORDER(right) || left.n - right.n);\n}\n\n// Numbered blocking first, so the order findings are handled in is their numbering.\nexport function replaceFindings(\n ctx: Ctx,\n session: string,\n agent: string,\n inputs: readonly FindingInput[],\n): Finding[] {\n const badRoutes = inputs.filter(\n (input) => input.route !== undefined && !isFindingRoute(input.route),\n );\n if (badRoutes.length) {\n throw new CarnetError(\n 'INVALID_ROUTE',\n `Unknown route ${badRoutes.map((input) => `\"${String(input.route)}\"`).join(', ')}: use ${FINDING_ROUTES.join(', ')}`,\n );\n }\n const sorted = [...inputs].sort(\n (a, b) => FINDING_SEVERITIES.indexOf(a.severity) - FINDING_SEVERITIES.indexOf(b.severity),\n );\n const id = requireAgentId(ctx, session, agent);\n ctx.db.prepare('DELETE FROM review_findings WHERE agent_id = ?').run(id);\n const insert = ctx.db.prepare(\n `INSERT INTO review_findings (agent_id, n, severity, location, text, fix, route)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n );\n sorted.forEach((input, index) => {\n insert.run(\n id,\n index + 1,\n input.severity,\n input.location?.trim() || null,\n input.text.trim(),\n input.fix?.trim() || null,\n input.route ?? null,\n );\n });\n return listFindings(ctx, session, agent);\n}\n\nexport function decideFindings(\n ctx: Ctx,\n session: string,\n agent: string,\n decisions: readonly DecisionInput[],\n override = false,\n): Finding[] {\n const current = new Map(listFindings(ctx, session, agent).map((finding) => [finding.n, finding]));\n const missing = decisions.filter((item) => !current.has(item.n)).map((item) => item.n);\n if (missing.length) {\n throw new CarnetError(\n 'FINDING_NOT_FOUND',\n `No finding ${missing.join(', ')} for ${agent}; review_findings lists them`,\n );\n }\n const unknown = decisions.filter((item) => !isFindingDecision(item.decision));\n if (unknown.length) {\n throw new CarnetError(\n 'INVALID_DECISION',\n `Unknown decision ${unknown.map((item) => `\"${String(item.decision)}\"`).join(', ')}: use ${FINDING_DECISIONS.join(', ')}`,\n );\n }\n const unexplained = decisions.filter(\n (item) => item.decision === 'ignored' && !item.reason?.trim(),\n );\n if (unexplained.length) {\n throw new CarnetError(\n 'REASON_REQUIRED',\n `Ignoring finding ${unexplained.map((item) => item.n).join(', ')} needs a short reason`,\n );\n }\n const unplanned = decisions.filter(\n (item) =>\n item.decision === 'spawned' &&\n (!item.agent?.trim() || !(SPAWN_KINDS as readonly string[]).includes(item.kind ?? '')),\n );\n if (unplanned.length) {\n throw new CarnetError(\n 'INVALID_DECISION',\n `Spawning finding ${unplanned.map((item) => item.n).join(', ')} needs the planned agent name and its kind (${SPAWN_KINDS.join(', ')})`,\n );\n }\n const stray = decisions.filter(\n (item) => item.decision !== 'spawned' && (item.agent !== undefined || item.kind !== undefined),\n );\n if (stray.length) {\n throw new CarnetError(\n 'INVALID_DECISION',\n `An agent and a kind go with spawned only (finding ${stray.map((item) => item.n).join(', ')})`,\n );\n }\n const settled = override\n ? []\n : decisions.filter((item) => !isOpen(current.get(item.n) as Finding)).map((item) => item.n);\n if (settled.length) {\n throw new CarnetError(\n 'FINDING_DECIDED',\n `Finding ${settled.join(', ')} of ${agent} is already decided`,\n 'pass override to correct a mistake',\n );\n }\n for (const item of decisions) {\n if (item.decision === 'spawned') checkAgentName(sanitizeNote(item.agent ?? ''));\n }\n const id = requireAgentId(ctx, session, agent);\n const at = nowIso(ctx);\n // The same spawn name and kind keep the agent already linked; a reason-only correction too.\n const update = ctx.db.prepare(\n `UPDATE review_findings SET decision = ?, reason = ?, decided_at = ?, spawn_name = ?,\n spawn_kind = ?,\n spawned_agent = CASE WHEN ? = 1 AND spawn_name = ? AND spawn_kind = ? THEN spawned_agent\n ELSE NULL END\n WHERE agent_id = ? AND n = ?`,\n );\n for (const item of decisions) {\n const spawned = item.decision === 'spawned';\n const spawnName = spawned ? sanitizeNote(item.agent ?? '') : null;\n const spawnKind = spawned ? (item.kind ?? null) : null;\n update.run(\n item.decision,\n item.reason?.trim() || null,\n at,\n spawnName,\n spawnKind,\n spawned ? 1 : 0,\n spawnName,\n spawnKind,\n id,\n item.n,\n );\n }\n return listFindings(ctx, session, agent);\n}\n\n// Sent findings not yet handed to their target: one message per target per round.\nexport function deliverSent(ctx: Ctx, session: string, agent: string): Finding[] {\n const id = requireAgentId(ctx, session, agent);\n const due = findingsOf(ctx, id).filter(\n (finding) => finding.decision === 'sent' && finding.deliveredAt === null,\n );\n if (due.length) {\n ctx.db\n .prepare(\n \"UPDATE review_findings SET delivered_at = ? WHERE agent_id = ? AND decision = 'sent' AND delivered_at IS NULL\",\n )\n .run(nowIso(ctx), id);\n }\n return due;\n}\n\nexport function checkSpawnLink(\n ctx: Ctx,\n reviewId: number,\n numbers: readonly number[],\n spawnName: string,\n spawnKind: string,\n): void {\n const findings = findingsOf(ctx, reviewId);\n const missing = numbers.filter((n) => !findings.some((finding) => finding.n === n));\n if (missing.length) {\n throw new CarnetError(\n 'FINDING_NOT_FOUND',\n `No finding ${missing.join(', ')} in that review; review_findings lists them`,\n );\n }\n const unspawned = findings.filter(\n (finding) =>\n numbers.includes(finding.n) &&\n (finding.decision !== 'spawned' ||\n finding.spawnName !== spawnName ||\n finding.spawnKind !== spawnKind),\n );\n if (unspawned.length) {\n throw new CarnetError(\n 'INVALID_ATTACHMENT',\n `Finding ${unspawned.map((finding) => finding.n).join(', ')} is not spawned for ${spawnName} as ${spawnKind}`,\n `record it with review_decide spawned for ${spawnName} as ${spawnKind} first`,\n );\n }\n}\n\nexport function linkSpawned(\n ctx: Ctx,\n reviewId: number,\n numbers: readonly number[],\n agentId: number,\n spawnKind: string,\n): void {\n const link = ctx.db.prepare(\n `UPDATE review_findings SET spawned_agent = ?\n WHERE agent_id = ? AND n = ? AND spawned_agent IS NULL AND spawn_kind = ?`,\n );\n for (const n of numbers) link.run(agentId, reviewId, n, spawnKind);\n}\n\nexport function formatFinding(finding: Finding): string {\n const location = finding.location ? ` ${finding.location}` : '';\n const fix = finding.fix ? ` (fix: ${finding.fix})` : '';\n return `${finding.n}/${finding.total} [${finding.severity}]${location} — ${finding.text}${fix}`;\n}\n\nexport function renderFindings(findings: readonly Finding[]): string {\n const lines = findings.map((finding) => {\n const location = finding.location ? ` \\`${finding.location}\\`` : '';\n const fix = finding.fix ? `\\n Fix: ${finding.fix}` : '';\n return `${finding.n}. **${finding.severity}**${location}: ${finding.text}${fix}`;\n });\n return `## Findings\\n\\n${lines.join('\\n')}`;\n}\n","import type { Ctx } from './context.ts';\nimport type { Workspace } from './workspace/locate.ts';\nimport {\n compareNotes,\n DEFAULT_HALF_LIFE_DAYS,\n listNotes,\n NOTE_KINDS,\n type NoteKind,\n type WeightedNote,\n} from './notes.ts';\n\nexport const MEMORY_MAX_CHARACTERS = 1000;\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\nexport function startNotes(\n ctx: Ctx,\n repo: string | null,\n halfLifeDays = DEFAULT_HALF_LIFE_DAYS,\n): WeightedNote[] {\n const byId = new Map<number, WeightedNote>();\n const add = (notes: WeightedNote[]) => notes.forEach((note) => byId.set(note.id, note));\n add(listNotes(ctx, { general: true, halfLifeDays }));\n if (repo) add(listNotes(ctx, { repo, halfLifeDays }));\n return [...byId.values()].sort(compareNotes);\n}\n\n// Repo notes stay out of context until asked for; this line says they exist.\nexport function repoNotesIndex(ctx: Ctx, shown: WeightedNote[]): string | undefined {\n const shownIds = new Set(shown.map((note) => note.id));\n const counts = new Map<string, number>();\n for (const note of listNotes(ctx)) {\n if (shownIds.has(note.id)) continue;\n for (const repo of note.repos) counts.set(repo, (counts.get(repo) ?? 0) + 1);\n }\n if (!counts.size) return undefined;\n const repos = [...counts].sort(([first], [second]) => first.localeCompare(second));\n return `Repo notes on demand (note_list repo): ${repos.map(([repo, count]) => `${repo} ${count}`).join(', ')}`;\n}\n\nexport function memoryPart(\n ctx: Ctx,\n title: string,\n notes: WeightedNote[],\n maxCharacters = MEMORY_MAX_CHARACTERS,\n): string | undefined {\n const index = repoNotesIndex(ctx, notes);\n if (!notes.length) return index;\n const budget = index ? maxCharacters - index.length - 2 : maxCharacters;\n const text = renderMemory({ title, notes }, Math.max(budget, 1));\n return index ? `${text}\\n\\n${index}` : text;\n}\n\nfunction workspaceTitle(workspace: Workspace | null): string {\n return workspace ? `Rucher memory of the ${workspace.name} workspace` : 'Rucher memory';\n}\n\nexport function sessionStartMemory(\n ctx: Ctx,\n workspace: Workspace | null,\n session: { repo: string | null },\n options: MemoryOptions = {},\n): string | undefined {\n const notes = startNotes(ctx, session.repo, options.halfLifeDays);\n return memoryPart(ctx, workspaceTitle(workspace), notes, options.maxCharacters);\n}\n","import { agentIdOf, requireAgentId } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\n\nexport const MAX_ALTERNATIVES = 3;\n\nexport interface QuestionInput {\n text: string;\n context?: string | undefined;\n recommendation: string;\n alternatives?: readonly string[] | undefined;\n}\n\nexport interface Question {\n n: number;\n total: number;\n text: string;\n context: string | null;\n recommendation: string;\n alternatives: string[];\n answer: string | null;\n answeredAt: string | null;\n}\n\nexport interface AnswerInput {\n n: number;\n answer: string;\n}\n\ninterface QuestionRow {\n n: number;\n text: string;\n context: string | null;\n recommendation: string;\n alternatives: string;\n answer: string | null;\n answered_at: string | null;\n}\n\nexport function listQuestions(\n ctx: Ctx,\n session: string,\n agent: string,\n openOnly = false,\n): Question[] {\n const id = agentIdOf(ctx, session, agent);\n return id === undefined ? [] : questionsOf(ctx, id, openOnly);\n}\n\nexport function questionsOf(ctx: Ctx, id: number, openOnly = false): Question[] {\n const rows = ctx.db\n .prepare('SELECT * FROM agent_questions WHERE agent_id = ? ORDER BY n')\n .all(id) as unknown as QuestionRow[];\n const total = rows.length;\n return rows\n .filter((row) => !openOnly || row.answer === null)\n .map((row) => ({\n n: row.n,\n total,\n text: row.text,\n context: row.context,\n recommendation: row.recommendation,\n alternatives: JSON.parse(row.alternatives) as string[],\n answer: row.answer,\n answeredAt: row.answered_at,\n }));\n}\n\n// A revised plan replaces the questions still open; answered ones stay, so numbering goes on.\nexport function addQuestions(\n ctx: Ctx,\n session: string,\n agent: string,\n inputs: readonly QuestionInput[],\n): Question[] {\n for (const input of inputs) {\n if ((input.alternatives?.length ?? 0) > MAX_ALTERNATIVES) {\n throw new CarnetError(\n 'INVALID_QUESTIONS',\n `A question takes at most ${MAX_ALTERNATIVES} alternatives; list more in its text`,\n );\n }\n }\n const id = requireAgentId(ctx, session, agent);\n ctx.db.prepare('DELETE FROM agent_questions WHERE agent_id = ? AND answer IS NULL').run(id);\n const last = ctx.db\n .prepare('SELECT COALESCE(MAX(n), 0) AS n FROM agent_questions WHERE agent_id = ?')\n .get(id) as { n: number };\n const insert = ctx.db.prepare(\n `INSERT INTO agent_questions (agent_id, n, text, context, recommendation, alternatives)\n VALUES (?, ?, ?, ?, ?, ?)`,\n );\n inputs.forEach((input, index) => {\n insert.run(\n id,\n last.n + index + 1,\n input.text.trim(),\n input.context?.trim() || null,\n input.recommendation.trim(),\n JSON.stringify(input.alternatives ?? []),\n );\n });\n return listQuestions(ctx, session, agent);\n}\n\nexport function answerQuestions(\n ctx: Ctx,\n session: string,\n agent: string,\n answers: readonly AnswerInput[],\n): Question[] {\n const known = new Set(listQuestions(ctx, session, agent).map((question) => question.n));\n const missing = answers.filter((answer) => !known.has(answer.n)).map((answer) => answer.n);\n if (missing.length) {\n throw new CarnetError(\n 'QUESTION_NOT_FOUND',\n `No question ${missing.join(', ')} for ${agent}; agent_questions lists them`,\n );\n }\n const id = requireAgentId(ctx, session, agent);\n const at = nowIso(ctx);\n const update = ctx.db.prepare(\n 'UPDATE agent_questions SET answer = ?, answered_at = ? WHERE agent_id = ? AND n = ?',\n );\n for (const answer of answers) update.run(answer.answer.trim(), at, id, answer.n);\n return listQuestions(ctx, session, agent);\n}\n\nexport function renderQuestions(questions: readonly Question[]): string {\n const blocks = questions.map((question) => {\n const lines = [`${question.n}. ${question.text}`];\n if (question.context) lines.push(` Context: ${question.context}`);\n lines.push(` Recommendation: ${question.recommendation}`);\n if (question.alternatives.length) {\n lines.push(` Alternatives: ${question.alternatives.join(' · ')}`);\n }\n return lines.join('\\n');\n });\n return `## Questions\\n\\n${blocks.join('\\n')}`;\n}\n","import { appendFileSync, existsSync, readFileSync } from 'node:fs';\n\nconst HEADING = /^##\\s+(.+?)\\s*$/;\nconst FENCE = /^\\s*(```|~~~)/;\n\nfunction normalize(text: string): string {\n return text\n .toLowerCase()\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '');\n}\n\nexport function hasSection(markdown: string, names: readonly string[]): boolean {\n return extractSection(markdown, names) !== undefined;\n}\n\n// A `## ` line inside a code fence is an example, not a section of the report.\nfunction headings(lines: readonly string[]): (string | undefined)[] {\n let fenced = false;\n return lines.map((line) => {\n if (FENCE.test(line)) fenced = !fenced;\n return fenced ? undefined : HEADING.exec(line)?.[1];\n });\n}\n\nfunction headingTitle(heading: string): string {\n const [title = ''] = normalize(heading)\n .replace(/^\\d+[.)]\\s*/, '')\n .replace(/[*_`]/g, '')\n .split(/[:(]/);\n return title.trim();\n}\n\nfunction escape(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction matchRank(heading: string, names: readonly string[]): number {\n const title = headingTitle(heading);\n if (names.some((name) => title === name || title === `${name}s`)) return 1;\n const word = names.some((name) =>\n new RegExp(`(^|[^a-z0-9])${escape(name)}s?($|[^a-z0-9])`).test(title),\n );\n return word ? 2 : 0;\n}\n\nexport function extractSection(markdown: string, names: readonly string[]): string | undefined {\n const wanted = names.map(normalize);\n const lines = markdown.split('\\n');\n const titles = headings(lines);\n const ranks = titles.map((heading) => (heading === undefined ? 0 : matchRank(heading, wanted)));\n // An exact heading wins over one that only contains the name: `## Done` over `## Verification done`.\n const exact = ranks.indexOf(1);\n const start = exact !== -1 ? exact : ranks.indexOf(2);\n if (start === -1) return undefined;\n const end = titles.findIndex((heading, index) => index > start && heading !== undefined);\n return lines\n .slice(start + 1, end === -1 ? undefined : end)\n .join('\\n')\n .trim();\n}\n\nexport function readReport(path: string | null): string | undefined {\n return path && existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n}\n\nexport function appendToReport(path: string | null, markdown: string): void {\n const current = readReport(path);\n if (current === undefined || !path) return;\n const separator = current.endsWith('\\n\\n') ? '' : current.endsWith('\\n') ? '\\n' : '\\n\\n';\n appendFileSync(path, `${separator}${markdown.trimEnd()}\\n`);\n}\n\n// A promoted agent's next report replaces this one, and a review still needs the plan.\nexport function keptReportPath(report: string, kind: 'research' | 'plan'): string {\n return report.replace(/(\\.md)?$/, kind === 'plan' ? '.plan.md' : '.research.md');\n}\n","// Generated from docs/kinds/*.md by pnpm run build. Do not edit.\nexport const KIND_CONTRACTS: Record<string, string> = {\n research: `You are a research agent: answer the question you were given. Read code, docs and the web; change nothing. No Edit or NotebookEdit, no Write except your report in the scratchpad, no shell command that writes, no commit.\n\nReport sections, in this order:\n\n- \\`## For the main\\`: a dense answer, 15 lines at most, with no nested bullets. This is what the main agent injects into its context, so it stands on its own.\n- \\`## Findings\\`: the details, each with its source (\\`file:line\\`, URL).\n- \\`## Gaps\\`: what you could not find or confirm.\n- \\`## Learnings\\`: candidate notes, or \\`none\\`.\n\nWhen your prompt gives you a sandbox folder, you may write, install packages and commit there, never elsewhere, and never push or install globally. Start every writing shell command with \\`cd <sandbox> &&\\`, since each command starts outside it. To work on a copy of a repo, clone or copy it into the sandbox (\\`git clone <repo>\\`, \\`cp -al\\`), never \\`git worktree add\\` from a real repo, which writes into that repo. Carnet removes the sandbox when you close: add a \\`## Cleanup\\` section before Learnings with what you created outside it (caches, logins, keys) and how to remove it.\n\nEnd with \\`agent_done\\` (your name, the report path) as your last tool action, then reply with one line: \\`<name> done, report written\\`.`,\n plan: `You are a plan agent: understand the task, check it against the real code, and plan its implementation. Change nothing: no Edit or NotebookEdit, no Write except your report in the scratchpad, no shell command that writes, no commit.\n\nReport sections, in this order:\n\n- \\`## Understanding\\`: the task restated, with its scope.\n- \\`## Plan\\`: always present. The steps, the files touched, the choices made by default. The plan assumes every recommendation below is accepted.\n- \\`## Learnings\\`: candidate notes, or \\`none\\`.\n\nWhen the task asks for no change, say so in Understanding and answer it there, write Plan as \\`none: no change asked\\`, and ask no implementation question.\n\nWhen your prompt gives you a sandbox folder, you may write, install packages and commit there, never elsewhere, and never push or install globally. Start every writing shell command with \\`cd <sandbox> &&\\`, since each command starts outside it. To work on a copy of a repo, clone or copy it into the sandbox (\\`git clone <repo>\\`, \\`cp -al\\`), never \\`git worktree add\\` from a real repo, which writes into that repo. Carnet removes the sandbox when you close: add a \\`## Cleanup\\` section before Learnings with what you created outside it (caches, logins, keys) and how to remove it.\n\nAsk questions only for choices you can't settle alone, and only through \\`agent_done\\`, never in the report: Carnet adds them to it. Each question has a \\`text\\`, a \\`recommendation\\`, an optional short \\`context\\`, and at most 3 \\`alternatives\\`. With more options than that, ask an open question and list them in its context.\n\nEnd with \\`agent_done\\` (your name, the report path, \\`questions\\` when you have some) as your last tool action, then reply with one line: \\`<name> done, report written\\`.`,\n implement: `You are an implement agent: implement the task in your worktree.\n\n- First step, always: \\`git reset --hard <base commit>\\` in the worktree, then reinstall dependencies with the lockfile frozen.\n- Write only in your worktree, plus your report. Never commit, push or stash.\n- Run the build, the checks and the tests before you finish.\n\nReport sections, in this order:\n\n- \\`## Done\\`: what changed, file by file.\n- \\`## Deviations\\`: what differs from the task or the plan.\n- \\`## To test\\`: the commands and the cases to check.\n- \\`## Risks\\`\n- \\`## Commit message\\`: one line.\n- \\`## Learnings\\`: candidate notes, or \\`none\\`.\n\nQuestions for the human go through \\`agent_done\\` only, never in the report, with the same shape as a plan agent's. Review findings sent back to you come as a list of fixes: handle them, then finish again.\n\nEnd with \\`agent_done\\` (your name, the report path, \\`questions\\` when you have some) as your last tool action, then reply with one line: \\`<name> done, report written\\`.`,\n review: `You are a review agent: review the diff of your target and judge it against what was asked (the task, the plan, its answers), not against what the code claims to do. Read the diff with \\`git -C <worktree> diff <base>\\` for an agent, or \\`git diff\\` / \\`git diff <range>\\` in the main repo. Change nothing: no Edit or NotebookEdit, no Write except your report in the scratchpad, no shell command that writes, no commit.\n\nReport sections, in this order:\n\n- \\`## Verdict\\`: one line, \\`OK\\`, \\`OK with remarks\\` or \\`Needs rework\\`.\n- \\`## Not verified\\`: what you could not judge (tests not run, external services).\n- \\`## Learnings\\`: candidate notes, or \\`none\\`.\n\nFindings go through \\`agent_done\\` only, never in the report: Carnet adds them to it, blocking first. Each finding has a \\`severity\\` (\\`blocking\\`, \\`to_fix\\` or \\`suggestion\\`), a \\`location\\` (\\`file:line\\`), a \\`text\\` explaining the problem, a proposed \\`fix\\` and, when you have a view on how it should be fixed, a \\`route\\`: \\`send back\\` (to the implement agent, only before it is applied), \\`in main\\`, or a new \\`implement\\`, \\`plan\\` or \\`research\\` agent.\n\nEnd with \\`agent_done\\` (your name, the report path, \\`findings\\`) as your last tool action, then reply with one line: \\`<name> done, report written\\`.`,\n};\n","import { homedir, userInfo } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport type { Workspace } from './workspace/workspace.ts';\n\nexport interface RucherPaths {\n config: string;\n data: string;\n state: string;\n run: string;\n}\n\n// The XDG spec says relative values must be ignored.\nfunction xdgDirectory(value: string | undefined, fallback: string): string {\n return value && isAbsolute(value) ? value : fallback;\n}\n\nexport function rucherPaths(env: NodeJS.ProcessEnv = process.env): RucherPaths {\n if (env.RUCHER_HOME) {\n const home = env.RUCHER_HOME;\n return {\n config: join(home, 'config'),\n data: join(home, 'data'),\n state: join(home, 'state'),\n run: join(home, 'run'),\n };\n }\n const home = env.HOME || homedir();\n const state = join(xdgDirectory(env.XDG_STATE_HOME, join(home, '.local', 'state')), 'rucher');\n return {\n config: join(xdgDirectory(env.XDG_CONFIG_HOME, join(home, '.config')), 'rucher'),\n data: join(xdgDirectory(env.XDG_DATA_HOME, join(home, '.local', 'share')), 'rucher'),\n state,\n run:\n env.XDG_RUNTIME_DIR && isAbsolute(env.XDG_RUNTIME_DIR)\n ? join(env.XDG_RUNTIME_DIR, 'rucher')\n : join(state, 'run'),\n };\n}\n\nexport function databasePath(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).data, 'carnet.db');\n}\n\n// Windows has no Unix sockets: a per-user named pipe stands in.\nexport function serverSocketPath(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string {\n if (platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\rucher-server-${env.USERNAME || userInfo().username}`;\n }\n return join(rucherPaths(env).run, 'server.sock');\n}\n\nexport function workspacesDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).config, 'workspaces');\n}\n\nexport function workspaceDefinition(name: string, env?: NodeJS.ProcessEnv): string {\n return join(workspacesDirectory(env), name);\n}\n\nexport function defaultRunDirectory(name: string, env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).data, 'workspaces', name);\n}\n\nexport function promptsDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).state, 'prompts');\n}\n\nexport function corePromptPath(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).config, 'prompt.md');\n}\n\nexport function reportsDirectory(workspace: Workspace): string {\n return join(workspace.runDirectory, 'reports');\n}\n\nexport function sandboxesDirectory(workspace: Workspace): string {\n return join(workspace.runDirectory, 'sandboxes');\n}\n\n// The id keeps a reused name, or the same name in another session, from overwriting a report.\nexport function reportPath(workspace: Workspace, agentName: string, agentId: number): string {\n return join(reportsDirectory(workspace), `${agentName}-${agentId}.md`);\n}\n","import * as z from 'zod/v4';\nimport { CarnetError } from '../errors.ts';\n\nexport const BACKENDS = ['claude', 'cursor'] as const;\nexport type Backend = (typeof BACKENDS)[number];\n\n// Names only: endpoints and protocols arrive with the decider.\nexport const DECIDER_PROVIDERS = ['cloudflare', 'typesafe', 'openai', 'ollama'] as const;\n\nexport const GESTURES = [\n 'permission',\n 'read',\n 'question',\n 'launch',\n 'plan',\n 'triage',\n 'apply',\n 'commit',\n 'push',\n 'pr',\n] as const;\n\nexport const DECISION_USAGES = [\n 'permission',\n 'launch',\n 'routing',\n 'question',\n 'findings',\n 'digest',\n 'notify',\n 'loop',\n 'plans',\n 'dream',\n] as const;\n\nexport interface RunPair {\n backend?: Backend | undefined;\n model?: string | undefined;\n}\n\nfunction backendOf(value: string, context: z.core.$RefinementCtx<unknown>): Backend | undefined {\n if ((BACKENDS as readonly string[]).includes(value)) return value as Backend;\n context.addIssue({\n code: 'custom',\n message: `run uses a backend: ${BACKENDS.join(' or ')}, not ${value}`,\n });\n return undefined;\n}\n\nconst pairSchema = z\n .union([\n z.string().min(1),\n z.strictObject({ backend: z.string().min(1).optional(), model: z.string().min(1).optional() }),\n ])\n .transform((value, context): RunPair => {\n if (typeof value === 'string') {\n const slash = value.indexOf('/');\n const backend = backendOf(slash === -1 ? value : value.slice(0, slash), context);\n return slash === -1 ? { backend } : { backend, model: value.slice(slash + 1) };\n }\n return {\n ...(value.backend === undefined ? {} : { backend: backendOf(value.backend, context) }),\n ...(value.model === undefined ? {} : { model: value.model }),\n };\n });\n\nconst COUNT_UNITS: Record<string, number> = { k: 1e3, m: 1e6 };\nconst DURATION_UNITS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86400 };\n\nconst count = z.union([\n z.number().int().nonnegative(),\n z\n .string()\n .regex(/^\\d+(\\.\\d+)?[kKmM]$/, 'a number, or a count like 80k or 2M')\n .transform((value) =>\n Math.round(Number(value.slice(0, -1)) * (COUNT_UNITS[value.at(-1)!.toLowerCase()] ?? 1)),\n ),\n]);\n\nconst duration = z.union([\n z.number().int().nonnegative(),\n z\n .string()\n .regex(/^\\d+[smhd]$/, 'seconds, or a duration like 30m, 4h or 2d')\n .transform((value) => Number(value.slice(0, -1)) * (DURATION_UNITS[value.at(-1)!] ?? 1)),\n]);\n\nconst providerModel = z\n .string()\n .regex(/^[a-z0-9-]+\\/.+$/, 'provider/model, e.g. cloudflare/clef-flash');\n\nconst gesture = z.enum(['auto', 'human']);\nconst probability = z.number().min(0).max(1);\n\nconst autonomySchema = z.union([\n z.string().min(1),\n z.strictObject({\n profile: z.string().min(1).optional(),\n shadow: z.boolean().optional(),\n supervisor: providerModel.optional(),\n gestures: z\n .strictObject(\n Object.fromEntries(\n GESTURES.map((name) => [\n name,\n (name === 'permission'\n ? z.union([gesture, z.record(z.string(), gesture)])\n : gesture\n ).optional(),\n ]),\n ),\n )\n .optional(),\n budget: z\n .strictObject({\n tokens: count.optional(),\n waves: z.number().int().positive().optional(),\n timeout: duration.optional(),\n reviewRounds: z.number().int().nonnegative().optional(),\n })\n .optional(),\n stopAfterEscalations: z.number().int().positive().optional(),\n }),\n]);\n\nconst fallback = z.enum(['none', 'backend-small']);\n\nconst decisionSchema = z.strictObject({\n mode: z.enum(['off', 'shadow', 'on']).optional(),\n above: probability.optional(),\n below: probability.optional(),\n minConfidence: probability.optional(),\n fallback: fallback.optional(),\n});\n\nconst deciderValue = z.union([z.literal('none'), providerModel]);\n\nconst providerSchema = z.looseObject({\n token: z\n .string()\n .regex(/^env:[A-Za-z_][A-Za-z0-9_]*$/, 'keep secrets out of config files: use env:NAME')\n .optional(),\n url: z.string().min(1).optional(),\n account: z.string().min(1).optional(),\n local: z.boolean().optional(),\n});\n\nexport const configSchema = z.strictObject({\n run: z\n .object({ default: pairSchema.optional(), kinds: z.record(z.string(), pairSchema).optional() })\n .catchall(pairSchema)\n .optional(),\n autonomy: autonomySchema.optional(),\n decider: deciderValue.optional(),\n decide: z\n .strictObject({\n model: deciderValue.optional(),\n fallback: fallback.optional(),\n decisions: z\n .strictObject(\n Object.fromEntries(DECISION_USAGES.map((usage) => [usage, decisionSchema.optional()])),\n )\n .optional(),\n })\n .optional(),\n context: z.strictObject({ coldAbove: count.optional() }).optional(),\n waves: z.strictObject({ launch: z.enum(['confirm', 'auto']).optional() }).optional(),\n apply: z\n .strictObject({ target: z.enum(['main', 'branch']).optional(), check: z.string().optional() })\n .optional(),\n providers: z.record(z.string().regex(/^[a-z0-9-]+$/), providerSchema).optional(),\n});\n\ntype PairInput = z.input<typeof pairSchema>;\n\n// The schema's catchall would make kinds clash with the kind shorthand index signature.\nexport type ConfigFile = Omit<z.input<typeof configSchema>, 'run'> & {\n run?:\n | ({ default?: PairInput; kinds?: Record<string, PairInput> } & Record<string, unknown>)\n | undefined;\n};\n\n/** One validated source, flattened to canonical dotted keys. */\nexport type Source = Map<string, unknown>;\n\nfunction issueText(issue: z.core.$ZodIssue): string {\n if (issue.code === 'unrecognized_keys') {\n return issue.keys.map((key) => `unknown key ${[...issue.path, key].join('.')}`).join(', ');\n }\n const path = issue.path.join('.');\n return path ? `${path}: ${issue.message}` : issue.message;\n}\n\nexport function parseConfig(value: unknown, origin: string): Source {\n const result = configSchema.safeParse(value);\n if (!result.success) {\n throw new CarnetError(\n 'CONFIG_INVALID',\n `${origin}: ${result.error.issues.map(issueText).join('; ')}`,\n );\n }\n return flatten(result.data);\n}\n\n// A run pair and a permission table stay whole: last write wins on the whole value.\n// run.<kind> is the same pair as run.kinds.<kind>.\nexport function isLeaf(path: readonly string[]): boolean {\n const key = path.join('.');\n return (\n key === 'run.default' ||\n (path.length === 3 && key.startsWith('run.kinds.')) ||\n (path.length === 2 && path[0] === 'run' && path[1] !== 'default' && path[1] !== 'kinds') ||\n key === 'autonomy.gestures.permission'\n );\n}\n\nfunction walk(value: unknown, path: string[], into: Source): void {\n if (value === undefined) return;\n if (value === null || typeof value !== 'object' || Array.isArray(value) || isLeaf(path)) {\n into.set(path.join('.'), value);\n return;\n }\n for (const [key, child] of Object.entries(value)) walk(child, [...path, key], into);\n}\n\nfunction flatten(file: z.output<typeof configSchema>): Source {\n const { run, autonomy, decider, decide, ...rest } = file;\n const source: Source = new Map();\n if (run) {\n const { default: fallbackPair, kinds, ...shorthand } = run;\n walk(fallbackPair, ['run', 'default'], source);\n for (const [kind, pair] of Object.entries({ ...shorthand, ...kinds })) {\n walk(pair, ['run', 'kinds', kind], source);\n }\n }\n walk(typeof autonomy === 'string' ? { profile: autonomy } : autonomy, ['autonomy'], source);\n walk(decide, ['decide'], source);\n if (decider !== undefined) source.set('decide.model', decider);\n walk(rest, [], source);\n return source;\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { rucherPaths } from '../paths.ts';\nimport { parseConfig, type Source } from './schema.ts';\n\nexport const CONFIG_FILE = 'config.json';\n\nexport function globalConfigPath(env: NodeJS.ProcessEnv = process.env): string {\n return join(rucherPaths(env).config, CONFIG_FILE);\n}\n\nexport function readJson(path: string): unknown {\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch (error) {\n throw new CarnetError(\n 'CONFIG_INVALID',\n `${path}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function loadGlobalConfig(env: NodeJS.ProcessEnv = process.env): Source {\n const path = globalConfigPath(env);\n return existsSync(path) ? parseConfig(readJson(path), path) : new Map();\n}\n\nconst WORKSPACE_KEYS = ['name', 'repos', 'hosts', 'backends'];\n\n/** The config keys of a workspace.json; any other key besides the workspace's own is refused. */\nexport function workspaceConfig(file: Record<string, unknown>, origin: string): Source {\n const picked = Object.fromEntries(\n Object.entries(file).filter(([key]) => !WORKSPACE_KEYS.includes(key)),\n );\n return parseConfig(picked, origin);\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 { workspaceConfig } from '../config/load.ts';\nimport type { ConfigFile, Source } from '../config/schema.ts';\nimport { CarnetError } from '../errors.ts';\nimport { DEFAULT_HOST } from '../hosts/host.ts';\nimport { defaultRunDirectory, workspacesDirectory, workspaceDefinition } from '../paths.ts';\n\nexport interface WorkspaceRepo {\n path: string;\n name: string;\n}\n\nexport interface Workspace {\n name: string;\n definition: string;\n runDirectory: string;\n repos: WorkspaceRepo[];\n hosts: Record<string, { settings?: Record<string, unknown> }>;\n config: Source;\n /** Why the config keys of workspace.json were ignored; they are then empty. */\n configProblem?: string | undefined;\n}\n\nexport interface WorkspaceFile extends ConfigFile {\n name?: string | undefined;\n repos?: { path: string; name?: string | undefined }[] | undefined;\n hosts?: Workspace['hosts'] | undefined;\n /** Former name of hosts, still read. */\n backends?: Workspace['hosts'] | undefined;\n}\n\nexport const WORKSPACE_FILE = 'workspace.json';\nexport const INSTRUCTIONS_FILE = 'CLAUDE.md';\nexport const AGENTS_FILE = 'AGENTS.md';\nexport const REPO_INSTRUCTIONS_DIRECTORY = 'repos';\nconst WORKSPACE_NAME = /^[a-z0-9-]+$/;\n\nexport function isWorkspaceName(name: string): boolean {\n return WORKSPACE_NAME.test(name);\n}\n\nfunction requireWorkspaceName(name: string): void {\n if (!isWorkspaceName(name)) {\n throw new CarnetError(\n 'WORKSPACE_NAME_INVALID',\n `Invalid workspace name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`,\n );\n }\n}\n\nexport function expandHome(path: string, env: NodeJS.ProcessEnv = process.env): string {\n if (path !== '~' && !path.startsWith('~/')) return path;\n return join(env.HOME || homedir(), path.slice(1));\n}\n\nfunction workspaceFilePath(name: string, env?: NodeJS.ProcessEnv): string {\n return join(workspaceDefinition(name, env), WORKSPACE_FILE);\n}\n\nexport function workspaceExists(name: string, env?: NodeJS.ProcessEnv): boolean {\n return isWorkspaceName(name) && existsSync(workspaceFilePath(name, env));\n}\n\nfunction readWorkspaceFile(name: string, env?: NodeJS.ProcessEnv): WorkspaceFile {\n if (!workspaceExists(name, env)) {\n throw new CarnetError(\n 'WORKSPACE_NOT_FOUND',\n `No workspace named ${name}: see \"rucher ws list\"`,\n );\n }\n return JSON.parse(readFileSync(workspaceFilePath(name, env), 'utf8')) as WorkspaceFile;\n}\n\nexport function workspaceFileHosts(file: WorkspaceFile): Workspace['hosts'] {\n return file.hosts ?? file.backends ?? {};\n}\n\n/** Writes hosts under its current name, so an older backends key moves on the next write. */\nexport function serializeWorkspaceFile(file: WorkspaceFile): string {\n const { backends: _backends, ...rest } = file;\n return `${JSON.stringify({ ...rest, hosts: workspaceFileHosts(file) }, null, 2)}\\n`;\n}\n\nfunction writeWorkspaceFile(name: string, file: WorkspaceFile, env?: NodeJS.ProcessEnv): void {\n writeFileSync(workspaceFilePath(name, env), serializeWorkspaceFile(file));\n}\n\n// Hooks of every session load workspaces, so a bad config key must not take the workspace down.\nfunction tolerantConfig(\n file: WorkspaceFile,\n origin: string,\n): Pick<Workspace, 'config' | 'configProblem'> {\n try {\n return { config: workspaceConfig({ ...file }, origin) };\n } catch (error) {\n if (!(error instanceof CarnetError)) throw error;\n return { config: new Map(), configProblem: error.message };\n }\n}\n\nexport function loadWorkspace(name: string, env: NodeJS.ProcessEnv = process.env): Workspace {\n const file = readWorkspaceFile(name, env);\n return {\n name,\n definition: workspaceDefinition(name, env),\n runDirectory: defaultRunDirectory(name, env),\n repos: (file.repos ?? []).map((repo) => {\n const path = resolve(expandHome(repo.path, env));\n return { path, name: repo.name ?? basename(path) };\n }),\n hosts: workspaceFileHosts(file),\n ...tolerantConfig(file, workspaceFilePath(name, env)),\n };\n}\n\n/** The workspace config where it decides something: an ignored invalid config is refused there. */\nexport function usableWorkspaceConfig(workspace: Workspace | null | undefined): Source | undefined {\n if (workspace?.configProblem) throw new CarnetError('CONFIG_INVALID', workspace.configProblem);\n return workspace?.config;\n}\n\n// An unreadable workspace.json must not take the hooks down, the fork guard above all.\nexport function loadableWorkspace(name: string, env: NodeJS.ProcessEnv): Workspace | undefined {\n try {\n return loadWorkspace(name, env);\n } catch {\n return undefined;\n }\n}\n\nexport function listWorkspaces(env: NodeJS.ProcessEnv = process.env): Workspace[] {\n const directory = workspacesDirectory(env);\n if (!existsSync(directory)) return [];\n return readdirSync(directory)\n .filter((name) => workspaceExists(name, env))\n .sort()\n .map((name) => loadableWorkspace(name, env))\n .filter((workspace): workspace is Workspace => workspace !== undefined);\n}\n\nexport function workspaceHosts(workspace: Workspace): string[] {\n const hosts = Object.keys(workspace.hosts);\n return hosts.length ? hosts : [DEFAULT_HOST];\n}\n\nfunction checkedRepo(path: string, env?: NodeJS.ProcessEnv): string {\n const absolute = resolve(expandHome(path, env));\n if (!existsSync(absolute))\n throw new CarnetError('REPO_NOT_FOUND', `Repo path does not exist: ${absolute}`);\n return absolute;\n}\n\n// Notes reference repos by name, so two repos cannot share one.\nfunction requireDistinctNames(workspace: string, repos: readonly WorkspaceRepo[]): void {\n const names = repos.map((repo) => repo.name);\n const shared = names.find((name, index) => names.indexOf(name) !== index);\n if (shared) {\n throw new CarnetError(\n 'REPO_NAME_TAKEN',\n `${workspace} would have two repos named ${shared}: give them distinct names`,\n );\n }\n}\n\nexport interface CreateWorkspaceOptions {\n repos?: readonly string[] | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nexport function createWorkspace(name: string, options: CreateWorkspaceOptions = {}): Workspace {\n const { env } = options;\n requireWorkspaceName(name);\n if (workspaceExists(name, env))\n throw new CarnetError('WORKSPACE_EXISTS', `Workspace ${name} already exists`);\n const paths = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))];\n const repos = paths.map((path) => ({ path, name: basename(path) }));\n requireDistinctNames(name, repos);\n const definition = workspaceDefinition(name, env);\n const runDirectory = defaultRunDirectory(name, env);\n mkdirSync(definition, { recursive: true });\n mkdirSync(runDirectory, { recursive: true });\n writeWorkspaceFile(name, { name, repos, hosts: {} }, env);\n const instructions = join(definition, AGENTS_FILE);\n if (!existsSync(instructions)) writeFileSync(instructions, '');\n return loadWorkspace(name, env);\n}\n\n// CLAUDE.md is the legacy name, kept until migrateInstructions renames it.\nexport function definitionInstructions(workspace: Workspace): string {\n const legacy = existsSync(join(workspace.definition, INSTRUCTIONS_FILE));\n if (legacy && existsSync(join(workspace.definition, AGENTS_FILE))) {\n throw new CarnetError(\n 'WORKSPACE_INSTRUCTIONS_CONFLICT',\n `Workspace ${workspace.name} has both ${AGENTS_FILE} and ${INSTRUCTIONS_FILE} in ${workspace.definition}: remove ${INSTRUCTIONS_FILE}`,\n );\n }\n return legacy ? INSTRUCTIONS_FILE : AGENTS_FILE;\n}\n\nexport function migrateInstructions(workspace: Workspace): boolean {\n if (definitionInstructions(workspace) !== INSTRUCTIONS_FILE) return false;\n renameSync(\n join(workspace.definition, INSTRUCTIONS_FILE),\n join(workspace.definition, AGENTS_FILE),\n );\n return true;\n}\n\nexport function repoInstructionsPath(workspace: Workspace, repoName: string): string {\n return join(workspace.definition, REPO_INSTRUCTIONS_DIRECTORY, `${repoName}.md`);\n}\n\nexport interface RepoInstructionsFile {\n repo: string;\n path: string;\n // No repo of the workspace has this name any more.\n orphan: boolean;\n}\n\nexport function repoInstructionFiles(workspace: Workspace): RepoInstructionsFile[] {\n const directory = join(workspace.definition, REPO_INSTRUCTIONS_DIRECTORY);\n if (!existsSync(directory)) return [];\n const names = new Set(workspace.repos.map((repo) => repo.name));\n return readdirSync(directory, { withFileTypes: true })\n .filter((item) => item.isFile() && item.name.endsWith('.md'))\n .map((item) => {\n const repo = item.name.slice(0, -'.md'.length);\n return { repo, path: join(directory, item.name), orphan: !names.has(repo) };\n })\n .sort((a, b) => a.repo.localeCompare(b.repo));\n}\n\nexport function addWorkspaceRepo(name: string, repo: string, env?: NodeJS.ProcessEnv): Workspace {\n const file = readWorkspaceFile(name, env);\n const workspace = loadWorkspace(name, env);\n const path = checkedRepo(repo, env);\n if (workspace.repos.some((existing) => existing.path === path)) return workspace;\n requireDistinctNames(name, [...workspace.repos, { path, name: basename(path) }]);\n writeWorkspaceFile(\n name,\n { ...file, repos: [...(file.repos ?? []), { path, name: basename(path) }] },\n env,\n );\n return loadWorkspace(name, env);\n}\n\nexport function removeWorkspaceRepo(\n name: string,\n repo: string,\n env?: NodeJS.ProcessEnv,\n): Workspace {\n const file = readWorkspaceFile(name, env);\n const workspace = loadWorkspace(name, env);\n const path = resolve(expandHome(repo, env));\n const index = workspace.repos.findIndex(\n (existing) => existing.path === path || existing.name === repo,\n );\n if (index === -1) throw new CarnetError('REPO_NOT_FOUND', `${repo} is not a repo of ${name}`);\n writeWorkspaceFile(\n name,\n { ...file, repos: (file.repos ?? []).filter((_, position) => position !== index) },\n env,\n );\n return loadWorkspace(name, env);\n}\n\nexport interface DropWorkspaceOptions {\n purge?: boolean | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nexport function dropWorkspace(name: string, options: DropWorkspaceOptions = {}): Workspace {\n const workspace = loadWorkspace(name, options.env);\n rmSync(workspace.definition, { recursive: true, force: true });\n if (options.purge) rmSync(workspace.runDirectory, { recursive: true, force: true });\n return workspace;\n}\n","// Generated from docs/workflow.md by pnpm run build. Do not edit.\nexport const CORE_RULES = `- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches agents, asks for their report and its next action (inject, validate, apply, triage), applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the Main line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When an agent finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that report or its next action (/rucher:next), even when answering about something else.\n- Agents never commit, push, stash or record notes. An agent follows its kind's contract, writes its report to a file ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- Instructions stack from general to specific, the more specific winning: Rucher rules, workspace instructions, the human's own instructions for a repo, the repo's own files, then the session files. None overrides your kind's contract: its access, deliverable and final action.\n- To launch agents or handle their results, load the rucher skill: it holds the full workflow.`;\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n definitionInstructions,\n repoInstructionsPath,\n type Workspace,\n} from './workspace/workspace.ts';\n\n// Literal names: workspace.ts is still loading when the hosts it imports load this module.\nexport const REPO_INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md', join('.claude', 'CLAUDE.md')];\n\n// What Claude Code loads by itself from an added directory, given CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD.\nexport const CLAUDE_NATIVE_FILES: readonly string[] = ['CLAUDE.md', join('.claude', 'CLAUDE.md')];\n\nexport const CLAUDE_BACKEND_NOTES = join('backends', 'claude.md');\n\nexport interface ContextText {\n file: string;\n text: string;\n}\n\nexport interface RepoOwnFile {\n file: string;\n path: string;\n // skipped: a file the harness loads already covers the repo.\n loading: 'native' | 'listed' | 'skipped';\n}\n\nexport interface RepoContext {\n name: string;\n path: string;\n personal?: ContextText;\n own: RepoOwnFile[];\n}\n\nexport interface WorkspaceContext {\n name: string;\n workspace?: ContextText;\n backendNotes?: ContextText;\n repos: RepoContext[];\n}\n\nexport interface ContextOptions {\n // Instruction files the harness loads itself from each repo; empty when it loads none.\n nativeFiles: readonly string[];\n backend?: string | undefined;\n // False when the workspace instructions reach the agent another way, as files.\n workspaceText?: boolean | undefined;\n}\n\nexport interface ContextAppendOptions {\n workspace: boolean;\n repoFiles: boolean;\n}\n\nfunction readText(path: string): string | undefined {\n if (!existsSync(path)) return undefined;\n return readFileSync(path, 'utf8').trim() || undefined;\n}\n\n// One level of @ imports of definition files, for a backend that gets the text without the files.\nfunction inlineImports(text: string, definition: string): string {\n return text\n .split('\\n')\n .map((line) => {\n const target = /^@([\\w./-]+\\.md)\\s*$/.exec(line)?.[1];\n if (!target || target.startsWith('/') || target.includes('..')) return line;\n return readText(join(definition, target)) ?? line;\n })\n .join('\\n');\n}\n\nfunction repoOwnFiles(repoPath: string, nativeFiles: readonly string[]): RepoOwnFile[] {\n const present = REPO_INSTRUCTION_FILES.filter((file) => existsSync(join(repoPath, file)));\n const covered = present.some((file) => nativeFiles.includes(file));\n return present.map((file) => ({\n file,\n path: join(repoPath, file),\n loading: nativeFiles.includes(file) ? 'native' : covered ? 'skipped' : 'listed',\n }));\n}\n\nexport function workspaceContext(workspace: Workspace, options: ContextOptions): WorkspaceContext {\n const instructionsFile = options.workspaceText === false ? '' : definitionInstructions(workspace);\n const instructions = instructionsFile\n ? readText(join(workspace.definition, instructionsFile))\n : undefined;\n const notesFile = options.backend && join('backends', `${options.backend}.md`);\n const notes = notesFile ? readText(join(workspace.definition, notesFile)) : undefined;\n return {\n name: workspace.name,\n ...(instructions\n ? {\n workspace: {\n file: instructionsFile,\n text: inlineImports(instructions, workspace.definition),\n },\n }\n : {}),\n ...(notesFile && notes ? { backendNotes: { file: notesFile, text: notes } } : {}),\n repos: workspace.repos.map((repo) => {\n const personal = readText(repoInstructionsPath(workspace, repo.name));\n return {\n name: repo.name,\n path: repo.path,\n ...(personal\n ? { personal: { file: join('repos', `${repo.name}.md`), text: personal } }\n : {}),\n own: repoOwnFiles(repo.path, options.nativeFiles),\n };\n }),\n };\n}\n\n// Most general first: a later section refines an earlier one.\nexport function contextAppend(context: WorkspaceContext, options: ContextAppendOptions): string {\n const sections: string[] = [];\n if (options.workspace && (context.workspace || context.backendNotes)) {\n const texts = [context.workspace?.text, context.backendNotes?.text].filter(Boolean);\n sections.push(`Instructions of the ${context.name} workspace:\\n\\n${texts.join('\\n\\n')}`);\n }\n const personal = context.repos.filter((repo) => repo.personal);\n if (personal.length) {\n sections.push(\n [\n \"The human's own instructions per repo, adding to each repo's instruction files:\",\n ...personal.map((repo) => `## Repo ${repo.name} (${repo.path})\\n\\n${repo.personal?.text}`),\n ].join('\\n\\n'),\n );\n }\n const listed = context.repos.flatMap((repo) =>\n repo.own.filter((own) => own.loading === 'listed').map((own) => `- ${repo.name}: ${own.path}`),\n );\n if (options.repoFiles && listed.length) {\n sections.push(\n `Instruction files of the repos, not loaded for you: read a repo's before working in it.\\n${listed.join('\\n')}`,\n );\n }\n return sections.join('\\n\\n');\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Workspace } from '../workspace/workspace.ts';\nimport { corePromptPath, promptsDirectory } from '../paths.ts';\nimport { shortId, type SessionKind } from '../sessions.ts';\nimport { CORE_RULES } from './core-rules.ts';\nimport { CLAUDE_NATIVE_FILES, contextAppend, workspaceContext } from '../context-files.ts';\n\nexport const PROMPT_FILE = 'prompt.md';\n\nexport interface PromptSession {\n id: string;\n name: string | null;\n kind: SessionKind;\n}\n\nexport interface AssembledPrompt {\n text: string;\n version: string;\n}\n\nexport interface AppendPromptFile {\n path: string;\n version: string;\n}\n\nfunction readIfPresent(path: string): string | undefined {\n if (!existsSync(path)) return undefined;\n const content = readFileSync(path, 'utf8').trim();\n return content || undefined;\n}\n\nexport function baseRules(env: NodeJS.ProcessEnv = process.env): string {\n return readIfPresent(corePromptPath(env)) ?? CORE_RULES;\n}\n\nexport function workspaceRules(workspace: Workspace | null): string | undefined {\n return workspace ? readIfPresent(join(workspace.definition, PROMPT_FILE)) : undefined;\n}\n\nexport function rulesText(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n const extra = workspaceRules(workspace);\n const base = `Rucher rules, always follow them:\\n${baseRules(env)}`;\n return extra && workspace\n ? `${base}\\n\\nRules of the ${workspace.name} workspace:\\n${extra}`\n : base;\n}\n\n// The workspace instructions themselves reach Claude Code through the run directory's CLAUDE.md.\nexport function contextText(workspace: Workspace | null): string {\n if (!workspace) return '';\n const context = workspaceContext(workspace, {\n nativeFiles: CLAUDE_NATIVE_FILES,\n workspaceText: false,\n });\n return contextAppend(context, { workspace: false, repoFiles: false });\n}\n\nfunction instructionsText(workspace: Workspace | null, env: NodeJS.ProcessEnv): string {\n const context = contextText(workspace);\n return context ? `${rulesText(workspace, env)}\\n\\n${context}` : rulesText(workspace, env);\n}\n\n// The identity block is left out so that renaming a session doesn't read as a rules change.\nexport function rulesVersion(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return createHash('sha256').update(instructionsText(workspace, env)).digest('hex').slice(0, 12);\n}\n\nexport function assemblePrompt(\n workspace: Workspace | null,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AssembledPrompt {\n const label = session.name ?? shortId(session.id);\n const identity = workspace\n ? `This is the Rucher session ${label} (${session.kind}) of the ${workspace.name} workspace.`\n : `This is the Rucher session ${label} (${session.kind}), outside any workspace.`;\n return {\n text: `${instructionsText(workspace, env)}\\n\\n${identity}\\n`,\n version: rulesVersion(workspace, env),\n };\n}\n\nexport function appendPromptFile(\n workspace: Workspace | null,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AppendPromptFile {\n const { text, version } = assemblePrompt(workspace, session, env);\n const directory = promptsDirectory(env);\n mkdirSync(directory, { recursive: true });\n const path = join(directory, `${session.id}.md`);\n writeFileSync(path, text);\n return { path, version };\n}\n\nexport function compactReminder(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${instructionsText(workspace, env)}`;\n}\n\nexport function outsideRucherContext(\n workspace: Workspace | null,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return `This session was started without rucher, so its system prompt does not hold the Rucher rules. ${instructionsText(workspace, env)}`;\n}\n\nexport const OUTSIDE_RUCHER_NOTICE =\n 'rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)';\n\nexport const RULES_UPDATED_NOTICE =\n 'rucher: rules updated, will apply after the next compaction or in a new session';\n\nexport const SUBAGENT_RULES =\n 'Rucher rules for sub-agents: never commit, push or stash. When your task asks for a report, write it to the file it names. If your prompt names you as a Carnet agent, follow the contract of its kind, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.';\n","import { lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CarnetError } from './errors.ts';\n\nexport const GENERATED_MARKER = 'generated by rucher, do not edit';\n\nfunction refuse(path: string): never {\n throw new CarnetError(\n 'RUN_DIRECTORY_FILE_CONFLICT',\n `${path} was not written by rucher: move its content to the workspace definition, then remove it`,\n );\n}\n\nfunction entry(path: string): ReturnType<typeof lstatSync> | undefined {\n try {\n return lstatSync(path);\n } catch {\n return undefined;\n }\n}\n\n// Claude Code strips HTML block comments from instruction files, so the marker costs no tokens.\nexport const MARKDOWN_MARKER = `<!-- ${GENERATED_MARKER} -->\\n`;\n\nexport function markdownCopy(content: string): string {\n return `${MARKDOWN_MARKER}${content}`;\n}\n\nfunction isMarkdownCopy(path: string): boolean {\n const current = entry(path);\n if (!current?.isFile()) return false;\n return readFileSync(path, 'utf8').startsWith(MARKDOWN_MARKER);\n}\n\n// Copies whose definition file is gone, at the top level of the directory; hand-written files stay.\nexport function removeStaleCopies(directory: string, keep: ReadonlySet<string>): string[] {\n const removed: string[] = [];\n if (!entry(directory)) return removed;\n for (const name of readdirSync(directory)) {\n if (!name.endsWith('.md') || keep.has(name)) continue;\n const path = join(directory, name);\n if (!isMarkdownCopy(path)) continue;\n rmSync(path, { force: true });\n removed.push(name);\n }\n return removed;\n}\n\nexport function writeGenerated(path: string, content: string): boolean {\n const current = entry(path);\n if (current?.isSymbolicLink()) rmSync(path, { force: true });\n else if (current) {\n const existing = readFileSync(path, 'utf8');\n if (existing === content) return false;\n if (!existing.includes(GENERATED_MARKER)) refuse(path);\n }\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content);\n return true;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function mergeSettings(\n base: Record<string, unknown>,\n extra: Record<string, unknown>,\n leafAt?: (path: readonly string[]) => boolean,\n path: readonly string[] = [],\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(extra)) {\n const child = [...path, key];\n const current = merged[key];\n if (leafAt?.(child)) {\n merged[key] = value;\n } else 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, leafAt, child);\n } else {\n merged[key] = value;\n }\n }\n return merged;\n}\n","import { renameSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { CarnetError } from '../errors.ts';\n\nexport interface UndoStep {\n // The shell command that does the same by hand, printed when the step itself fails.\n command: string;\n run: () => void;\n}\n\nexport interface UndoOutcome {\n undone: string[];\n left: string[];\n}\n\nexport class UndoList {\n private readonly steps: UndoStep[] = [];\n\n push(step: UndoStep): void {\n this.steps.push(step);\n }\n\n // Once one step fails, the later ones would act on a half-restored tree, so they are only listed.\n undo(): UndoOutcome {\n const outcome: UndoOutcome = { undone: [], left: [] };\n for (const step of [...this.steps].reverse()) {\n if (outcome.left.length) {\n outcome.left.push(step.command);\n continue;\n }\n try {\n step.run();\n outcome.undone.push(step.command);\n } catch {\n outcome.left.push(step.command);\n }\n }\n this.steps.length = 0;\n return outcome;\n }\n}\n\nexport function shellQuote(path: string): string {\n return `'${path.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nexport function moveTracked(undo: UndoList, move: { from: string; to: string }): void {\n renameSync(move.from, move.to);\n undo.push({\n command: `mv ${shellQuote(move.to)} ${shellQuote(move.from)}`,\n run: () => renameSync(move.to, move.from),\n });\n}\n\nexport function relocateFailed(error: unknown, undo: UndoList, backup: string): never {\n const outcome = undo.undo();\n const cause = error instanceof Error ? error.message : String(error);\n if (outcome.left.length === 0) {\n if (error instanceof CarnetError) throw error;\n throw new CarnetError('WORKSPACE_RELOCATE_FAILED', `${cause}; nothing was changed`);\n }\n throw new CarnetError(\n 'WORKSPACE_RELOCATE_FAILED',\n `${cause}; undo stopped, run by hand:\\n${outcome.left.join('\\n')}\\nDatabase backup: ${join(backup, 'carnet.db')}`,\n );\n}\n","import { closeSync, fstatSync, openSync, readSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nconst TRANSCRIPT_TAIL_BYTES = 256 * 1024;\nconst TRANSCRIPT_HEAD_BYTES = 64 * 1024;\nconst TITLE_PATTERN = /\"type\":\"custom-title\",\"customTitle\":(\"(?:[^\"\\\\]|\\\\.)*\")/g;\n\n// A slice of the file, so a long transcript is never read whole.\nfunction readSlice(path: string, from: 'start' | 'end', bytes: number): string | undefined {\n let descriptor: number | undefined;\n try {\n descriptor = openSync(path, 'r');\n const size = fstatSync(descriptor).size;\n const length = Math.min(size, bytes);\n const buffer = Buffer.alloc(length);\n readSync(descriptor, buffer, 0, length, from === 'end' ? size - length : 0);\n return buffer.toString('utf8');\n } catch {\n return undefined;\n } finally {\n if (descriptor !== undefined) closeSync(descriptor);\n }\n}\n\nexport function transcriptTitle(path: string): string | undefined {\n const tail = readSlice(path, 'end', TRANSCRIPT_TAIL_BYTES);\n if (tail === undefined) return undefined;\n const last = [...tail.matchAll(TITLE_PATTERN)].at(-1)?.[1];\n return last === undefined ? undefined : (JSON.parse(last) as string);\n}\n\nfunction records(text: string | undefined): Record<string, unknown>[] {\n return (text ?? '').split('\\n').flatMap((line) => {\n try {\n const value = JSON.parse(line) as unknown;\n return value && typeof value === 'object' ? [value as Record<string, unknown>] : [];\n } catch {\n return [];\n }\n });\n}\n\n// Claude Code hands a conversation over to a new id (Remote Control, its daemon) by forking it:\n// the old transcript ends with continued-in, the new one opens with derived-from.\nexport function continuesConversation(\n parentFile: string,\n childFile: string,\n parentId: string,\n childId: string,\n): boolean {\n const handedOver = records(readSlice(parentFile, 'end', TRANSCRIPT_TAIL_BYTES)).some(\n (record) => record.type === 'continued-in' && record.continuedInSessionId === childId,\n );\n if (handedOver) return true;\n return records(readSlice(childFile, 'start', TRANSCRIPT_HEAD_BYTES)).some(\n (record) =>\n record.type === 'derived-from' &&\n Array.isArray(record.sessions) &&\n record.sessions.some(\n (source: unknown) =>\n !!source &&\n typeof source === 'object' &&\n (source as Record<string, unknown>).id === parentId &&\n (source as Record<string, unknown>).via === 'resume',\n ),\n );\n}\n\nexport function projectsDirectory(env: NodeJS.ProcessEnv): string {\n return join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');\n}\n\n// Folder names are prefixes of each other (shop, shop-web): always compute the exact one.\nexport function claudeProjectFolder(cwd: string, env: NodeJS.ProcessEnv = process.env): string {\n return join(projectsDirectory(env), cwd.replace(/[^a-zA-Z0-9]/g, '-'));\n}\n\nexport function claudeConfigFile(env: NodeJS.ProcessEnv = process.env): string {\n return env.CLAUDE_CONFIG_DIR\n ? join(env.CLAUDE_CONFIG_DIR, '.claude.json')\n : join(env.HOME || homedir(), '.claude.json');\n}\n","import { closeSync, openSync, readFileSync, readSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type {\n HookHost,\n HostPromptPayload,\n HostSessionEndPayload,\n HostSessionPayload,\n HostStopPayload,\n HostSubagentPayload,\n HostToolPayload,\n} from './host.ts';\nimport { transcriptTitle } from './claude-code-store.ts';\n\nconst FORK_NAME_PATTERN = /You are (?:agent|fork) `([^`]+)`/;\nconst RENDERING_SOURCES = new Set(['startup', 'clear', 'compact', '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\nconst PROMPT_LINE_BYTES = 64 * 1024;\n\n// The stop payload names the subagent transcript; earlier hooks only give the main one, beside which\n// Claude Code keeps the subagent files from launch.\nfunction subagentTranscript(payload: HostSubagentPayload): string | undefined {\n if (payload.agent_transcript_path) return payload.agent_transcript_path;\n if (!payload.transcript_path) return undefined;\n return join(\n dirname(payload.transcript_path),\n payload.session_id,\n 'subagents',\n `agent-${payload.agent_id}.jsonl`,\n );\n}\n\nfunction subagentMetadataDescription(transcriptPath: string): string | undefined {\n try {\n const metadata = JSON.parse(\n readFileSync(transcriptPath.replace(/\\.jsonl$/, '.meta.json'), 'utf8'),\n ) as Record<string, unknown>;\n return text(metadata, 'description');\n } catch {\n return undefined;\n }\n}\n\nfunction launchedNames(toolInput: Record<string, unknown>): string[] | undefined {\n const prompt = text(toolInput, 'prompt');\n const names = [text(toolInput, 'description'), prompt && FORK_NAME_PATTERN.exec(prompt)?.[1]];\n const found = names.filter((name): name is string => Boolean(name));\n return found.length > 0 ? [...new Set(found)] : undefined;\n}\n\nfunction subagentPromptName(transcriptPath: string): string | undefined {\n let descriptor: number;\n try {\n descriptor = openSync(transcriptPath, 'r');\n } catch {\n return undefined;\n }\n try {\n const buffer = Buffer.alloc(PROMPT_LINE_BYTES);\n const read = readSync(descriptor, buffer, 0, PROMPT_LINE_BYTES, 0);\n const firstLine = buffer.subarray(0, read).toString('utf8').split('\\n', 1)[0] ?? '';\n return FORK_NAME_PATTERN.exec(firstLine)?.[1];\n } finally {\n closeSync(descriptor);\n }\n}\n\nexport const claudeCodeHooks: HookHost = {\n processId(env) {\n const processId = Number(env.CLAUDE_PID);\n return Number.isInteger(processId) && processId > 0 ? processId : null;\n },\n sessionIdFromEnvironment(env) {\n return env.CLAUDE_CODE_SESSION_ID || undefined;\n },\n projectDirectory(env) {\n return env.CLAUDE_PROJECT_DIR || undefined;\n },\n parseSessionPayload(json): HostSessionPayload {\n const data = payloadObject(json);\n return {\n session_id: data.session_id as string,\n cwd: text(data, 'cwd'),\n source: text(data, 'source'),\n session_title: text(data, 'session_title'),\n };\n },\n parseStopPayload(json): HostStopPayload {\n const data = payloadObject(json);\n return {\n session_id: data.session_id as string,\n cwd: text(data, 'cwd'),\n failed: data.hook_event_name === 'StopFailure',\n transcript_path: text(data, 'transcript_path'),\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 transcript_path: text(data, '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 transcript_path: text(data, 'transcript_path'),\n };\n },\n parseToolPayload(json): HostToolPayload {\n const data = payloadObject(json);\n const toolName = text(data, 'tool_name');\n const cwd = text(data, 'cwd');\n const toolInput =\n typeof data.tool_input === 'object' && data.tool_input !== null\n ? (data.tool_input as Record<string, unknown>)\n : {};\n return {\n session_id: data.session_id as string,\n cwd,\n tool_name: toolName,\n agent_id: text(data, 'agent_id'),\n agent_type: text(data, 'agent_type'),\n transcript_path: text(data, 'transcript_path'),\n path: touchedPath(toolName, data.tool_input, cwd),\n file_path: text(toolInput, 'file_path') ?? text(toolInput, 'notebook_path'),\n command: text(toolInput, 'command'),\n subagent_type: text(toolInput, 'subagent_type'),\n launched_names: launchedNames(toolInput),\n };\n },\n subagentInheritsContext(payload) {\n return payload.agent_type === 'fork';\n },\n // The system prompt is rendered again on these sources and kept as is on resume.\n rendersSystemPrompt(source) {\n return RENDERING_SOURCES.has(source);\n },\n subagentNames(payload) {\n const transcript = subagentTranscript(payload);\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};\n","import { closeSync, fstatSync, openSync, readSync } from 'node:fs';\nimport type { TranscriptChunk, TranscriptSlice } from './host.ts';\n\nconst MESSAGE_MAX_CHARACTERS = 8 * 1024;\nconst CHUNK_MAX_CHARACTERS = 16 * 1024;\nconst SKIP_BLOCK_BYTES = 1024 * 1024;\nconst NEWLINE = 0x0a;\n\n// Text the host injects into the conversation, not what the human or the model wrote.\nconst INJECTED =\n /<(system-reminder|task-notification|local-command-[a-z]+|command-[a-z]+|bash-[a-z]+)>[\\s\\S]*?<\\/\\1>/g;\n\nfunction clean(text: string): string {\n const stripped = text.replace(INJECTED, '').trim();\n return stripped.length > MESSAGE_MAX_CHARACTERS\n ? stripped.slice(0, MESSAGE_MAX_CHARACTERS)\n : stripped;\n}\n\nfunction textBlocks(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .flatMap((block: unknown) => {\n if (!block || typeof block !== 'object') return [];\n const { type, text } = block as Record<string, unknown>;\n return type === 'text' && typeof text === 'string' ? [text] : [];\n })\n .join('\\n');\n}\n\ninterface Message {\n role: 'user' | 'assistant';\n at: string | null;\n text: string;\n}\n\n// Tool calls and their outputs, thinking, images and side chains are left out.\nfunction message(line: string): Message | undefined {\n let record: Record<string, unknown>;\n try {\n const value = JSON.parse(line) as unknown;\n if (!value || typeof value !== 'object') return undefined;\n record = value as Record<string, unknown>;\n } catch {\n return undefined;\n }\n const role = record.type;\n if (role !== 'user' && role !== 'assistant') return undefined;\n if (record.isMeta === true || record.isSidechain === true) return undefined;\n const content = (record.message as Record<string, unknown> | undefined)?.content;\n const text = clean(textBlocks(content));\n if (!text) return undefined;\n return { role, at: typeof record.timestamp === 'string' ? record.timestamp : null, text };\n}\n\n// Skips one line too long to be worth reading; undefined when it is still being written.\nfunction endOfLine(descriptor: number, from: number, size: number): number | undefined {\n const block = Buffer.alloc(SKIP_BLOCK_BYTES);\n for (let position = from; position < size; position += SKIP_BLOCK_BYTES) {\n const read = readSync(\n descriptor,\n block,\n 0,\n Math.min(SKIP_BLOCK_BYTES, size - position),\n position,\n );\n const newline = block.subarray(0, read).indexOf(NEWLINE);\n if (newline !== -1) return position + newline + 1;\n }\n return undefined;\n}\n\n// Only whole lines are read, so a line being written is picked up by the next call.\nexport function readClaudeTranscript(\n path: string,\n fromOffset: number,\n maxBytes: number,\n): TranscriptSlice {\n const descriptor = openSync(path, 'r');\n try {\n const size = fstatSync(descriptor).size;\n if (fromOffset >= size) return { chunks: [], nextOffset: fromOffset, size };\n const length = Math.min(maxBytes, size - fromOffset);\n const buffer = Buffer.alloc(length);\n readSync(descriptor, buffer, 0, length, fromOffset);\n const lastNewline = buffer.lastIndexOf(NEWLINE);\n if (lastNewline === -1) {\n const next = length < size - fromOffset ? endOfLine(descriptor, fromOffset, size) : undefined;\n return { chunks: [], nextOffset: next ?? fromOffset, size };\n }\n const chunks: TranscriptChunk[] = [];\n let current: TranscriptChunk | undefined;\n let start = 0;\n while (start <= lastNewline) {\n const end = buffer.indexOf(NEWLINE, start);\n const found = message(buffer.toString('utf8', start, end));\n // A full chunk starts another one, so a later assistant line is still indexed.\n const full = current !== undefined && current.text.length >= CHUNK_MAX_CHARACTERS;\n if (found && (found.role === 'user' || !current || full)) {\n current = { offset: fromOffset + start, at: found.at, text: found.text };\n chunks.push(current);\n } else if (found && current) {\n current.text = `${current.text}\\n${found.text}`.slice(0, CHUNK_MAX_CHARACTERS);\n }\n start = end + 1;\n }\n return { chunks, nextOffset: fromOffset + lastNewline + 1, size };\n } finally {\n closeSync(descriptor);\n }\n}\n","import { closeSync, fstatSync, openSync, readSync } from 'node:fs';\nimport type { TranscriptUsage } from './host.ts';\n\nconst TAIL_BYTES = 512 * 1024;\nconst CHUNK_BYTES = 1024 * 1024;\n\ninterface Usage {\n input: number;\n cacheRead: number;\n cacheCreation: number;\n output: number;\n}\n\nfunction count(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction assistantUsage(line: string): { id: string; usage: Usage } | undefined {\n let record: Record<string, unknown>;\n try {\n const value = JSON.parse(line) as unknown;\n if (!value || typeof value !== 'object') return undefined;\n record = value as Record<string, unknown>;\n } catch {\n return undefined;\n }\n if (record.type !== 'assistant') return undefined;\n const message = record.message as Record<string, unknown> | undefined;\n const usage = message?.usage as Record<string, unknown> | undefined;\n if (!usage) return undefined;\n const id =\n typeof message?.id === 'string'\n ? message.id\n : typeof record.uuid === 'string'\n ? record.uuid\n : '';\n return {\n id,\n usage: {\n input: count(usage.input_tokens),\n cacheRead: count(usage.cache_read_input_tokens),\n cacheCreation: count(usage.cache_creation_input_tokens),\n output: count(usage.output_tokens),\n },\n };\n}\n\nconst contextOf = (usage: Usage) => usage.input + usage.cacheRead + usage.cacheCreation;\n\n// A subagent transcript can hold tens of megabytes: it is read by chunks, never whole.\nfunction* fileLines(path: string): Generator<string> {\n const descriptor = openSync(path, 'r');\n try {\n const buffer = Buffer.alloc(CHUNK_BYTES);\n let rest = Buffer.alloc(0);\n for (;;) {\n const read = readSync(descriptor, buffer, 0, CHUNK_BYTES, null);\n if (read === 0) break;\n let data = Buffer.concat([rest, buffer.subarray(0, read)]);\n let newline = data.indexOf(10);\n while (newline !== -1) {\n yield data.subarray(0, newline).toString('utf8');\n data = data.subarray(newline + 1);\n newline = data.indexOf(10);\n }\n rest = Buffer.from(data);\n }\n if (rest.length) yield rest.toString('utf8');\n } finally {\n closeSync(descriptor);\n }\n}\n\n// Claude Code writes one line per content block of a message, each repeating the message's usage,\n// so a message counts once.\nexport function claudeTranscriptUsage(path: string): TranscriptUsage | undefined {\n const seen = new Set<string>();\n const total: TranscriptUsage = {\n turns: 0,\n input: 0,\n cacheRead: 0,\n cacheCreation: 0,\n output: 0,\n firstContext: 0,\n lastContext: 0,\n };\n try {\n for (const line of fileLines(path)) {\n const found = assistantUsage(line);\n if (!found) continue;\n if (found.id) {\n if (seen.has(found.id)) continue;\n seen.add(found.id);\n }\n total.turns += 1;\n total.input += found.usage.input;\n total.cacheRead += found.usage.cacheRead;\n total.cacheCreation += found.usage.cacheCreation;\n total.output += found.usage.output;\n if (total.turns === 1) total.firstContext = contextOf(found.usage);\n total.lastContext = contextOf(found.usage);\n }\n } catch {\n return undefined;\n }\n return total.turns ? total : undefined;\n}\n\n// Only the tail is read: a main transcript can hold megabytes.\nexport function claudeLastContext(path: string): number | undefined {\n let descriptor: number;\n try {\n descriptor = openSync(path, 'r');\n } catch {\n return undefined;\n }\n try {\n const size = fstatSync(descriptor).size;\n const length = Math.min(TAIL_BYTES, size);\n const buffer = Buffer.alloc(length);\n readSync(descriptor, buffer, 0, length, size - length);\n const lines = buffer.toString('utf8').split('\\n');\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n const found = assistantUsage(lines[index] ?? '');\n if (found) return contextOf(found.usage);\n }\n return undefined;\n } finally {\n closeSync(descriptor);\n }\n}\n","import { spawnSync } from 'node:child_process';\nimport { existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { LaunchPlan } from '../launch-plan.ts';\nimport type { LaunchHost, LiveSession } from './host.ts';\nimport {\n claudeProjectFolder,\n continuesConversation,\n projectsDirectory,\n} from './claude-code-store.ts';\nimport { readClaudeTranscript } from './claude-code-transcript.ts';\nimport { claudeLastContext, claudeTranscriptUsage } from './claude-code-usage.ts';\n\nfunction modeArguments(plan: LaunchPlan): string[] {\n if (plan.mode === 'fork') return ['--resume', plan.parentId ?? '', '--fork-session'];\n if (plan.mode === 'resume') return ['--resume', plan.sessionId ?? ''];\n return ['--session-id', plan.sessionId ?? ''];\n}\n\nconst AGENTS_TIMEOUT_MILLISECONDS = 3000;\n\n// `claude agents --json` lists the live sessions, interactive and background; its shape is not a\n// documented contract, so anything unexpected reads as not live.\nexport function claudeLiveSession(json: string, sessionId: string): LiveSession | undefined {\n let entries: unknown;\n try {\n entries = JSON.parse(json);\n } catch {\n return undefined;\n }\n if (!Array.isArray(entries)) return undefined;\n for (const entry of entries) {\n if (!entry || typeof entry !== 'object') continue;\n const record = entry as Record<string, unknown>;\n if (record.sessionId !== sessionId) continue;\n if (record.kind === 'background' && typeof record.id === 'string') {\n return { kind: 'background', id: record.id };\n }\n if (record.kind === 'interactive') return { kind: 'interactive' };\n }\n return undefined;\n}\n\nexport const claudeCodeLaunch: LaunchHost = {\n command(plan, passthrough = []) {\n return {\n command: 'claude',\n args: [\n ...modeArguments(plan),\n ...(plan.name ? ['--name', plan.name] : []),\n '--append-system-prompt-file',\n plan.systemAppend.path,\n ...plan.dirs.flatMap((directory) => ['--add-dir', directory]),\n ...(plan.model ? ['--model', plan.model] : []),\n ...passthrough,\n ],\n // Repos are added directories: without it Claude Code skips their CLAUDE.md.\n env: { CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: '1' },\n };\n },\n liveSession(sessionId, env = process.env) {\n const result = spawnSync('claude', ['agents', '--json'], {\n encoding: 'utf8',\n env,\n stdio: ['ignore', 'pipe', 'ignore'],\n timeout: AGENTS_TIMEOUT_MILLISECONDS,\n });\n if (result.error || result.status !== 0 || !result.stdout) return undefined;\n return claudeLiveSession(result.stdout, sessionId);\n },\n attachCommand(id) {\n return { command: 'claude', args: ['attach', id], env: {} };\n },\n // Claude Code keeps each conversation under a project directory derived from its cwd.\n transcriptFiles(session, env = process.env) {\n if (!session.cwd) return [];\n const project = claudeProjectFolder(session.cwd, env);\n return [join(project, `${session.id}.jsonl`), join(project, session.id)].filter((path) =>\n existsSync(path),\n );\n },\n readTranscript: readClaudeTranscript,\n transcriptUsage: claudeTranscriptUsage,\n lastContext: claudeLastContext,\n // Claude Code writes no transcript before the first message. Every project directory is\n // searched, so a conversation filed under another cwd is never shadowed by a fresh one.\n hasConversation(session, env = process.env) {\n const projects = projectsDirectory(env);\n if (!existsSync(projects)) return false;\n return readdirSync(projects).some((project) =>\n existsSync(join(projects, project, `${session.id}.jsonl`)),\n );\n },\n continues(parent, childId, env = process.env) {\n if (!parent.cwd) return false;\n const project = claudeProjectFolder(parent.cwd, env);\n return continuesConversation(\n join(project, `${parent.id}.jsonl`),\n join(project, `${childId}.jsonl`),\n parent.id,\n childId,\n );\n },\n renameInstruction(name) {\n return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;\n },\n};\n","import {\n existsSync,\n readdirSync,\n readFileSync,\n mkdirSync,\n renameSync,\n rmdirSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport {\n AGENTS_FILE,\n type Workspace,\n INSTRUCTIONS_FILE,\n definitionInstructions,\n} from '../workspace/workspace.ts';\nimport { PROMPT_FILE } from '../prompt/prompt.ts';\nimport { CLAUDE_NATIVE_FILES, workspaceContext } from '../context-files.ts';\nimport {\n GENERATED_MARKER,\n markdownCopy,\n mergeSettings,\n removeStaleCopies,\n writeGenerated,\n} from '../run-directory-files.ts';\nimport type { Host, HostRender, ProjectRelocation } from './host.ts';\nimport { CarnetError } from '../errors.ts';\nimport { shellQuote, type UndoStep } from '../workspace/undo.ts';\nimport { claudeConfigFile, claudeProjectFolder } from './claude-code-store.ts';\nimport { claudeCodeHooks } from './claude-code-hooks.ts';\nimport { claudeCodeLaunch } from './claude-code-launch.ts';\n\nexport { claudeConfigFile, claudeProjectFolder, transcriptTitle } from './claude-code-store.ts';\n\nconst SETTINGS_FILE = join('.claude', 'settings.json');\nconst BACKEND_NOTES = 'backends/claude.md';\n\n// Instruction files are copied, not linked: an @ import inside a link resolves next to its target,\n// outside the run directory, where Claude Code skips it without approval.\nexport function instructionFiles(workspace: Workspace): string[] {\n if (!existsSync(workspace.definition)) return [];\n return readdirSync(workspace.definition, { withFileTypes: true })\n .filter((item) => item.isFile() && item.name.endsWith('.md') && item.name !== PROMPT_FILE)\n .map((item) => item.name)\n .sort();\n}\n\nfunction repoAgentsImports(workspace: Workspace): string[] {\n return workspaceContext(workspace, { nativeFiles: CLAUDE_NATIVE_FILES }).repos.flatMap((repo) =>\n repo.own.filter((own) => own.loading === 'listed').map((own) => `@${own.path}`),\n );\n}\n\n// Claude Code has no reliable native AGENTS.md loading, so a generated CLAUDE.md imports it.\nfunction runDirectoryCopies(workspace: Workspace): Map<string, string> {\n const agents = definitionInstructions(workspace) === AGENTS_FILE;\n const read = (name: string) => readFileSync(join(workspace.definition, name), 'utf8');\n const copies = new Map(\n instructionFiles(workspace).map((name) => [name, markdownCopy(read(name))]),\n );\n if (!agents) return copies;\n const imports = copies.has(AGENTS_FILE) ? [`@${AGENTS_FILE}`] : [];\n if (existsSync(join(workspace.definition, BACKEND_NOTES))) {\n copies.set(BACKEND_NOTES, markdownCopy(read(BACKEND_NOTES)));\n imports.push(`@${BACKEND_NOTES}`);\n }\n imports.push(...repoAgentsImports(workspace));\n if (imports.length) copies.set(INSTRUCTIONS_FILE, markdownCopy(`${imports.join('\\n')}\\n`));\n return copies;\n}\n\nexport function workspaceSettings(workspace: Workspace): Record<string, unknown> {\n return mergeSettings(\n {\n '//': GENERATED_MARKER,\n permissions: {\n additionalDirectories: workspace.repos.map((repo) => repo.path),\n // The copies are rewritten on every render: instructions are edited in the definition.\n deny: [...runDirectoryCopies(workspace).keys()].sort().map((name) => `Edit(/${name})`),\n },\n },\n workspace.hosts['claude-code']?.settings ?? {},\n );\n}\n\nfunction removeStaleBackendNotes(workspace: Workspace, keep: ReadonlySet<string>): string[] {\n const directory = join(workspace.runDirectory, dirname(BACKEND_NOTES));\n const removed = removeStaleCopies(\n directory,\n new Set(\n [...keep]\n .filter((name) => dirname(name) === dirname(BACKEND_NOTES))\n .map((name) => basename(name)),\n ),\n );\n if (existsSync(directory) && readdirSync(directory).length === 0) rmdirSync(directory);\n return removed.map((name) => join(dirname(BACKEND_NOTES), name));\n}\n\nfunction renderClaudeRunDirectory(workspace: Workspace): HostRender {\n const rendered: HostRender = { written: [], removed: [] };\n const copies = runDirectoryCopies(workspace);\n for (const [name, content] of [...copies].sort(([a], [b]) => a.localeCompare(b))) {\n if (writeGenerated(join(workspace.runDirectory, name), content)) rendered.written.push(name);\n }\n const names = new Set(copies.keys());\n rendered.removed.push(...removeStaleCopies(workspace.runDirectory, names));\n rendered.removed.push(...removeStaleBackendNotes(workspace, names));\n const settings = `${JSON.stringify(workspaceSettings(workspace), null, 2)}\\n`;\n if (writeGenerated(join(workspace.runDirectory, SETTINGS_FILE), settings)) {\n rendered.written.push(SETTINGS_FILE);\n }\n return rendered;\n}\n\nfunction renameStep(from: string, to: string): UndoStep {\n return {\n command: `mv ${shellQuote(to)} ${shellQuote(from)}`,\n run: () => renameSync(to, from),\n };\n}\n\nfunction moveProject(source: string, target: string): ProjectRelocation {\n if (existsSync(target)) {\n throw new CarnetError(\n 'WORKSPACE_EXISTS',\n `Claude Code already has a project folder: ${target}`,\n );\n }\n renameSync(source, target);\n return { moves: [{ from: source, to: target }], undo: [renameStep(source, target)] };\n}\n\nconst MEMORY_INDEX = 'MEMORY.md';\n\n// Conversations are named by uuid and never collide; memory files can, so they take a prefix.\nfunction mergeProject(source: string, target: string, prefix: string): ProjectRelocation {\n const relocation: ProjectRelocation = { moves: [], undo: [] };\n const move = (from: string, to: string) => {\n if (existsSync(to)) {\n throw new CarnetError('WORKSPACE_EXISTS', `Claude Code project file already exists: ${to}`);\n }\n mkdirSync(dirname(to), { recursive: true });\n renameSync(from, to);\n relocation.moves.push({ from, to });\n relocation.undo.push(renameStep(from, to));\n };\n for (const entry of readdirSync(source)) {\n if (entry !== 'memory') move(join(source, entry), join(target, entry));\n }\n const memory = join(source, 'memory');\n if (!existsSync(memory)) return removeEmpty(relocation, [source]);\n const renamed = new Map<string, string>();\n for (const entry of readdirSync(memory)) {\n if (entry === MEMORY_INDEX) continue;\n const name = existsSync(join(target, 'memory', entry)) ? `${prefix}-${entry}` : entry;\n if (name !== entry) renamed.set(entry, name);\n move(join(memory, entry), join(target, 'memory', name));\n }\n const fromIndex = join(memory, MEMORY_INDEX);\n if (existsSync(fromIndex)) {\n const intoIndex = join(target, 'memory', MEMORY_INDEX);\n if (!existsSync(intoIndex)) move(fromIndex, intoIndex);\n else {\n const original = readFileSync(intoIndex, 'utf8');\n const added = [...renamed].reduce(\n (text, [from, to]) => text.replaceAll(`(${from})`, `(${to})`),\n readFileSync(fromIndex, 'utf8'),\n );\n const separator = original.endsWith('\\n') || original === '' ? '' : '\\n';\n writeFileSync(intoIndex, `${original}${separator}\\n## Ex-workspace ${prefix}\\n\\n${added}`);\n const fromText = readFileSync(fromIndex, 'utf8');\n unlinkSync(fromIndex);\n relocation.undo.push({\n command: `# restore ${shellQuote(intoIndex)} and ${shellQuote(fromIndex)} by hand`,\n run: () => {\n writeFileSync(fromIndex, fromText);\n writeFileSync(intoIndex, original);\n },\n });\n }\n }\n return removeEmpty(relocation, [memory, source]);\n}\n\n// The emptied folders go too; the undo recreates them before moving the files back.\nfunction removeEmpty(relocation: ProjectRelocation, folders: string[]): ProjectRelocation {\n for (const folder of folders) {\n if (readdirSync(folder).length > 0) continue;\n rmdirSync(folder);\n relocation.undo.push({\n command: `mkdir -p ${shellQuote(folder)}`,\n run: () => mkdirSync(folder, { recursive: true }),\n });\n }\n return relocation;\n}\n\nfunction relocateProject(\n from: string,\n to: string,\n env: NodeJS.ProcessEnv,\n mode: 'move' | 'merge' = 'move',\n): ProjectRelocation | null {\n const source = claudeProjectFolder(from, env);\n const target = claudeProjectFolder(to, env);\n if (!existsSync(source)) return null;\n if (mode === 'move') return moveProject(source, target);\n if (!existsSync(target)) return moveProject(source, target);\n return mergeProject(source, target, basename(from));\n}\n\n// Every running Claude session rewrites this file, so it is re-read right before the write and\n// only the trust entry changes. Without a target, the entry is dropped.\nfunction moveTrust(from: string, to: string | null, env: NodeJS.ProcessEnv): boolean {\n const file = claudeConfigFile(env);\n if (!existsSync(file)) return false;\n const config = JSON.parse(readFileSync(file, 'utf8')) as { projects?: Record<string, unknown> };\n const projects = config.projects;\n if (!projects || !(from in projects) || (to !== null && to in projects)) return false;\n config.projects = Object.fromEntries(\n Object.entries(projects).flatMap(([key, value]) =>\n key !== from ? [[key, value]] : to === null ? [] : [[to, value]],\n ),\n );\n const temporary = `${file}.rucher-${process.pid}`;\n writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\\n`, { mode: statSync(file).mode });\n renameSync(temporary, file);\n return true;\n}\n\nexport const claudeCode: Host = {\n id: 'claude-code',\n displayName: 'Claude Code',\n orchestration: 'main',\n renderRunDirectory: renderClaudeRunDirectory,\n relocateProject,\n moveTrust,\n hooks: claudeCodeHooks,\n launch: claudeCodeLaunch,\n};\n","import type { Host } from './host.ts';\n\n// The Rucher server runs its sessions through its own backend adapters: no hooks, no command line.\nexport const rucherServer: Host = {\n id: 'rucher',\n displayName: 'Rucher server',\n orchestration: 'server',\n renderRunDirectory: () => ({ written: [], removed: [] }),\n};\n","import { CarnetError } from '../errors.ts';\nimport type { Workspace } from '../workspace/locate.ts';\nimport type { Session } from '../sessions.ts';\nimport { claudeCode } from './claude-code.ts';\nimport { rucherServer } from './rucher.ts';\nimport type { LaunchPlan } from '../launch-plan.ts';\nimport type { UndoStep } from '../workspace/undo.ts';\n\nexport interface HostSessionPayload {\n session_id: string;\n cwd?: string | undefined;\n source?: string | undefined;\n session_title?: string | undefined;\n}\n\nexport interface HostPromptPayload {\n session_id: string;\n cwd?: string | undefined;\n session_title?: string | undefined;\n transcript_path?: string | undefined;\n}\n\nexport interface HostSubagentPayload {\n session_id: string;\n agent_id: string;\n agent_type?: string | undefined;\n cwd?: string | undefined;\n description?: string | undefined;\n agent_transcript_path?: string | undefined;\n // The main session's transcript, from which the subagent's own files are found at its start.\n transcript_path?: string | undefined;\n}\n\nexport interface HostStopPayload {\n session_id: string;\n cwd?: string | undefined;\n failed: boolean;\n transcript_path?: string | undefined;\n}\n\nexport interface HostSessionEndPayload {\n session_id: string;\n cwd?: string | undefined;\n reason?: string | undefined;\n transcript_path?: string | undefined;\n}\n\n// One exchange of a conversation: a prompt and the text answered to it.\nexport interface TranscriptChunk {\n offset: number;\n at: string | null;\n text: string;\n}\n\nexport interface TranscriptSlice {\n chunks: TranscriptChunk[];\n nextOffset: number;\n size: number;\n}\n\nexport interface HostToolPayload {\n session_id: string;\n cwd?: string | undefined;\n tool_name?: string | undefined;\n agent_id?: string | undefined;\n agent_type?: string | undefined;\n transcript_path?: string | undefined;\n path?: string | undefined;\n file_path?: string | undefined;\n command?: string | undefined;\n // An Agent call's subagent type, and the agent names it may launch: description, then prompt.\n subagent_type?: string | undefined;\n launched_names?: string[] | undefined;\n}\n\nexport interface HostCommand {\n command: string;\n args: string[];\n env: Record<string, string>;\n}\n\nexport interface HostRender {\n written: string[];\n removed: string[];\n}\n\nexport interface RelocatedFolder {\n from: string;\n to: string;\n}\n\nexport interface ProjectRelocation {\n moves: RelocatedFolder[];\n // In the order applied, so they undo in reverse.\n undo: UndoStep[];\n}\n\nexport type Orchestration = 'main' | 'server';\n\nexport interface HookHost {\n processId(env: NodeJS.ProcessEnv): number | null;\n sessionIdFromEnvironment(env: NodeJS.ProcessEnv): string | undefined;\n projectDirectory(env: NodeJS.ProcessEnv): string | undefined;\n parseSessionPayload(json: string): HostSessionPayload;\n parseStopPayload(json: string): HostStopPayload;\n parsePromptPayload(json: string): HostPromptPayload;\n parseSubagentPayload(json: string): HostSubagentPayload;\n parseSessionEndPayload(json: string): HostSessionEndPayload;\n parseToolPayload(json: string): HostToolPayload;\n subagentNames(payload: HostSubagentPayload): string[];\n subagentInheritsContext(payload: HostSubagentPayload): boolean;\n rendersSystemPrompt(source: string): boolean;\n promptTitle(payload: HostPromptPayload): string | undefined;\n}\n\nexport interface TranscriptUsage {\n turns: number;\n input: number;\n cacheRead: number;\n cacheCreation: number;\n output: number;\n // Tokens the model read on its first and last turn: what the agent started from and ended with.\n firstContext: number;\n lastContext: number;\n}\n\nexport type LiveSession = { kind: 'background'; id: string } | { kind: 'interactive' };\n\nexport interface LaunchHost {\n command(plan: LaunchPlan, passthrough?: readonly string[]): HostCommand;\n // Where the host is still running the session, if anywhere; undefined when it can't tell.\n liveSession?(sessionId: string, env?: NodeJS.ProcessEnv): LiveSession | undefined;\n attachCommand?(id: string): HostCommand;\n renameInstruction(name: string): string;\n transcriptFiles(session: Session, env?: NodeJS.ProcessEnv): string[];\n readTranscript?(path: string, fromOffset: number, maxBytes: number): TranscriptSlice;\n transcriptUsage?(path: string): TranscriptUsage | undefined;\n lastContext?(path: string): number | undefined;\n hasConversation(session: Session, env?: NodeJS.ProcessEnv): boolean;\n // True when the host carried the parent's conversation on under childId, rather than forking it.\n continues(parent: Session, childId: string, env?: NodeJS.ProcessEnv): boolean;\n}\n\nexport interface Host {\n id: string;\n displayName: string;\n orchestration: Orchestration;\n renderRunDirectory(workspace: Workspace): HostRender;\n // The host's own files kept per run directory, moved when a workspace is renamed.\n relocateProject?(\n from: string,\n to: string,\n env: NodeJS.ProcessEnv,\n mode?: 'move' | 'merge',\n ): ProjectRelocation | null;\n moveTrust?(from: string, to: string | null, env: NodeJS.ProcessEnv): boolean;\n hooks?: HookHost;\n launch?: LaunchHost;\n}\n\nexport const DEFAULT_HOST = 'claude-code';\n\nconst HOSTS: Readonly<Record<string, Host>> = {\n [claudeCode.id]: claudeCode,\n [rucherServer.id]: rucherServer,\n};\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\nexport function hookHost(id: string): HookHost {\n const host = hostById(id);\n if (!host.hooks) {\n throw new CarnetError('HOST_WITHOUT_HOOKS', `${host.displayName} sessions run no hooks`);\n }\n return host.hooks;\n}\n\nexport function launchHost(id: string): LaunchHost {\n const host = hostById(id);\n if (!host.launch) {\n throw new CarnetError(\n 'HOST_CANNOT_LAUNCH',\n `${host.displayName} sessions are not launched from the command line`,\n );\n }\n return host.launch;\n}\n","import { realpathSync } from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { closeAgentsWhere } from './agents.ts';\n\nfunction inTransaction<T>(db: DatabaseSync, run: () => T): T {\n db.exec('BEGIN IMMEDIATE');\n try {\n const result = run();\n db.exec('COMMIT');\n return result;\n } catch (error) {\n db.exec('ROLLBACK');\n throw error;\n }\n}\n\nexport function sessionWorkspaceName(db: DatabaseSync, sessionId: string): string | undefined {\n const row = db.prepare('SELECT workspace FROM sessions WHERE id = ?').get(sessionId) as\n | { workspace: string }\n | undefined;\n return row?.workspace;\n}\n\nexport function archiveWorkspaceSessions(db: DatabaseSync, name: string, at: string): number {\n return inTransaction(db, () => {\n closeAgentsWhere(db, 'session IN (SELECT id FROM sessions WHERE workspace = ?)', [name], at);\n return Number(\n db\n .prepare(\n `UPDATE sessions SET status = 'archived', last_active_at = ?\n WHERE workspace = ? AND status != 'archived'`,\n )\n .run(at, name).changes,\n );\n });\n}\n\nexport function deleteWorkspaceNotes(db: DatabaseSync, name: string): number {\n return Number(db.prepare('DELETE FROM notes WHERE workspace = ?').run(name).changes);\n}\n\nexport function workspaceSessionCounts(db: DatabaseSync): Map<string, number> {\n const rows = db\n .prepare(\n `SELECT workspace, COUNT(*) AS count FROM sessions\n WHERE status != 'archived' GROUP BY workspace`,\n )\n .all() as { workspace: string; count: number }[];\n return new Map(rows.map((row) => [row.workspace, Number(row.count)]));\n}\n\nexport function workspaceLastActive(db: DatabaseSync): Map<string, string> {\n const rows = db\n .prepare('SELECT workspace, MAX(last_active_at) AS at FROM sessions GROUP BY workspace')\n .all() as { workspace: string; at: string }[];\n return new Map(rows.map((row) => [row.workspace, row.at]));\n}\n\n// Not LIKE: a home path can hold _ or %, and the slash keeps workspace a from matching a-b.\nfunction rewritePrefix(\n db: DatabaseSync,\n table: string,\n column: string,\n from: string,\n to: string,\n): number {\n return Number(\n db\n .prepare(\n `UPDATE ${table} SET ${column} = ? || substr(${column}, length(?) + 1)\n WHERE ${column} = ? OR substr(${column}, 1, length(?) + 1) = ? || '/'`,\n )\n .run(to, from, from, from, from).changes,\n );\n}\n\nconst RUN_PATH_COLUMNS = [\n ['sessions', 'cwd'],\n ['agents', 'report_path'],\n ['agents', 'sandbox'],\n ['agents', 'worktree'],\n ['events', 'link'],\n ['reference_docs', 'path'],\n] as const;\n\nexport function realPathOf(path: string): string | undefined {\n try {\n return realpathSync(path);\n } catch {\n return undefined;\n }\n}\n\n// realFrom is realpath(from) taken before the directory moves. After the move, from is gone,\n// and a row stored as that real path would miss the logical prefix.\nexport function rewriteRunDirectory(\n db: DatabaseSync,\n from: string,\n to: string,\n realFrom?: string,\n): number {\n const rewrite = (prefix: string) =>\n RUN_PATH_COLUMNS.reduce(\n (total, [table, column]) => total + rewritePrefix(db, table, column, prefix, to),\n 0,\n );\n const rewritten = rewrite(from);\n return realFrom && realFrom !== from ? rewritten + rewrite(realFrom) : rewritten;\n}\n\nexport interface WorkspaceRowCounts {\n sessions: number;\n notes: number;\n activeDays: number;\n}\n\nexport function workspaceRowCounts(db: DatabaseSync, name: string): WorkspaceRowCounts {\n const count = (table: string) =>\n Number(\n (\n db.prepare(`SELECT COUNT(*) AS total FROM ${table} WHERE workspace = ?`).get(name) as {\n total: number;\n }\n ).total,\n );\n return { sessions: count('sessions'), notes: count('notes'), activeDays: count('active_days') };\n}\n\nexport interface RunningSessionRow {\n id: string;\n name: string | null;\n hostPid: number;\n}\n\nexport function runningWorkspaceSessions(db: DatabaseSync, name: string): RunningSessionRow[] {\n const rows = db\n .prepare(\n `SELECT id, name, host_pid FROM sessions\n WHERE workspace = ? AND status = 'running' AND host_pid IS NOT NULL`,\n )\n .all(name) as { id: string; name: string | null; host_pid: number }[];\n return rows.map((row) => ({ id: row.id, name: row.name, hostPid: Number(row.host_pid) }));\n}\n\nexport function renameWorkspaceRows(\n db: DatabaseSync,\n names: { from: string; to: string },\n runDirectories: { from: string; to: string },\n realFrom?: string,\n): WorkspaceRowCounts & { paths: number } {\n return inTransaction(db, () => {\n const counts = workspaceRowCounts(db, names.from);\n for (const table of ['sessions', 'notes', 'active_days']) {\n db.prepare(`UPDATE ${table} SET workspace = ? WHERE workspace = ?`).run(names.to, names.from);\n }\n return {\n ...counts,\n paths: rewriteRunDirectory(db, runDirectories.from, runDirectories.to, realFrom),\n };\n });\n}\n\nexport interface MergeRowsInput {\n names: { from: string; into: string };\n runDirectories: { from: string; into: string };\n // Old → new paths of what was renamed on collision, applied before the run directory rewrite.\n paths: ReadonlyMap<string, string>;\n realFrom?: string | undefined;\n // A repo of from known under another name in into: from's name → into's name.\n repos: ReadonlyMap<string, string>;\n}\n\nexport interface MergeRowsResult extends WorkspaceRowCounts {\n firstNumber: number;\n}\n\nexport function nextNoteNumber(db: DatabaseSync, name: string): number {\n const row = db\n .prepare('SELECT COALESCE(MAX(number), 0) AS top FROM notes WHERE workspace = ?')\n .get(name) as { top: number };\n return Number(row.top) + 1;\n}\n\nexport function mergeWorkspaceRows(db: DatabaseSync, input: MergeRowsInput): MergeRowsResult {\n const { from, into } = input.names;\n return inTransaction(db, () => {\n const counts = workspaceRowCounts(db, from);\n for (const [fromName, intoName] of input.repos) {\n db.prepare(\n `UPDATE note_repos SET repo = ?\n WHERE repo = ? AND note IN (SELECT id FROM notes WHERE workspace = ?)`,\n ).run(intoName, fromName, from);\n db.prepare(\n `UPDATE session_repos SET repo = ?\n WHERE repo = ? AND session IN (SELECT id FROM sessions WHERE workspace = ?)`,\n ).run(intoName, fromName, from);\n db.prepare('UPDATE sessions SET repo = ? WHERE repo = ? AND workspace = ?').run(\n intoName,\n fromName,\n from,\n );\n }\n const firstNumber = nextNoteNumber(db, into);\n // Offset, not renumbered densely: from's order and gaps stay, and no number can clash.\n db.prepare('UPDATE notes SET workspace = ?, number = number + ? WHERE workspace = ?').run(\n into,\n firstNumber - 1,\n from,\n );\n db.prepare('UPDATE sessions SET workspace = ? WHERE workspace = ?').run(into, from);\n db.prepare(\n 'INSERT OR IGNORE INTO active_days (workspace, day) SELECT ?, day FROM active_days WHERE workspace = ?',\n ).run(into, from);\n db.prepare('DELETE FROM active_days WHERE workspace = ?').run(from);\n const fromDirectory = input.runDirectories.from;\n for (const [oldPath, newPath] of input.paths) {\n // A row stored under the real path of a renamed file must follow the rename too.\n const realOld =\n input.realFrom && oldPath.startsWith(fromDirectory)\n ? input.realFrom + oldPath.slice(fromDirectory.length)\n : undefined;\n rewriteRunDirectory(db, oldPath, newPath, realOld);\n }\n rewriteRunDirectory(db, input.runDirectories.from, input.runDirectories.into, input.realFrom);\n return { ...counts, firstNumber };\n });\n}\n","import type { DatabaseSync } from 'node:sqlite';\nimport { join, relative, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { allHosts } from '../hosts/host.ts';\nimport { sessionWorkspaceName } from '../workspace-rows.ts';\nimport {\n type Workspace,\n type WorkspaceRepo,\n workspaceExists,\n listWorkspaces,\n loadableWorkspace,\n loadWorkspace,\n} from './workspace.ts';\n\nexport type { Workspace, WorkspaceRepo } from './workspace.ts';\n\nexport function isInside(directory: string, path: string): boolean {\n const relativePath = relative(directory, path);\n return (\n relativePath === '' ||\n (!relativePath.startsWith('..') && !resolve(relativePath).startsWith(relativePath))\n );\n}\n\nfunction repoOf(workspace: Workspace | null, path: string): WorkspaceRepo | undefined {\n const absolutePath = resolve(path);\n return workspace?.repos.find((repo) => isInside(repo.path, absolutePath));\n}\n\nexport function repoNameFor(workspace: Workspace | null, path: string | undefined): string | null {\n return path ? (repoOf(workspace, path)?.name ?? null) : null;\n}\n\nexport function repoPathFor(\n workspace: Workspace | null,\n path: string | undefined | null,\n): string | null {\n if (!path) return null;\n const repo = repoOf(workspace, path);\n if (!repo) return null;\n const relativePath = relative(repo.path, resolve(path));\n return relativePath ? join(repo.name, relativePath) : repo.name;\n}\n\nexport type WorkspaceOrigin = 'session' | 'option' | 'env' | 'run-directory' | 'none';\n\nexport interface WorkspaceResolution {\n workspace: Workspace | null;\n origin: WorkspaceOrigin;\n}\n\nexport interface ResolveWorkspaceOptions {\n db?: DatabaseSync | undefined;\n sessionId?: string | undefined;\n workspace?: string | undefined;\n cwd?: string | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n // A named workspace whose file can't be read resolves to null instead of throwing.\n tolerant?: boolean | undefined;\n}\n\nfunction namedWorkspace(name: string, env: NodeJS.ProcessEnv, tolerant: boolean): Workspace | null {\n if (!workspaceExists(name, env)) {\n throw new CarnetError(\n 'WORKSPACE_NOT_FOUND',\n `No workspace named ${name}: see \"rucher ws list\"`,\n );\n }\n return tolerant ? (loadableWorkspace(name, env) ?? null) : loadWorkspace(name, env);\n}\n\nfunction byRunDirectory(\n workspaces: readonly Workspace[],\n directories: readonly string[],\n): Workspace | undefined {\n return workspaces.find((workspace) =>\n directories.some((directory) => isInside(workspace.runDirectory, directory)),\n );\n}\n\nexport function resolveWorkspace({\n db,\n sessionId,\n workspace,\n cwd = process.cwd(),\n env = process.env,\n tolerant = false,\n}: ResolveWorkspaceOptions = {}): WorkspaceResolution {\n if (db && sessionId) {\n const name = sessionWorkspaceName(db, sessionId);\n if (name !== undefined && workspaceExists(name, env)) {\n return { workspace: loadableWorkspace(name, env) ?? null, origin: 'session' };\n }\n }\n if (workspace) return { workspace: namedWorkspace(workspace, env, tolerant), origin: 'option' };\n if (env.RUCHER_WS) {\n return { workspace: namedWorkspace(env.RUCHER_WS, env, tolerant), origin: 'env' };\n }\n const projectDirectories = allHosts()\n .map((host) => host.hooks?.projectDirectory(env))\n .filter((directory): directory is string => directory !== undefined);\n const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];\n const runDirectoryWorkspace = byRunDirectory(listWorkspaces(env), directories);\n if (runDirectoryWorkspace) return { workspace: runDirectoryWorkspace, origin: 'run-directory' };\n return { workspace: null, origin: 'none' };\n}\n\nexport function workspaceLabel(workspace: Workspace | null): string {\n return workspace?.name ?? 'no workspace';\n}\n\nexport function requireWorkspace(workspace: Workspace | null): Workspace {\n if (workspace) return workspace;\n throw new CarnetError(\n 'NO_WORKSPACE',\n \"No Rucher workspace here: pass --ws <name>, or run this from a workspace's run directory\",\n );\n}\n","import { fromJsonColumn, type Snapshot, snapshot } from './agent-json.ts';\nimport { CLAUDE_BACKEND, closeAgentsWhere } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { logEvent } from './events.ts';\nimport { type Workspace, repoNameFor } from './workspace/locate.ts';\nimport { DEFAULT_HOST, type HostSessionPayload } from './hosts/host.ts';\n\nexport type SessionKind = 'active' | 'temp';\nexport type SessionStatus = 'running' | 'idle' | 'archived';\n\nexport interface Session {\n id: string;\n workspace: string;\n name: string | null;\n purpose: string | null;\n kind: SessionKind;\n status: SessionStatus;\n cwd: string | null;\n repo: string | null;\n host: string;\n hostPid: number | null;\n hookedAt: string | null;\n lastTitle: string | null;\n parentId: string | null;\n promptVersion: string | null;\n pluginVersion: string | null;\n createdAt: string;\n lastActiveAt: string;\n endedAt: string | null;\n // The main agent's backend and model; backendRef is its id there when it differs from id.\n backend: string | null;\n model: string | null;\n backendRef: string | null;\n profile: string | null;\n // The resolved profile and where each setting came from, frozen for the session.\n profileDef: Snapshot | null;\n}\n\ninterface SessionRow {\n id: string;\n workspace: string;\n name: string | null;\n purpose: string | null;\n kind: SessionKind;\n status: SessionStatus;\n cwd: string | null;\n repo: string | null;\n host: string;\n host_pid: number | null;\n hooked_at: string | null;\n last_title: string | null;\n parent_id: string | null;\n prompt_version: string | null;\n plugin_version: string | null;\n created_at: string;\n last_active_at: string;\n ended_at: string | null;\n backend: string | null;\n model: string | null;\n backend_ref: string | null;\n profile: string | null;\n profile_def: string | null;\n}\n\nexport type HookSessionPayload = HostSessionPayload;\n\nexport interface HookEnv {\n host?: string | undefined;\n processId?: number | null | undefined;\n RUCHER_PURGE_DAYS?: string | undefined;\n RUCHER_HOME?: string | undefined;\n RUCHER_SESSION_ID?: string | undefined;\n RUCHER_SESSION_KIND?: string | undefined;\n RUCHER_SESSION_NAME?: string | undefined;\n RUCHER_PROMPT_VERSION?: string | undefined;\n RUCHER_MEMORY_MAX_CHARACTERS?: string | undefined;\n RUCHER_MEMORY_HALF_LIFE_DAYS?: string | undefined;\n CLAUDE_CONFIG_DIR?: string | undefined;\n}\n\nexport interface CreateSessionInput {\n id: string;\n kind: SessionKind;\n name?: string | null | undefined;\n cwd: string;\n repo?: string | null | undefined;\n host?: string | undefined;\n}\n\nexport interface ListSessionsOptions {\n includeTemp?: boolean | undefined;\n includeArchived?: boolean | undefined;\n}\n\nconst COLUMNS = `id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,\n parent_id, prompt_version, plugin_version, created_at, last_active_at, ended_at, backend, model,\n backend_ref, profile, profile_def`;\n\n// The claude-code host only runs Claude; other hosts set their backend themselves.\nfunction hostBackend(host: string): string | null {\n return host === DEFAULT_HOST ? CLAUDE_BACKEND : null;\n}\n\nfunction toSession(row: SessionRow): Session {\n return {\n id: row.id,\n workspace: row.workspace,\n name: row.name,\n purpose: row.purpose,\n kind: row.kind,\n status: row.status,\n cwd: row.cwd,\n repo: row.repo,\n host: row.host,\n hostPid: row.host_pid,\n hookedAt: row.hooked_at,\n lastTitle: row.last_title,\n parentId: row.parent_id,\n promptVersion: row.prompt_version,\n pluginVersion: row.plugin_version,\n createdAt: row.created_at,\n lastActiveAt: row.last_active_at,\n endedAt: row.ended_at,\n backend: row.backend,\n model: row.model,\n backendRef: row.backend_ref,\n profile: row.profile,\n profileDef: fromJsonColumn(snapshot, row.profile_def),\n };\n}\n\nfunction workspaceOf(ctx: Ctx): string {\n if (ctx.workspace !== null) return ctx.workspace;\n throw new CarnetError('NO_WORKSPACE', 'A session belongs to a workspace: there is none here');\n}\n\nexport function getSession(ctx: Ctx, id: string): Session | undefined {\n const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id) as\n | SessionRow\n | undefined;\n return row && toSession(row);\n}\n\nexport function requireSession(ctx: Ctx, id: string): Session {\n const session = getSession(ctx, id);\n if (!session) throw new CarnetError('SESSION_NOT_FOUND', `Unknown session ${id}`);\n return session;\n}\n\nexport function ensureSession(\n ctx: Ctx,\n id: string,\n cwd?: string,\n workspace?: Workspace | null,\n): Session {\n const existing = getSession(ctx, id);\n if (existing) return existing;\n const at = nowIso(ctx);\n ctx.db\n .prepare(\n `INSERT INTO sessions (id, workspace, cwd, repo, backend, created_at, last_active_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n id,\n workspaceOf(ctx),\n cwd ?? null,\n workspace ? repoNameFor(workspace, cwd) : null,\n hostBackend(DEFAULT_HOST),\n at,\n at,\n );\n return requireSession(ctx, id);\n}\n\nfunction nameTaken(error: unknown, name: string | null | undefined): never {\n if (name && error instanceof Error && error.message.includes('UNIQUE')) {\n throw new CarnetError('SESSION_NAME_TAKEN', `A session named \"${name}\" already exists`);\n }\n throw error;\n}\n\nexport function createSession(ctx: Ctx, input: CreateSessionInput): Session {\n if (input.kind === 'active' && !input.name) {\n throw new CarnetError('SESSION_NAME_REQUIRED', 'An active session needs a name');\n }\n const at = nowIso(ctx);\n try {\n ctx.db\n .prepare(\n `INSERT INTO sessions (id, workspace, name, kind, status, cwd, repo, host, backend,\n last_title, created_at, last_active_at)\n VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n input.id,\n workspaceOf(ctx),\n input.name ?? null,\n input.kind,\n input.cwd,\n input.repo ?? null,\n input.host ?? DEFAULT_HOST,\n hostBackend(input.host ?? DEFAULT_HOST),\n input.name ?? null,\n at,\n at,\n );\n } catch (error) {\n nameTaken(error, input.name);\n }\n return requireSession(ctx, input.id);\n}\n\nexport function setSessionKind(\n ctx: Ctx,\n id: string,\n kind: SessionKind,\n name?: string | null,\n): Session {\n const session = requireSession(ctx, id);\n const nextName = name ?? session.name;\n if (kind === 'active' && !nextName) {\n throw new CarnetError('SESSION_NAME_REQUIRED', 'An active session needs a name');\n }\n try {\n ctx.db\n .prepare('UPDATE sessions SET kind = ?, name = ?, last_title = ? WHERE id = ?')\n .run(kind, nextName, nextName ?? session.lastTitle, id);\n } catch (error) {\n nameTaken(error, nextName);\n }\n return requireSession(ctx, id);\n}\n\n// Both the launching process and the SessionEnd hook report the end: only the first one counts.\nexport function endSession(ctx: Ctx, id: string): Session {\n const session = requireSession(ctx, id);\n if (session.status !== 'running') return session;\n const ended = setSessionStatus(ctx, id, 'idle');\n logEvent(ctx, id, { type: 'session.ended' });\n return ended;\n}\n\nfunction titleAvailable(ctx: Ctx, id: string, title: string): boolean {\n const owner = sessionByName(ctx, title);\n return !owner || owner.id === id;\n}\n\n// The Rucher name is canonical: a host title only renames the session when the title itself\n// changed since it was last seen, so a rename made in Rucher survives the next prompt.\nexport function adoptTitle(ctx: Ctx, id: string, rawTitle: string | undefined): Session {\n const session = requireSession(ctx, id);\n const title = rawTitle?.trim() || null;\n if (title === null || title === session.lastTitle) return session;\n ctx.db.prepare('UPDATE sessions SET last_title = ? WHERE id = ?').run(title, id);\n if (title === session.name || !titleAvailable(ctx, id, title)) return requireSession(ctx, id);\n ctx.db\n .prepare(\n `UPDATE sessions\n SET name = ?, kind = CASE WHEN name IS NULL THEN 'active' ELSE kind END\n WHERE id = ?`,\n )\n .run(title, id);\n return requireSession(ctx, id);\n}\n\nexport function upsertFromHook(\n ctx: Ctx,\n workspace: Workspace | null,\n payload: HookSessionPayload,\n env: HookEnv = {},\n): Session {\n const at = nowIso(ctx);\n const host = env.host ?? DEFAULT_HOST;\n const hostPid = env.processId ?? null;\n const repo = workspace ? repoNameFor(workspace, payload.cwd) : null;\n const existing = getSession(ctx, payload.session_id);\n if (!existing) {\n ctx.db\n .prepare(\n `INSERT INTO sessions (id, workspace, cwd, repo, host, backend, host_pid, hooked_at,\n created_at, last_active_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n payload.session_id,\n workspaceOf(ctx),\n payload.cwd ?? null,\n repo,\n host,\n hostBackend(host),\n hostPid,\n at,\n at,\n at,\n );\n } else {\n ctx.db\n .prepare(\n `UPDATE sessions\n SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?\n WHERE id = ?`,\n )\n .run(\n at,\n at,\n // Claude Code keeps transcripts under the launch cwd; the hook's cwd follows every `cd`.\n existing.cwd ?? payload.cwd ?? null,\n existing.cwd ? existing.repo : (repo ?? existing.repo),\n host,\n hostPid ?? existing.hostPid,\n payload.session_id,\n );\n }\n return adoptTitle(ctx, payload.session_id, payload.session_title);\n}\n\nexport function touchSession(ctx: Ctx, id: string): void {\n ctx.db.prepare('UPDATE sessions SET last_active_at = ? WHERE id = ?').run(nowIso(ctx), id);\n}\n\nexport function nameSession(ctx: Ctx, id: string, name: string, purpose?: string): Session {\n requireSession(ctx, id);\n try {\n ctx.db\n .prepare(\n `UPDATE sessions\n SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,\n kind = 'active'\n WHERE id = ?`,\n )\n .run(name, purpose ?? null, nowIso(ctx), id);\n } catch (error) {\n if (error instanceof Error && error.message.includes('UNIQUE')) {\n throw new CarnetError('SESSION_NAME_TAKEN', `A session named \"${name}\" already exists`);\n }\n throw error;\n }\n return requireSession(ctx, id);\n}\n\nexport function listSessions(ctx: Ctx, options: ListSessionsOptions = {}): Session[] {\n const conditions: string[] = ['workspace = ?'];\n if (!options.includeTemp) conditions.push(\"kind != 'temp'\");\n if (!options.includeArchived) conditions.push(\"status != 'archived'\");\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(' AND ')} ORDER BY last_active_at DESC, rowid DESC`,\n )\n .all(ctx.workspace) as unknown as SessionRow[];\n return rows.map(toSession);\n}\n\nexport function dropSession(ctx: Ctx, id: string): Session {\n requireSession(ctx, id);\n const at = nowIso(ctx);\n closeAgentsWhere(ctx.db, 'session = ?', [id], at);\n ctx.db\n .prepare(\"UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?\")\n .run(at, id);\n return requireSession(ctx, id);\n}\n\nexport function defaultSession(ctx: Ctx): Session | undefined {\n const row = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND status != 'archived'\n ORDER BY last_active_at DESC, rowid DESC LIMIT 1`,\n )\n .get(ctx.workspace) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport function sessionByName(ctx: Ctx, name: string): Session | undefined {\n const row = ctx.db\n .prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND name = ?`)\n .get(ctx.workspace, name) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport const MINIMUM_ID_PREFIX = 4;\n\nexport function shortId(id: string): string {\n return id.slice(0, 8);\n}\n\nexport function findSession(ctx: Ctx, reference: string): Session {\n const byName = sessionByName(ctx, reference);\n if (byName) return byName;\n const byId = getSession(ctx, reference);\n if (byId) return byId;\n const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);\n if (isIdPrefix && reference.length >= MINIMUM_ID_PREFIX) {\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND id LIKE ?\n ORDER BY last_active_at DESC, rowid DESC`,\n )\n .all(ctx.workspace, `${reference.toLowerCase()}%`) as unknown as SessionRow[];\n const [only, ...others] = rows;\n if (only && others.length === 0) return toSession(only);\n if (only) {\n const matches = rows.map((row) => shortId(row.id)).join(', ');\n throw new CarnetError(\n 'SESSION_AMBIGUOUS',\n `Session id \"${reference}\" matches several sessions: ${matches}`,\n );\n }\n }\n const hint =\n isIdPrefix && reference.length < MINIMUM_ID_PREFIX\n ? ` (an id prefix needs at least ${MINIMUM_ID_PREFIX} characters)`\n : '';\n throw new CarnetError('SESSION_NOT_FOUND', `Unknown session \"${reference}\"${hint}`);\n}\n\nexport function sessionByHostProcess(\n ctx: Ctx,\n host: string,\n processId: number,\n): Session | undefined {\n const row = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions\n WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL\n ORDER BY hooked_at DESC, rowid DESC LIMIT 1`,\n )\n .get(host, processId) as SessionRow | undefined;\n return row && toSession(row);\n}\n\nexport function recordPluginVersion(ctx: Ctx, id: string, version: string | null): void {\n ctx.db.prepare('UPDATE sessions SET plugin_version = ? WHERE id = ?').run(version, id);\n}\n\nexport function recordPromptVersion(ctx: Ctx, id: string, version: string | null): Session {\n requireSession(ctx, id);\n ctx.db.prepare('UPDATE sessions SET prompt_version = ? WHERE id = ?').run(version, id);\n return requireSession(ctx, id);\n}\n\nexport function setParent(ctx: Ctx, id: string, parentId: string): Session {\n requireSession(ctx, id);\n requireSession(ctx, parentId);\n ctx.db.prepare('UPDATE sessions SET parent_id = ? WHERE id = ?').run(parentId, id);\n return requireSession(ctx, id);\n}\n\nexport function setSessionStatus(ctx: Ctx, id: string, status: SessionStatus): Session {\n requireSession(ctx, id);\n const at = nowIso(ctx);\n ctx.db\n .prepare(\n `UPDATE sessions\n SET status = ?, last_active_at = ?,\n ended_at = CASE WHEN ? = 'running' THEN NULL WHEN ? = 'idle' THEN ? ELSE ended_at END\n WHERE id = ?`,\n )\n .run(status, at, status, status, at, id);\n return requireSession(ctx, id);\n}\n\nfunction refuseWhileRunning(session: Session, action: string): void {\n if (session.status === 'running') {\n throw new CarnetError(\n 'SESSION_RUNNING',\n `Session ${session.name ?? shortId(session.id)} is running: ${action} it once it has ended`,\n );\n }\n}\n\n// last_title keeps the host title last seen: the old title then matches it and doesn't undo the rename.\nexport function renameSession(ctx: Ctx, id: string, name: string): Session {\n const session = requireSession(ctx, id);\n refuseWhileRunning(session, 'rename');\n try {\n ctx.db.prepare('UPDATE sessions SET name = ? WHERE id = ?').run(name, id);\n } catch (error) {\n nameTaken(error, name);\n }\n return requireSession(ctx, id);\n}\n\nexport function promoteSession(ctx: Ctx, id: string, name?: string): Session {\n const session = requireSession(ctx, id);\n if (session.kind === 'active') {\n throw new CarnetError('SESSION_KIND_INVALID', `Session ${session.name} is already active`);\n }\n const nextName = name ?? session.name;\n if (!nextName) {\n throw new CarnetError('SESSION_NAME_REQUIRED', 'An active session needs a name');\n }\n if (nextName !== session.name) refuseWhileRunning(session, 'rename');\n try {\n ctx.db.prepare(\"UPDATE sessions SET kind = 'active', name = ? WHERE id = ?\").run(nextName, id);\n } catch (error) {\n nameTaken(error, nextName);\n }\n return requireSession(ctx, id);\n}\n\nexport function demoteSession(ctx: Ctx, id: string): Session {\n const session = requireSession(ctx, id);\n if (session.kind === 'temp') {\n throw new CarnetError(\n 'SESSION_KIND_INVALID',\n `Session ${session.name ?? shortId(session.id)} is already temp`,\n );\n }\n ctx.db.prepare(\"UPDATE sessions SET kind = 'temp' WHERE id = ?\").run(id);\n return requireSession(ctx, id);\n}\n\nexport function staleTempSessions(ctx: Ctx, olderThanMilliseconds: number): Session[] {\n const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();\n const rows = ctx.db\n .prepare(\n `SELECT ${COLUMNS} FROM sessions\n WHERE workspace = ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?\n ORDER BY last_active_at ASC, rowid ASC`,\n )\n .all(ctx.workspace, before) as unknown as SessionRow[];\n return rows.map(toSession);\n}\n\nexport function resetDeadSessions(ctx: Ctx, isAlive: (processId: number) => boolean): Session[] {\n const running = (\n ctx.db\n .prepare(`SELECT ${COLUMNS} FROM sessions WHERE status = 'running'`)\n .all() as unknown as SessionRow[]\n ).map(toSession);\n const dead = running.filter((session) => session.hostPid === null || !isAlive(session.hostPid));\n return dead.map((session) => endSession(ctx, session.id));\n}\n","import { existsSync, statSync } from 'node:fs';\nimport type { Attachment } from './agent-json.ts';\nimport {\n type Agent,\n type AgentContext,\n getAgent,\n getAgentById,\n mainTargetRange,\n} from './agents.ts';\nimport type { Ctx } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { type Finding, findingsOf } from './findings.ts';\nimport { memoryPart, startNotes } from './memory.ts';\nimport { compareNotes, DEFAULT_HALF_LIFE_DAYS, listNotes, type WeightedNote } from './notes.ts';\nimport { type Question, questionsOf } from './questions.ts';\nimport { getReference, listReferences } from './references.ts';\nimport { extractSection, keptReportPath, readReport } from './report.ts';\nimport { KIND_CONTRACTS } from './prompt/kind-contracts.ts';\nimport { getSession } from './sessions.ts';\nimport { kindTag } from './status/model.ts';\n\nexport const FOR_MAIN_SECTIONS = ['for the main', 'pour le main'];\nexport const PLAN_SECTIONS = ['plan'];\n\nexport type BriefPartType =\n | 'workplace'\n | 'target'\n | 'reference'\n | 'deliverable'\n | 'for_main'\n | 'findings'\n | 'notes';\n\n// Documents and full reports stay files the agent opens; only short extracts carry text.\nexport interface BriefPart {\n type: BriefPartType;\n title: string;\n path?: string | undefined;\n bytes?: number | null | undefined;\n text?: string | undefined;\n missing?: boolean | undefined;\n}\n\nexport interface Brief {\n agentId: number;\n name: string;\n kind: string;\n context: AgentContext | null;\n task: string | null;\n mission: string | null;\n contract?: string | undefined;\n parts: BriefPart[];\n}\n\nexport interface BriefOptions {\n maxCharacters?: number | undefined;\n halfLifeDays?: number | undefined;\n}\n\nfunction decisionLines(questions: readonly Question[]): string[] {\n return questions.flatMap((question) => [\n `${question.n}. ${question.text}`,\n ` Recommended: ${question.recommendation}`,\n ` Answered: ${question.answer ?? 'open'}`,\n ]);\n}\n\n// The plan as the human validated it: each question beside its answer.\nexport function planAsAnswered(\n title: string,\n report: string,\n questions: readonly Question[],\n): string | undefined {\n const plan = extractSection(report, PLAN_SECTIONS);\n if (plan === undefined) return undefined;\n const understanding = extractSection(report, ['understanding']);\n const lines = [`# ${title}: the plan as answered`];\n if (understanding !== undefined) lines.push('', '## Understanding', '', understanding);\n lines.push('', '## Plan', '', plan);\n if (questions.length > 0) lines.push('', '## Decisions', '', ...decisionLines(questions));\n return lines.join('\\n');\n}\n\nfunction fileBytes(path: string): number | null {\n return existsSync(path) ? statSync(path).size : null;\n}\n\nfunction missingPart(type: BriefPartType, title: string): BriefPart {\n return { type, title, missing: true };\n}\n\nexport function targetText(ctx: Ctx, session: string, target: string): string | undefined {\n const range = mainTargetRange(target);\n if (range !== undefined) {\n return range\n ? `target main, commits ${range}`\n : 'target main, the uncommitted changes of the main repo';\n }\n const agent = getAgent(ctx, session, target);\n if (agent?.kind !== 'implement') return undefined;\n const from = agent.promotedFrom ? `, promoted from ${agent.promotedFrom}` : '';\n const lines = [`target ${target} (implement${from}, ${agent.status})`];\n if (agent.task) lines.push(`task: ${agent.task}`);\n if (agent.reportPath) lines.push(`report: ${agent.reportPath}`);\n if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);\n if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);\n for (const kind of ['research', 'plan'] as const) {\n const kept = agent.reportPath ? keptReportPath(agent.reportPath, kind) : null;\n if (kept && existsSync(kept)) lines.push(`${kind}: ${kept}`);\n }\n const answered = questionsOf(ctx, agent.id).filter((question) => question.answer);\n if (answered.length) {\n lines.push('answers:');\n for (const question of answered) {\n lines.push(` ${question.n}. ${question.text} → ${question.answer}`);\n }\n }\n return lines.join('\\n');\n}\n\nfunction planPart(ctx: Ctx, source: Agent): BriefPart {\n const title = `Plan of ${source.name}`;\n // A plan promoted to implement keeps its plan beside the report the implement overwrites.\n const kept = source.reportPath ? keptReportPath(source.reportPath, 'plan') : null;\n const path = kept && existsSync(kept) ? kept : source.reportPath;\n const report = readReport(path);\n const text =\n report &&\n planAsAnswered(`${source.name} ${kindTag(source.kind)}`, report, questionsOf(ctx, source.id));\n return text && path\n ? { type: 'deliverable', title, path, text }\n : missingPart('deliverable', title);\n}\n\nfunction deliverablePart(\n ctx: Ctx,\n attachment: Extract<Attachment, { type: 'deliverable' }>,\n): BriefPart {\n const source = getAgentById(ctx, attachment.agent);\n if (!source) return missingPart('deliverable', `Agent ${attachment.agent}`);\n if (attachment.section === 'plan') return planPart(ctx, source);\n const title = `Report of ${source.name}`;\n const bytes = source.reportPath ? fileBytes(source.reportPath) : null;\n return source.reportPath && bytes !== null\n ? { type: 'deliverable', title, path: source.reportPath, bytes }\n : missingPart('deliverable', title);\n}\n\nfunction forMainPart(ctx: Ctx, agentId: number): BriefPart {\n const source = getAgentById(ctx, agentId);\n const title = `For the main, from ${source?.name ?? `agent ${agentId}`}`;\n const report = readReport(source?.reportPath ?? null);\n const text = report && extractSection(report, FOR_MAIN_SECTIONS);\n return text && source?.reportPath\n ? { type: 'for_main', title, path: source.reportPath, text }\n : missingPart('for_main', title);\n}\n\nfunction findingLines(findings: readonly Finding[]): string[] {\n return findings.flatMap((finding) => {\n const location = finding.location ? ` ${finding.location}` : '';\n const lines = [`${finding.n}. [${finding.severity}]${location} — ${finding.text}`];\n if (finding.fix) lines.push(` Proposed fix: ${finding.fix}`);\n return lines;\n });\n}\n\nfunction findingsPart(ctx: Ctx, attachment: Extract<Attachment, { type: 'findings' }>): BriefPart {\n const review = getAgentById(ctx, attachment.review);\n if (!review) return missingPart('findings', `Findings of review ${attachment.review}`);\n const findings = findingsOf(ctx, review.id).filter((finding) => attachment.n.includes(finding.n));\n const target = review.target ? targetText(ctx, review.session, review.target) : undefined;\n const lines = [`From review ${review.name} of ${review.target ?? 'its target'}.`];\n if (target) lines.push(target);\n lines.push('Findings:', ...findingLines(findings));\n return {\n type: 'findings',\n title: `Findings ${attachment.n.join(', ')} of ${review.name}`,\n path: review.reportPath ?? undefined,\n text: lines.join('\\n'),\n missing: findings.length < attachment.n.length || undefined,\n };\n}\n\nfunction attachedNotes(\n ctx: Ctx,\n attachment: Extract<Attachment, { type: 'notes' }>,\n halfLifeDays: number,\n): { notes: WeightedNote[]; missing: number[] } {\n const all = listNotes(ctx, { halfLifeDays, query: attachment.query });\n if (!attachment.ids) return { notes: all, missing: [] };\n const notes = all.filter((note) => attachment.ids?.includes(note.id));\n const found = new Set(notes.map((note) => note.id));\n return { notes, missing: attachment.ids.filter((id) => !found.has(id)) };\n}\n\nfunction notesPart(ctx: Ctx, agent: Agent, options: BriefOptions): BriefPart[] {\n const halfLifeDays = options.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;\n const byId = new Map<number, WeightedNote>();\n const add = (notes: WeightedNote[]) => notes.forEach((note) => byId.set(note.id, note));\n const missing: number[] = [];\n for (const attachment of agent.attachments ?? []) {\n if (attachment.type !== 'notes') continue;\n const attached = attachedNotes(ctx, attachment, halfLifeDays);\n add(attached.notes);\n missing.push(...attached.missing);\n }\n const session = getSession(ctx, agent.session);\n const cold = agent.context === 'cold' && session;\n if (cold) add(startNotes(ctx, session.repo, halfLifeDays));\n const notes = [...byId.values()].sort(compareNotes);\n const parts: BriefPart[] = [];\n const text =\n cold || notes.length\n ? memoryPart(ctx, 'Workspace notes', notes, options.maxCharacters)\n : undefined;\n if (text) parts.push({ type: 'notes', title: 'Workspace notes', text });\n for (const id of new Set(missing)) parts.push(missingPart('notes', `Note #${id}`));\n return parts;\n}\n\nfunction referenceParts(ctx: Ctx, agent: Agent): BriefPart[] {\n const ids = (agent.attachments ?? []).flatMap((attachment) =>\n attachment.type === 'ref' ? [attachment.id] : [],\n );\n const references = listReferences(ctx, agent.session, { ids });\n const unknown = ids.filter((id) => !getReference(ctx, id));\n return [\n ...references\n .filter((reference) => !reference.removedAt)\n .map((reference): BriefPart => ({\n type: 'reference',\n title: reference.title ?? 'Reference',\n path: reference.path,\n bytes: reference.bytes,\n missing: reference.missing || undefined,\n })),\n ...unknown.map((id) => missingPart('reference', `Reference ${id}`)),\n ];\n}\n\nexport function buildBrief(ctx: Ctx, agentId: number, options: BriefOptions = {}): Brief {\n const agent = getAgentById(ctx, agentId);\n if (!agent) throw new CarnetError('AGENT_NOT_FOUND', `No agent ${agentId}`);\n const parts: BriefPart[] = [];\n const workplace = [\n agent.worktree && `worktree: ${agent.worktree}`,\n agent.baseCommit && `base: ${agent.baseCommit}`,\n agent.sandbox && `sandbox: ${agent.sandbox}`,\n ].filter(Boolean);\n if (workplace.length) {\n parts.push({ type: 'workplace', title: 'Where you work', text: workplace.join('\\n') });\n }\n if (agent.kind === 'review' && agent.target) {\n const text = targetText(ctx, agent.session, agent.target);\n parts.push(\n text\n ? { type: 'target', title: `Target ${agent.target}`, text }\n : missingPart('target', `Target ${agent.target}`),\n );\n }\n parts.push(...referenceParts(ctx, agent));\n for (const attachment of agent.attachments ?? []) {\n if (attachment.type === 'deliverable') parts.push(deliverablePart(ctx, attachment));\n if (attachment.type === 'for_main') parts.push(forMainPart(ctx, attachment.agent));\n if (attachment.type === 'findings') parts.push(findingsPart(ctx, attachment));\n }\n parts.push(...notesPart(ctx, agent, options));\n return {\n agentId: agent.id,\n name: agent.name,\n kind: agent.kind,\n context: agent.context,\n task: agent.task,\n mission: agent.mission,\n // A cold agent's definition already holds its contract; a fork gets it here, for its current kind.\n contract: agent.context === 'cold' ? undefined : KIND_CONTRACTS[agent.kind],\n parts,\n };\n}\n","// Carnet rows reach the search index through triggers, so no write site has to remember it.\n// A migration that rebuilds one of these tables drops its triggers: it runs SEARCH_TRIGGERS again.\n\ninterface RowSource {\n source: string;\n table: string;\n key: string;\n session: string;\n agentId: string;\n title: string;\n body: string;\n at: string;\n when: string;\n // An update of any other column leaves the document as it is.\n columns: readonly string[];\n}\n\nconst ROW_SOURCES: readonly RowSource[] = [\n {\n source: 'session',\n table: 'sessions',\n key: '{r}.id',\n session: '{r}.id',\n agentId: 'NULL',\n title: \"COALESCE({r}.name, '')\",\n body: \"COALESCE(concat_ws(char(10), {r}.purpose, {r}.last_title, {r}.summary), '')\",\n at: '{r}.created_at',\n when: 'COALESCE({r}.name, {r}.purpose, {r}.last_title, {r}.summary) IS NOT NULL',\n columns: ['name', 'purpose', 'last_title', 'summary'],\n },\n {\n source: 'agent',\n table: 'agents',\n key: '{r}.id',\n session: '{r}.session',\n agentId: '{r}.id',\n title: '{r}.name',\n body: \"COALESCE(concat_ws(char(10), {r}.task, {r}.mission), '')\",\n at: '{r}.started_at',\n when: '1',\n columns: ['name', 'task', 'mission'],\n },\n {\n source: 'note',\n table: 'notes',\n key: '{r}.id',\n session: '{r}.session',\n agentId: 'NULL',\n title: '{r}.kind',\n body: '{r}.text',\n at: '{r}.created_at',\n when: '{r}.dropped_at IS NULL',\n columns: ['kind', 'text', 'session', 'dropped_at'],\n },\n {\n source: 'question',\n table: 'agent_questions',\n key: \"{r}.agent_id || ':' || {r}.n\",\n session: '(SELECT session FROM agents WHERE agents.id = {r}.agent_id)',\n agentId: '{r}.agent_id',\n title: \"'question'\",\n body: 'concat_ws(char(10), {r}.text, {r}.context, {r}.recommendation, {r}.answer)',\n at: \"COALESCE({r}.answered_at, '')\",\n when: '1',\n columns: ['text', 'context', 'recommendation', 'answer'],\n },\n {\n source: 'finding',\n table: 'review_findings',\n key: \"{r}.agent_id || ':' || {r}.n\",\n session: '(SELECT session FROM agents WHERE agents.id = {r}.agent_id)',\n agentId: '{r}.agent_id',\n title: \"'finding'\",\n body: 'concat_ws(char(10), {r}.location, {r}.text, {r}.fix, {r}.reason)',\n at: \"COALESCE({r}.decided_at, '')\",\n when: '1',\n columns: ['location', 'text', 'fix', 'reason'],\n },\n {\n source: 'event',\n table: 'events',\n key: '{r}.id',\n session: '{r}.session',\n agentId: '{r}.agent_id',\n title: \"concat_ws(' ', {r}.type, {r}.agent)\",\n body: '{r}.note',\n at: '{r}.at',\n when: '{r}.note IS NOT NULL',\n columns: ['session', 'note'],\n },\n];\n\nconst DOC_COLUMNS = 'source, key, session, agent_id, title, body, at';\n\nfunction values(row: RowSource, alias: string): string {\n return [\n `'${row.source}'`,\n `CAST(${row.key} AS TEXT)`,\n row.session,\n row.agentId,\n row.title,\n row.body,\n row.at,\n ]\n .join(', ')\n .replaceAll('{r}', alias);\n}\n\nfunction rowTriggers(row: RowSource): string {\n const name = `${row.table}_search`;\n const remove = (alias: string) =>\n `DELETE FROM search_docs WHERE source = '${row.source}' AND key = CAST(${row.key.replaceAll('{r}', alias)} AS TEXT);`;\n const add = `INSERT INTO search_docs (${DOC_COLUMNS}) SELECT ${values(row, 'new')} WHERE ${row.when.replaceAll('{r}', 'new')};`;\n return `\nDROP TRIGGER IF EXISTS ${name}_insert;\nDROP TRIGGER IF EXISTS ${name}_update;\nDROP TRIGGER IF EXISTS ${name}_delete;\nCREATE TRIGGER ${name}_insert AFTER INSERT ON ${row.table} BEGIN ${add} END;\nCREATE TRIGGER ${name}_update AFTER UPDATE OF ${row.columns.join(', ')} ON ${row.table} BEGIN\n ${remove('old')}\n ${add}\nEND;\nCREATE TRIGGER ${name}_delete AFTER DELETE ON ${row.table} BEGIN ${remove('old')} END;`;\n}\n\nexport const SEARCH_TRIGGERS = `\n${ROW_SOURCES.map(rowTriggers).join('\\n')}\n-- A session merge moves agents: their questions, findings, reports and events follow.\nDROP TRIGGER IF EXISTS agents_search_move;\nCREATE TRIGGER agents_search_move AFTER UPDATE OF session ON agents BEGIN\n UPDATE search_docs SET session = new.session WHERE agent_id = new.id;\nEND;\nDROP TRIGGER IF EXISTS sessions_search_forget;\nCREATE TRIGGER sessions_search_forget AFTER DELETE ON sessions BEGIN\n DELETE FROM search_docs WHERE session = old.id;\n DELETE FROM search_sources WHERE session = old.id;\nEND;\n`;\n\nexport const SEARCH_TRIGGER_NAMES: readonly string[] = [\n ...ROW_SOURCES.flatMap((row) =>\n ['insert', 'update', 'delete'].map((event) => `${row.table}_search_${event}`),\n ),\n 'agents_search_move',\n 'sessions_search_forget',\n];\n\nexport const ROW_SOURCE_NAMES: readonly string[] = ROW_SOURCES.map((row) => row.source);\n\n// Rebuilds the documents of Carnet rows; transcripts and reports are read from their files.\nexport const SEARCH_BACKFILL = ROW_SOURCES.map(\n (row) =>\n `DELETE FROM search_docs WHERE source = '${row.source}';\nINSERT INTO search_docs (${DOC_COLUMNS}) SELECT ${values(row, row.table)} FROM ${row.table} WHERE ${row.when.replaceAll('{r}', row.table)};`,\n).join('\\n');\n\nexport const SEARCH_TABLES = `\nALTER TABLE sessions ADD COLUMN summary TEXT;\n\n-- No foreign keys: an index row must never make a Carnet write fail. Triggers clean up instead.\nCREATE TABLE search_docs (\n id INTEGER PRIMARY KEY,\n source TEXT NOT NULL,\n key TEXT NOT NULL,\n session TEXT,\n agent_id INTEGER,\n title TEXT NOT NULL DEFAULT '',\n body TEXT NOT NULL DEFAULT '',\n at TEXT,\n UNIQUE (source, key)\n);\nCREATE INDEX search_docs_session ON search_docs(session);\nCREATE INDEX search_docs_agent ON search_docs(agent_id);\nCREATE VIRTUAL TABLE search_index USING fts5(\n title, body, content='search_docs', content_rowid='id',\n tokenize='unicode61 remove_diacritics 2'\n);\nCREATE TRIGGER search_docs_insert AFTER INSERT ON search_docs BEGIN\n INSERT INTO search_index (rowid, title, body) VALUES (new.id, new.title, new.body);\nEND;\nCREATE TRIGGER search_docs_delete AFTER DELETE ON search_docs BEGIN\n INSERT INTO search_index (search_index, rowid, title, body)\n VALUES ('delete', old.id, old.title, old.body);\nEND;\nCREATE TRIGGER search_docs_update AFTER UPDATE OF title, body ON search_docs BEGIN\n INSERT INTO search_index (search_index, rowid, title, body)\n VALUES ('delete', old.id, old.title, old.body);\n INSERT INTO search_index (rowid, title, body) VALUES (new.id, new.title, new.body);\nEND;\n\n-- Files read incrementally: a transcript per session, a report per agent.\nCREATE TABLE search_sources (\n key TEXT PRIMARY KEY,\n session TEXT NOT NULL,\n path TEXT NOT NULL,\n offset INTEGER NOT NULL DEFAULT 0,\n size INTEGER NOT NULL DEFAULT 0,\n mtime REAL NOT NULL DEFAULT 0,\n indexed INTEGER NOT NULL DEFAULT 0,\n partial INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX search_sources_session ON search_sources(session);\n`;\n","import type { DatabaseSync } from 'node:sqlite';\nimport { CarnetError } from '../errors.ts';\nimport { SEARCH_BACKFILL, SEARCH_TABLES, SEARCH_TRIGGERS } from './search-schema.ts';\n\n// Before v11, sessions started outside any workspace had none. Those that hold no work go;\n// the others stop the migration, since their workspace can't be guessed.\nconst DISPOSABLE_SESSION = `workspace IS NULL\n AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id)\n AND NOT EXISTS (\n SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'\n )\n AND NOT EXISTS (SELECT 1 FROM notes WHERE notes.session = sessions.id OR notes.dropped_session = sessions.id)\n AND NOT EXISTS (SELECT 1 FROM note_citations WHERE note_citations.session = sessions.id)\n AND NOT EXISTS (SELECT 1 FROM sessions AS child WHERE child.parent_id = sessions.id)`;\n\nexport const migrations: readonly string[] = [\n `\nCREATE TABLE sessions (\n id TEXT PRIMARY KEY,\n name TEXT UNIQUE,\n purpose TEXT,\n status TEXT NOT NULL DEFAULT 'temporary'\n CHECK (status IN ('temporary', 'active', 'dropped')),\n cwd TEXT,\n repo TEXT,\n claude_pid INTEGER,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL\n);\n\nCREATE TABLE agents (\n session TEXT NOT NULL REFERENCES sessions(id),\n name TEXT NOT NULL,\n task TEXT,\n status TEXT NOT NULL\n CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'commit', 'branch', 'closed')),\n note TEXT,\n report_path TEXT,\n base_commit TEXT,\n worktree TEXT,\n queue_order INTEGER,\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session, name)\n);\n\nCREATE TABLE table_items (\n session TEXT PRIMARY KEY REFERENCES sessions(id),\n text TEXT NOT NULL,\n status TEXT,\n main_working INTEGER NOT NULL DEFAULT 0,\n updated_at TEXT NOT NULL\n);\n\nCREATE TABLE events (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id),\n at TEXT NOT NULL,\n type TEXT NOT NULL\n CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped')),\n agent TEXT,\n commit_sha TEXT,\n link TEXT,\n note TEXT\n);\n\nCREATE INDEX events_session_at ON events(session, at);\nCREATE INDEX agents_session_status ON agents(session, status);\n`,\n `\nALTER TABLE agents ADD COLUMN claude_agent_id TEXT;\n`,\n `\nALTER TABLE sessions ADD COLUMN hooked_at TEXT;\nCREATE INDEX sessions_claude_pid ON sessions(claude_pid, hooked_at);\n`,\n `\nALTER TABLE agents ADD COLUMN pending_status TEXT;\nALTER TABLE agents ADD COLUMN done_at TEXT;\n`,\n `\nUPDATE sessions SET status = 'active' WHERE status = 'paused';\n`,\n `\nALTER TABLE sessions RENAME COLUMN claude_pid TO host_pid;\nALTER TABLE sessions ADD COLUMN host TEXT NOT NULL DEFAULT 'claude-code';\nALTER TABLE agents RENAME COLUMN claude_agent_id TO host_agent_id;\nDROP INDEX sessions_claude_pid;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\n`,\n `\nCREATE TABLE sessions_new (\n id TEXT PRIMARY KEY,\n name TEXT UNIQUE,\n purpose TEXT,\n kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),\n status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),\n cwd TEXT,\n repo TEXT,\n host TEXT NOT NULL DEFAULT 'claude-code',\n host_pid INTEGER,\n hooked_at TEXT,\n last_title TEXT,\n parent_id TEXT REFERENCES sessions(id),\n prompt_version TEXT,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL,\n ended_at TEXT,\n CHECK (kind = 'temp' OR name IS NOT NULL)\n);\nINSERT INTO sessions_new (id, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at,\n last_title, created_at, last_active_at)\nSELECT id, name, purpose,\n CASE WHEN status = 'active' AND name IS NOT NULL THEN 'active'\n WHEN status = 'dropped' AND name IS NOT NULL THEN 'active'\n ELSE 'temp' END,\n CASE WHEN status = 'dropped' THEN 'archived' ELSE 'idle' END,\n cwd, repo, host, host_pid, hooked_at, name, created_at, last_active_at\nFROM sessions;\nDROP TABLE sessions;\nALTER TABLE sessions_new RENAME TO sessions;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\n\nCREATE TABLE events_new (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id),\n at TEXT NOT NULL,\n type TEXT NOT NULL\n CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped',\n 'session.started', 'session.resumed', 'session.ended', 'session.forked')),\n agent TEXT,\n commit_sha TEXT,\n link TEXT,\n note TEXT\n);\nINSERT INTO events_new SELECT id, session, at, type, agent, commit_sha, link, note FROM events;\nDROP TABLE events;\nALTER TABLE events_new RENAME TO events;\nCREATE INDEX events_session_at ON events(session, at);\n`,\n `\nCREATE TABLE notes (\n id INTEGER PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('learning', 'dead_end', 'decision')),\n text TEXT NOT NULL,\n session TEXT REFERENCES sessions(id) ON DELETE SET NULL,\n agent TEXT,\n similar_notes TEXT,\n created_at TEXT NOT NULL,\n dropped_at TEXT,\n dropped_reason TEXT,\n dropped_session TEXT REFERENCES sessions(id) ON DELETE SET NULL,\n replaced_by INTEGER REFERENCES notes(id)\n);\n\nCREATE INDEX notes_active ON notes(dropped_at, kind);\nCREATE INDEX notes_session ON notes(session);\n\nCREATE TABLE note_repos (\n note INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,\n repo TEXT NOT NULL,\n PRIMARY KEY (note, repo)\n);\n\nCREATE INDEX note_repos_repo ON note_repos(repo);\n\nCREATE TABLE note_citations (\n id INTEGER PRIMARY KEY,\n note INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,\n session TEXT REFERENCES sessions(id) ON DELETE SET NULL,\n agent TEXT,\n why TEXT NOT NULL,\n at TEXT NOT NULL\n);\n\nCREATE INDEX note_citations_note_at ON note_citations(note, at);\nCREATE INDEX note_citations_session ON note_citations(session);\n\nCREATE TABLE active_days (\n day TEXT PRIMARY KEY\n);\n\nCREATE TABLE session_repos (\n session TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,\n repo TEXT NOT NULL,\n injected_at TEXT NOT NULL,\n PRIMARY KEY (session, repo)\n);\n`,\n // Rows from before v9 get the placeholder group '' until the move to one database assigns them.\n `\nCREATE TABLE sessions_new (\n id TEXT PRIMARY KEY,\n group_name TEXT,\n name TEXT,\n purpose TEXT,\n kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),\n status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),\n cwd TEXT,\n repo TEXT,\n host TEXT NOT NULL DEFAULT 'claude-code',\n host_pid INTEGER,\n hooked_at TEXT,\n last_title TEXT,\n parent_id TEXT REFERENCES sessions(id),\n prompt_version TEXT,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL,\n ended_at TEXT,\n CHECK (kind = 'temp' OR name IS NOT NULL)\n);\nINSERT INTO sessions_new (id, group_name, name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)\nSELECT id, '', name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at\nFROM sessions;\nDROP TABLE sessions;\nALTER TABLE sessions_new RENAME TO sessions;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\nCREATE INDEX sessions_group_status ON sessions(group_name, status, last_active_at);\nCREATE UNIQUE INDEX sessions_group_name ON sessions(group_name, name)\n WHERE group_name IS NOT NULL AND name IS NOT NULL;\nCREATE UNIQUE INDEX sessions_free_name ON sessions(name)\n WHERE group_name IS NULL AND name IS NOT NULL;\n\nALTER TABLE notes ADD COLUMN group_name TEXT NOT NULL DEFAULT '';\nALTER TABLE notes ADD COLUMN number INTEGER NOT NULL DEFAULT 0;\nUPDATE notes SET number = id;\nDROP INDEX notes_active;\nCREATE INDEX notes_active ON notes(group_name, dropped_at, kind);\nCREATE UNIQUE INDEX notes_group_number ON notes(group_name, number);\n\nCREATE TABLE active_days_new (\n group_name TEXT NOT NULL,\n day TEXT NOT NULL,\n PRIMARY KEY (group_name, day)\n);\nINSERT INTO active_days_new (group_name, day) SELECT '', day FROM active_days;\nDROP TABLE active_days;\nALTER TABLE active_days_new RENAME TO active_days;\n`,\n `\nALTER TABLE sessions RENAME COLUMN group_name TO workspace;\nALTER TABLE notes RENAME COLUMN group_name TO workspace;\nALTER TABLE active_days RENAME COLUMN group_name TO workspace;\nDROP INDEX sessions_group_status;\nDROP INDEX sessions_group_name;\nDROP INDEX notes_group_number;\nCREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_active_at);\nCREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name)\n WHERE workspace IS NOT NULL AND name IS NOT NULL;\nCREATE UNIQUE INDEX notes_workspace_number ON notes(workspace, number);\n`,\n `\nDELETE FROM events WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});\nDELETE FROM table_items WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});\nDELETE FROM session_repos WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});\nDELETE FROM sessions WHERE ${DISPOSABLE_SESSION};\n\nCREATE TABLE sessions_new (\n id TEXT PRIMARY KEY,\n workspace TEXT NOT NULL,\n name TEXT,\n purpose TEXT,\n kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),\n status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),\n cwd TEXT,\n repo TEXT,\n host TEXT NOT NULL DEFAULT 'claude-code',\n host_pid INTEGER,\n hooked_at TEXT,\n last_title TEXT,\n parent_id TEXT REFERENCES sessions(id),\n prompt_version TEXT,\n created_at TEXT NOT NULL,\n last_active_at TEXT NOT NULL,\n ended_at TEXT,\n turn TEXT CHECK (turn IN ('working', 'waiting', 'failed')),\n turn_started_at TEXT,\n CHECK (kind = 'temp' OR name IS NOT NULL)\n);\nINSERT INTO sessions_new (id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)\nSELECT id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,\n hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at\nFROM sessions;\nDROP TABLE sessions;\nALTER TABLE sessions_new RENAME TO sessions;\nCREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);\nCREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_active_at);\nCREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name) WHERE name IS NOT NULL;\n\nALTER TABLE table_items DROP COLUMN main_working;\n\nALTER TABLE agents ADD COLUMN kind TEXT NOT NULL DEFAULT 'analyze'\n CHECK (kind IN ('research', 'analyze', 'implement', 'review'));\nALTER TABLE agents ADD COLUMN promoted_from TEXT\n CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review'));\nALTER TABLE agents ADD COLUMN target TEXT;\n-- Older agents waiting on code steps, or given a worktree, wrote code.\nUPDATE agents SET kind = 'implement'\nWHERE (status IN ('apply', 'test', 'commit')) OR worktree IS NOT NULL;\n\nCREATE TABLE agent_questions (\n session TEXT NOT NULL,\n agent TEXT NOT NULL,\n n INTEGER NOT NULL CHECK (n >= 1),\n text TEXT NOT NULL,\n context TEXT,\n recommendation TEXT NOT NULL,\n alternatives TEXT NOT NULL DEFAULT '[]',\n answer TEXT,\n answered_at TEXT,\n PRIMARY KEY (session, agent, n),\n FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE\n);\n\nCREATE TABLE review_findings (\n session TEXT NOT NULL,\n agent TEXT NOT NULL,\n n INTEGER NOT NULL CHECK (n >= 1),\n severity TEXT NOT NULL CHECK (severity IN ('blocking', 'to_fix', 'suggestion')),\n location TEXT,\n text TEXT NOT NULL,\n fix TEXT,\n decision TEXT CHECK (decision IN ('sent', 'fixed', 'ignored')),\n reason TEXT,\n decided_at TEXT,\n PRIMARY KEY (session, agent, n),\n FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE\n);\n\nCREATE TABLE events_new (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id),\n at TEXT NOT NULL,\n type TEXT NOT NULL\n CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped',\n 'injected', 'promoted', 'triaged',\n 'session.started', 'session.resumed', 'session.ended', 'session.forked')),\n agent TEXT,\n commit_sha TEXT,\n link TEXT,\n note TEXT\n);\nINSERT INTO events_new SELECT id, session, at, type, agent, commit_sha, link, note FROM events;\nDROP TABLE events;\nALTER TABLE events_new RENAME TO events;\nCREATE INDEX events_session_at ON events(session, at);\n`,\n `\n-- Testing and committing are one human step, and no step ever led to branch.\nUPDATE agents SET status = 'test' WHERE status IN ('commit', 'branch');\nUPDATE agents SET pending_status = 'test' WHERE pending_status IN ('commit', 'branch');\nUPDATE table_items SET status = 'test' WHERE status IN ('commit', 'branch');\nCREATE TABLE agents_new (\n session TEXT NOT NULL REFERENCES sessions(id),\n name TEXT NOT NULL,\n task TEXT,\n status TEXT NOT NULL\n CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),\n note TEXT,\n report_path TEXT,\n base_commit TEXT,\n worktree TEXT,\n queue_order INTEGER,\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n host_agent_id TEXT,\n pending_status TEXT,\n done_at TEXT,\n kind TEXT NOT NULL DEFAULT 'analyze'\n CHECK (kind IN ('research', 'analyze', 'implement', 'review')),\n promoted_from TEXT CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review')),\n target TEXT,\n blocked_on TEXT,\n PRIMARY KEY (session, name)\n);\nINSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target)\nSELECT session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target\nFROM agents;\nDROP TABLE agents;\nALTER TABLE agents_new RENAME TO agents;\nCREATE INDEX agents_session_status ON agents(session, status);\n-- The CLI and the plugin update separately; the pane warns when the hooks lag behind.\nALTER TABLE sessions ADD COLUMN plugin_version TEXT;\n`,\n `\n-- A research or analyze agent's throwaway folder under the run directory, writable through the guard.\nALTER TABLE agents ADD COLUMN sandbox TEXT;\n`,\n `\n-- The analyze kind is now plan. launch_requested_at marks the Agent call that launches an agent,\n-- so the next subagent pairs with it rather than with an older registered one.\nCREATE TABLE agents_new (\n session TEXT NOT NULL REFERENCES sessions(id),\n name TEXT NOT NULL,\n task TEXT,\n status TEXT NOT NULL\n CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),\n note TEXT,\n report_path TEXT,\n base_commit TEXT,\n worktree TEXT,\n queue_order INTEGER,\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n host_agent_id TEXT,\n pending_status TEXT,\n done_at TEXT,\n kind TEXT NOT NULL CHECK (kind IN ('research', 'plan', 'implement', 'review')),\n promoted_from TEXT CHECK (promoted_from IN ('research', 'plan', 'implement', 'review')),\n target TEXT,\n blocked_on TEXT,\n sandbox TEXT,\n launch_requested_at TEXT,\n PRIMARY KEY (session, name)\n);\nINSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from,\n target, blocked_on, sandbox)\nSELECT session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at,\n CASE kind WHEN 'analyze' THEN 'plan' ELSE kind END,\n CASE promoted_from WHEN 'analyze' THEN 'plan' ELSE promoted_from END,\n target, blocked_on, sandbox\nFROM agents;\nDROP TABLE agents;\nALTER TABLE agents_new RENAME TO agents;\nCREATE INDEX agents_session_status ON agents(session, status);\n`,\n `\n-- When the status last changed; rows from before it start from their last update.\nALTER TABLE agents ADD COLUMN status_since TEXT;\nUPDATE agents SET status_since = updated_at;\n`,\n `\n-- 'fix': the human chose to fix the finding, its route comes in a second pass.\nCREATE TABLE review_findings_new (\n session TEXT NOT NULL,\n agent TEXT NOT NULL,\n n INTEGER NOT NULL CHECK (n >= 1),\n severity TEXT NOT NULL CHECK (severity IN ('blocking', 'to_fix', 'suggestion')),\n location TEXT,\n text TEXT NOT NULL,\n fix TEXT,\n decision TEXT CHECK (decision IN ('fix', 'sent', 'fixed', 'ignored')),\n reason TEXT,\n decided_at TEXT,\n PRIMARY KEY (session, agent, n),\n FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE\n);\nINSERT INTO review_findings_new (session, agent, n, severity, location, text, fix, decision,\n reason, decided_at)\nSELECT session, agent, n, severity, location, text, fix, decision, reason, decided_at\nFROM review_findings;\nDROP TABLE review_findings;\nALTER TABLE review_findings_new RENAME TO review_findings;\n`,\n `\n-- Agents get an id: a closed agent keeps its row, questions, findings and events when its name is\n-- reused, and a name is unique among open agents only. Kinds, decisions and event types are\n-- checked in code, so adding one needs no rebuild.\nCREATE TABLE agents_new (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id),\n name TEXT NOT NULL,\n task TEXT,\n status TEXT NOT NULL\n CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),\n note TEXT,\n report_path TEXT,\n base_commit TEXT,\n worktree TEXT,\n queue_order INTEGER,\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n host_agent_id TEXT,\n pending_status TEXT,\n done_at TEXT,\n kind TEXT NOT NULL,\n promoted_from TEXT,\n target TEXT,\n blocked_on TEXT,\n sandbox TEXT,\n launch_requested_at TEXT,\n status_since TEXT,\n backend TEXT,\n model TEXT,\n backend_ref TEXT,\n kind_def TEXT,\n context TEXT CHECK (context IN ('fork', 'cold')),\n mission TEXT,\n attachments TEXT,\n produced TEXT,\n recommended_then TEXT\n);\n-- A research agent could have been a fork or a cold one: nothing recorded which.\nINSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from,\n target, blocked_on, sandbox, launch_requested_at, status_since, backend, context)\nSELECT session, name, task, status, note, report_path, base_commit, worktree,\n queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from,\n target, blocked_on, sandbox, launch_requested_at, status_since, 'claude',\n CASE kind WHEN 'review' THEN 'cold' WHEN 'research' THEN NULL ELSE 'fork' END\nFROM agents ORDER BY started_at, rowid;\n\nCREATE TABLE agent_questions_new (\n agent_id INTEGER NOT NULL REFERENCES agents(id) ON DELETE CASCADE,\n n INTEGER NOT NULL CHECK (n >= 1),\n text TEXT NOT NULL,\n context TEXT,\n recommendation TEXT NOT NULL,\n alternatives TEXT NOT NULL DEFAULT '[]',\n answer TEXT,\n answered_at TEXT,\n PRIMARY KEY (agent_id, n)\n);\nINSERT INTO agent_questions_new (agent_id, n, text, context, recommendation, alternatives,\n answer, answered_at)\nSELECT agents_new.id, q.n, q.text, q.context, q.recommendation, q.alternatives, q.answer,\n q.answered_at\nFROM agent_questions q JOIN agents_new ON agents_new.session = q.session AND agents_new.name = q.agent;\n\nCREATE TABLE review_findings_new (\n agent_id INTEGER NOT NULL REFERENCES agents(id) ON DELETE CASCADE,\n n INTEGER NOT NULL CHECK (n >= 1),\n severity TEXT NOT NULL CHECK (severity IN ('blocking', 'to_fix', 'suggestion')),\n location TEXT,\n text TEXT NOT NULL,\n fix TEXT,\n decision TEXT,\n reason TEXT,\n decided_at TEXT,\n route TEXT,\n spawn_name TEXT,\n spawn_kind TEXT,\n spawned_agent INTEGER REFERENCES agents(id) ON DELETE SET NULL,\n delivered_at TEXT,\n PRIMARY KEY (agent_id, n)\n);\nINSERT INTO review_findings_new (agent_id, n, severity, location, text, fix, decision, reason,\n decided_at)\nSELECT agents_new.id, f.n, f.severity, f.location, f.text, f.fix, f.decision, f.reason,\n f.decided_at\nFROM review_findings f JOIN agents_new ON agents_new.session = f.session AND agents_new.name = f.agent;\n\n-- An event older than its agent's row belonged to an earlier agent of that name, deleted when the\n-- name was reused: it keeps only the name.\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 agent TEXT,\n agent_id INTEGER REFERENCES agents(id) ON DELETE SET NULL,\n commit_sha TEXT,\n link TEXT,\n note TEXT,\n payload TEXT\n);\nINSERT INTO events_new (id, session, at, type, agent, agent_id, commit_sha, link, note)\nSELECT id, session, at, type, agent,\n (SELECT agents_new.id FROM agents_new\n WHERE agents_new.session = events.session AND agents_new.name = events.agent\n AND agents_new.started_at <= events.at),\n commit_sha, link, note\nFROM events;\n\nDROP TABLE agent_questions;\nDROP TABLE review_findings;\nDROP TABLE events;\nDROP TABLE agents;\nALTER TABLE agents_new RENAME TO agents;\nALTER TABLE agent_questions_new RENAME TO agent_questions;\nALTER TABLE review_findings_new RENAME TO review_findings;\nALTER TABLE events_new RENAME TO events;\nCREATE UNIQUE INDEX agents_open_name ON agents(session, name) WHERE status != 'closed';\nCREATE INDEX agents_session_status ON agents(session, status);\nCREATE INDEX agents_session_name ON agents(session, name, id);\nCREATE INDEX agents_host_agent_id ON agents(session, host_agent_id);\nCREATE INDEX events_session_at ON events(session, at);\nCREATE INDEX events_agent_id ON events(agent_id);\n\nALTER TABLE sessions ADD COLUMN backend TEXT;\nALTER TABLE sessions ADD COLUMN model TEXT;\nALTER TABLE sessions ADD COLUMN backend_ref TEXT;\nALTER TABLE sessions ADD COLUMN profile TEXT;\nALTER TABLE sessions ADD COLUMN profile_def TEXT;\nUPDATE sessions SET backend = 'claude' WHERE host = 'claude-code';\n`,\n `${SEARCH_TABLES}\n${SEARCH_TRIGGERS}\n${SEARCH_BACKFILL}`,\n // `references` is an SQL keyword. An agent's own documents are scope 'agent' rows that its\n // attachments point to; session documents go into every brief of the session.\n `\nCREATE TABLE reference_docs (\n id INTEGER PRIMARY KEY,\n session TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,\n scope TEXT NOT NULL CHECK (scope IN ('session', 'agent')),\n path TEXT NOT NULL,\n title TEXT,\n added_at TEXT NOT NULL,\n removed_at TEXT\n);\nCREATE UNIQUE INDEX reference_docs_session_path ON reference_docs(session, path)\n WHERE scope = 'session' AND removed_at IS NULL;\nCREATE INDEX reference_docs_session ON reference_docs(session);\n`,\n];\n\nconst preconditions: Readonly<Record<number, (db: DatabaseSync) => void>> = {\n 11: (db) => {\n const kept = db\n .prepare(\n `SELECT id, name FROM sessions WHERE workspace IS NULL AND NOT (${DISPOSABLE_SESSION})`,\n )\n .all() as { id: string; name: string | null }[];\n if (kept.length === 0) return;\n const list = kept.map((row) => row.name ?? row.id).join(', ');\n throw new Error(\n `Every session now needs a workspace, and these sessions without one hold agents, notes or forks: ${list}. ` +\n \"Give each one a workspace with the previous rucher (rucher sessions move), or in SQL: UPDATE sessions SET workspace = '<name>' WHERE id = '<id>'\",\n );\n },\n};\n\nexport function schemaVersion(db: DatabaseSync): number {\n const row = db.prepare('PRAGMA user_version').get() as { user_version: number };\n return row.user_version;\n}\n\nfunction foreignKeyViolations(db: DatabaseSync): number {\n return db.prepare('PRAGMA foreign_key_check').all().length;\n}\n\nfunction knownVersion(db: DatabaseSync): number {\n const version = schemaVersion(db);\n if (version > migrations.length) {\n throw new CarnetError(\n 'SCHEMA_TOO_NEW',\n `The Carnet database is at schema v${version}, newer than this rucher (v${migrations.length}). ` +\n 'Update rucher and its plugin; sessions started before the update run the old version until they are restarted.',\n );\n }\n return version;\n}\n\n// `target` stops early, so a test can check one migration on the shape it produced.\nexport function migrate(db: DatabaseSync, target = migrations.length): void {\n if (knownVersion(db) >= target) return;\n const foreignKeys = db.prepare('PRAGMA foreign_keys').get() as { foreign_keys: number };\n // Table rebuilds need foreign keys off, and SQLite ignores that pragma inside a transaction.\n db.exec('PRAGMA foreign_keys = OFF');\n try {\n for (;;) {\n // Several processes open the database at once after an update: reading the version under\n // the write lock keeps a step another process already applied from running twice.\n db.exec('BEGIN IMMEDIATE');\n try {\n const version = knownVersion(db);\n const migration = version < target ? migrations[version] : undefined;\n if (migration === undefined) {\n db.exec('COMMIT');\n return;\n }\n preconditions[version + 1]?.(db);\n db.exec(migration);\n if (foreignKeyViolations(db) > 0) {\n throw new Error(`Migration ${version + 1} broke foreign keys`);\n }\n db.exec(`PRAGMA user_version = ${version + 1}`);\n db.exec('COMMIT');\n } catch (error) {\n db.exec('ROLLBACK');\n throw error;\n }\n }\n } finally {\n db.exec(`PRAGMA foreign_keys = ${foreignKeys.foreign_keys ? 'ON' : 'OFF'}`);\n }\n}\n","import { DatabaseSync } from 'node:sqlite';\nimport { migrate } from './schema.ts';\n\nexport const MEMORY_DB = ':memory:';\n\n// WAL persists in the file, so only a new database switches. SQLite skips the busy handler for\n// that switch, so processes creating the file together retry it briefly.\nfunction useWal(db: DatabaseSync): void {\n const mode = db.prepare('PRAGMA journal_mode').get() as { journal_mode: string };\n if (mode.journal_mode === 'wal') return;\n for (let attempt = 1; ; attempt += 1) {\n try {\n db.exec('PRAGMA journal_mode = WAL');\n return;\n } catch (error) {\n if (attempt >= 50 || !String(error).includes('database is locked')) throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);\n }\n }\n}\n\nexport function openDatabase(path: string): DatabaseSync {\n const db = new DatabaseSync(path);\n db.exec('PRAGMA busy_timeout = 5000');\n if (path !== MEMORY_DB) useWal(db);\n db.exec('PRAGMA foreign_keys = ON');\n migrate(db);\n return db;\n}\n","import { mergeReferences } from './references.ts';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { closeAgentsWhere } from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { requireSession, type Session } from './sessions.ts';\n\nexport interface MergeResult {\n session: Session;\n movedAgents: string[];\n closedAgents: string[];\n movedEvents: number;\n movedTable: boolean;\n}\n\nexport interface AgentMergePlan {\n moved: string[];\n // Open in both sessions: the source's agent is closed, since a name is unique among open agents.\n closed: { id: number; name: string }[];\n}\n\n// Every agent follows its session, closed ones included, so none loses its history.\nexport function agentMergePlan(db: DatabaseSync, fromId: string, intoId: string): AgentMergePlan {\n const rows = db\n .prepare(\n `SELECT id, name, status != 'closed' AND EXISTS (\n SELECT 1 FROM agents other\n WHERE other.session = ? AND other.name = agents.name AND other.status != 'closed'\n ) AS collides\n FROM agents WHERE session = ? ORDER BY started_at, id`,\n )\n .all(intoId, fromId) as { id: number; name: string; collides: number }[];\n return {\n moved: [...new Set(rows.filter((row) => !row.collides).map((row) => row.name))],\n closed: rows\n .filter((row) => row.collides)\n .map((row) => ({ id: Number(row.id), name: row.name })),\n };\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 plan = agentMergePlan(ctx.db, fromId, intoId);\n ctx.db.exec('BEGIN');\n try {\n for (const agent of plan.closed) closeAgentsWhere(ctx.db, 'id = ?', [agent.id], at);\n ctx.db\n .prepare('UPDATE agents SET session = ?, updated_at = ? WHERE session = ?')\n .run(intoId, at, fromId);\n mergeReferences(ctx, fromId, intoId, at);\n const movedEvents = Number(\n ctx.db.prepare('UPDATE events SET session = ? WHERE session = ?').run(intoId, fromId).changes,\n );\n const intoHasTable =\n ctx.db.prepare('SELECT 1 FROM table_items WHERE session = ?').get(intoId) !== undefined;\n const movedTable =\n !intoHasTable &&\n Number(\n ctx.db.prepare('UPDATE table_items SET session = ? WHERE session = ?').run(intoId, fromId)\n .changes,\n ) > 0;\n ctx.db.prepare('DELETE FROM table_items WHERE session = ?').run(fromId);\n const keepName = into.name === null && from.name !== null;\n ctx.db\n .prepare(\n \"UPDATE sessions SET status = 'archived', kind = 'temp', name = NULL, turn = NULL, turn_started_at = NULL, last_active_at = ? WHERE id = ?\",\n )\n .run(at, fromId);\n ctx.db\n .prepare(\n `UPDATE sessions\n SET name = COALESCE(?, name), purpose = COALESCE(purpose, ?), last_active_at = ?,\n kind = CASE WHEN ? THEN ? ELSE kind END\n WHERE id = ?`,\n )\n .run(keepName ? from.name : null, from.purpose, at, keepName ? 1 : 0, from.kind, intoId);\n ctx.db.exec('COMMIT');\n return {\n session: requireSession(ctx, intoId),\n movedAgents: plan.moved,\n closedAgents: plan.closed.map((agent) => agent.name),\n movedEvents,\n movedTable,\n };\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n","import { existsSync, lstatSync, mkdirSync, readdirSync, rmSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { CarnetError } from './errors.ts';\nimport { sandboxesDirectory } from './paths.ts';\nimport type { Workspace } from './workspace/workspace.ts';\n\nfunction strictlyInside(path: string, folder: string): boolean {\n const rest = relative(folder, path);\n return rest !== '' && !rest.startsWith('..') && !isAbsolute(rest);\n}\n\n// A sandbox lives only in the run directory's sandboxes folder, so removing it can never reach\n// a repo or the human's files.\nexport function resolveSandbox(workspace: Workspace | null, path: string): string {\n if (!workspace) {\n throw new CarnetError('INVALID_SANDBOX', 'A sandbox needs a workspace: none is resolved');\n }\n const root = sandboxesDirectory(workspace);\n const expanded = path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;\n const resolved = resolve(workspace.runDirectory, expanded);\n if (!strictlyInside(resolved, root)) {\n throw new CarnetError(\n 'INVALID_SANDBOX',\n `${path} is not a folder under ${root}: a sandbox lives in the workspace's sandboxes folder`,\n );\n }\n if (existsSync(resolved)) {\n if (!lstatSync(resolved).isDirectory() || readdirSync(resolved).length > 0) {\n throw new CarnetError('INVALID_SANDBOX', `${resolved} already exists and is not empty`);\n }\n }\n return resolved;\n}\n\nexport function sandboxRemovedSuffix(removed: boolean): string {\n return removed ? ', sandbox removed' : '';\n}\n\nexport function createSandbox(path: string): void {\n mkdirSync(path, { recursive: true });\n}\n\nexport function removeSandbox(workspace: Workspace | null, path: string | null): boolean {\n if (!workspace || !path) return false;\n const resolved = resolve(path);\n if (!strictlyInside(resolved, sandboxesDirectory(workspace)) || !existsSync(resolved)) {\n return false;\n }\n rmSync(resolved, { recursive: true, force: true });\n return true;\n}\n","import type { Ctx } from './context.ts';\n\nexport const DEFAULT_PURGE_DAYS = 3;\nconst DAY_MILLISECONDS = 24 * 60 * 60 * 1000;\n\nexport function purgeDays(value: string | undefined): number {\n const days = Number(value);\n return Number.isFinite(days) && days > 0 ? days : DEFAULT_PURGE_DAYS;\n}\n\n// Only sessions without agent events go: the agent journal is never deleted, lifecycle events are.\nconst PURGEABLE = `\n workspace = ? AND id != ? AND last_active_at < ?\n AND NOT EXISTS (\n SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'\n )\n AND (\n status = 'archived'\n OR (kind = 'temp' AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id))\n )`;\n\nexport function purgeSessions(ctx: Ctx, keepId: string, days: number): string[] {\n const cutoff = new Date(ctx.now().getTime() - days * DAY_MILLISECONDS).toISOString();\n ctx.db.exec('BEGIN');\n try {\n const rows = ctx.db\n .prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`)\n .all(ctx.workspace, keepId, cutoff) as unknown as { id: string }[];\n const ids = rows.map((row) => row.id);\n for (const table of ['table_items', 'reference_docs', 'agents', 'events']) {\n const statement = ctx.db.prepare(`DELETE FROM ${table} WHERE session = ?`);\n for (const id of ids) statement.run(id);\n }\n const deleteSession = ctx.db.prepare('DELETE FROM sessions WHERE id = ?');\n for (const id of ids) deleteSession.run(id);\n ctx.db.exec('COMMIT');\n return ids;\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n","import type { NoteActivity } from '../notes.ts';\nimport type { TableItem } from '../table.ts';\nimport type { Turn } from '../turn.ts';\nimport {\n EMOJI,\n KIND_LEGEND,\n kindTag,\n LEGEND,\n MAIN_FAILED_EMOJI,\n MAIN_WAITING_EMOJI,\n MAIN_WORKING_EMOJI,\n} from './model.ts';\nimport type { StatusLine, StatusView } from './view.ts';\n\nexport const MAIN_HEADER = 'Main';\nexport const MAIN_WORKING_SUFFIX = '(main working)';\nexport const BLOCKED_HEADER = 'Waiting on agents';\nexport const MAIN_WAITING_SUFFIX = '(waiting on you)';\nexport const MAIN_FAILED_SUFFIX = '(turn failed)';\n\nexport function renderTableLine(item: TableItem): string {\n return `${EMOJI[item.status ?? 'discussing']} ${item.text}`;\n}\n\nconst TURN_MARKS = {\n working: { emoji: MAIN_WORKING_EMOJI, suffix: MAIN_WORKING_SUFFIX, alone: 'main working' },\n waiting: { emoji: MAIN_WAITING_EMOJI, suffix: MAIN_WAITING_SUFFIX, alone: 'waiting on you' },\n failed: { emoji: MAIN_FAILED_EMOJI, suffix: MAIN_FAILED_SUFFIX, alone: 'turn failed' },\n} as const;\n\nexport const MAIN_IDLE = 'idle';\n\nexport function renderMainLine(item: TableItem | null, turn: Turn | null): string {\n if (!turn) return item ? renderTableLine(item) : MAIN_IDLE;\n const mark = TURN_MARKS[turn];\n return item ? `${mark.emoji} ${item.text} ${mark.suffix}` : `${mark.emoji} ${mark.alone}`;\n}\n\nexport function renderAgentLine(line: StatusLine, nameWidth = 0): string {\n const head = `${line.emoji} ${kindTag(line.kind)} ${line.name}`;\n const action = line.action\n ? ` ${' '.repeat(Math.max(nameWidth - line.name.length, 0))} ${line.action}`\n : '';\n return line.note ? `${head}${action} — ${line.note}` : `${head}${action}`;\n}\n\n// Aligns the actions of one section, so the eye reads them as a column.\nfunction nameWidth(lines: readonly StatusLine[]): number {\n return Math.max(0, ...lines.map((line) => line.name.length));\n}\n\nexport const NOTES_HEADER = 'Notes';\nexport const NOTES_FOLD_LINES = 5;\nconst ACTIVITY_MARK = { added: '+', cited: '★', dropped: '−' } as const;\nconst LABEL_WIDTH = 'dead_end'.length;\nexport const SIMILAR_PREFIX = 'similar to ';\n\nexport type NotesMode = 'full' | 'summary' | 'expanded';\n\nexport interface RenderOptions {\n notes?: NotesMode | undefined;\n}\n\nfunction plural(count: number, word: string): string {\n return `${count} ${word}${count > 1 ? 's' : ''}`;\n}\n\nexport function renderNotesSummary(notes: NoteActivity[]): string {\n const count = (activity: NoteActivity['activity']) =>\n notes.filter((item) => item.activity === activity).length;\n const duplicates = notes.filter(\n (item) => item.activity === 'added' && item.similarNotes.length > 0,\n ).length;\n const parts = [\n count('added') && `${count('added')} added`,\n count('cited') && `${count('cited')} cited`,\n count('dropped') && `${count('dropped')} dropped`,\n duplicates && plural(duplicates, 'possible duplicate'),\n ].filter(Boolean);\n return `${NOTES_HEADER} ${parts.join(' · ')}`;\n}\n\nexport function renderNoteLine(item: NoteActivity, idWidth: number): string {\n const id = `#${item.note}`.padEnd(idWidth);\n const label = (item.activity === 'added' ? item.kind : item.activity).padEnd(LABEL_WIDTH);\n let text = item.text;\n // Before the text, so a narrow terminal cuts the note rather than the duplicate warning.\n if (item.activity === 'added' && item.similarNotes.length > 0) {\n text = `${SIMILAR_PREFIX}${item.similarNotes.map((note) => `#${note}`).join(', ')} · ${text}`;\n }\n if (item.activity === 'dropped' && item.replacedBy !== null)\n text = `replaced by #${item.replacedBy}`;\n return `${ACTIVITY_MARK[item.activity]} ${id} ${label} ${text}`;\n}\n\nexport function renderNotes(notes: NoteActivity[], mode: NotesMode = 'full'): string[] {\n if (notes.length === 0) return [];\n if (mode === 'summary' || (mode === 'full' && notes.length > NOTES_FOLD_LINES)) {\n return [renderNotesSummary(notes)];\n }\n const idWidth = Math.max(...notes.map((item) => `#${item.note}`.length));\n return [NOTES_HEADER, ...notes.map((item) => ` ${renderNoteLine(item, idWidth)}`)];\n}\n\nexport function renderSections(view: StatusView, options: RenderOptions = {}): string {\n const out: string[] = [];\n // Always shown, so the sections below never jump when a turn starts or ends.\n out.push(MAIN_HEADER, ` ${renderMainLine(view.table, view.turn)}`, '');\n out.push('Waiting on you');\n if (view.waiting.length === 0) out.push(' nothing');\n const waitingWidth = nameWidth(view.waiting);\n view.waiting.forEach((line, index) => {\n out.push(` ${index + 1}.${line.pinned ? '📌' : ''} ${renderAgentLine(line, waitingWidth)}`);\n });\n if (view.blocked.length > 0) {\n out.push('', BLOCKED_HEADER);\n const blockedWidth = nameWidth(view.blocked);\n for (const line of view.blocked) out.push(` ${renderAgentLine(line, blockedWidth)}`);\n }\n out.push('', 'Running');\n if (view.running.length === 0) out.push(' nothing');\n const runningWidth = nameWidth(view.running);\n for (const line of view.running) out.push(` ${renderAgentLine(line, runningWidth)}`);\n const notes = renderNotes(view.notes, options.notes);\n if (notes.length > 0) out.push('', ...notes);\n return out.join('\\n');\n}\n\nexport function renderStatus(view: StatusView, options?: RenderOptions): string {\n return [view.time, '', renderSections(view, options), '', KIND_LEGEND, LEGEND].join('\\n');\n}\n","import { type Ctx, nowIso } from './context.ts';\nimport { CarnetError } from './errors.ts';\nimport { type UserActionStatus, isUserActionStatus } from './status/model.ts';\nimport { sanitizeNote } from './status/note.ts';\n\nexport interface TableItem {\n session: string;\n text: string;\n status: UserActionStatus | null;\n updatedAt: string;\n}\n\nexport interface SetTableInput {\n text: string;\n status?: UserActionStatus | undefined;\n}\n\ninterface TableRow {\n session: string;\n text: string;\n status: UserActionStatus | null;\n updated_at: string;\n}\n\nfunction toItem(row: TableRow): TableItem {\n return { session: row.session, text: row.text, status: row.status, updatedAt: row.updated_at };\n}\n\nexport function tableIsAbout(item: TableItem | undefined | null, name: string): boolean {\n const text = item?.text;\n return text?.startsWith(name) === true && !/[\\w-]/.test(text.charAt(name.length));\n}\n\nexport function getTable(ctx: Ctx, session: string): TableItem | undefined {\n const row = ctx.db.prepare('SELECT * FROM table_items WHERE session = ?').get(session) as\n | TableRow\n | undefined;\n return row && toItem(row);\n}\n\nexport function setTable(ctx: Ctx, session: string, input: SetTableInput): TableItem {\n if (input.status !== undefined && !isUserActionStatus(input.status)) {\n throw new CarnetError('INVALID_STATUS', `Invalid table status \"${String(input.status)}\"`);\n }\n ctx.db\n .prepare(\n `INSERT INTO table_items (session, text, status, updated_at) VALUES (?, ?, ?, ?)\n ON CONFLICT(session) DO UPDATE SET text = excluded.text, status = excluded.status,\n updated_at = excluded.updated_at`,\n )\n .run(session, sanitizeNote(input.text), input.status ?? null, nowIso(ctx));\n return getTable(ctx, session) as TableItem;\n}\n\nexport function clearTable(ctx: Ctx, session: string): void {\n ctx.db.prepare('DELETE FROM table_items WHERE session = ?').run(session);\n}\n","import { type Ctx, nowIso } from './context.ts';\n\nexport const TURNS = ['working', 'waiting', 'failed'] as const;\nexport type Turn = (typeof TURNS)[number];\n\nexport interface TurnOptions {\n // Off when the installed hooks cannot end a turn, so the Main line never shows a turn stuck on.\n trackTurn?: boolean | undefined;\n}\n\nexport function getTurn(ctx: Ctx, session: string): Turn | null {\n const row = ctx.db.prepare('SELECT turn FROM sessions WHERE id = ?').get(session) as\n | { turn: Turn | null }\n | undefined;\n return row?.turn ?? null;\n}\n\n// The UPDATE matches no row when the state already holds, so repeating a call writes nothing.\n// A running turn keeps its start time when it moves between working and waiting.\nfunction setTurn(ctx: Ctx, session: string, turn: Turn | null): void {\n ctx.db\n .prepare(\n `UPDATE sessions SET turn = ?1,\n turn_started_at = CASE\n WHEN ?1 IS NULL THEN NULL\n WHEN ?1 <> 'failed' AND turn IN ('working', 'waiting') THEN turn_started_at\n ELSE ?2 END\n WHERE id = ?3 AND turn IS NOT ?1`,\n )\n .run(turn, nowIso(ctx), session);\n}\n\nexport function startTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, 'working');\n}\n\nexport function waitTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, 'waiting');\n}\n\nexport function failTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, 'failed');\n}\n\nexport function endTurn(ctx: Ctx, session: string): void {\n setTurn(ctx, session, null);\n}\n","import { type Agent, type AgentKind, KIND_ACTIONS, listAgents } from '../agents.ts';\nimport type { Ctx } from '../context.ts';\nimport { listFindings } from '../findings.ts';\nimport { type NoteActivity, sessionNoteActivity } from '../notes.ts';\nimport { listQuestions } from '../questions.ts';\nimport type { Session } from '../sessions.ts';\nimport { getTable, type TableItem, tableIsAbout } from '../table.ts';\nimport { getTurn, type Turn } from '../turn.ts';\nimport { type AgentStatus, EMOJI, isUserActionStatus } from './model.ts';\n\nexport interface StatusLine {\n name: string;\n kind: AgentKind;\n status: AgentStatus;\n emoji: string;\n // What the human does next, or what a running agent is, with its detail.\n action: string | null;\n note: string | null;\n pinned: boolean;\n}\n\nexport interface StatusView {\n time: string;\n sessionName: string | null;\n table: TableItem | null;\n turn: Turn | null;\n waiting: StatusLine[];\n blocked: StatusLine[];\n running: StatusLine[];\n notes: NoteActivity[];\n}\n\nexport interface StatusViewOptions {\n kind?: AgentKind | undefined;\n}\n\n// A test ties the main repo up, so it comes first; then what resumes a fork; then new main-repo work;\n// then what nothing waits on.\nconst ACTION_RANK: Record<string, number> = {\n test: 0,\n answer: 1,\n validate: 2,\n triage: 3,\n apply: 4,\n inject: 5,\n};\nconst REST_RANK = Object.keys(ACTION_RANK).length;\n// The human already put these off once: they come back only when nothing else waits.\nconst DEFERRED_RANK = REST_RANK + 1;\n\nfunction plural(count: number, word: string): string {\n return `${count} ${word}${count === 1 ? '' : 's'}`;\n}\n\nfunction actionWord(agent: Agent): string {\n const { kind, status } = agent;\n if (status === 'answer') return kind === 'plan' ? 'validate' : 'answer';\n if (status === 'review' && kind !== 'implement') return KIND_ACTIONS[kind];\n if (status === 'apply' && kind === 'implement') return 'apply';\n if (status === 'test') return status;\n return status === 'discussing' ? 'discuss' : status;\n}\n\nfunction actionDetail(ctx: Ctx, agent: Agent, word: string): string | null {\n if (word === 'validate' || word === 'answer') {\n const open = listQuestions(ctx, agent.session, agent.name, true).length;\n if (open > 0) return plural(open, 'question');\n // Questions asked only in the report prose have no count to show.\n if (agent.status === 'answer') return 'questions';\n return 'plan';\n }\n if (word === 'triage') {\n const pending = listFindings(ctx, agent.session, agent.name, 'open');\n const blocking = pending.filter((finding) => finding.severity === 'blocking').length;\n const deferred = pending.filter((finding) => finding.decision === 'deferred').length;\n const onlyDeferred = deferred > 0 && deferred === pending.length;\n const parts = [\n onlyDeferred ? `${deferred} deferred` : null,\n !onlyDeferred && pending.length > 0 ? plural(pending.length, 'finding') : null,\n blocking > 0 ? `(${blocking} blocking)` : null,\n agent.target ? `→ ${agent.target}` : null,\n ].filter(Boolean);\n return parts.length > 0 ? parts.join(' ') : null;\n }\n return null;\n}\n\nfunction waitingAction(ctx: Ctx, agent: Agent): string {\n const word = actionWord(agent);\n const detail = actionDetail(ctx, agent, word);\n return detail ? `${word} · ${detail}` : word;\n}\n\nfunction runningAction(agent: Agent): string | null {\n return agent.promotedFrom ? `promoted from ${agent.promotedFrom}` : null;\n}\n\nfunction onlyDeferred(ctx: Ctx, agent: Agent): boolean {\n const open = listFindings(ctx, agent.session, agent.name, 'open');\n return open.length > 0 && open.every((finding) => finding.decision === 'deferred');\n}\n\nfunction rankOf(ctx: Ctx, agent: Agent): number {\n if (agent.status === 'answer') return ACTION_RANK.answer as number;\n const word = actionWord(agent);\n if (word === 'triage' && agent.status === 'review' && onlyDeferred(ctx, agent)) {\n return DEFERRED_RANK;\n }\n return ACTION_RANK[word] ?? REST_RANK;\n}\n\nfunction compareWaiting(ranks: Map<number, number>, 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 (ranks.get(left.id) as number) - (ranks.get(right.id) as number) ||\n left.statusSince.localeCompare(right.statusSince) ||\n left.name.localeCompare(right.name)\n );\n}\n\nfunction toLine(agent: Agent, action: string | null): StatusLine {\n return {\n name: agent.name,\n kind: agent.kind,\n status: agent.status,\n emoji: agent.status === 'closed' ? '' : EMOJI[agent.status],\n action,\n note: agent.note,\n pinned: agent.queueOrder !== null,\n };\n}\n\nexport function formatClock(date: Date): string {\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n return `${hours}:${minutes}`;\n}\n\nexport function buildStatusView(\n ctx: Ctx,\n session: Session,\n options: StatusViewOptions = {},\n): StatusView {\n const all = listAgents(ctx, session.id);\n const open = new Set(all.map((agent) => agent.name));\n // Nothing releases a blocked agent: it waits only while its blocker is still open.\n const isBlocked = (agent: Agent) => agent.blockedOn !== null && open.has(agent.blockedOn);\n const agents = all.filter((agent) => !options.kind || agent.kind === options.kind);\n const table = getTable(ctx, session.id) ?? null;\n const handed = agents.filter((agent) => isUserActionStatus(agent.status));\n // An agent named on the Main line is the main agent's business, not waiting on the human.\n const ranks = new Map(handed.map((agent) => [agent.id, rankOf(ctx, agent)]));\n const waiting = handed\n .filter((agent) => !isBlocked(agent) && !tableIsAbout(table, agent.name))\n .sort((left, right) => compareWaiting(ranks, left, right))\n .map((agent) => toLine(agent, waitingAction(ctx, agent)));\n // Whatever its status, even one registered as running before its launch.\n const blocked = agents.filter(isBlocked).map((agent) => toLine(agent, `→ ${agent.blockedOn}`));\n const running = agents\n .filter((agent) => agent.status === 'running' && !isBlocked(agent))\n .map((agent) => toLine(agent, runningAction(agent)));\n return {\n time: formatClock(ctx.now()),\n sessionName: session.name,\n table,\n turn: getTurn(ctx, session.id),\n waiting,\n blocked,\n running,\n notes: sessionNoteActivity(ctx, session.id),\n };\n}\n","import {\n AGENT_BY_NAME_SQL,\n type Agent,\n type AgentContext,\n type AgentRow,\n moveAgentStatus,\n publishPending,\n toAgent,\n} from './agents.ts';\nimport { type Ctx, nowIso } from './context.ts';\nimport { logEvent } from './events.ts';\nimport type { TranscriptUsage } from './hosts/host.ts';\n\nexport const PAIRING_WINDOW_MILLISECONDS = 60_000;\nexport const STOPPED_NOTE = 'stopped without agent_done';\n\nexport function byHostAgentId(ctx: Ctx, session: string, hostAgentId: string): Agent | undefined {\n const row = ctx.db\n .prepare(\n `SELECT * FROM agents WHERE session = ? AND host_agent_id = ?\n ORDER BY status = 'closed', id DESC LIMIT 1`,\n )\n .get(session, hostAgentId) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nfunction unpairedByName(ctx: Ctx, session: string, names: readonly string[]): AgentRow | undefined {\n for (const name of names) {\n const row = ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND name = ? AND status != 'closed' AND host_agent_id IS NULL`,\n )\n .get(session, name) as AgentRow | undefined;\n if (row) return row;\n }\n return undefined;\n}\n\nexport function unpairedAgent(\n ctx: Ctx,\n session: string,\n names: readonly string[],\n): Agent | undefined {\n const row = unpairedByName(ctx, session, names);\n return row && toAgent(row);\n}\n\nexport function pendingPlanAgent(ctx: Ctx, session: string): Agent | undefined {\n const row = ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND kind = 'plan' AND status = 'running' AND host_agent_id IS NULL\n ORDER BY started_at ASC, id ASC LIMIT 1`,\n )\n .get(session) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nexport function requestLaunch(ctx: Ctx, session: string, name: string): void {\n ctx.db\n .prepare(\n \"UPDATE agents SET launch_requested_at = ? WHERE session = ? AND name = ? AND status != 'closed'\",\n )\n .run(nowIso(ctx), session, name);\n}\n\n// Helpers (Explore, general-purpose) never stand in: only a fork or a Rucher cold agent can be\n// the launch an agent waits for. No type at all keeps the fallbacks for hosts that send none.\nexport function pairsByFallback(agentType: string | undefined): boolean {\n return agentType === undefined || agentType === 'fork' || /^rucher[\\w-]*:/.test(agentType);\n}\n\nfunction openByName(ctx: Ctx, session: string, names: readonly string[]): AgentRow | undefined {\n for (const name of names) {\n const row = ctx.db\n .prepare(`SELECT * FROM agents WHERE session = ? AND name = ? AND status != 'closed'`)\n .get(session, name) as AgentRow | undefined;\n if (row) return row;\n }\n return undefined;\n}\n\n// Only the host knows how the agent was really launched.\nfunction contextOf(agentType: string | undefined): AgentContext | null {\n if (agentType === 'fork') return 'fork';\n return agentType !== undefined && /^rucher[\\w-]*:/.test(agentType) ? 'cold' : null;\n}\n\nfunction pairWith(\n ctx: Ctx,\n session: string,\n id: number,\n hostAgentId: string,\n agentType: string | undefined,\n): Agent | undefined {\n ctx.db\n .prepare(\n `UPDATE agents SET host_agent_id = ?, launch_requested_at = NULL, context = COALESCE(?, context)\n WHERE id = ?`,\n )\n .run(hostAgentId, contextOf(agentType), id);\n return byHostAgentId(ctx, session, hostAgentId);\n}\n\n// A name from the subagent pairs exactly, taking the agent back from a fallback holder since two\n// subagents never carry one name. Then the agent an Agent call announced; only then does the oldest\n// unpaired, unblocked agent of the last minute stand in, and the stop corrects it by name.\nexport function pairSubagent(\n ctx: Ctx,\n session: string,\n hostAgentId: string,\n names: readonly string[] = [],\n agentType?: string,\n): Agent | undefined {\n const paired = byHostAgentId(ctx, session, hostAgentId);\n if (paired) return paired;\n const named = openByName(ctx, session, names);\n if (named) return pairWith(ctx, session, Number(named.id), hostAgentId, agentType);\n if (!pairsByFallback(agentType)) return undefined;\n const since = new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS).toISOString();\n const row =\n (ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND status != 'closed' AND host_agent_id IS NULL\n AND launch_requested_at >= ?\n ORDER BY launch_requested_at ASC, id ASC LIMIT 1`,\n )\n .get(session, since) as AgentRow | undefined) ??\n (ctx.db\n .prepare(\n `SELECT * FROM agents\n WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND blocked_on IS NULL\n AND started_at >= ?\n ORDER BY started_at ASC, id ASC LIMIT 1`,\n )\n .get(session, since) as AgentRow | undefined);\n return row && pairWith(ctx, session, Number(row.id), hostAgentId, agentType);\n}\n\nfunction byName(ctx: Ctx, session: string, name: string): Agent | undefined {\n const row = ctx.db.prepare(AGENT_BY_NAME_SQL).get(session, name) as AgentRow | undefined;\n return row && toAgent(row);\n}\n\nfunction setHostAgentId(ctx: Ctx, id: number, hostAgentId: string | null) {\n ctx.db.prepare('UPDATE agents SET host_agent_id = ? WHERE id = ?').run(hostAgentId, id);\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, holder.id, named.hostAgentId);\n setHostAgentId(ctx, named.id, hostAgentId);\n}\n\n// A launch in parallel can be paired by start order with a sibling's agent; its name, readable once\n// it runs, puts it back on its own before the guard judges its calls.\nexport function confirmSubagent(\n ctx: Ctx,\n session: string,\n hostAgentId: string,\n names: string[],\n): Agent | undefined {\n repairByName(ctx, session, hostAgentId, names);\n return byHostAgentId(ctx, session, hostAgentId);\n}\n\n// Agents the start-order fallback could still pick: more than none means a pairing just made by it\n// may belong to a sibling.\nexport function fallbackCandidates(ctx: Ctx, session: string): number {\n const since = new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS).toISOString();\n const row = ctx.db\n .prepare(\n `SELECT COUNT(*) AS count FROM agents\n WHERE session = ? AND host_agent_id IS NULL AND status != 'closed'\n AND (launch_requested_at >= ?\n OR (status = 'running' AND blocked_on IS NULL AND started_at >= ?))`,\n )\n .get(session, since, since) as { count: number };\n return Number(row.count);\n}\n\nexport function stopSubagent(\n ctx: Ctx,\n session: string,\n hostAgentId: string,\n names: string[] = [],\n usage?: TranscriptUsage,\n): Agent | undefined {\n repairByName(ctx, session, hostAgentId, names);\n const agent = byHostAgentId(ctx, session, hostAgentId);\n if (agent && agent.status !== 'running' && usage) attachUsage(ctx, agent.id, usage);\n if (!agent || agent.status !== 'running') return undefined;\n const payload = usage ? { usage } : undefined;\n if (agent.pendingStatus) {\n publishPending(ctx, agent.id, payload);\n return byHostAgentId(ctx, session, hostAgentId);\n }\n moveAgentStatus(ctx, agent.id, 'review', STOPPED_NOTE);\n logEvent(ctx, session, {\n type: 'finished',\n agent: agent.name,\n agentId: agent.id,\n note: STOPPED_NOTE,\n payload,\n });\n return byHostAgentId(ctx, session, hostAgentId);\n}\n\n// The stop can arrive after the fallback published the agent: its finished event still gets the usage.\nfunction attachUsage(ctx: Ctx, agentId: number, usage: TranscriptUsage): void {\n const row = ctx.db\n .prepare(\n \"SELECT id, payload FROM events WHERE agent_id = ? AND type = 'finished' ORDER BY id DESC LIMIT 1\",\n )\n .get(agentId) as { id: number; payload: string | null } | undefined;\n if (!row) return;\n const payload = row.payload === null ? {} : (JSON.parse(row.payload) as Record<string, unknown>);\n if (payload.usage) return;\n ctx.db\n .prepare('UPDATE events SET payload = ? WHERE id = ?')\n .run(JSON.stringify({ ...payload, usage }), row.id);\n}\n","import { closeSync, fstatSync, openSync, readSync, statSync } from 'node:fs';\nimport type { Ctx } from './context.ts';\nimport { SEARCH_BACKFILL } from './db/search-schema.ts';\nimport { hostById } from './hosts/host.ts';\nimport { getSession, type Session } from './sessions.ts';\n\nexport const SEARCH_LIMITS = {\n // Read per session at each end of turn; the rest waits for the next one.\n turnBytes: 2 * 1024 * 1024,\n // Read in all by one `rucher find` catching up before it searches.\n refreshBytes: 16 * 1024 * 1024,\n sessionTranscriptCharacters: 4 * 1024 * 1024,\n reportBytes: 256 * 1024,\n} as const;\n\nexport type SearchSource =\n | 'session'\n | 'agent'\n | 'note'\n | 'question'\n | 'finding'\n | 'event'\n | 'report'\n | 'transcript';\n\nconst SOURCE_WEIGHTS: Readonly<Record<SearchSource, number>> = {\n session: 3,\n agent: 2,\n note: 2,\n report: 2,\n question: 1.5,\n finding: 1.5,\n event: 1,\n transcript: 1,\n};\n\nconst SOURCE_WEIGHT_SQL = `CASE d.source ${Object.entries(SOURCE_WEIGHTS)\n .map(([source, weight]) => `WHEN '${source}' THEN ${weight}`)\n .join(' ')} ELSE 1 END`;\n\nexport interface IndexOptions {\n env?: NodeJS.ProcessEnv | undefined;\n // The host's own path for the transcript, when its hook gives one.\n transcriptPath?: string | undefined;\n maxBytes?: number | undefined;\n}\n\ninterface SourceRow {\n path: string;\n offset: number;\n size: number;\n mtime: number;\n indexed: number;\n partial: number;\n}\n\nexport function transcriptsIndexed(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.RUCHER_SEARCH_TRANSCRIPTS !== '0';\n}\n\nfunction sourceRow(ctx: Ctx, key: string): SourceRow | undefined {\n return ctx.db\n .prepare('SELECT path, offset, size, mtime, indexed, partial FROM search_sources WHERE key = ?')\n .get(key) as SourceRow | undefined;\n}\n\nfunction saveSource(ctx: Ctx, key: string, session: string, row: SourceRow): void {\n ctx.db\n .prepare(\n `INSERT INTO search_sources (key, session, path, offset, size, mtime, indexed, partial)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (key) DO UPDATE SET session = excluded.session, path = excluded.path,\n offset = excluded.offset, size = excluded.size, mtime = excluded.mtime,\n indexed = excluded.indexed, partial = excluded.partial`,\n )\n .run(key, session, row.path, row.offset, row.size, row.mtime, row.indexed, row.partial);\n}\n\ninterface Doc {\n source: SearchSource;\n key: string;\n session: string;\n agentId: number | null;\n title: string;\n body: string;\n at: string | null;\n}\n\nfunction saveDoc(ctx: Ctx, doc: Doc): void {\n ctx.db\n .prepare(\n `INSERT INTO search_docs (source, key, session, agent_id, title, body, at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (source, key) DO UPDATE SET session = excluded.session,\n agent_id = excluded.agent_id, title = excluded.title, body = excluded.body, at = excluded.at`,\n )\n .run(doc.source, doc.key, doc.session, doc.agentId, doc.title, doc.body, doc.at);\n}\n\nfunction transcriptFile(session: Session, options: IndexOptions): string | undefined {\n if (options.transcriptPath) return options.transcriptPath;\n const launch = hostById(session.host).launch;\n return launch\n ?.transcriptFiles(session, options.env)\n .find((path) => statSync(path, { throwIfNoEntry: false })?.isFile());\n}\n\nfunction forgetTranscriptRows(ctx: Ctx, sessionId: string): void {\n ctx.db\n .prepare(\"DELETE FROM search_docs WHERE source = 'transcript' AND session = ?\")\n .run(sessionId);\n ctx.db.prepare('DELETE FROM search_sources WHERE key = ?').run(`transcript:${sessionId}`);\n}\n\n// Returns the bytes read, and whether some are left for a later call.\nfunction indexTranscript(\n ctx: Ctx,\n session: Session,\n options: IndexOptions,\n maxBytes: number,\n): { read: number; pending: boolean } {\n const idle = { read: 0, pending: false };\n const launch = hostById(session.host).launch;\n const path = launch?.readTranscript && transcriptFile(session, options);\n if (!launch?.readTranscript || !path) return idle;\n const size = statSync(path, { throwIfNoEntry: false })?.size;\n if (size === undefined) return idle;\n const key = `transcript:${session.id}`;\n let source = sourceRow(ctx, key);\n // A shorter file was rewritten, not appended to.\n if (source && size < source.offset) {\n forgetTranscriptRows(ctx, session.id);\n source = undefined;\n }\n const from = source?.offset ?? 0;\n if (from >= size) return idle;\n if (source?.partial) {\n saveSource(ctx, key, session.id, { ...source, path, offset: size, size });\n return idle;\n }\n const slice = launch.readTranscript(path, from, maxBytes);\n let indexed = source?.indexed ?? 0;\n let partial = source?.partial ?? 0;\n for (const chunk of slice.chunks) {\n if (indexed + chunk.text.length > SEARCH_LIMITS.sessionTranscriptCharacters) {\n partial = 1;\n break;\n }\n indexed += chunk.text.length;\n saveDoc(ctx, {\n source: 'transcript',\n key: `${session.id}:${chunk.offset}`,\n session: session.id,\n agentId: null,\n title: '',\n body: chunk.text,\n at: chunk.at,\n });\n }\n saveSource(ctx, key, session.id, {\n path,\n offset: slice.nextOffset,\n size: slice.size,\n mtime: 0,\n indexed,\n partial,\n });\n return { read: slice.nextOffset - from, pending: slice.nextOffset < slice.size };\n}\n\nfunction readHead(path: string, bytes: number): string {\n const descriptor = openSync(path, 'r');\n try {\n const length = Math.min(bytes, fstatSync(descriptor).size);\n const buffer = Buffer.alloc(length);\n readSync(descriptor, buffer, 0, length, 0);\n return buffer.toString('utf8');\n } finally {\n closeSync(descriptor);\n }\n}\n\nfunction indexReports(ctx: Ctx, sessionId: string): void {\n const agents = ctx.db\n .prepare(\n 'SELECT id, name, report_path FROM agents WHERE session = ? AND report_path IS NOT NULL',\n )\n .all(sessionId) as { id: number; name: string; report_path: string }[];\n for (const agent of agents) {\n const stat = statSync(agent.report_path, { throwIfNoEntry: false });\n if (!stat?.isFile()) {\n ctx.db\n .prepare(\"DELETE FROM search_docs WHERE source = 'report' AND key = ?\")\n .run(String(agent.id));\n ctx.db.prepare('DELETE FROM search_sources WHERE key = ?').run(`report:${agent.id}`);\n continue;\n }\n const key = `report:${agent.id}`;\n const source = sourceRow(ctx, key);\n if (\n source &&\n source.path === agent.report_path &&\n source.size === stat.size &&\n source.mtime === stat.mtimeMs\n ) {\n continue;\n }\n saveDoc(ctx, {\n source: 'report',\n key: String(agent.id),\n session: sessionId,\n agentId: Number(agent.id),\n title: agent.name,\n body: readHead(agent.report_path, SEARCH_LIMITS.reportBytes),\n at: stat.mtime.toISOString(),\n });\n saveSource(ctx, key, sessionId, {\n path: agent.report_path,\n offset: stat.size,\n size: stat.size,\n mtime: stat.mtimeMs,\n indexed: 0,\n partial: 0,\n });\n }\n}\n\nfunction inTransaction<T>(ctx: Ctx, run: () => T): T {\n ctx.db.exec('BEGIN IMMEDIATE');\n try {\n const result = run();\n ctx.db.exec('COMMIT');\n return result;\n } catch (error) {\n ctx.db.exec('ROLLBACK');\n throw error;\n }\n}\n\nexport interface IndexResult {\n read: number;\n pending: boolean;\n}\n\n// Carnet rows index themselves; this reads what lives in files: reports and the transcript.\nexport function indexSession(ctx: Ctx, sessionId: string, options: IndexOptions = {}): IndexResult {\n const session = getSession(ctx, sessionId);\n if (!session) return { read: 0, pending: false };\n return inTransaction(ctx, () => {\n indexReports(ctx, session.id);\n if (!transcriptsIndexed(options.env)) {\n forgetTranscriptRows(ctx, session.id);\n return { read: 0, pending: false };\n }\n return indexTranscript(ctx, session, options, options.maxBytes ?? SEARCH_LIMITS.turnBytes);\n });\n}\n\nexport function forgetTranscript(ctx: Ctx, sessionId: string): void {\n forgetTranscriptRows(ctx, sessionId);\n}\n\nfunction scopeSessions(ctx: Ctx, all: boolean): string[] {\n const rows = (\n all\n ? ctx.db.prepare('SELECT id FROM sessions ORDER BY last_active_at DESC')\n : ctx.db.prepare('SELECT id FROM sessions WHERE workspace = ? ORDER BY last_active_at DESC')\n ).all(...(all ? [] : [ctx.workspace])) as { id: string }[];\n return rows.map((row) => row.id);\n}\n\nexport interface RefreshOptions {\n all?: boolean | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n maxBytes?: number | undefined;\n}\n\n// Catches up what no hook indexed, such as a turn interrupted before its Stop hook, within a budget.\nexport function refreshIndex(ctx: Ctx, options: RefreshOptions = {}): { pending: boolean } {\n let budget = options.maxBytes ?? SEARCH_LIMITS.refreshBytes;\n let pending = false;\n for (const id of scopeSessions(ctx, options.all ?? false)) {\n if (budget <= 0) {\n pending = true;\n break;\n }\n const result = indexSession(ctx, id, { env: options.env, maxBytes: budget });\n budget -= result.read;\n pending ||= result.pending;\n }\n return { pending };\n}\n\nexport function reindex(\n ctx: Ctx,\n options: { all?: boolean | undefined; env?: NodeJS.ProcessEnv | undefined } = {},\n): { sessions: number } {\n const ids = scopeSessions(ctx, options.all ?? false);\n inTransaction(ctx, () => {\n ctx.db.exec(SEARCH_BACKFILL);\n for (const id of ids) {\n ctx.db\n .prepare(\"DELETE FROM search_docs WHERE source IN ('transcript', 'report') AND session = ?\")\n .run(id);\n ctx.db.prepare('DELETE FROM search_sources WHERE session = ?').run(id);\n }\n });\n for (const id of ids) {\n for (;;) {\n const result = indexSession(ctx, id, {\n env: options.env,\n maxBytes: SEARCH_LIMITS.refreshBytes,\n });\n if (!result.pending || result.read === 0) break;\n }\n }\n return { sessions: ids.length };\n}\n\nconst STOP_WORDS = new Set(\n (\n 'a an and are as at be by did do does for from had has have how i in is it its me my of on or ' +\n 'that the this to was we were what when where which who why with session sessions talked ' +\n 'about ai au aux avec ce ces dans de des du elle en est et il je la le les leur ma mes mon ' +\n 'ne nous on ou par pas pour qu que qui quoi sa se ses son sur ta te tes ton tu un une vous ' +\n 'parle parlait parlé parler où quand quel quelle laquelle lequel'\n ).split(' '),\n);\n\n// The question is never handed to MATCH as is: FTS5 syntax in it would throw.\nexport function searchQuery(question: string): string | null {\n const tokens = [\n ...new Set(\n (\n question\n .normalize('NFC')\n .toLowerCase()\n .match(/[\\p{L}\\p{N}]+/gu) ?? []\n ).filter((token) => token.length >= 2 && !STOP_WORDS.has(token)),\n ),\n ];\n if (tokens.length === 0) return null;\n return tokens.map((token) => `\"${token}\"${token.length >= 4 ? '*' : ''}`).join(' OR ');\n}\n\nexport interface SearchHit {\n source: SearchSource;\n title: string;\n snippet: string;\n at: string | null;\n agentId: number | null;\n score: number;\n}\n\nexport interface SessionMatch {\n session: Session;\n score: number;\n hits: SearchHit[];\n // Part of its transcript was past the size cap and is not searched.\n partial: boolean;\n}\n\nexport interface NoteMatch {\n number: number;\n workspace: string;\n kind: string;\n snippet: string;\n score: number;\n}\n\nexport interface SearchResults {\n sessions: SessionMatch[];\n notes: NoteMatch[];\n}\n\nexport interface SearchOptions {\n all?: boolean | undefined;\n limit?: number | undefined;\n hitsPerSession?: number | undefined;\n // Rows kept after source weight and recency, before sessions are grouped.\n candidates?: number | undefined;\n}\n\ninterface HitRow {\n source: SearchSource;\n session: string | null;\n agent_id: number | null;\n at: string | null;\n title: string;\n snippet: string;\n rank: number;\n note_number: number | null;\n note_workspace: string | null;\n}\n\nconst CANDIDATES = 400;\nconst RECENCY_HALF_LIFE_DAYS = 14;\nconst DAY_MILLISECONDS = 24 * 60 * 60 * 1000;\nconst RECENCY_SQL = `CASE WHEN s.last_active_at IS NULL THEN 1.0\n ELSE 1.0 + 0.25 * pow(0.5, max(0.0, (julianday(?) - julianday(s.last_active_at)) / ${RECENCY_HALF_LIFE_DAYS}))\nEND`;\n\nexport const SNIPPET_OPEN = '«';\nexport const SNIPPET_CLOSE = '»';\n\nexport function searchSessions(\n ctx: Ctx,\n question: string,\n options: SearchOptions = {},\n): SearchResults {\n const query = searchQuery(question);\n if (!query) return { sessions: [], notes: [] };\n const all = options.all ?? false;\n const candidates = options.candidates ?? CANDIDATES;\n const rows = ctx.db\n .prepare(\n `SELECT d.source, d.session, d.agent_id, d.at, d.title,\n snippet(search_index, -1, '${SNIPPET_OPEN}', '${SNIPPET_CLOSE}', '…', 14) AS snippet,\n bm25(search_index, 5.0, 1.0) AS rank,\n n.number AS note_number, n.workspace AS note_workspace\n FROM search_index\n JOIN search_docs d ON d.id = search_index.rowid\n LEFT JOIN sessions s ON s.id = d.session\n LEFT JOIN notes n ON d.source = 'note' AND n.id = CAST(d.key AS INTEGER)\n WHERE search_index MATCH ?\n AND (? OR COALESCE(s.workspace, n.workspace) = ?)\n ORDER BY (-bm25(search_index, 5.0, 1.0)) * (${SOURCE_WEIGHT_SQL}) * (${RECENCY_SQL}) DESC\n LIMIT ?`,\n )\n .all(\n query,\n all ? 1 : 0,\n ctx.workspace,\n ctx.now().toISOString(),\n candidates,\n ) as unknown as HitRow[];\n const bySession = new Map<string, SearchHit[]>();\n const notes: NoteMatch[] = [];\n for (const row of rows) {\n const score = -Number(row.rank) * (SOURCE_WEIGHTS[row.source] ?? 1);\n if (row.session === null) {\n if (row.note_number !== null && row.note_workspace !== null) {\n notes.push({\n number: Number(row.note_number),\n workspace: row.note_workspace,\n kind: row.title,\n snippet: row.snippet,\n score,\n });\n }\n continue;\n }\n const hits = bySession.get(row.session) ?? [];\n hits.push({\n source: row.source,\n title: row.title,\n snippet: row.snippet,\n at: row.at,\n agentId: row.agent_id === null ? null : Number(row.agent_id),\n score,\n });\n bySession.set(row.session, hits);\n }\n const now = ctx.now().getTime();\n const sessions: SessionMatch[] = [];\n for (const [id, hits] of bySession) {\n const session = getSession(ctx, id);\n if (!session) continue;\n hits.sort((left, right) => right.score - left.score);\n const ageDays = Math.max(0, now - Date.parse(session.lastActiveAt)) / DAY_MILLISECONDS;\n const recency = 1 + 0.25 * 0.5 ** (ageDays / RECENCY_HALF_LIFE_DAYS);\n const score = hits.slice(0, 3).reduce((total, hit) => total + hit.score, 0) * recency;\n sessions.push({\n session,\n score,\n hits: distinctSources(hits, options.hitsPerSession ?? 2),\n partial: false,\n });\n }\n sessions.sort((left, right) => right.score - left.score);\n const limited = sessions.slice(0, options.limit ?? 5);\n for (const match of limited) match.partial = transcriptPartial(ctx, match.session.id);\n notes.sort((left, right) => right.score - left.score);\n return { sessions: limited, notes: notes.slice(0, options.limit ?? 5) };\n}\n\n// The best hit of each source first, so two snippets show two different places.\nfunction distinctSources(hits: SearchHit[], count: number): SearchHit[] {\n const seen = new Set<SearchSource>();\n const first = hits.filter((hit) => !seen.has(hit.source) && seen.add(hit.source));\n return [...first, ...hits.filter((hit) => !first.includes(hit))].slice(0, count);\n}\n\nfunction transcriptPartial(ctx: Ctx, sessionId: string): boolean {\n const row = ctx.db\n .prepare('SELECT partial FROM search_sources WHERE key = ?')\n .get(`transcript:${sessionId}`) as { partial: number } | undefined;\n return Boolean(row?.partial);\n}\n","import { mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync } from 'node:sqlite';\nimport {\n type Agent,\n type AgentKind,\n clearSandbox,\n closeAgent,\n closedSandboxes,\n dropAgent,\n finishAgent,\n type FinishAgentInput,\n getAgent,\n listAgents,\n type ListAgentsOptions,\n promoteAgent,\n type PromoteAgentInput,\n reorderQueue,\n moveAgentStatus,\n startAgent,\n type StartAgentInput,\n updateAgent,\n type UpdateAgentInput,\n getAgentById,\n kindHistory,\n requireAgent,\n resolveAttachments,\n addAttachments,\n} from './agents.ts';\nimport { type Brief, buildBrief } from './brief.ts';\nimport { addReference, listReferences, removeReference } from './references.ts';\nimport { memoryHalfLife } from './notes.ts';\nimport { CarnetError } from './errors.ts';\nimport type { Attachment, AttachmentInput } from './agent-json.ts';\nimport type { Ctx } from './context.ts';\nimport { type AgentStatus } from './status/model.ts';\nimport { sanitizeNote } from './status/note.ts';\nimport { MEMORY_DB, openDatabase } from './db/open.ts';\nimport { databasePath } from './paths.ts';\nimport { logEvent, type LogEventInput, readEvents } from './events.ts';\nimport {\n type DecisionInput,\n decideFindings,\n deliverSent,\n type FindingFilter,\n type FindingInput,\n checkSpawnLink,\n linkSpawned,\n listFindings,\n replaceFindings,\n} from './findings.ts';\nimport {\n type AnswerInput,\n addQuestions,\n answerQuestions,\n listQuestions,\n type QuestionInput,\n} from './questions.ts';\nimport {\n type Workspace,\n type WorkspaceResolution,\n requireWorkspace,\n resolveWorkspace,\n} from './workspace/locate.ts';\nimport { memoryMaxCharacters, type MemoryOptions, sessionStartMemory } from './memory.ts';\nimport { mergeSessions } from './merge.ts';\nimport { createSandbox, removeSandbox, resolveSandbox } from './sandbox.ts';\nimport {\n type AddNoteInput,\n addNote,\n type CiteNoteInput,\n citeNote,\n type DropNoteInput,\n dropNote,\n dropNotes,\n getNote,\n listNotes,\n type ListNotesOptions,\n noteDetail,\n recordActiveDay,\n staleNotes,\n sessionNoteActivity,\n} from './notes.ts';\nimport { purgeSessions } from './purge.ts';\nimport {\n createSession,\n type CreateSessionInput,\n defaultSession,\n dropSession,\n endSession,\n ensureSession,\n getSession,\n type HookEnv,\n type HookSessionPayload,\n listSessions,\n type ListSessionsOptions,\n nameSession,\n adoptTitle,\n requireSession,\n findSession,\n recordPluginVersion,\n recordPromptVersion,\n type Session,\n type SessionKind,\n type SessionStatus,\n setParent,\n setSessionKind,\n setSessionStatus,\n demoteSession,\n promoteSession,\n renameSession,\n resetDeadSessions,\n staleTempSessions,\n sessionByHostProcess,\n sessionByName,\n touchSession,\n upsertFromHook,\n} from './sessions.ts';\nimport { type RenderOptions, renderSections, renderStatus } from './status/render.ts';\nimport { buildStatusView, type StatusViewOptions } from './status/view.ts';\nimport {\n byHostAgentId,\n confirmSubagent,\n fallbackCandidates,\n pairSubagent,\n pendingPlanAgent,\n requestLaunch,\n stopSubagent,\n unpairedAgent,\n} from './subagents.ts';\nimport { clearTable, getTable, setTable, type SetTableInput } from './table.ts';\nimport {\n forgetTranscript,\n indexSession,\n type IndexOptions,\n refreshIndex,\n reindex,\n searchSessions,\n type SearchOptions,\n} from './search.ts';\nimport { endTurn, failTurn, getTurn, startTurn, waitTurn } from './turn.ts';\nimport type { TranscriptUsage } from './hosts/host.ts';\n\nexport interface CarnetOptions {\n now?: () => Date;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nexport interface ClosedAgent extends Agent {\n sandboxRemoved: boolean;\n}\n\nexport class Carnet {\n readonly db: DatabaseSync;\n readonly env: NodeJS.ProcessEnv;\n private readonly ctx: Ctx;\n\n constructor(\n db: DatabaseSync,\n readonly workspace: Workspace | null,\n options: CarnetOptions = {},\n ) {\n this.db = db;\n this.env = options.env ?? process.env;\n this.ctx = { db, now: options.now ?? (() => new Date()), workspace: workspace?.name ?? null };\n }\n\n now(): Date {\n return this.ctx.now();\n }\n\n requireWorkspace(): Workspace {\n return requireWorkspace(this.workspace);\n }\n\n readonly sessions = {\n get: (id: string) => getSession(this.ctx, id),\n find: (reference: string) => findSession(this.ctx, reference),\n require: (id: string) => requireSession(this.ctx, id),\n ensure: (id: string, cwd?: string) =>\n ensureSession(this.ctx, id, cwd, this.workspace ?? undefined),\n upsertFromHook: (payload: HookSessionPayload, env?: HookEnv) =>\n upsertFromHook(this.ctx, this.workspace, payload, env),\n touch: (id: string) => touchSession(this.ctx, id),\n merge: (fromId: string, intoId: string) => {\n const result = mergeSessions(this.ctx, fromId, intoId);\n this.releaseClosedSandboxes(fromId);\n this.releaseClosedSandboxes(intoId);\n return result;\n },\n purge: (keepId: string, days: number) => purgeSessions(this.ctx, keepId, days),\n name: (id: string, name: string, purpose?: string) => nameSession(this.ctx, id, name, purpose),\n adoptTitle: (id: string, title: string | undefined) => adoptTitle(this.ctx, id, title),\n list: (options?: ListSessionsOptions) => listSessions(this.ctx, options),\n drop: (id: string) => {\n const session = dropSession(this.ctx, id);\n this.releaseClosedSandboxes(id);\n return session;\n },\n default: () => defaultSession(this.ctx),\n byName: (name: string) => sessionByName(this.ctx, name),\n byHostProcess: (host: string, processId: number) =>\n sessionByHostProcess(this.ctx, host, processId),\n recordPluginVersion: (id: string, version: string | null) =>\n recordPluginVersion(this.ctx, id, version),\n recordPromptVersion: (id: string, version: string | null) =>\n recordPromptVersion(this.ctx, id, version),\n setParent: (id: string, parentId: string) => setParent(this.ctx, id, parentId),\n setStatus: (id: string, status: SessionStatus) => setSessionStatus(this.ctx, id, status),\n create: (input: CreateSessionInput) => createSession(this.ctx, input),\n setKind: (id: string, kind: SessionKind, name?: string | null) =>\n setSessionKind(this.ctx, id, kind, name),\n end: (id: string) => endSession(this.ctx, id),\n rename: (id: string, name: string) => renameSession(this.ctx, id, name),\n promote: (id: string, name?: string) => promoteSession(this.ctx, id, name),\n demote: (id: string) => demoteSession(this.ctx, id),\n staleTemp: (olderThanMilliseconds: number) =>\n staleTempSessions(this.ctx, olderThanMilliseconds),\n resetDead: (isAlive: (processId: number) => boolean) => resetDeadSessions(this.ctx, isAlive),\n };\n\n private releaseSandbox(agent: Agent): ClosedAgent {\n if (!agent.sandbox) return { ...agent, sandboxRemoved: false };\n const sandboxRemoved = removeSandbox(this.workspace, agent.sandbox);\n clearSandbox(this.ctx, agent.id);\n return { ...agent, sandbox: null, sandboxRemoved };\n }\n\n releaseClosedSandboxes(session?: string): number {\n let removed = 0;\n for (const row of closedSandboxes(this.ctx, session)) {\n if (removeSandbox(this.workspace, row.sandbox)) removed += 1;\n clearSandbox(this.ctx, row.id);\n }\n return removed;\n }\n\n readonly agents = {\n get: (session: string, name: string) => getAgent(this.ctx, session, name),\n require: (session: string, name: string) => requireAgent(this.ctx, session, name),\n byId: (id: number) => getAgentById(this.ctx, id),\n kindHistory: (id: number) => kindHistory(this.ctx, id),\n resolveAttachments: (session: string, inputs: readonly AttachmentInput[]) =>\n resolveAttachments(this.ctx, session, inputs, this.workspace?.runDirectory),\n // A doc attachment adds a reference row before the start's own checks, which may still fail.\n startWith: (\n session: string,\n input: Omit<StartAgentInput, 'attachments'>,\n attachments?: readonly AttachmentInput[],\n ) => {\n this.ctx.db.exec('BEGIN IMMEDIATE');\n try {\n const agent = this.agents.start(session, {\n ...input,\n attachments: attachments && this.agents.resolveAttachments(session, attachments),\n });\n this.ctx.db.exec('COMMIT');\n return agent;\n } catch (error) {\n this.ctx.db.exec('ROLLBACK');\n throw error;\n }\n },\n attach: (id: number, attachments: readonly Attachment[]) =>\n addAttachments(this.ctx, id, attachments),\n start: (session: string, input: StartAgentInput) => {\n const sandbox = input.sandbox ? resolveSandbox(this.workspace, input.sandbox) : undefined;\n const spawnedFrom = (input.attachments ?? []).filter(\n (attachment) => attachment.type === 'findings',\n );\n for (const findings of spawnedFrom) {\n checkSpawnLink(\n this.ctx,\n findings.review,\n findings.n,\n sanitizeNote(input.name),\n input.kind ?? '',\n );\n }\n const agent = startAgent(this.ctx, session, { ...input, sandbox });\n for (const findings of spawnedFrom) {\n linkSpawned(this.ctx, findings.review, findings.n, agent.id, input.kind ?? '');\n }\n if (sandbox) createSandbox(sandbox);\n return agent;\n },\n update: (session: string, name: string, input: UpdateAgentInput) =>\n updateAgent(this.ctx, session, name, input),\n moveStatus: (id: number, status: AgentStatus, note: string | null) =>\n moveAgentStatus(this.ctx, id, status, note),\n finish: (session: string, name: string, input: FinishAgentInput) =>\n finishAgent(this.ctx, session, name, input),\n drop: (session: string, name: string, reason?: string) =>\n this.releaseSandbox(dropAgent(this.ctx, session, name, reason)),\n close: (session: string, name: string, event: Omit<LogEventInput, 'agent' | 'agentId'>) =>\n this.releaseSandbox(closeAgent(this.ctx, session, name, event)),\n promote: (session: string, name: string, input: PromoteAgentInput) => {\n const agent = promoteAgent(this.ctx, session, name, input);\n return agent.kind === 'implement'\n ? this.releaseSandbox(agent)\n : { ...agent, sandboxRemoved: false };\n },\n list: (session: string, options?: ListAgentsOptions) => listAgents(this.ctx, session, options),\n reorderQueue: (session: string, names: string[]) => reorderQueue(this.ctx, session, names),\n byHostAgentId: (session: string, hostAgentId: string) =>\n byHostAgentId(this.ctx, session, hostAgentId),\n pairSubagent: (\n session: string,\n hostAgentId: string,\n names?: readonly string[],\n agentType?: string,\n ) => pairSubagent(this.ctx, session, hostAgentId, names, agentType),\n confirmSubagent: (session: string, hostAgentId: string, names: string[]) =>\n confirmSubagent(this.ctx, session, hostAgentId, names),\n fallbackCandidates: (session: string) => fallbackCandidates(this.ctx, session),\n unpaired: (session: string, names: readonly string[]) =>\n unpairedAgent(this.ctx, session, names),\n pendingPlan: (session: string) => pendingPlanAgent(this.ctx, session),\n requestLaunch: (session: string, name: string) => requestLaunch(this.ctx, session, name),\n stopSubagent: (\n session: string,\n hostAgentId: string,\n names?: string[],\n usage?: TranscriptUsage,\n ) => stopSubagent(this.ctx, session, hostAgentId, names, usage),\n };\n\n readonly questions = {\n list: (session: string, agent: string, openOnly?: boolean) =>\n listQuestions(this.ctx, session, agent, openOnly),\n add: (session: string, agent: string, inputs: readonly QuestionInput[]) =>\n addQuestions(this.ctx, session, agent, inputs),\n answer: (session: string, agent: string, answers: readonly AnswerInput[]) =>\n answerQuestions(this.ctx, session, agent, answers),\n };\n\n readonly findings = {\n list: (session: string, agent: string, filter?: FindingFilter) =>\n listFindings(this.ctx, session, agent, filter),\n replace: (session: string, agent: string, inputs: readonly FindingInput[]) =>\n replaceFindings(this.ctx, session, agent, inputs),\n decide: (\n session: string,\n agent: string,\n decisions: readonly DecisionInput[],\n override?: boolean,\n ) => decideFindings(this.ctx, session, agent, decisions, override),\n deliverSent: (session: string, agent: string) => deliverSent(this.ctx, session, agent),\n };\n\n readonly table = {\n get: (session: string) => getTable(this.ctx, session),\n set: (session: string, input: SetTableInput) => setTable(this.ctx, session, input),\n clear: (session: string) => clearTable(this.ctx, session),\n };\n\n readonly turn = {\n get: (session: string) => getTurn(this.ctx, session),\n start: (session: string) => startTurn(this.ctx, session),\n wait: (session: string) => waitTurn(this.ctx, session),\n fail: (session: string) => failTurn(this.ctx, session),\n end: (session: string) => endTurn(this.ctx, session),\n };\n\n readonly events = {\n log: (session: string, input: LogEventInput) => logEvent(this.ctx, session, input),\n read: (session: string, limit?: number, agentOnly?: boolean, kind?: AgentKind) =>\n readEvents(this.ctx, { session, limit, agentOnly, kind }),\n };\n\n readonly notes = {\n add: (input: AddNoteInput) => addNote(this.ctx, this.workspace, input),\n get: (id: number) => getNote(this.ctx, id),\n show: (id: number, halfLifeDays?: number) => noteDetail(this.ctx, id, halfLifeDays),\n list: (options?: ListNotesOptions) => listNotes(this.ctx, options),\n stale: (halfLifeDays?: number) => staleNotes(this.ctx, halfLifeDays),\n drop: (id: number, input: DropNoteInput) => dropNote(this.ctx, id, input),\n dropMany: (ids: number[], input: Parameters<typeof dropNotes>[2]) =>\n dropNotes(this.ctx, ids, input),\n cite: (id: number, input: CiteNoteInput) => citeNote(this.ctx, id, input),\n recordActiveDay: () => recordActiveDay(this.ctx),\n activity: (session: string) => sessionNoteActivity(this.ctx, session),\n };\n\n readonly memory = {\n atStart: (session: Session, options?: MemoryOptions) =>\n sessionStartMemory(this.ctx, this.workspace, session, options),\n };\n\n readonly references = {\n // With an agent, the document goes into that open agent's brief only.\n add: (\n session: string,\n path: string,\n options: { agent?: string | undefined; cwd?: string | undefined } = {},\n ) => {\n const agent = options.agent ? requireAgent(this.ctx, session, options.agent) : undefined;\n if (agent?.status === 'closed') {\n throw new CarnetError('INVALID_ATTACHMENT', `${agent.name} is closed`);\n }\n const reference = addReference(this.ctx, session, {\n path,\n scope: agent ? 'agent' : 'session',\n cwd: options.cwd,\n runDirectory: this.workspace?.runDirectory,\n });\n if (agent) addAttachments(this.ctx, agent.id, [{ type: 'ref', id: reference.id }]);\n return reference;\n },\n list: (\n session: string,\n options: { agent?: string | undefined; all?: boolean | undefined } = {},\n ) => {\n const agent = options.agent ? requireAgent(this.ctx, session, options.agent) : undefined;\n const ids = (agent?.attachments ?? []).flatMap((attachment) =>\n attachment.type === 'ref' ? [attachment.id] : [],\n );\n return listReferences(this.ctx, session, { ids, all: options.all });\n },\n remove: (session: string, idOrPath: string) =>\n removeReference(this.ctx, session, idOrPath, this.workspace?.runDirectory),\n };\n\n // The first read of a brief is logged once, with what it held.\n brief(session: string, name: string): Brief {\n const agent = requireAgent(this.ctx, session, name);\n const brief = buildBrief(this.ctx, agent.id, {\n maxCharacters: memoryMaxCharacters(this.env.RUCHER_MEMORY_MAX_CHARACTERS),\n halfLifeDays: memoryHalfLife(this.env.RUCHER_MEMORY_HALF_LIFE_DAYS),\n });\n const logged = this.ctx.db\n .prepare(\"SELECT 1 FROM events WHERE agent_id = ? AND type = 'briefed'\")\n .get(agent.id);\n if (!logged) {\n logEvent(this.ctx, session, {\n type: 'briefed',\n agent: agent.name,\n agentId: agent.id,\n note: `${brief.parts.length} part${brief.parts.length === 1 ? '' : 's'}`,\n payload: {\n parts: brief.parts.map((part) => ({\n type: part.type,\n chars: part.text?.length ?? 0,\n bytes: part.bytes ?? null,\n missing: part.missing ?? false,\n })),\n },\n });\n }\n return brief;\n }\n\n readonly search = {\n index: (session: string, options: IndexOptions = {}) =>\n indexSession(this.ctx, session, { env: this.env, ...options }),\n refresh: (all = false) => refreshIndex(this.ctx, { all, env: this.env }),\n reindex: (all = false) => reindex(this.ctx, { all, env: this.env }),\n forgetTranscript: (session: string) => forgetTranscript(this.ctx, session),\n find: (question: string, options?: SearchOptions) =>\n searchSessions(this.ctx, question, options),\n };\n\n readonly status = {\n view: (session: Session, options?: StatusViewOptions) =>\n buildStatusView(this.ctx, session, options),\n render: (session: Session, options?: RenderOptions & StatusViewOptions) =>\n renderStatus(buildStatusView(this.ctx, session, options), options),\n sections: (session: Session) => renderSections(buildStatusView(this.ctx, session)),\n };\n\n close(): void {\n this.db.close();\n }\n}\n\nexport interface OpenCarnetOptions extends CarnetOptions {\n workspace?: string | undefined;\n sessionId?: string | undefined;\n cwd?: string | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n dbPath?: string | undefined;\n tolerant?: boolean | undefined;\n}\n\nfunction openStore(options: OpenCarnetOptions): DatabaseSync {\n const path = options.dbPath ?? databasePath(options.env);\n if (path !== MEMORY_DB) mkdirSync(dirname(path), { recursive: true });\n return openDatabase(path);\n}\n\nexport function openCarnet(options: OpenCarnetOptions = {}): Carnet {\n return openResolvedCarnet(options).carnet;\n}\n\nexport interface ResolvedCarnet {\n carnet: Carnet;\n resolution: WorkspaceResolution;\n}\n\nexport function openResolvedCarnet(options: OpenCarnetOptions = {}): ResolvedCarnet {\n const db = openStore(options);\n try {\n const resolution = resolveWorkspace({ ...options, db });\n return { carnet: new Carnet(db, resolution.workspace, options), resolution };\n } catch (error) {\n db.close();\n throw error;\n }\n}\n\nexport function openWorkspaceCarnet(\n workspace: Workspace | null,\n options: OpenCarnetOptions = {},\n): Carnet {\n return new Carnet(openStore(options), workspace, options);\n}\n","// Generated from docs/kinds/*.md by pnpm run build. Do not edit.\nexport const NEXT_STEPS: Record<string, Record<string, string>> = {\n research: {\n inject: `A research can end here or continue as the same agent, so after the summary ask with \\`AskUserQuestion\\`, unless the human's words already chose:\n\n- **Inject (Recommended):** \\`agent_inject(name, echo: false)\\`: the summary already showed the \"For the main\" section, so it only closes the agent, removing its sandbox. \"Inject all of <name>\" passes \\`full: true\\` without \\`echo: false\\`. Confirm in one line: \\`<name> injected (<n> lines).\\`\n- **Inject and summarize:** \\`agent_inject(name)\\` closes the agent and returns the whole \"For the main\", which the summary may have cut. Then write the human a summary of at most 10 lines: the answer or findings, the ranked options with their trade-offs, and the decision now theirs, with a recommendation. Read another section with \\`agent_inject(name, section)\\` only when \"For the main\" lacks what the summary needs; \"inject all of <name> and summarize\" passes \\`full: true\\`.\n- **Plan next:** ask what to plan, unless the human said it, then see \"Promoting an agent\" in the workflow, with \\`kind: plan\\`. It keeps its sandbox.\n- **Implement next:** see \"Promoting an agent\" in the workflow, with \\`kind: implement\\`.\n- **Later:** nothing. The agent stays waiting.`,\n },\n plan: {\n questions: `**Questions.** \\`agent_questions(name)\\` lists the open ones.\n\n- **Default, one at a time:** one \\`AskUserQuestion\\` call per question. Header \\`Q <n>/<total>\\`, question \\`Question <n>/<total>: <text>\\`, plus its context on a second line. Options: the recommendation first, suffixed \\`(Recommended)\\`, then the alternatives; free text stays possible. For an open question with no alternative, the options are the recommendation and \"I'll answer freely\". Record each answer at once with \\`agent_answer(name, [{n, answer}])\\`. When the human stops, the rest stays open, and the next validate resumes at the first open question with the same numbering.\n- **Text mode,** on \\`--text\\` or \"in text\": show every open question in one block, then let the human answer in one message.\n\n \\`\\`\\`text\n Questions of cache (5)\n\n 1/5: Where does the cache key live?\n Recommended: Redis (A) · Alternatives: B) local memory, C) database\n \\`\\`\\`\n\n The human replies like \\`1 A, 2 ok, 3 no: …\\`. \\`ok\\`, or a question left out, accepts the recommendation. Recap, then record every answer in one \\`agent_answer\\` call.`,\n validate: `**Plan.** Once no question is open, show the plan's steps from the summary, adjusted to the answers, without fetching the plan: \\`agent_inject\\` of a plan gives only its outline, and \\`full: true\\` the whole text, which the main never needs. Then ask with \\`AskUserQuestion\\`. The question names \\`rucher report <name>\\`, which prints the whole plan with each answer beside its question in a terminal, and \\`rucher report <name> --edit\\`, which opens the report in \\`$EDITOR\\`, so the human can read the plan before choosing:\n\n- **Implement (Recommended):** see \"Promoting an agent\" in the workflow, with \\`kind: implement\\`.\n- **Modify:** send the human's changes to the fork with \\`SendMessage\\`, and \\`agent_step answered\\` with \\`next: running\\`. The fork revises its plan and finishes again, possibly with new questions.\n- **Close:** \\`agent_step dropped\\` with note \\`plan kept\\`. The plan stays injectable, and the sandbox is removed.\n- **Later:** nothing. The agent stays on 👀 review.\n\nA plan of \\`none: no change asked\\` has nothing to implement: recommend Close.`,\n },\n implement: {\n apply: `1. \\`agent_step applying\\`. The Main line names the agent and leaves it out of \"Waiting on you\". It warns when a review of the agent is not triaged yet: say so, and go on only if the human confirms.\n2. Diff the worktree (\\`git add -N\\` for new files), \\`git apply -3\\` into the main repo, uncommitted. Resolve conflicts.\n3. Run typecheck and tests in the main repo. Audit the comments.\n4. Present only the check results, how to test, the open questions with recommendations, and a one-line commit message: the summary already showed what was done.\n5. \\`agent_step applied\\`: the agent moves to 🧪 test, first in \"Waiting on you\". \\`tested\\` is optional: it logs the test and keeps the agent on test until the commit.\n\n**Conflict** the main agent can't resolve: revert the partial apply, \\`agent_step answered\\` with \\`next: running\\` and note \\`conflict\\`, then send the fork the new base with \\`SendMessage\\`. It rebases its worktree and finishes again.`,\n commit: `**Tested:** when the agent is on 🧪 test, the human has tested the applied work. Ask with \\`AskUserQuestion\\`:\n\n- **Commit (Recommended):** with the report's commit message, after checking the branch, then \\`agent_step committed\\` with the sha (it closes the agent and clears its Main line), sort its Learnings ([Memory](../workflow.md#memory)), and remove the worktree. Free text can change the message.\n- **Not yet:** nothing, it stays on test.`,\n },\n review: {\n triage: `\\`review_findings(name)\\` lists the open findings in two groups, each finding with its recommended route: the reviewer's when it gave one (\\`send back\\` only while possible), else \\`send back\\` while the target is an implement agent not yet applied, else \\`in main\\` for a suggestion and \\`implement\\` for the rest. **To decide** holds the findings with no decision yet, blocking first, then the ones deferred in an earlier round, marked \\`deferred\\`; **To route** those chosen for a fix whose route is not set. Its last line, \\`next: decide\\` or \\`next: route\\`, names the pass to run, so a triage cut halfway resumes where it stopped. Triage runs in two passes, recording each answer at once with \\`review_decide(name, [{n, decision, reason?, agent?, kind?}])\\`. Ask the list fetched once at the start: a finding deferred in this round is not asked again before the next time the human handles the review.`,\n decide: `**Pass 1, what:** one question per finding to decide, one at a time by default (\\`AskUserQuestion\\`, header \\`R <n>/<total>\\`, the severity, location, text and proposed fix in the question, and \\`deferred earlier\\` for a deferred one):\n\n- **Fix (Recommended),** its description naming the recommended route: record \\`fix\\`;\n- **Ignore,** with a short reason: record \\`ignored\\`;\n- **Discuss:** talk the finding over with the human, then ask it again;\n- **Later:** record \\`deferred\\`. The finding comes back the next time the human handles the review, which stays open; a review with only deferred findings waits last in \"Waiting on you\".`,\n route: `**Pass 2, how,** right after pass 1, for every finding to route. One \\`AskUserQuestion\\` lists them, each with its recommended route and, for a new agent, a short name from its location, never with a kind word; one agent per finding. Options:\n\n- **Accept all recommended (Recommended);**\n- **Choose per finding:** one question each, header \\`R <n>/<total> how\\`, the recommended route first;\n- free text, like \\`2 plan guard-git, 3 with guard-git, 4 in main, 5 ignore: <reason>\\`, where \\`with <name>\\` joins an agent named earlier in this pass, so several findings share one agent.\n\nThe routes:\n\n- **Send back to the agent,** only while the target is an implement agent not yet applied: the finding joins its list of fixes;\n- **In main:** the main agent makes the fix;\n- **Implement agent:** a new agent fixes it;\n- **Plan agent:** a new agent plans the fix, when it needs choices;\n- **Research agent:** a new agent confirms the cause, when it is not certain.\n\nWith send back available, a per-finding question offers send back, in main, implement and plan; research goes through free text. Record each route: \\`sent\\`, \\`fixed\\` (in main), or \\`spawned\\` with the planned \\`agent\\` name and its \\`kind\\`; a finding to route can still be \\`ignored\\`, with its reason.\n\nA decided finding is refused (\\`FINDING_DECIDED\\`); pass \\`override: true\\` only to correct a mistake the human points out.\n\n\\`--text\\` shows every open finding with its route in one block; the human answers both passes in one message, like \\`1 fix, 2 fix implement guard-git, 3 fix with guard-git, 4 fix plan, 5 discuss, 6 later, 7 ignore: <reason>\\`, where \\`fix\\` alone takes the recommended route and \\`later\\` records \\`deferred\\`. A finding to route takes \\`ok\\` for its recommended route, or another route.`,\n after: `A round ends once nothing is left to decide or route. The result then lists the sent findings not delivered yet, under \\`send to <target>:\\`. With deferred findings left, it reads \\`<name>: N deferred, stays open\\`; otherwise the review is closed and \\`triaged\\` logged. Then:\n\n- **Sent findings:** \\`agent_step answered\\` on the target with \\`next: running\\`, then \\`SendMessage\\` them to its fork: it fixes them and finishes again.\n- **In main:** fix them one at a time.\n- **New agents,** all at once after the last finding was routed: \\`agent_start\\` each with a one-line \\`mission\\` and \\`attachments: [{type: 'findings', review: <review name>, n: [..]}]\\`, which links the findings to it (an implement agent gets its worktree first), then in a later message launch it as a fork with \\`\\`You are agent \\`<name>\\`.\\`\\`, the mission, and \"Your contract and brief: \\`agent_brief\\` with your name.\": the fork's start hook also gives its contract, and the brief gives the review, its target and each finding with its location and proposed fix. Never paste the findings. Choosing Fix with an agent is the human's request to launch it.\n\nA new review of the same target can follow.`,\n },\n};\n","import { copyFileSync, existsSync } from 'node:fs';\nimport {\n type Agent,\n isAgentKind,\n KIND_ACTIONS,\n agentMode,\n type KindAction,\n mainTargetRange,\n type PromoteAgentInput,\n statusAfterAnswers,\n statusWhenDone,\n} from './agents.ts';\nimport type { Carnet } from './carnet.ts';\nimport { planAsAnswered } from './brief.ts';\nimport { CarnetError } from './errors.ts';\nimport { KIND_CONTRACTS } from './prompt/kind-contracts.ts';\nimport { NEXT_STEPS } from './prompt/next-actions.ts';\nimport { sandboxRemovedSuffix } from './sandbox.ts';\nimport {\n type DecisionInput,\n type FindingInput,\n type Finding,\n formatFinding,\n isOpen,\n recommendedRoute,\n renderFindings,\n} from './findings.ts';\nimport {\n type AnswerInput,\n type Question,\n type QuestionInput,\n renderQuestions,\n} from './questions.ts';\nimport {\n appendToReport,\n extractSection,\n hasSection,\n keptReportPath,\n readReport,\n} from './report.ts';\nimport { type Session, shortId } from './sessions.ts';\nimport { EMOJI, kindTag } from './status/model.ts';\n\nconst article = (kind: string) => (/^[aeiou]/.test(kind) ? `an ${kind}` : `a ${kind}`);\n\n// Reaches a fork through its start hook, so the main never pastes contracts into launch prompts.\nexport function forkStartContext(agent: Pick<Agent, 'name' | 'kind'>): string | undefined {\n const contract = KIND_CONTRACTS[agent.kind];\n if (!contract) return undefined;\n return `You are agent \\`${agent.name}\\`, ${article(agent.kind)} agent. Your contract:\\n\\n${contract}\\n\\n\\`agent_brief\\` with your name gives it again, with what the main attached.`;\n}\n\n// Given instead of a contract when the pairing is only a guess between sibling launches.\nexport const AGENT_BRIEF_HINT =\n 'Your contract: call `agent_brief` with the agent name your prompt gives you.';\n\nexport function kindAction(agent: Pick<Agent, 'kind'>): KindAction {\n return KIND_ACTIONS[agent.kind];\n}\n\nexport interface FinishWithItemsInput {\n reportPath: string;\n hasQuestions?: boolean | undefined;\n questions?: readonly QuestionInput[] | undefined;\n findings?: readonly FindingInput[] | undefined;\n}\n\n// Structured questions and findings are the only copy the fork writes; the report gets them from here.\nexport function finishWithItems(\n carnet: Carnet,\n session: string,\n name: string,\n input: FinishWithItemsInput,\n): Agent {\n const agent = requireAgent(carnet, session, name);\n if (input.findings?.length && agent.kind !== 'review') {\n throw new CarnetError(\n 'INVALID_KIND',\n `Only a review agent reports findings; ${name} is ${agent.kind}`,\n );\n }\n const report = readReport(input.reportPath);\n if (input.questions?.length) {\n const open = carnet.questions\n .add(session, name, input.questions)\n .filter((question) => question.answer === null);\n if (report !== undefined && !hasSection(report, ['questions'])) {\n appendToReport(input.reportPath, renderQuestions(open));\n }\n }\n if (input.findings?.length) {\n const findings = carnet.findings.replace(session, name, input.findings);\n if (report !== undefined && !hasSection(report, ['findings'])) {\n appendToReport(input.reportPath, renderFindings(findings));\n }\n }\n const openQuestions = carnet.questions.list(session, name, true).length;\n return carnet.agents.finish(session, name, {\n reportPath: input.reportPath,\n hasQuestions: openQuestions > 0 || input.hasQuestions === true,\n });\n}\n\nfunction requireAgent(carnet: Carnet, session: string, name: string): Agent {\n const agent = carnet.agents.get(session, name);\n if (!agent) throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n return agent;\n}\n\n// The human reads a report from another terminal, so the asking session isn't always the most\n// recently active one: every open session is searched, and an open agent wins over a closed homonym.\nexport function locateAgent(carnet: Carnet, name: string): { session: Session; agent: Agent } {\n const found = carnet.sessions.list({ includeTemp: true }).flatMap((session) => {\n const agent = carnet.agents.get(session.id, name);\n return agent ? [{ session, agent }] : [];\n });\n const open = found.filter((entry) => entry.agent.status !== 'closed');\n const only = found.length === 1 ? found[0] : open.length === 1 ? open[0] : undefined;\n if (only) return only;\n if (found.length === 0) {\n throw new CarnetError(\n 'AGENT_NOT_FOUND',\n `No agent \"${name}\" in the open sessions of this workspace`,\n );\n }\n const labels = found.map((entry) => entry.session.name ?? shortId(entry.session.id));\n throw new CarnetError(\n 'AGENT_AMBIGUOUS',\n `\"${name}\" is in several sessions: ${labels.join(', ')}; pass --session`,\n );\n}\n\n// The named agent (or the only one starting with it), else the first of Waiting on you, so the\n// model never sorts the queue itself.\nexport function nextAgent(carnet: Carnet, session: string, prefix?: string): string | undefined {\n if (!prefix) {\n return carnet.status.view(carnet.sessions.require(session)).waiting[0]?.name;\n }\n if (carnet.agents.get(session, prefix)) return prefix;\n const matches = carnet.agents\n .list(session, { includeClosed: true })\n .filter((agent) => agent.name.startsWith(prefix))\n .map((agent) => agent.name);\n const names = [...new Set(matches)];\n if (names.length === 1) return names[0];\n if (names.length === 0) {\n throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${prefix}\" in this session`);\n }\n throw new CarnetError('AGENT_AMBIGUOUS', `\"${prefix}\" matches ${names.join(', ')}: which one?`);\n}\n\nfunction formatQuestion(question: Question): string {\n const lines = [`${question.n}/${question.total} ${question.text}`];\n if (question.context) lines.push(` context: ${question.context}`);\n lines.push(` recommended: ${question.recommendation}`);\n if (question.alternatives.length) {\n lines.push(` alternatives: ${question.alternatives.join(' | ')}`);\n }\n return lines.join('\\n');\n}\n\nexport function openQuestionsText(carnet: Carnet, session: string, name: string): string {\n requireAgent(carnet, session, name);\n const open = carnet.questions.list(session, name, true);\n if (!open.length) return `${name}: no open questions`;\n const total = open[0]?.total ?? open.length;\n return [`${name}: ${open.length} of ${total} open`, ...open.map(formatQuestion)].join('\\n');\n}\n\nfunction today(carnet: Carnet): string {\n return carnet.now().toISOString().slice(0, 10);\n}\n\nexport function answerQuestionsText(\n carnet: Carnet,\n session: string,\n name: string,\n answers: readonly AnswerInput[],\n): string {\n const agent = requireAgent(carnet, session, name);\n const questions = carnet.questions.answer(session, name, answers);\n const lines = [...answers]\n .sort((a, b) => a.n - b.n)\n .map((answer) => `${answer.n}. ${answer.answer.trim()}`);\n appendToReport(agent.reportPath, `## Answers (${today(carnet)})\\n\\n${lines.join('\\n')}`);\n const open = questions.filter((question) => question.answer === null).length;\n if (open) return `answered ${answers.length} · ${open} of ${questions.length} open`;\n const next = statusAfterAnswers(agent.kind);\n carnet.events.log(session, { type: 'answered', agent: name });\n carnet.agents.update(session, name, { status: next, note: null });\n return `all ${questions.length} answered · ${EMOJI[next]} ${name} ${next}`;\n}\n\nconst FOR_MAIN = ['for the main', 'pour le main'];\nconst PLAN = ['plan'];\n\nexport interface InjectInput {\n full?: boolean | undefined;\n section?: string | undefined;\n echo?: boolean | undefined;\n // False when the caller named a session to read: return the section and leave the agent open.\n close?: boolean | undefined;\n}\n\nexport function injectReport(\n carnet: Carnet,\n session: string,\n name: string,\n input: InjectInput,\n): string {\n const agent = requireAgent(carnet, session, name);\n const report = readReport(agent.reportPath);\n if (report === undefined) {\n throw new CarnetError('REPORT_MISSING', `${name} has no report to inject yet`);\n }\n const names = input.section\n ? [input.section]\n : agent.kind === 'plan' || agent.promotedFrom === 'plan'\n ? PLAN\n : FOR_MAIN;\n const planOutline = !input.full && !input.section && names === PLAN;\n const section = input.full ? report.trim() : extractSection(report, names);\n const text = planOutline && section !== undefined ? outline(section) : section;\n if (text === undefined) {\n throw new CarnetError(\n 'SECTION_NOT_FOUND',\n `No \"## ${names[0]}\" section in ${name}'s report; pass section or full`,\n );\n }\n const lineCount = text.split('\\n').length;\n const note = `${input.full ? 'full report' : planOutline ? 'plan outline' : names[0]}, ${lineCount} lines`;\n let removed = false;\n if (input.close !== false && agent.kind === 'research' && agent.status !== 'closed') {\n removed = carnet.agents.close(session, name, {\n type: 'injected',\n note,\n link: agent.reportPath ?? undefined,\n }).sandboxRemoved;\n } else {\n carnet.events.log(session, { type: 'injected', agent: name, note });\n }\n const confirmation = `${name} injected (${lineCount} lines)${sandboxRemovedSuffix(removed)}`;\n return input.echo === false ? confirmation : `${confirmation}\\n${text}`;\n}\n\nconst FILE_PATH = /`((?:[\\w.@-]+\\/)*[\\w.@-]+\\.(?:ts|tsx|js|mjs|json|md|yml|yaml|sh|sql))`/g;\n\n// The main validates and applies from steps and files; the full plan stays with the agent that\n// wrote it, or reaches a cold implementer through its brief.\nfunction outline(plan: string): string {\n const steps = planSteps(plan);\n const files = [...new Set([...plan.matchAll(FILE_PATH)].map((match) => match[1]))];\n const lines = steps.length > 0 ? steps : firstLines(plan, 15);\n if (files.length > 0) lines.push(`Files: ${files.join(', ')}`);\n return lines.join('\\n');\n}\n\nfunction firstLines(text: string | undefined, max: number): string[] {\n if (!text) return [];\n const lines = text.split('\\n').filter((line) => line.trim() !== '');\n return lines.length > max ? [...lines.slice(0, max), '…'] : lines;\n}\n\nfunction firstParagraph(text: string | undefined, max: number): string[] {\n return firstLines(text?.split(/\\n\\s*\\n/)[0], max);\n}\n\nconst TOP_LEVEL_ITEM = /^(-|\\*|\\d+\\.)\\s|^\\*\\*/;\n\nfunction topLevelItems(text: string | undefined, max: number): string[] {\n return firstLines(\n text\n ?.split('\\n')\n .filter((line) => TOP_LEVEL_ITEM.test(line))\n .join('\\n'),\n max,\n );\n}\n\nfunction planSteps(plan: string | undefined): string[] {\n if (!plan) return [];\n const headings = plan.split('\\n').filter((line) => /^###\\s/.test(line));\n const steps =\n headings.length > 0 ? headings : plan.split('\\n').filter((line) => /^\\d+\\.\\s/.test(line));\n return steps.map((line) => line.replace(/^###\\s+/, '').trim());\n}\n\nfunction block(title: string, lines: string[]): string[] {\n return lines.length > 0 ? [`${title}:`, ...lines] : [];\n}\n\n// A preview before the kind's action, built from the sections each contract requires, so the\n// main agent never reads a whole report into its context.\nexport function reportSummary(carnet: Carnet, session: string, name: string): string {\n const agent = requireAgent(carnet, session, name);\n const report = readReport(agent.reportPath);\n if (report === undefined) {\n throw new CarnetError('REPORT_MISSING', `${name} has no report yet`);\n }\n const section = (...names: string[]) => extractSection(report, names);\n const emoji = agent.status === 'closed' ? '' : `${EMOJI[agent.status]} `;\n const lines = [`${name} ${kindTag(agent.kind)} ${emoji}→ ${kindAction(agent)}`];\n if (agent.kind === 'research') {\n lines.push(\n ...block('For the main', firstLines(section(...FOR_MAIN), 15)),\n ...block('Gaps', firstLines(section('gaps'), 3)),\n );\n } else if (agent.kind === 'plan') {\n const plan = section(...PLAN);\n const steps = planSteps(plan);\n const open = carnet.questions.list(session, name, true).length;\n // Without steps the plan agent answered a question in Understanding, so show the answer whole.\n const understanding = section('understanding');\n lines.push(\n ...block(\n 'Understanding',\n steps.length > 0 ? firstParagraph(understanding, 5) : firstLines(understanding, 15),\n ),\n ...(steps.length > 0\n ? block(`Plan, ${steps.length} steps`, steps)\n : [`Plan: ${firstLines(plan, 1)[0] ?? 'none'}`]),\n `Questions: ${open} open`,\n );\n } else if (agent.kind === 'implement') {\n lines.push(\n ...block('Done', topLevelItems(section('done'), 8)),\n ...block('Deviations', firstLines(section('deviations'), 6)),\n ...block('Risks', firstLines(section('risks'), 6)),\n ...block('Commit message', firstLines(section('commit message')?.replace(/```\\w*/g, ''), 1)),\n );\n } else {\n const pending = carnet.findings.list(session, name, 'open');\n const bySeverity = ['blocking', 'to_fix', 'suggestion']\n .map((severity) => [severity, pending.filter((f) => f.severity === severity).length] as const)\n .filter(([, count]) => count > 0)\n .map(([severity, count]) => `${count} ${severity.replace('_', ' ')}`);\n const toRoute = pending.filter((finding) => finding.decision === 'fix').length;\n const deferred = pending.filter((finding) => finding.decision === 'deferred').length;\n const routing = `${toRoute > 0 ? ` · ${toRoute} to route` : ''}${deferred > 0 ? ` · ${deferred} deferred` : ''}`;\n lines.push(\n ...block('Verdict', firstLines(section('verdict'), 1)),\n `Findings: ${bySeverity.length > 0 ? bySeverity.join(', ') + routing : 'none pending'}`,\n ...block('Not verified', firstLines(section('not verified'), 3)),\n );\n }\n const contractSections = [...FOR_MAIN, ...PLAN, 'understanding', 'done', 'verdict'];\n if (!hasSection(report, contractSections)) {\n lines.push(...block('Report', firstLines(report.replace(/^#[^\\n]*\\n/, ''), 10)));\n }\n lines.push(`report: ${agent.reportPath}`);\n const steps = nextSteps(carnet, session, agent);\n if (steps) lines.push('', 'Next:', steps);\n return lines.join('\\n');\n}\n\n// Only the part of the kind's next action that fits the agent's state, so the main never loads\n// every kind's procedure to handle one agent.\nfunction nextStates(carnet: Carnet, session: string, agent: Agent): string[] {\n if (agent.kind === 'research') return ['inject'];\n if (agent.kind === 'plan') {\n const open = carnet.questions.list(session, agent.name, true).length;\n return open > 0 ? ['questions', 'validate'] : ['validate'];\n }\n if (agent.kind === 'implement') return agent.status === 'test' ? ['commit'] : ['apply'];\n const toDecide = carnet.findings\n .list(session, agent.name, 'open')\n .filter((finding) => finding.decision !== 'fix').length;\n return toDecide > 0 ? ['triage', 'decide', 'route', 'after'] : ['triage', 'route', 'after'];\n}\n\nfunction nextSteps(carnet: Carnet, session: string, agent: Agent): string | undefined {\n if (agent.status === 'closed' || agent.status === 'running') return undefined;\n const parts = NEXT_STEPS[agent.kind];\n if (!parts) return undefined;\n const text = nextStates(carnet, session, agent)\n .map((state) => parts[state])\n .filter(Boolean)\n .join('\\n\\n');\n return text || undefined;\n}\n\nexport interface ReportDocument {\n text: string;\n path: string;\n}\n\n// What the human reads in full before validating: the plan as written, each question beside its answer.\nexport function reportDocument(carnet: Carnet, session: string, name: string): ReportDocument {\n const agent = requireAgent(carnet, session, name);\n const report = readReport(agent.reportPath);\n if (report === undefined || !agent.reportPath) {\n throw new CarnetError('REPORT_MISSING', `${name} has no report yet`);\n }\n const plan =\n agent.kind === 'plan'\n ? planAsAnswered(\n `${name} ${kindTag(agent.kind)}`,\n report,\n carnet.questions.list(session, name),\n )\n : undefined;\n return { text: plan ?? report.trimEnd(), path: agent.reportPath };\n}\n\nexport function promoteText(\n carnet: Carnet,\n session: string,\n name: string,\n input: PromoteAgentInput,\n): string {\n const current = requireAgent(carnet, session, name);\n const cold = promotionIsCold(current, input);\n if (cold && !input.mission?.trim() && !current.mission) {\n throw new CarnetError(\n 'MISSION_REQUIRED',\n `${name} continues cold and will not see the conversation: pass a mission`,\n );\n }\n const agent = carnet.agents.promote(session, name, { ...input, cold });\n const lines = [`${EMOJI.running} ${name} promoted to ${agent.kind}`];\n const from = current.kind;\n if ((from === 'research' || from === 'plan') && current.reportPath) {\n if (existsSync(current.reportPath)) {\n const kept = keptReportPath(current.reportPath, from);\n copyFileSync(current.reportPath, kept);\n lines.push(`${from === 'plan' ? 'plan' : 'research'} kept: ${kept}`);\n if (cold) {\n carnet.agents.attach(\n agent.id,\n carnet.agents.resolveAttachments(session, [{ type: 'doc', path: kept }]),\n );\n }\n }\n }\n if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);\n if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);\n if (agent.sandbox) lines.push(`sandbox kept: ${agent.sandbox}`);\n if (agent.sandboxRemoved) lines.push('sandbox removed');\n lines.push(\n cold\n ? `cold: launch the rucher ${agent.kind} agent; it reads its mission and the kept report with agent_brief`\n : `message: You are now ${article(agent.kind)} agent: read your contract with agent_brief.`,\n );\n return lines.join('\\n');\n}\n\n// A cold agent has no conversation to resume as a fork.\nfunction promotionIsCold(current: Agent, input: PromoteAgentInput): boolean {\n if (current.context === 'cold') {\n if (input.fork) {\n throw new CarnetError(\n 'INVALID_KIND',\n `${current.name} ran cold: it has no conversation to continue as a fork`,\n );\n }\n return true;\n }\n if (!isAgentKind(input.kind)) return false;\n return agentMode(input.kind, { cold: input.cold, fork: input.fork }) === 'cold';\n}\n\nexport function findingsText(\n carnet: Carnet,\n session: string,\n name: string,\n openOnly: boolean,\n): string {\n const agent = requireAgent(carnet, session, name);\n const all = carnet.findings.list(session, name);\n const open = carnet.findings.list(session, name, 'open');\n if (!(openOnly ? open : all).length) {\n return `${name}: ${all.length ? 'no pending findings' : 'no findings'}`;\n }\n const toDecide = open.filter((finding) => finding.decision !== 'fix');\n const toRoute = open.filter((finding) => finding.decision === 'fix');\n const deferred = toDecide.filter((finding) => finding.decision === 'deferred').length;\n const target = agent.target ? ` · target ${agent.target}` : '';\n const later = deferred > 0 ? ` (${deferred} deferred)` : '';\n const header = `${name}: ${toDecide.length} to decide${later}, ${toRoute.length} to route of ${all.length}${target}`;\n const sendable = canSendBack(carnet, session, agent.target);\n const line = (finding: Finding) => {\n const after = isOpen(finding)\n ? `${finding.decision === 'deferred' ? ' · deferred' : ''} · route: ${recommendedRoute(finding.severity, sendable, finding.route)}`\n : ` → ${decisionLabel(finding)}`;\n return `${formatFinding(finding)}${after}`;\n };\n const group = (title: string, items: Finding[]) =>\n items.length ? [`${title}:`, ...items.map(line)] : [];\n const lines = [\n header,\n ...group('To decide', toDecide),\n ...group('To route', toRoute),\n ...(openOnly\n ? []\n : group(\n 'Decided',\n all.filter((finding) => !isOpen(finding)),\n )),\n ];\n if (toDecide.length + toRoute.length > 0) {\n lines.push(`next: ${toDecide.length > 0 ? 'decide' : 'route'}`);\n }\n return lines.join('\\n');\n}\n\nfunction decisionLabel(finding: Finding): string {\n const spawn =\n finding.decision === 'spawned' && finding.spawnName\n ? ` ${[finding.spawnKind, 'agent', finding.spawnName].filter(Boolean).join(' ')}`\n : '';\n const reason = finding.reason ? ` (${finding.reason})` : '';\n return `${finding.decision}${spawn}${reason}`;\n}\n\nfunction canSendBack(carnet: Carnet, session: string, target: string | null): boolean {\n if (!target || mainTargetRange(target) !== undefined) return false;\n const source = carnet.agents.get(session, target);\n return !!source && source.status !== 'test' && source.status !== 'closed';\n}\n\nexport function decideText(\n carnet: Carnet,\n session: string,\n name: string,\n decisions: readonly DecisionInput[],\n override = false,\n): string {\n const agent = requireAgent(carnet, session, name);\n if (agent.kind !== 'review') {\n throw new CarnetError('INVALID_KIND', `${name} is ${agent.kind}, not review`);\n }\n if (\n decisions.some((item) => item.decision === 'sent') &&\n agent.target &&\n mainTargetRange(agent.target) !== undefined\n ) {\n throw new CarnetError(\n 'INVALID_TARGET',\n `${name} reviews main: there is no agent to send findings to; fix or ignore them`,\n );\n }\n const findings = carnet.findings.decide(session, name, decisions, override);\n if (agent.status === 'closed' && findings.some((finding) => isOpen(finding))) {\n carnet.agents.moveStatus(agent.id, statusWhenDone(agent.kind, false), null);\n carnet.events.log(session, { type: 'reopened', agent: name, agentId: agent.id });\n }\n const toDecide = findings.filter((finding) => finding.decision === null).length;\n const toRoute = findings.filter((finding) => finding.decision === 'fix').length;\n if (toDecide + toRoute > 0) {\n return `decided ${decisions.length} · ${toDecide} to decide, ${toRoute} to route of ${findings.length}`;\n }\n // The end of a round: what was sent goes to the target now, even while deferred findings keep\n // the review open.\n const sent = carnet.findings.deliverSent(session, name);\n const deferred = findings.filter((finding) => finding.decision === 'deferred').length;\n const lines: string[] = [];\n if (deferred > 0) {\n lines.push(`${name}: ${deferred} deferred, stays open`);\n } else if (agent.status === 'closed') {\n lines.push(`${name}: corrected, already closed`);\n } else {\n const count = (decision: string) =>\n findings.filter((finding) => finding.decision === decision).length;\n const spawned = count('spawned');\n const note = `${count('sent')} sent, ${count('fixed')} fixed, ${spawned > 0 ? `${spawned} spawned, ` : ''}${count('ignored')} ignored`;\n carnet.agents.close(session, name, {\n type: 'triaged',\n note,\n link: agent.reportPath ?? undefined,\n });\n lines.push(`${name} triaged: ${note}, closed`);\n }\n if (sent.length && agent.target) {\n lines.push(`send to ${agent.target}:`, ...sent.map(formatFinding));\n }\n return lines.join('\\n');\n}\n","import type { Carnet } from './carnet.ts';\nimport type { CarnetEvent } from './events.ts';\nimport type { Session } from './sessions.ts';\nimport { formatClock } from './status/view.ts';\n\nexport const RESUME_EVENTS = 20;\nexport const RESUME_MAX_CHARACTERS = 2000;\n\nexport interface ResumeContextOptions {\n events?: number;\n maxCharacters?: number;\n}\n\nexport function formatEventLine(event: CarnetEvent): string {\n return [\n formatClock(new Date(event.at)),\n event.type,\n event.agent,\n event.link ?? event.note,\n event.commit?.slice(0, 7),\n ]\n .filter(Boolean)\n .join(' ');\n}\n\nexport function sessionLabel(session: Session): string {\n const name = session.name ?? session.id;\n return session.purpose ? `${name} (${session.purpose})` : name;\n}\n\nexport function resumeContext(\n carnet: Carnet,\n session: Session,\n { events = RESUME_EVENTS, maxCharacters = RESUME_MAX_CHARACTERS }: ResumeContextOptions = {},\n): string {\n const head = `Rucher session ${sessionLabel(session)}, state when resumed:\\n\\n${carnet.status.render(session, { notes: 'summary' })}`;\n const lines = carnet.events.read(session.id, events, true).map(formatEventLine);\n const build = () =>\n lines.length ? `${head}\\n\\nLast events\\n${lines.map((line) => ` ${line}`).join('\\n')}` : head;\n let text = build();\n // Drop the oldest events first: the latest steps matter most when picking up work.\n while (text.length > maxCharacters && lines.length > 0) {\n lines.shift();\n text = build();\n }\n return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;\n}\n\nfunction count(lines: readonly unknown[], label: string): string | undefined {\n return lines.length ? `${lines.length} ${label}` : undefined;\n}\n\n// A resumed conversation already holds its history: one line says what changed hands, and\n// session_resume_info gives the full view when the main agent needs it.\nexport function resumeSummary(carnet: Carnet, session: Session): string {\n const view = carnet.status.view(session);\n const [next] = view.waiting;\n const waiting = next\n ? `${view.waiting.length} waiting on you, first ${next.name} (${[next.kind, next.action].filter(Boolean).join(' ')})`\n : undefined;\n const [last] = carnet.events.read(session.id, 1, true);\n const parts = [\n view.table ? `Main: ${view.table.text}` : undefined,\n waiting,\n count(view.running, 'running'),\n count(view.blocked, 'blocked'),\n last ? `last event ${formatEventLine(last)}` : undefined,\n ].filter(Boolean);\n const state = parts.length ? parts.join('; ') : 'no open agent';\n return `Rucher session ${sessionLabel(session)} resumed: ${state}. Full state: session_resume_info.`;\n}\n","import { statusAfterAnswers } from './agents.ts';\nimport type { Carnet } from './carnet.ts';\nimport { CarnetError } from './errors.ts';\nimport { sandboxRemovedSuffix } from './sandbox.ts';\nimport { EMOJI, OPEN_AGENT_STATUSES } from './status/model.ts';\nimport { tableIsAbout } from './table.ts';\n\ntype OpenAgentStatus = (typeof OPEN_AGENT_STATUSES)[number];\n\nexport const AGENT_STEPS = [\n 'answered',\n 'applying',\n 'applied',\n 'tested',\n 'committed',\n 'dropped',\n] as const;\nexport type AgentStep = (typeof AGENT_STEPS)[number];\n\nexport interface StepAgentInput {\n name: string;\n step: AgentStep;\n commit?: string | undefined;\n note?: string | undefined;\n next?: OpenAgentStatus | undefined;\n}\n\nconst DEFAULT_NEXT: Partial<Record<AgentStep, OpenAgentStatus>> = {\n applied: 'test',\n tested: 'test',\n};\n\nfunction clearTableOf(carnet: Carnet, session: string, name: string): void {\n if (tableIsAbout(carnet.table.get(session), name)) carnet.table.clear(session);\n}\n\nexport function stepAgent(carnet: Carnet, session: string, input: StepAgentInput): string {\n const { name, step, commit, note } = input;\n const agent = carnet.agents.get(session, name);\n if (!agent) {\n throw new CarnetError('AGENT_NOT_FOUND', `No agent \"${name}\" in this session`);\n }\n switch (step) {\n case 'applying': {\n if (agent.kind !== 'implement') {\n throw new CarnetError(\n 'INVALID_KIND',\n `${name} is ${agent.kind}: only an implement agent is applied`,\n );\n }\n carnet.table.set(session, { text: `${name} applying` });\n carnet.agents.update(session, name, {\n status: agent.status,\n note: note ?? null,\n blockedOn: null,\n });\n const reviews = carnet.agents\n .list(session)\n .filter((other) => other.kind === 'review' && other.target === name);\n const warning = reviews.length\n ? `\\nwarning: review ${reviews.map((review) => review.name).join(', ')} not triaged yet`\n : '';\n return `⚙️ ${name} applying${warning}`;\n }\n case 'committed': {\n if (!commit) throw new CarnetError('COMMIT_REQUIRED', 'The committed step needs the commit');\n carnet.events.log(session, { type: 'committed', agent: name, commit, note });\n const closed = carnet.agents.drop(session, name, `committed ${commit}`);\n clearTableOf(carnet, session, name);\n return `✅ ${name} committed ${commit}, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;\n }\n case 'dropped': {\n const closed = carnet.agents.drop(session, name, note);\n clearTableOf(carnet, session, name);\n return `${name} dropped, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;\n }\n default: {\n const next =\n input.next ??\n (step === 'answered'\n ? statusAfterAnswers(agent.kind)\n : (DEFAULT_NEXT[step] as OpenAgentStatus));\n carnet.events.log(session, { type: step, agent: name, note });\n // A step means the human is handling the agent, so it no longer waits on another one.\n carnet.agents.update(session, name, { status: next, note: note ?? null, blockedOn: null });\n // Once applied, the agent waits on the human under test, so the Main line lets it show there.\n if (next === 'running' || step !== 'answered') clearTableOf(carnet, session, name);\n return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;\n }\n }\n}\n","import { CarnetError } from '../errors.ts';\nimport { GESTURES, parseConfig, type ConfigFile, type Source } from './schema.ts';\n\nexport const DEFAULT_PROFILE = 'off';\n\n// research keeps the cheaper model its cold agent always had.\nexport const RUCHER_DEFAULTS: ConfigFile = {\n run: { default: { backend: 'claude' }, kinds: { research: 'claude/sonnet' } },\n autonomy: { profile: DEFAULT_PROFILE, shadow: false },\n decide: { model: 'none', fallback: 'none' },\n context: { coldAbove: 80_000 },\n};\n\ntype GestureValue = 'auto' | 'human';\ntype Mode = 'off' | 'shadow' | 'on';\n\nfunction profile(options: {\n permissionMode: Mode;\n otherModes: Mode;\n supervisorGestures: GestureValue;\n bot: boolean;\n}): ConfigFile {\n const delegated = ['permission', 'read', 'question', 'launch', 'plan', 'triage', 'apply'];\n const gestures = Object.fromEntries(\n GESTURES.map((name) => [\n name,\n delegated.includes(name) ? options.supervisorGestures : options.bot ? 'auto' : 'human',\n ]),\n );\n const mode = (value: Mode) => ({ mode: value });\n return {\n autonomy: { gestures },\n decide: {\n decisions: {\n permission: mode(options.permissionMode),\n launch: mode(options.otherModes),\n routing: mode(options.otherModes),\n findings: mode(options.otherModes),\n notify: mode(options.otherModes),\n },\n },\n apply: { target: options.bot ? 'branch' : 'main' },\n waves: { launch: options.supervisorGestures === 'auto' ? 'auto' : 'confirm' },\n };\n}\n\n// Every built-in profile fixes the same keys, so choosing one overwrites all of them.\nexport const BUILT_IN_PROFILES: Record<string, ConfigFile> = {\n off: profile({\n permissionMode: 'off',\n otherModes: 'off',\n supervisorGestures: 'human',\n bot: false,\n }),\n assist: profile({\n permissionMode: 'shadow',\n otherModes: 'on',\n supervisorGestures: 'human',\n bot: false,\n }),\n auto: profile({ permissionMode: 'on', otherModes: 'on', supervisorGestures: 'auto', bot: false }),\n bot: profile({ permissionMode: 'on', otherModes: 'on', supervisorGestures: 'auto', bot: true }),\n};\n\nexport const BUILT_IN_PROFILE_NAMES = Object.keys(BUILT_IN_PROFILES);\n\nexport const BUILT_IN_PROFILE_NOTES: Record<string, string> = {\n off: 'Every gesture is yours and the decider is off.',\n assist: 'The decider shadows permissions and runs elsewhere; every gesture stays yours.',\n auto: 'The supervisor takes every gesture up to apply; commit, push and PR stay yours.',\n bot: 'Everything is automatic on a task branch: commits and pushes there, a PR at the end.',\n};\n\nexport function builtInProfileSource(name: string): Source {\n const file = BUILT_IN_PROFILES[name];\n if (!file) {\n throw new CarnetError(\n 'CONFIG_INVALID',\n `No profile named ${name}: use ${BUILT_IN_PROFILE_NAMES.join(', ')}`,\n );\n }\n return parseConfig(file, `profile ${name}`);\n}\n","import { parse } from 'yaml';\n\nexport interface Frontmatter {\n meta: Record<string, unknown>;\n body: string;\n}\n\nconst BLOCK = /^---\\r?\\n(?:([\\s\\S]*?)\\r?\\n)?---[ \\t]*(?:\\r?\\n|$)/;\n\n/** Throws with a message ready to be prefixed with the file path. */\nexport function parseFrontmatter(text: string): Frontmatter {\n const match = BLOCK.exec(text);\n if (!match) throw new Error('no frontmatter: the file must start with a --- block');\n let meta: unknown;\n try {\n meta = parse(match[1] ?? '');\n } catch (error) {\n throw new Error(\n `invalid frontmatter: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (meta === null || meta === undefined) meta = {};\n if (typeof meta !== 'object' || Array.isArray(meta)) {\n throw new Error('invalid frontmatter: expected keys, not a single value or a list');\n }\n return { meta: meta as Record<string, unknown>, body: text.slice(match[0].length) };\n}\n","import { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { basename, join } from 'node:path';\nimport { parseFrontmatter } from './frontmatter.ts';\n\nexport const LAYERS = ['built-in', 'user', 'workspace'] as const;\nexport type Layer = (typeof LAYERS)[number];\n\nexport interface Definition<T> {\n name: string;\n layer: Layer;\n path?: string | undefined;\n extends?: string | undefined;\n /** Own values, before extends; undefined when the file is invalid. */\n value?: T | undefined;\n body: string;\n error?: string | undefined;\n}\n\nexport interface Resolved<T> {\n name: string;\n layer: Layer;\n path?: string | undefined;\n body: string;\n value: T;\n /** The definition first, then each base it extends. */\n chain: Definition<T>[];\n}\n\nexport interface LayerProblem {\n name?: string | undefined;\n layer: Layer;\n path?: string | undefined;\n message: string;\n}\n\nexport interface Layered<T> {\n /** The definition each name resolves to: the one of the highest layer. */\n top: Map<string, Definition<T>>;\n resolved: Map<string, Resolved<T>>;\n problems: LayerProblem[];\n}\n\nexport interface LayeredOptions<T> {\n builtIns: { name: string; extends?: string; value: T; body?: string }[];\n directories: { layer: Exclude<Layer, 'built-in'>; path: string }[];\n /** Frontmatter minus name and extends; throws with a message on invalid values. */\n parse: (meta: Record<string, unknown>, path: string) => T;\n merge: (base: T, child: T) => T;\n /** Problems of a resolved definition, which then stops resolving. */\n check?: (value: T, name: string) => string[];\n}\n\nconst NAME = /^[a-z0-9][a-z0-9-]*$/;\n\nfunction fileDefinition<T>(\n layer: Layer,\n path: string,\n parse: LayeredOptions<T>['parse'],\n): Definition<T> {\n const fallbackName = basename(path, '.md');\n // A parse error after the name is read still replaces that name, not the file name.\n let declaredName: string | undefined;\n try {\n const { meta, body } = parseFrontmatter(readFileSync(path, 'utf8'));\n const { name = fallbackName, extends: base, ...rest } = meta;\n if (typeof name !== 'string' || !NAME.test(name)) {\n throw new Error(`name ${JSON.stringify(name)}: lowercase letters, digits and dashes`);\n }\n declaredName = name;\n if (base !== undefined && (typeof base !== 'string' || !base)) {\n throw new Error('extends: the name of another definition');\n }\n return { name, layer, path, extends: base, value: parse(rest, path), body: body.trim() };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { name: declaredName ?? fallbackName, layer, path, body: '', error: message };\n }\n}\n\nfunction readLayer<T>(\n layer: Layer,\n directory: string,\n parse: LayeredOptions<T>['parse'],\n problems: LayerProblem[],\n): Map<string, Definition<T>> {\n const definitions = new Map<string, Definition<T>>();\n if (!existsSync(directory)) return definitions;\n const files = readdirSync(directory)\n .filter((file) => file.endsWith('.md'))\n .sort();\n for (const file of files) {\n const definition = fileDefinition(layer, join(directory, file), parse);\n const twin = definitions.get(definition.name);\n if (twin) {\n problems.push({\n name: definition.name,\n layer,\n path: definition.path,\n message: `${definition.name} is already defined by ${twin.path}`,\n });\n continue;\n }\n definitions.set(definition.name, definition);\n }\n return definitions;\n}\n\n/** Built-in, user then workspace definitions; a same name replaces the one below it. */\nexport function loadLayered<T>(options: LayeredOptions<T>): Layered<T> {\n const problems: LayerProblem[] = [];\n const builtIns = new Map<string, Definition<T>>(\n options.builtIns.map((definition) => [\n definition.name,\n { ...definition, layer: 'built-in', body: definition.body ?? '' },\n ]),\n );\n const layers = [\n builtIns,\n ...options.directories.map(({ layer, path }) =>\n readLayer(layer, path, options.parse, problems),\n ),\n ];\n\n const layerIndex = new Map<Definition<T>, number>(\n layers.flatMap((layer, index) => [...layer.values()].map((definition) => [definition, index])),\n );\n\n // A base is looked up in the definition's own layer, then below; a definition never extends itself.\n const baseOf = (definition: Definition<T>, index: number): Definition<T> | undefined => {\n for (let layer = index; layer >= 0; layer--) {\n const found = layers[layer]!.get(definition.extends!);\n if (found && found !== definition) return found;\n }\n return undefined;\n };\n\n const done = new Map<Definition<T>, Resolved<T> | string>();\n const resolve = (\n definition: Definition<T>,\n index: number,\n visiting: Set<Definition<T>>,\n ): Resolved<T> | string => {\n const known = done.get(definition);\n if (known !== undefined) return known;\n const outcome = (() => {\n if (definition.error !== undefined) return definition.error;\n if (visiting.has(definition)) return `extends cycle through ${definition.name}`;\n const own = { ...definition, value: definition.value as T };\n if (definition.extends === undefined) {\n return { ...own, chain: [definition] } satisfies Resolved<T>;\n }\n const base = baseOf(definition, index);\n if (!base) return `extends ${definition.extends}, which is not defined`;\n visiting.add(definition);\n const resolvedBase = resolve(base, layerIndex.get(base)!, visiting);\n visiting.delete(definition);\n if (typeof resolvedBase === 'string') {\n return resolvedBase.startsWith('extends cycle')\n ? resolvedBase\n : `extends ${definition.extends}, which is invalid`;\n }\n return {\n ...own,\n value: options.merge(resolvedBase.value, own.value),\n chain: [definition, ...resolvedBase.chain],\n } satisfies Resolved<T>;\n })();\n const checked =\n typeof outcome === 'string'\n ? outcome\n : (options.check?.(outcome.value, outcome.name) ?? []).join('; ') || outcome;\n // A cycle is only known once the walk comes back to its start, so it is not cached midway.\n if (!visiting.size) done.set(definition, checked);\n return checked;\n };\n\n const top = new Map<string, Definition<T>>();\n const resolved = new Map<string, Resolved<T>>();\n layers.forEach((layer, index) => {\n for (const definition of layer.values()) {\n const outcome = resolve(definition, index, new Set());\n top.set(definition.name, definition);\n if (typeof outcome === 'string') {\n resolved.delete(definition.name);\n problems.push({\n name: definition.name,\n layer: definition.layer,\n path: definition.path,\n message: outcome,\n });\n } else resolved.set(definition.name, outcome);\n }\n });\n return { top, resolved, problems };\n}\n","import { CarnetError } from '../errors.ts';\nimport { builtInProfileSource, RUCHER_DEFAULTS } from './defaults.ts';\nimport {\n type Backend,\n DECIDER_PROVIDERS,\n parseConfig,\n type RunPair,\n type Source,\n} from './schema.ts';\n\nexport const CONFIG_LEVELS = ['default', 'global', 'workspace', 'session'] as const;\nexport type ConfigLevel = (typeof CONFIG_LEVELS)[number];\n\nexport interface KeySource {\n level: ConfigLevel;\n /** `default`, `profile <name>` or `key` */\n origin: string;\n}\n\nexport interface ResolvedConfig {\n values: Map<string, unknown>;\n sources: Map<string, KeySource>;\n problems: string[];\n}\n\nexport type ProfileLookup = (name: string) => Source;\n\nexport interface ConfigLevels {\n global?: Source | undefined;\n workspace?: Source | undefined;\n session?: Source | undefined;\n /** Built-in profiles only when omitted. */\n profiles?: ProfileLookup | undefined;\n}\n\nconst DEFAULTS = parseConfig(RUCHER_DEFAULTS, 'Rucher defaults');\n\nfunction isPair(key: string): boolean {\n return key === 'run.default' || key.startsWith('run.kinds.');\n}\n\n/** The value a key takes when `value` is written over `below`. */\nexport function overlay(key: string, below: unknown, value: unknown): unknown {\n // A pair naming only a model keeps the backend below it, so a model never lands on another backend.\n return isPair(key) && below && (value as RunPair).backend === undefined\n ? { ...(below as RunPair), ...(value as RunPair) }\n : value;\n}\n\nfunction write(resolved: ResolvedConfig, source: Source, level: ConfigLevel, origin: string): void {\n for (const [key, value] of source) {\n resolved.values.set(key, overlay(key, resolved.values.get(key), value));\n resolved.sources.set(key, { level, origin });\n }\n}\n\nfunction writeLevel(\n resolved: ResolvedConfig,\n source: Source,\n level: ConfigLevel,\n profiles: ProfileLookup,\n): void {\n const profile = source.get('autonomy.profile');\n if (typeof profile === 'string') write(resolved, profiles(profile), level, `profile ${profile}`);\n write(resolved, source, level, level === 'default' ? 'default' : 'key');\n}\n\n/** Nothing commits or pushes the main branch: checked on resolved configs and on profiles. */\nexport function branchProblems(values: Map<string, unknown>): string[] {\n const onBranch = values.get('apply.target') === 'branch';\n return ['commit', 'push']\n .filter((gesture) => values.get(`autonomy.gestures.${gesture}`) === 'auto' && !onBranch)\n .map(\n (gesture) =>\n `autonomy.gestures.${gesture}: auto needs apply.target: branch, nothing commits or pushes the main branch`,\n );\n}\n\nfunction crossChecks(values: Map<string, unknown>): string[] {\n const problems = branchProblems(values);\n const decider = values.get('decide.model');\n if (typeof decider === 'string' && decider !== 'none') {\n const provider = decider.slice(0, decider.indexOf('/'));\n const known = (DECIDER_PROVIDERS as readonly string[]).includes(provider);\n if (!known && !values.has(`providers.${provider}.url`)) {\n problems.push(\n `decide.model: unknown provider ${provider}: declare it under providers with its url`,\n );\n }\n }\n return problems;\n}\n\n/** Levels stack from Rucher defaults to the session; per key the last write wins */\nexport function resolveConfig(levels: ConfigLevels = {}): ResolvedConfig {\n const resolved: ResolvedConfig = { values: new Map(), sources: new Map(), problems: [] };\n const profiles = levels.profiles ?? builtInProfileSource;\n writeLevel(resolved, DEFAULTS, 'default', profiles);\n for (const level of ['global', 'workspace', 'session'] as const) {\n const source = levels[level];\n if (source) writeLevel(resolved, source, level, profiles);\n }\n resolved.problems = crossChecks(resolved.values);\n return resolved;\n}\n\nexport type RunContext = 'fork' | 'cold' | 'promote';\n\nexport interface ResolveRunInput {\n kind: string;\n context: RunContext;\n override?: RunPair | undefined;\n /** The main's pair for a fork, the agent's for a promotion; unknown fields stay undefined. */\n parent?: RunPair | undefined;\n host: string;\n config?: Omit<ConfigLevels, 'session'> | undefined;\n}\n\nexport interface ResolvedRun {\n backend?: Backend | undefined;\n model?: string | undefined;\n source: KeySource | 'parent';\n key?: string | undefined;\n}\n\nconst FIXED_BY: Record<'fork' | 'promote', string> = {\n fork: \"A fork keeps the main's backend and model\",\n promote: \"A promotion keeps the agent's backend and model\",\n};\n\nfunction pairText(pair: RunPair): string {\n return [pair.backend, pair.model].filter(Boolean).join('/');\n}\n\nexport function effectiveRun(\n resolved: ResolvedConfig,\n kind: string,\n): { pair: RunPair; key: string; source: KeySource } {\n const kindKey = `run.kinds.${kind}`;\n const key = resolved.values.has(kindKey) ? kindKey : 'run.default';\n const pair = { ...(resolved.values.get(key) as RunPair) };\n if (!pair.backend) pair.backend = (resolved.values.get('run.default') as RunPair).backend;\n return { pair, key, source: resolved.sources.get(key) as KeySource };\n}\n\nexport function resolveRun(input: ResolveRunInput): ResolvedRun {\n const override = Object.fromEntries(\n Object.entries(input.override ?? {}).filter(([, value]) => value !== undefined),\n ) as RunPair;\n if (input.context !== 'cold') {\n const parent = input.parent ?? {};\n const changed = (Object.keys(override) as (keyof RunPair)[]).some(\n (field) => override[field] !== parent[field],\n );\n if (changed) {\n throw new CarnetError(\n 'RUN_FIXED',\n `${FIXED_BY[input.context]}: no backend or model for ${input.kind} here`,\n );\n }\n return { ...parent, source: 'parent' };\n }\n const session = Object.keys(override).length\n ? parseConfig({ run: { kinds: { [input.kind]: override } } }, 'launch')\n : undefined;\n const resolved = resolveConfig({ ...input.config, session });\n const { pair, key, source } = effectiveRun(resolved, input.kind);\n if (input.host === 'claude-code' && pair.backend !== 'claude') {\n throw new CarnetError(\n 'BACKEND_UNAVAILABLE',\n `${source.level} ${key} asks ${pairText(pair)} for ${input.kind}: the claude-code host runs claude only; launch with --backend claude or change ${key}`,\n );\n }\n return { ...pair, source, key };\n}\n\nexport function sourceLabel(source: KeySource | 'parent'): string {\n if (source === 'parent') return 'parent';\n return source.origin === 'default' || source.level === 'default'\n ? source.origin\n : `${source.level} · ${source.origin}`;\n}\n","import { join } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { type Layered, loadLayered } from '../layers.ts';\nimport { rucherPaths } from '../paths.ts';\nimport type { Workspace } from '../workspace/workspace.ts';\nimport { BUILT_IN_PROFILE_NOTES, BUILT_IN_PROFILES } from './defaults.ts';\nimport { branchProblems, overlay, type ProfileLookup } from './resolve.ts';\nimport { parseConfig, type Source } from './schema.ts';\n\nexport const PROFILES_DIRECTORY = 'profiles';\n\n// A profile writes its autonomy keys at the top: `gestures: { commit: human }`.\nconst AUTONOMY_KEYS = ['shadow', 'supervisor', 'gestures', 'budget', 'stopAfterEscalations'];\n\nexport function profileValues(meta: Record<string, unknown>): Source {\n const { autonomy, ...rest } = meta;\n if (typeof autonomy === 'string') {\n throw new Error('autonomy: a profile cannot choose another profile, use extends');\n }\n const lifted: Record<string, unknown> = { ...(autonomy as Record<string, unknown> | undefined) };\n for (const key of AUTONOMY_KEYS) {\n if (!(key in rest)) continue;\n if (key in lifted) throw new Error(`${key} is set both at the top and under autonomy`);\n lifted[key] = rest[key];\n delete rest[key];\n }\n if ('profile' in lifted) {\n throw new Error('autonomy.profile: a profile cannot choose another profile, use extends');\n }\n const file = Object.keys(lifted).length ? { ...rest, autonomy: lifted } : rest;\n try {\n return parseConfig(file, 'profile');\n } catch (error) {\n throw new Error(\n error instanceof Error ? error.message.replace(/^profile: /, '') : String(error),\n );\n }\n}\n\nfunction mergeSources(base: Source, child: Source): Source {\n const merged = new Map(base);\n for (const [key, value] of child) merged.set(key, overlay(key, merged.get(key), value));\n return merged;\n}\n\nexport function profileDirectories(\n env: NodeJS.ProcessEnv = process.env,\n workspace?: Pick<Workspace, 'definition'> | null,\n): { layer: 'user' | 'workspace'; path: string }[] {\n return [\n { layer: 'user', path: join(rucherPaths(env).config, PROFILES_DIRECTORY) },\n ...(workspace\n ? [{ layer: 'workspace' as const, path: join(workspace.definition, PROFILES_DIRECTORY) }]\n : []),\n ];\n}\n\nexport function loadProfiles(\n env: NodeJS.ProcessEnv = process.env,\n workspace?: Pick<Workspace, 'definition'> | null,\n): Layered<Source> {\n return loadLayered<Source>({\n builtIns: Object.entries(BUILT_IN_PROFILES).map(([name, file]) => ({\n name,\n value: parseConfig(file, `profile ${name}`),\n body: BUILT_IN_PROFILE_NOTES[name] ?? '',\n })),\n directories: profileDirectories(env, workspace),\n parse: (meta) => profileValues(meta),\n merge: mergeSources,\n check: branchProblems,\n });\n}\n\nexport function profileLookup(profiles: Layered<Source>): ProfileLookup {\n return (name) => {\n const resolved = profiles.resolved.get(name);\n if (resolved) return resolved.value;\n const problem = profiles.problems.find(\n (candidate) => candidate.name === name && candidate.path === profiles.top.get(name)?.path,\n );\n throw new CarnetError(\n 'CONFIG_INVALID',\n problem\n ? `profile ${name} (${problem.path ?? problem.layer}): ${problem.message}`\n : `no profile named ${name}: see rucher profiles list`,\n );\n };\n}\n\nexport function profileSource(\n name: string,\n workspace?: Pick<Workspace, 'definition'> | null,\n env: NodeJS.ProcessEnv = process.env,\n): Source {\n return profileLookup(loadProfiles(env, workspace))(name);\n}\n","import type { CarnetEvent } from './events.ts';\nimport type { TranscriptUsage } from './hosts/host.ts';\n\nexport function eventUsage(event: Pick<CarnetEvent, 'payload'>): TranscriptUsage | undefined {\n const usage = (event.payload as { usage?: unknown } | null)?.usage;\n if (!usage || typeof usage !== 'object') return undefined;\n const value = usage as Record<string, unknown>;\n return typeof value.turns === 'number' && typeof value.firstContext === 'number'\n ? (value as unknown as TranscriptUsage)\n : undefined;\n}\n\nexport function formatTokens(count: number): string {\n if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;\n if (count >= 1000) return `${Math.round(count / 1000)}k`;\n return String(count);\n}\n\n// Input counts every token the model read, cached or not: that is what a fork's inherited\n// conversation multiplies.\nexport function formatUsage(usage: TranscriptUsage): string {\n const input = usage.input + usage.cacheRead + usage.cacheCreation;\n return `${formatTokens(input)} in · ${formatTokens(usage.output)} out · starts at ${formatTokens(usage.firstContext)} · ${usage.turns} turns`;\n}\n"],"mappings":";;;;;;;;;AA2DA,IAAa,cAAb,cAAiC,MAAM;CAE1B;CAEA;CAHX,YACE,MACA,SACA,MACA;EACA,MAAM,OAAO;EAJJ,KAAA,OAAA;EAEA,KAAA,OAAA;EAGT,KAAK,OAAO;CACd;AACF;;ACjEA,MAAa,eAAe;CAAC;CAAU;CAAa;CAAQ;CAAY;AAAU;AAClF,MAAa,cAAc,EAAE,KAAK,YAAY;AAG9C,MAAM,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;AAE1C,SAAS,iBAA0C,OAAc;CAC/D,OAAO;EACL,EAAE,OAAO;GAAE,MAAM,EAAE,QAAQ,KAAK;GAAG,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;EAAE,CAAC;EACpE,EAAE,OAAO;GACP,MAAM,EAAE,QAAQ,aAAa;GAC7B;GACA,SAAS,EAAE,KAAK,CAAC,QAAQ,QAAQ,CAAC;EACpC,CAAC;EACD,EAAE,OAAO;GAAE,MAAM,EAAE,QAAQ,UAAU;GAAG;EAAM,CAAC;EAC/C,EAAE,OAAO;GACP,MAAM,EAAE,QAAQ,UAAU;GAC1B,QAAQ;GACR,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;EAC3C,CAAC;EACD,EACG,OAAO;GACN,MAAM,EAAE,QAAQ,OAAO;GACvB,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,S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