@rucher/carnet 0.3.0-beta.3 → 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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["absolute"],"sources":["../src/move.ts","../src/render.ts","../src/workspace/backup.ts","../src/workspace/git-trees.ts","../src/workspace/rename.ts","../src/workspace/merge.ts","../src/hook/session-end.ts","../src/hook/session-start.ts","../src/hook/user-prompt-submit.ts","../src/shell.ts","../src/guard.ts","../src/launch.ts","../src/hook/post-tool-use.ts","../src/status/line.ts"],"sourcesContent":["import type { Carnet } from './carnet.ts';\nimport { CarnetError } from './errors.ts';\nimport type { Session } from './sessions.ts';\n\nexport interface MoveOptions {\n merge?: boolean | undefined;\n dryRun?: boolean | undefined;\n}\n\nexport interface MoveResult {\n session: Session;\n into: Session | null;\n movedAgents: string[];\n skippedAgents: string[];\n movedEvents: number;\n movedTable: boolean;\n keptNotes: number;\n}\n\nfunction count(carnet: Carnet, sql: string, ...parameters: string[]): number {\n return Number((carnet.db.prepare(sql).get(...parameters) as { total: number }).total);\n}\n\nfunction agentNames(carnet: Carnet, session: string): string[] {\n return (\n carnet.db\n .prepare('SELECT name FROM agents WHERE session = ? ORDER BY started_at, rowid')\n .all(session) as unknown as { name: string }[]\n ).map((row) => row.name);\n}\n\nfunction sessionNamed(carnet: Carnet, workspace: string, name: string): Session | null {\n const row = carnet.db\n .prepare('SELECT id FROM sessions WHERE workspace = ? AND name = ?')\n .get(workspace, name) as { id: string } | undefined;\n return row ? carnet.sessions.require(row.id) : null;\n}\n\n// One database holds every workspace: moving a session only changes its workspace, and its agents,\n// events and Main line follow its id. Notes stay in the workspace they were written in.\nexport function moveSession(\n carnet: Carnet,\n sessionId: string,\n targetWorkspace: string,\n options: MoveOptions = {},\n): MoveResult {\n const session = carnet.sessions.require(sessionId);\n if (session.workspace !== (carnet.workspace?.name ?? null)) {\n throw new CarnetError('SESSION_NOT_FOUND', `Unknown session ${sessionId}`);\n }\n if (session.workspace === targetWorkspace) {\n throw new CarnetError('SESSION_MOVE_INVALID', 'The session is already in this workspace');\n }\n const into = session.name ? sessionNamed(carnet, targetWorkspace, session.name) : null;\n if (into && !options.merge) {\n throw new CarnetError(\n 'SESSION_NAME_TAKEN',\n `Workspace ${targetWorkspace} already has session ${into.name}: pass --merge to merge into it`,\n );\n }\n const agents = agentNames(carnet, session.id);\n const taken = new Set(into ? agentNames(carnet, into.id) : []);\n const hasTable = (id: string) =>\n carnet.db.prepare('SELECT 1 FROM table_items WHERE session = ?').get(id) !== undefined;\n const result: MoveResult = {\n session,\n into,\n movedAgents: agents.filter((name) => !taken.has(name)),\n skippedAgents: agents.filter((name) => taken.has(name)),\n movedEvents: count(\n carnet,\n 'SELECT COUNT(*) AS total FROM events WHERE session = ?',\n session.id,\n ),\n movedTable: hasTable(session.id) && !(into && hasTable(into.id)),\n keptNotes: count(\n carnet,\n 'SELECT COUNT(*) AS total FROM notes WHERE session = ? OR dropped_session = ?',\n session.id,\n session.id,\n ),\n };\n if (options.dryRun) return result;\n if (into) carnet.sessions.merge(session.id, into.id);\n carnet.db\n .prepare('UPDATE sessions SET workspace = ? WHERE id = ?')\n .run(targetWorkspace, session.id);\n return result;\n}\n","import { mkdirSync } from 'node:fs';\nimport { type Workspace, workspaceHosts } from './workspace/workspace.ts';\nimport { hostById } from './hosts/host.ts';\nimport { reportsDirectory } from './paths.ts';\n\nexport interface RenderResult {\n runDirectory: string;\n written: string[];\n removed: string[];\n}\n\nexport interface RunDirectoryRenderOptions {\n env?: NodeJS.ProcessEnv | undefined;\n host?: string | undefined;\n}\n\nexport function renderRunDirectory(\n workspace: Workspace,\n options: RunDirectoryRenderOptions = {},\n): RenderResult {\n mkdirSync(workspace.runDirectory, { recursive: true });\n mkdirSync(reportsDirectory(workspace), { recursive: true });\n const result: RenderResult = { runDirectory: workspace.runDirectory, written: [], removed: [] };\n for (const id of options.host ? [options.host] : workspaceHosts(workspace)) {\n const rendered = hostById(id).renderRunDirectory(workspace);\n result.written.push(...rendered.written);\n result.removed.push(...rendered.removed);\n }\n return result;\n}\n","import { mkdirSync, writeFileSync } from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { join } from 'node:path';\nimport { rucherPaths } from '../paths.ts';\n\nexport function backupsDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).state, 'backups');\n}\n\nexport function backupFolder(\n operation: string,\n name: string,\n at: Date,\n env?: NodeJS.ProcessEnv,\n): string {\n const stamp = at\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.\\d+Z$/, 'Z');\n return join(backupsDirectory(env), `${stamp}-${operation}-${name}`);\n}\n\nexport function writeBackup(db: DatabaseSync, folder: string, plan: unknown): void {\n mkdirSync(folder, { recursive: true });\n db.prepare('VACUUM INTO ?').run(join(folder, 'carnet.db'));\n writeFileSync(join(folder, 'plan.json'), `${JSON.stringify(plan, null, 2)}\\n`);\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, lstatSync, readdirSync, readFileSync, renameSync } from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { shellQuote, type UndoList } from './undo.ts';\n\nexport type GitTreeKind = 'worktree' | 'orphan' | 'clone';\n\nexport interface GitTree {\n path: string;\n kind: GitTreeKind;\n // The repo a linked worktree belongs to.\n repo?: string | undefined;\n}\n\nexport interface GitTreeHolder {\n session: string;\n name: string;\n}\n\nexport interface TreeMove extends GitTree {\n to: string;\n holders: GitTreeHolder[];\n}\n\nfunction adminFolder(tree: string): string | undefined {\n const match = /^gitdir:\\s*(.+)$/m.exec(readFileSync(join(tree, '.git'), 'utf8'));\n if (!match?.[1]) return undefined;\n const admin = match[1].trim();\n return isAbsolute(admin) ? admin : resolve(tree, admin);\n}\n\nfunction classify(tree: string): GitTree {\n if (lstatSync(join(tree, '.git')).isDirectory()) return { path: tree, kind: 'clone' };\n const admin = adminFolder(tree);\n if (!admin || !existsSync(admin)) return { path: tree, kind: 'orphan' };\n const common = join(admin, 'commondir');\n const gitDirectory = existsSync(common)\n ? resolve(admin, readFileSync(common, 'utf8').trim())\n : dirname(dirname(admin));\n return { path: tree, kind: 'worktree', repo: dirname(gitDirectory) };\n}\n\n// A folder holding a .git entry moves as one unit: its files are never listed one by one.\nexport function findGitTrees(root: string, skip: readonly string[] = []): GitTree[] {\n const trees: GitTree[] = [];\n const visit = (folder: string) => {\n if (!existsSync(folder)) return;\n for (const name of readdirSync(folder).sort()) {\n const path = join(folder, name);\n if (skip.includes(relative(root, path))) continue;\n if (!lstatSync(path).isDirectory()) continue;\n if (existsSync(join(path, '.git'))) trees.push(classify(path));\n else visit(path);\n }\n };\n visit(root);\n return trees;\n}\n\nexport function treeHolders(db: DatabaseSync, path: string): GitTreeHolder[] {\n return db\n .prepare(\n `SELECT session, name FROM agents WHERE status != 'closed' AND worktree = ?\n ORDER BY session, name`,\n )\n .all(path) as unknown as GitTreeHolder[];\n}\n\nexport function repairWorktree(path: string): void {\n try {\n execFileSync('git', ['-C', path, 'worktree', 'repair'], { stdio: 'pipe', timeout: 30_000 });\n } catch (error) {\n const stderr = (error as { stderr?: Buffer }).stderr?.toString().trim();\n throw new CarnetError(\n 'WORKSPACE_RELOCATE_FAILED',\n `git worktree repair failed in ${path}${stderr ? `: ${stderr}` : ''}`,\n );\n }\n}\n\nfunction repairCommand(path: string): string {\n return `git -C ${shellQuote(path)} worktree repair`;\n}\n\n// The repo's admin folder names the worktree by absolute path, so a moved worktree is repaired\n// from its new place, and undone by moving back then repairing there.\nexport function moveWithTrees(\n undo: UndoList,\n move: { from: string; to: string },\n trees: readonly GitTree[],\n): void {\n const linked = trees.filter((tree) => tree.kind === 'worktree');\n const at = (base: string, tree: GitTree) => join(base, relative(move.from, tree.path));\n renameSync(move.from, move.to);\n undo.push({\n command: [\n `mv ${shellQuote(move.to)} ${shellQuote(move.from)}`,\n ...linked.map((tree) => repairCommand(tree.path)),\n ].join(' && '),\n run: () => {\n renameSync(move.to, move.from);\n for (const tree of linked) repairWorktree(tree.path);\n },\n });\n for (const tree of linked) repairWorktree(at(move.to, tree));\n}\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { join, relative } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { hostById } from '../hosts/host.ts';\nimport { defaultRunDirectory, workspaceDefinition } from '../paths.ts';\nimport { renderRunDirectory } from '../render.ts';\nimport {\n renameWorkspaceRows,\n runningWorkspaceSessions,\n workspaceRowCounts,\n type RunningSessionRow,\n type WorkspaceRowCounts,\n} from '../workspace-rows.ts';\nimport { backupFolder, writeBackup } from './backup.ts';\nimport { findGitTrees, moveWithTrees, treeHolders, type TreeMove } from './git-trees.ts';\nimport { moveTracked, relocateFailed, UndoList } from './undo.ts';\nimport {\n isWorkspaceName,\n loadWorkspace,\n WORKSPACE_FILE,\n workspaceExists,\n workspaceHosts,\n} from './workspace.ts';\n\nexport interface RenameWorkspaceOptions {\n env?: NodeJS.ProcessEnv | undefined;\n dryRun?: boolean | undefined;\n isAlive: (processId: number) => boolean;\n now?: (() => Date) | undefined;\n}\n\nexport interface FolderMove {\n what: string;\n from: string;\n to: string;\n}\n\nexport interface RenamePlan {\n from: string;\n to: string;\n moves: FolderMove[];\n // Git trees inside the run directory, which move with it.\n trees: TreeMove[];\n rows: WorkspaceRowCounts;\n running: RunningSessionRow[];\n}\n\nexport interface RenameResult extends RenamePlan {\n backup: string;\n paths: number;\n trustMoved: boolean;\n warnings: string[];\n}\n\nfunction requireFree(db: DatabaseSync, name: string, env: NodeJS.ProcessEnv): void {\n const rows = workspaceRowCounts(db, name);\n const taken = [\n workspaceExists(name, env) ? 'a definition' : null,\n existsSync(workspaceDefinition(name, env)) && !workspaceExists(name, env)\n ? 'a definition folder'\n : null,\n existsSync(defaultRunDirectory(name, env)) ? 'a run directory' : null,\n rows.sessions + rows.notes + rows.activeDays > 0 ? 'sessions or notes kept after a drop' : null,\n ].filter((reason): reason is string => reason !== null);\n if (taken.length) {\n throw new CarnetError(\n 'WORKSPACE_EXISTS',\n `Workspace ${name} already has ${taken.join(', ')}: pick another name`,\n );\n }\n}\n\nexport function planWorkspaceRename(\n db: DatabaseSync,\n from: string,\n to: string,\n options: RenameWorkspaceOptions,\n): RenamePlan {\n const env = options.env ?? process.env;\n if (!isWorkspaceName(to)) {\n throw new CarnetError(\n 'WORKSPACE_NAME_INVALID',\n `Invalid workspace name ${JSON.stringify(to)}: use lowercase letters, digits and dashes`,\n );\n }\n const workspace = loadWorkspace(from, env);\n if (from === to) {\n throw new CarnetError('WORKSPACE_EXISTS', `Workspace ${from} already has this name`);\n }\n requireFree(db, to, env);\n const moves: FolderMove[] = [\n { what: 'definition', from: workspace.definition, to: workspaceDefinition(to, env) },\n ];\n const runDirectory = defaultRunDirectory(to, env);\n if (existsSync(workspace.runDirectory)) {\n moves.push({ what: 'run directory', from: workspace.runDirectory, to: runDirectory });\n }\n const trees = findGitTrees(workspace.runDirectory).map((tree) => ({\n ...tree,\n to: join(runDirectory, relative(workspace.runDirectory, tree.path)),\n holders: treeHolders(db, tree.path),\n }));\n return {\n from,\n to,\n moves,\n trees,\n rows: workspaceRowCounts(db, from),\n running: runningWorkspaceSessions(db, from).filter((row) => options.isAlive(row.hostPid)),\n };\n}\n\nfunction rewriteName(definition: string, name: string): void {\n const file = join(definition, WORKSPACE_FILE);\n const content = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>;\n if (!('name' in content)) return;\n writeFileSync(file, `${JSON.stringify({ ...content, name }, null, 2)}\\n`);\n}\n\n// The folders move first and the database last: a failure undoes the moves, the database never changed.\nexport function renameWorkspace(\n db: DatabaseSync,\n from: string,\n to: string,\n options: RenameWorkspaceOptions,\n): RenamePlan | RenameResult {\n const env = options.env ?? process.env;\n const plan = planWorkspaceRename(db, from, to, options);\n if (options.dryRun) return plan;\n if (plan.running.length) {\n throw new CarnetError(\n 'WORKSPACE_BUSY',\n `${plan.running.length} session${plan.running.length === 1 ? '' : 's'} of ${from} still running: ${plan.running.map((row) => row.name ?? row.id.slice(0, 8)).join(', ')}`,\n );\n }\n const workspace = loadWorkspace(from, env);\n const runDirectories = { from: workspace.runDirectory, to: defaultRunDirectory(to, env) };\n const backup = backupFolder('rename', from, (options.now ?? (() => new Date()))(), env);\n writeBackup(db, backup, plan);\n const hosts = workspaceHosts(workspace).map((id) => hostById(id));\n const undo = new UndoList();\n let paths = 0;\n try {\n for (const move of plan.moves) {\n if (move.what === 'run directory') moveWithTrees(undo, move, plan.trees);\n else moveTracked(undo, move);\n }\n rewriteName(workspaceDefinition(to, env), to);\n for (const host of hosts) {\n const relocation = host.relocateProject?.(runDirectories.from, runDirectories.to, env);\n if (!relocation) continue;\n for (const moved of relocation.moves) {\n plan.moves.push({ what: `${host.displayName} project folder`, ...moved });\n }\n for (const step of relocation.undo) undo.push(step);\n }\n paths = renameWorkspaceRows(db, { from, to }, runDirectories).paths;\n } catch (error) {\n relocateFailed(error, undo, backup);\n }\n const warnings: string[] = [];\n let trustMoved = false;\n for (const host of hosts) {\n try {\n trustMoved = host.moveTrust?.(runDirectories.from, runDirectories.to, env) || trustMoved;\n } catch (error) {\n warnings.push(`${host.displayName} trust entry not moved: ${(error as Error).message}`);\n }\n }\n try {\n renderRunDirectory(loadWorkspace(to, env), { env });\n } catch (error) {\n warnings.push(`run directory not synced: ${(error as Error).message}`);\n }\n return { ...plan, backup, paths, trustMoved, warnings };\n}\n","import {\n cpSync,\n existsSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { basename, dirname, join, relative } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { hostById } from '../hosts/host.ts';\nimport { renderRunDirectory } from '../render.ts';\nimport { GENERATED_MARKER, mergeSettings } from '../run-directory-files.ts';\nimport {\n mergeWorkspaceRows,\n nextNoteNumber,\n runningWorkspaceSessions,\n workspaceRowCounts,\n type RunningSessionRow,\n type WorkspaceRowCounts,\n} from '../workspace-rows.ts';\nimport { backupFolder, writeBackup } from './backup.ts';\nimport { findGitTrees, moveWithTrees, treeHolders, type TreeMove } from './git-trees.ts';\nimport { moveTracked, relocateFailed, UndoList } from './undo.ts';\nimport {\n definitionInstructions,\n loadWorkspace,\n type Workspace,\n WORKSPACE_FILE,\n type WorkspaceFile,\n workspaceHosts,\n} from './workspace.ts';\n\nexport interface MergeWorkspacesOptions {\n env?: NodeJS.ProcessEnv | undefined;\n isAlive: (processId: number) => boolean;\n now?: (() => Date) | undefined;\n}\n\nexport interface FileMove {\n from: string;\n to: string;\n}\n\nexport interface MergePlan {\n from: string;\n into: string;\n rows: WorkspaceRowCounts;\n // from's notes are shifted to start at firstNumber in into, keeping their order.\n firstNumber: number;\n lastNumber: number;\n running: RunningSessionRow[];\n reposAdded: string[];\n reposRenamed: [string, string][];\n settingsConflicts: string[];\n reports: FileMove[];\n sandboxes: FileMove[];\n trees: TreeMove[];\n files: FileMove[];\n instructions: string;\n}\n\nexport interface MergeResult extends MergePlan {\n backup: string;\n projectMoves: number;\n trustDropped: boolean;\n instructionsPath: string;\n warnings: string[];\n}\n\nconst BACKENDS_NOTES = join('backends', 'claude.md');\nconst REPORT_FAMILY = /(\\.plan\\.md|\\.research\\.md|\\.md)$/;\n\nfunction readFile(workspace: Workspace): WorkspaceFile {\n return JSON.parse(\n readFileSync(join(workspace.definition, WORKSPACE_FILE), 'utf8'),\n ) as WorkspaceFile;\n}\n\nfunction entries(folder: string): string[] {\n return existsSync(folder) ? readdirSync(folder).sort() : [];\n}\n\nfunction busy(db: DatabaseSync, names: string[], isAlive: MergeWorkspacesOptions['isAlive']) {\n return names.flatMap((name) =>\n runningWorkspaceSessions(db, name).filter((row) => isAlive(row.hostPid)),\n );\n}\n\nfunction sessionNameConflicts(db: DatabaseSync, from: string, into: string): string[] {\n return (\n db\n .prepare(\n `SELECT name FROM sessions WHERE workspace = ? AND name IS NOT NULL\n AND name IN (SELECT name FROM sessions WHERE workspace = ? AND name IS NOT NULL)\n ORDER BY name`,\n )\n .all(from, into) as { name: string }[]\n ).map((row) => row.name);\n}\n\nfunction repoPlan(from: Workspace, into: Workspace) {\n const added: string[] = [];\n const renamed: [string, string][] = [];\n for (const repo of from.repos) {\n const samePath = into.repos.find((existing) => existing.path === repo.path);\n if (samePath) {\n if (samePath.name !== repo.name) renamed.push([repo.name, samePath.name]);\n continue;\n }\n if (into.repos.some((existing) => existing.name === repo.name)) {\n throw new CarnetError(\n 'REPO_NAME_TAKEN',\n `${into.name} already has a repo named ${repo.name} at another path than ${repo.path}: rename one of them first`,\n );\n }\n added.push(repo.path);\n }\n return { added, renamed };\n}\n\nfunction conflicts(base: unknown, extra: unknown, path: string[] = []): string[] {\n const isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n if (isObject(base) && isObject(extra)) {\n return Object.keys(extra).flatMap((key) =>\n key in base ? conflicts(base[key], extra[key], [...path, key]) : [],\n );\n }\n if (Array.isArray(base) && Array.isArray(extra)) return [];\n return JSON.stringify(base) === JSON.stringify(extra) ? [] : [path.join('.')];\n}\n\nfunction settingsOf(file: WorkspaceFile): Record<string, unknown> {\n const { name: _name, repos: _repos, ...rest } = file;\n return rest;\n}\n\n// A report and the plan or research it kept travel together, so keptReportPath still finds them.\nfunction reportMoves(from: Workspace, into: Workspace): FileMove[] {\n const source = join(from.runDirectory, 'reports');\n const target = join(into.runDirectory, 'reports');\n const families = new Map<string, string[]>();\n for (const file of entries(source)) {\n const family = file.replace(REPORT_FAMILY, '');\n families.set(family, [...(families.get(family) ?? []), file]);\n }\n return [...families].flatMap(([family, files]) => {\n const taken = files.some((file) => existsSync(join(target, file)));\n return files.map((file) => ({\n from: join(source, file),\n to: join(target, taken ? `${from.name}-${family}${file.slice(family.length)}` : file),\n }));\n });\n}\n\nfunction sandboxMoves(from: Workspace, into: Workspace): FileMove[] {\n const source = join(from.runDirectory, 'sandboxes');\n const target = join(into.runDirectory, 'sandboxes');\n return entries(source).map((name) => ({\n from: join(source, name),\n to: join(target, existsSync(join(target, name)) ? `${from.name}-${name}` : name),\n }));\n}\n\nfunction generated(path: string): boolean {\n if (!lstatSync(path).isFile()) return false;\n return readFileSync(path, 'utf8').includes(GENERATED_MARKER);\n}\n\nconst OWN_FOLDERS = ['reports', 'sandboxes'];\n\n// A git tree keeps its place (where worktrees are looked for), with the from- prefix if taken.\nfunction treeMoves(db: DatabaseSync, from: Workspace, into: Workspace): TreeMove[] {\n return findGitTrees(from.runDirectory, OWN_FOLDERS).map((tree) => {\n const rest = relative(from.runDirectory, tree.path);\n const target = join(into.runDirectory, rest);\n return {\n ...tree,\n to: existsSync(target) ? join(dirname(target), `${from.name}-${basename(target)}`) : target,\n holders: treeHolders(db, tree.path),\n };\n });\n}\n\n// Hand-written files of the run directory; the generated ones are rendered again for into.\nfunction fileMoves(from: Workspace, into: Workspace, trees: readonly TreeMove[]): FileMove[] {\n const moves: FileMove[] = [];\n const treePaths = new Set(trees.map((tree) => tree.path));\n const visit = (folder: string) => {\n for (const name of entries(folder)) {\n const path = join(folder, name);\n const rest = relative(from.runDirectory, path);\n if (OWN_FOLDERS.includes(rest) || treePaths.has(path)) continue;\n if (lstatSync(path).isDirectory()) {\n visit(path);\n continue;\n }\n if (generated(path)) continue;\n const target = join(into.runDirectory, rest);\n moves.push({\n from: path,\n to: existsSync(target) ? join(into.runDirectory, `merged-${from.name}`, rest) : target,\n });\n }\n };\n visit(from.runDirectory);\n return moves;\n}\n\nexport function planWorkspaceMerge(\n db: DatabaseSync,\n fromName: string,\n intoName: string,\n options: MergeWorkspacesOptions,\n): MergePlan {\n const env = options.env ?? process.env;\n if (fromName === intoName) {\n throw new CarnetError('WORKSPACE_EXISTS', 'Cannot merge a workspace into itself');\n }\n const from = loadWorkspace(fromName, env);\n const into = loadWorkspace(intoName, env);\n const names = sessionNameConflicts(db, fromName, intoName);\n if (names.length) {\n throw new CarnetError(\n 'SESSION_NAME_TAKEN',\n `${intoName} already has sessions named ${names.join(', ')}: rename them in ${fromName} first (rucher sessions rename <name> <new> --ws ${fromName})`,\n );\n }\n const repos = repoPlan(from, into);\n const instructions = definitionInstructions(from);\n if (instructions !== definitionInstructions(into)) {\n throw new CarnetError(\n 'WORKSPACE_INSTRUCTIONS_CONFLICT',\n `${fromName} keeps its instructions in ${instructions} and ${intoName} in ${definitionInstructions(into)}: use the same file in both first`,\n );\n }\n const rows = workspaceRowCounts(db, fromName);\n const firstNumber = nextNoteNumber(db, intoName);\n const trees = treeMoves(db, from, into);\n const top = db\n .prepare('SELECT COALESCE(MAX(number), 0) AS top FROM notes WHERE workspace = ?')\n .get(fromName) as { top: number };\n return {\n from: fromName,\n into: intoName,\n rows,\n firstNumber,\n lastNumber: firstNumber - 1 + Number(top.top),\n running: busy(db, [fromName, intoName], options.isAlive),\n reposAdded: repos.added,\n reposRenamed: repos.renamed,\n settingsConflicts: conflicts(settingsOf(readFile(into)), settingsOf(readFile(from))),\n reports: reportMoves(from, into),\n sandboxes: sandboxMoves(from, into),\n trees,\n files: fileMoves(from, into, trees),\n instructions,\n };\n}\n\nfunction appendUnder(target: string, source: string, heading: string): void {\n if (!existsSync(source)) return;\n const added = readFileSync(source, 'utf8').trim();\n if (!added) return;\n mkdirSync(dirname(target), { recursive: true });\n const current = existsSync(target) ? readFileSync(target, 'utf8').trimEnd() : '';\n writeFileSync(target, `${current ? `${current}\\n\\n` : ''}${heading}\\n\\n${added}\\n`);\n}\n\nfunction writeDefinition(from: Workspace, into: Workspace, plan: MergePlan): void {\n const fromFile = readFile(from);\n const intoFile = readFile(into);\n const merged: WorkspaceFile = {\n ...mergeSettings(settingsOf(fromFile), settingsOf(intoFile)),\n name: into.name,\n repos: [\n ...(intoFile.repos ?? []),\n // loadWorkspace resolves the repos in file order.\n ...(fromFile.repos ?? []).filter((_, index) =>\n plan.reposAdded.includes(from.repos[index]?.path ?? ''),\n ),\n ],\n };\n writeFileSync(join(into.definition, WORKSPACE_FILE), `${JSON.stringify(merged, null, 2)}\\n`);\n const heading = `## Ex-workspace ${from.name}`;\n appendUnder(\n join(into.definition, plan.instructions),\n join(from.definition, plan.instructions),\n heading,\n );\n appendUnder(\n join(into.definition, BACKENDS_NOTES),\n join(from.definition, BACKENDS_NOTES),\n heading,\n );\n}\n\nfunction moveAway(from: string, to: string): void {\n if (!existsSync(from)) return;\n mkdirSync(dirname(to), { recursive: true });\n try {\n renameSync(from, to);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;\n cpSync(from, to, { recursive: true });\n rmSync(from, { recursive: true, force: true });\n }\n}\n\n// Files move first and the database last: a failure undoes the moves, the database never changed.\n// The definition is rewritten only after the commit, from the plan the human saw.\nexport function mergeWorkspaces(\n db: DatabaseSync,\n fromName: string,\n intoName: string,\n options: MergeWorkspacesOptions,\n): MergeResult {\n const env = options.env ?? process.env;\n const plan = planWorkspaceMerge(db, fromName, intoName, options);\n if (plan.running.length) {\n throw new CarnetError(\n 'WORKSPACE_BUSY',\n `${plan.running.length} session${plan.running.length === 1 ? '' : 's'} still running in ${fromName} or ${intoName}: ${plan.running.map((row) => row.name ?? row.id.slice(0, 8)).join(', ')}`,\n );\n }\n const from = loadWorkspace(fromName, env);\n const into = loadWorkspace(intoName, env);\n const backup = backupFolder('merge', fromName, (options.now ?? (() => new Date()))(), env);\n writeBackup(db, backup, plan);\n const hosts = workspaceHosts(from).map((id) => hostById(id));\n const undo = new UndoList();\n let projectMoves = 0;\n try {\n for (const host of hosts) {\n const relocation = host.relocateProject?.(from.runDirectory, into.runDirectory, env, 'merge');\n if (!relocation) continue;\n projectMoves += relocation.moves.length;\n for (const step of relocation.undo) undo.push(step);\n }\n for (const tree of plan.trees) {\n mkdirSync(dirname(tree.to), { recursive: true });\n moveWithTrees(undo, { from: tree.path, to: tree.to }, [tree]);\n }\n for (const move of [...plan.reports, ...plan.sandboxes, ...plan.files]) {\n mkdirSync(dirname(move.to), { recursive: true });\n moveTracked(undo, move);\n }\n const renamed = new Map(\n [\n ...plan.reports,\n ...plan.sandboxes,\n ...plan.trees.map((tree) => ({ ...tree, from: tree.path })),\n ]\n .filter(\n (move) => move.to !== join(into.runDirectory, relative(from.runDirectory, move.from)),\n )\n .map((move) => [move.from, move.to]),\n );\n mergeWorkspaceRows(db, {\n names: { from: fromName, into: intoName },\n runDirectories: { from: from.runDirectory, into: into.runDirectory },\n paths: renamed,\n repos: new Map(plan.reposRenamed),\n });\n } catch (error) {\n relocateFailed(error, undo, backup);\n }\n const warnings: string[] = [];\n const attempt = (what: string, run: () => void) => {\n try {\n run();\n } catch (error) {\n warnings.push(`${what}: ${(error as Error).message}`);\n }\n };\n attempt('definition not merged', () => writeDefinition(from, into, plan));\n attempt('definition of the merged workspace not moved to the backup', () => {\n moveAway(from.definition, join(backup, 'definition'));\n moveAway(from.runDirectory, join(backup, 'run-directory'));\n });\n let trustDropped = false;\n for (const host of hosts) {\n attempt(`${host.displayName} trust entry not dropped`, () => {\n trustDropped = host.moveTrust?.(from.runDirectory, null, env) || trustDropped;\n });\n }\n attempt('run directory not synced', () => {\n renderRunDirectory(loadWorkspace(intoName, env), { env });\n });\n return {\n ...plan,\n backup,\n projectMoves,\n trustDropped,\n instructionsPath: join(into.definition, plan.instructions),\n warnings,\n };\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { HostSessionEndPayload, HostStopPayload } from '../hosts/host.ts';\nimport type { Session } from '../sessions.ts';\n\nexport function handleSessionEnd(\n carnet: Carnet,\n payload: HostSessionEndPayload,\n): Session | undefined {\n if (!carnet.sessions.get(payload.session_id)) return undefined;\n carnet.turn.end(payload.session_id);\n return carnet.sessions.end(payload.session_id);\n}\n\n// A failed turn stays visible until the next one starts, so the human sees it went wrong.\nexport function handleStop(carnet: Carnet, payload: HostStopPayload): void {\n if (payload.failed) carnet.turn.fail(payload.session_id);\n else carnet.turn.end(payload.session_id);\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { SessionEventType } from '../events.ts';\nimport {\n compactReminder,\n outsideRucherContext,\n OUTSIDE_RUCHER_NOTICE,\n RULES_UPDATED_NOTICE,\n rulesVersion,\n} from '../prompt/prompt.ts';\nimport { hostById } from '../hosts/host.ts';\nimport { memoryMaxCharacters } from '../memory.ts';\nimport { memoryHalfLife } from '../notes.ts';\nimport { purgeDays } from '../purge.ts';\nimport { resumeContext } from '../resume.ts';\nimport type { HookEnv, HookSessionPayload, Session } from '../sessions.ts';\n\nexport interface SessionStartResult {\n session: Session;\n additionalContext?: string;\n contextParts: string[];\n notices: string[];\n}\n\nconst SOURCE_EVENTS: Readonly<Record<string, SessionEventType>> = {\n startup: 'session.started',\n resume: 'session.resumed',\n fork: 'session.forked',\n};\n\n// A fork gets a new id from the host; the launcher's env still carries the parent's.\nfunction adoptFork(carnet: Carnet, session: Session, env: HookEnv): Session {\n const parentId = env.RUCHER_SESSION_ID;\n if (!parentId || parentId === session.id || !carnet.sessions.get(parentId)) return session;\n let fork = carnet.sessions.setParent(session.id, parentId);\n carnet.memory.copyRepos(parentId, session.id);\n const kind = env.RUCHER_SESSION_KIND;\n if (kind === 'active' || kind === 'temp') {\n fork = carnet.sessions.setKind(session.id, kind, env.RUCHER_SESSION_NAME || null);\n }\n return fork;\n}\n\n// Claude Code carrying the conversation on under a new id is the same session, not a fork:\n// the new id takes the parent's name, agents, Main line and journal.\nfunction adoptContinuation(carnet: Carnet, session: Session, env: HookEnv): Session | undefined {\n const parentId = env.RUCHER_SESSION_ID;\n const parent = parentId && parentId !== session.id ? carnet.sessions.get(parentId) : undefined;\n if (!parent) return undefined;\n const hostEnv = env.CLAUDE_CONFIG_DIR ? { CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR } : {};\n if (!hostById(session.host).continues(parent, session.id, hostEnv)) return undefined;\n carnet.memory.copyRepos(parent.id, session.id);\n let merged = carnet.sessions.merge(parent.id, session.id).session;\n merged = carnet.sessions.recordPromptVersion(merged.id, parent.promptVersion);\n return parent.parentId ? carnet.sessions.setParent(merged.id, parent.parentId) : merged;\n}\n\n// A fork inherits its parent's conversation, notes included.\nfunction startMemory(\n carnet: Carnet,\n session: Session,\n source: string,\n env: HookEnv,\n): string | undefined {\n const options = {\n maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),\n halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS),\n };\n if (source === 'startup' || source === 'clear') return carnet.memory.atStart(session, options);\n if (source === 'resume' || source === 'compact') return carnet.memory.ofSession(session, options);\n return undefined;\n}\n\nexport function handleSessionStart(\n carnet: Carnet,\n payload: HookSessionPayload,\n env: HookEnv,\n): SessionStartResult {\n let session = carnet.sessions.upsertFromHook(payload, env);\n let source = payload.source ?? '';\n if (source === 'fork') {\n const continued = adoptContinuation(carnet, session, env);\n if (continued) {\n session = continued;\n source = 'resume';\n } else {\n session = adoptFork(carnet, session, env);\n }\n }\n const event = SOURCE_EVENTS[source];\n if (event) carnet.events.log(session.id, { type: event });\n session = carnet.sessions.setStatus(session.id, 'running');\n // A compaction happens inside a turn; any other start follows a turn that may have died unseen.\n if (source !== 'compact') carnet.turn.end(session.id);\n carnet.sessions.purge(session.id, purgeDays(env.RUCHER_PURGE_DAYS));\n\n const promptEnv = { RUCHER_HOME: env.RUCHER_HOME };\n const launchedVersion = env.RUCHER_PROMPT_VERSION || null;\n const contextParts: string[] = [];\n const notices: string[] = [];\n if (hostById(session.host).rendersSystemPrompt(source)) {\n session = carnet.sessions.recordPromptVersion(session.id, launchedVersion);\n }\n if (source === 'resume') contextParts.push(resumeContext(carnet, session));\n const memory = startMemory(carnet, session, source, env);\n if (memory) contextParts.push(memory);\n if (source === 'compact' && !launchedVersion) {\n contextParts.push(compactReminder(carnet.workspace, promptEnv));\n } else if (!env.RUCHER_SESSION_ID && !session.promptVersion) {\n contextParts.push(outsideRucherContext(carnet.workspace, promptEnv));\n notices.push(OUTSIDE_RUCHER_NOTICE);\n } else if (\n session.promptVersion &&\n session.promptVersion !== rulesVersion(carnet.workspace, promptEnv)\n ) {\n notices.push(RULES_UPDATED_NOTICE);\n }\n const additionalContext = contextParts.length ? contextParts.join('\\n\\n') : undefined;\n return { session, contextParts, notices, ...(additionalContext ? { additionalContext } : {}) };\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { Host, HostPromptPayload } from '../hosts/host.ts';\nimport type { Session } from '../sessions.ts';\nimport type { TurnOptions } from '../turn.ts';\n\nexport function handleUserPromptSubmit(\n carnet: Carnet,\n host: Host,\n payload: HostPromptPayload,\n options: TurnOptions = {},\n): Session {\n carnet.sessions.ensure(payload.session_id, payload.cwd);\n if (options.trackTurn ?? true) carnet.turn.start(payload.session_id);\n carnet.notes.recordActiveDay();\n return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));\n}\n","import { homedir } from 'node:os';\nimport { basename, isAbsolute, join, resolve } from 'node:path';\n\n// A reading of Bash just deep enough to find real git calls and where they run: quotes, comments\n// and heredoc bodies are text, not commands.\n\nexport interface Word {\n text: string;\n // Holds an expansion or a glob, so its value is not known before the shell runs it.\n dynamic: boolean;\n}\n\nexport interface ShellCommand {\n words: Word[];\n // undefined when it can't be known, like after cd - or cd $DIR.\n cwd: string | undefined;\n env: Map<string, string | undefined>;\n}\n\nexport interface GitCall {\n verb: string;\n sub: string | undefined;\n // Every directory the call acts on; undefined for one that can't be known.\n dirs: (string | undefined)[];\n}\n\ninterface State {\n cwd: string | undefined;\n env: Map<string, string | undefined>;\n}\n\nconst GIT_ENV = new Set(['GIT_DIR', 'GIT_WORK_TREE']);\nconst KEYWORDS = new Set(['!', '{', '}', 'if', 'then', 'else', 'elif', 'do', 'while', 'until']);\nconst SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);\nconst PLAIN_WRAPPERS = new Set(['command', 'builtin', 'exec', 'nohup', 'time']);\nconst SUDO_VALUES = new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U']);\nconst XARGS_VALUES = new Set(['-I', '-L', '-n', '-P', '-d', '-E', '-s', '-a']);\nconst GIT_VALUES = new Set([\n '-C',\n '-c',\n '--git-dir',\n '--work-tree',\n '--namespace',\n '--config-env',\n '--super-prefix',\n '--exec-path',\n '--list-cmds',\n '--attr-source',\n]);\n// sh -c strings and eval are read one level deep, no further.\nconst MAX_DEPTH = 1;\n\nfunction absolute(path: string, cwd: string): string {\n if (path === '~' || path.startsWith('~/')) return join(homedir(), path.slice(1));\n return isAbsolute(path) ? path : resolve(cwd, path);\n}\n\nfunction copy(state: State): State {\n return { cwd: state.cwd, env: new Map(state.env) };\n}\n\nclass Reader {\n private pos = 0;\n private heredocs: { delimiter: string; strip: boolean }[] = [];\n\n constructor(\n private readonly src: string,\n private readonly depth: number,\n private readonly out: ShellCommand[],\n ) {}\n\n walk(state: State, closer: ')' | '`' | null): void {\n let words: Word[] = [];\n let text = '';\n let dynamic = false;\n let started = false;\n let skipTarget = false;\n let previous: string | null = null;\n\n const endWord = () => {\n if (started) {\n if (skipTarget) skipTarget = false;\n else words.push({ text, dynamic });\n }\n text = '';\n dynamic = false;\n started = false;\n };\n const endCommand = (separator: string | null) => {\n endWord();\n const piped = previous === '|' || separator === '|';\n this.command(words, state, piped);\n words = [];\n skipTarget = false;\n previous = separator;\n };\n const nested = (until: ')' | '`') => {\n this.walk(copy(state), until);\n dynamic = true;\n started = true;\n };\n\n while (this.pos < this.src.length) {\n const c = this.src[this.pos] ?? '';\n const next = this.src[this.pos + 1] ?? '';\n if (closer !== null && c === closer) {\n this.pos++;\n endCommand(null);\n return;\n }\n if (c === ' ' || c === '\\t') {\n endWord();\n this.pos++;\n } else if (c === '\\n') {\n this.pos++;\n endCommand('\\n');\n this.skipHeredocs();\n } else if (c === '#' && !started) {\n while (this.pos < this.src.length && this.src[this.pos] !== '\\n') this.pos++;\n } else if (c === '\\\\') {\n if (next !== '\\n') {\n text += next;\n started = true;\n }\n this.pos += 2;\n } else if (c === \"'\") {\n const end = this.src.indexOf(\"'\", this.pos + 1);\n const stop = end === -1 ? this.src.length : end;\n text += this.src.slice(this.pos + 1, stop);\n started = true;\n this.pos = stop + 1;\n } else if (c === '\"') {\n this.pos++;\n started = true;\n while (this.pos < this.src.length && this.src[this.pos] !== '\"') {\n const d = this.src[this.pos] ?? '';\n if (d === '\\\\' && '\"\\\\$`'.includes(this.src[this.pos + 1] ?? '')) {\n text += this.src[this.pos + 1];\n this.pos += 2;\n } else if (d === '$' && this.src[this.pos + 1] === '(') {\n this.pos += 2;\n nested(')');\n } else if (d === '`') {\n this.pos++;\n nested('`');\n } else {\n if (d === '$') dynamic = true;\n text += d;\n this.pos++;\n }\n }\n this.pos++;\n } else if (c === '$' && next === '(' && this.src[this.pos + 2] === '(') {\n const end = this.src.indexOf('))', this.pos);\n this.pos = end === -1 ? this.src.length : end + 2;\n dynamic = true;\n started = true;\n } else if (c === '$' && next === '(') {\n this.pos += 2;\n nested(')');\n } else if (c === '$' && next === \"'\") {\n this.pos += 2;\n while (this.pos < this.src.length && this.src[this.pos] !== \"'\") {\n if (this.src[this.pos] === '\\\\') this.pos++;\n text += this.src[this.pos] ?? '';\n this.pos++;\n }\n this.pos++;\n started = true;\n } else if (c === '$') {\n text += c;\n dynamic = true;\n started = true;\n this.pos++;\n } else if (c === '`') {\n this.pos++;\n nested('`');\n } else if (c === ';') {\n this.pos += next === ';' ? 2 : 1;\n endCommand(';');\n } else if (c === '&' && next === '&') {\n this.pos += 2;\n endCommand('&&');\n } else if (c === '&' && next === '>') {\n endWord();\n this.pos += this.src[this.pos + 2] === '>' ? 3 : 2;\n skipTarget = true;\n } else if (c === '&') {\n this.pos++;\n endCommand('&');\n } else if (c === '|' && next === '|') {\n this.pos += 2;\n endCommand('||');\n } else if (c === '|') {\n this.pos += next === '&' ? 2 : 1;\n endCommand('|');\n } else if (c === '(' && !started && words.length === 0) {\n this.pos++;\n this.walk(copy(state), ')');\n } else if ((c === '<' || c === '>') && next === '(') {\n endWord();\n this.pos += 2;\n this.walk(copy(state), ')');\n } else if (c === '<' || c === '>') {\n if (started && /^\\d+$/.test(text)) {\n text = '';\n started = false;\n }\n endWord();\n skipTarget = this.redirect();\n } else {\n if (c === '*' || c === '?' || c === '[') dynamic = true;\n text += c;\n started = true;\n this.pos++;\n }\n }\n endCommand(null);\n }\n\n // Whether a target word follows; a heredoc's delimiter is read here.\n private redirect(): boolean {\n if (this.src.startsWith('<<<', this.pos)) {\n this.pos += 3;\n return true;\n }\n if (this.src.startsWith('<<', this.pos)) {\n this.pos += 2;\n const strip = this.src[this.pos] === '-';\n if (strip) this.pos++;\n while (this.src[this.pos] === ' ' || this.src[this.pos] === '\\t') this.pos++;\n const match = /^(?:'([^']*)'|\"([^\"]*)\"|([^\\s;&|<>()]+))/.exec(this.src.slice(this.pos));\n if (match) {\n this.heredocs.push({ delimiter: match[1] ?? match[2] ?? match[3] ?? '', strip });\n this.pos += match[0].length;\n }\n return false;\n }\n this.pos++;\n if ('>&|'.includes(this.src[this.pos] ?? '')) this.pos++;\n return true;\n }\n\n private skipHeredocs(): void {\n for (const { delimiter, strip } of this.heredocs) {\n while (this.pos < this.src.length) {\n const end = this.src.indexOf('\\n', this.pos);\n const stop = end === -1 ? this.src.length : end;\n let line = this.src.slice(this.pos, stop);\n if (strip) line = line.replace(/^\\t+/, '');\n this.pos = stop + 1;\n if (line === delimiter) break;\n }\n }\n this.heredocs = [];\n }\n\n private command(all: Word[], state: State, piped: boolean): void {\n let words = all;\n while (words[0] && KEYWORDS.has(words[0].text)) words = words.slice(1);\n const env = new Map(state.env);\n const assigned = new Map<string, string | undefined>();\n const assign = (word: Word) => {\n const at = word.text.indexOf('=');\n const name = word.text.slice(0, at);\n if (GIT_ENV.has(name)) assigned.set(name, word.dynamic ? undefined : word.text.slice(at + 1));\n };\n while (words[0] && /^[A-Za-z_]\\w*=/.test(words[0].text)) {\n assign(words[0]);\n words = words.slice(1);\n }\n if (words.length === 0) {\n if (!piped) for (const [name, value] of assigned) state.env.set(name, value);\n return;\n }\n words = this.unwrap(words, assign);\n for (const [name, value] of assigned) env.set(name, value);\n const name = words[0]?.text ?? '';\n const args = words.slice(1);\n\n if (name === 'cd' || name === 'pushd' || name === 'popd') {\n if (!piped) state.cwd = this.cd(name, args, state.cwd);\n return;\n }\n if (name === 'export') {\n for (const word of args) if (word.text.includes('=')) assign(word);\n if (!piped) for (const [key, value] of assigned) state.env.set(key, value);\n return;\n }\n if (this.depth < MAX_DEPTH && SHELLS.has(basename(name))) {\n const flag = args.findIndex((word) => /^-[a-z]*c[a-z]*$/.test(word.text));\n const script = flag === -1 ? undefined : args[flag + 1];\n if (script) this.nested(script.text, { cwd: state.cwd, env });\n return;\n }\n if (this.depth < MAX_DEPTH && name === 'eval') {\n this.nested(args.map((word) => word.text).join(' '), { cwd: state.cwd, env });\n return;\n }\n if (words.length > 0) this.out.push({ words, cwd: state.cwd, env });\n }\n\n private unwrap(start: Word[], assign: (word: Word) => void): Word[] {\n let words = start;\n for (;;) {\n const name = words[0]?.text ?? '';\n let i = 1;\n if (name === 'env') {\n while (words[i] && (words[i]?.text.startsWith('-') || words[i]?.text.includes('='))) {\n const word = words[i] as Word;\n if (word.text.includes('=') && !word.text.startsWith('-')) assign(word);\n i += word.text === '-u' || word.text === '-C' ? 2 : 1;\n }\n } else if (PLAIN_WRAPPERS.has(name)) {\n while (words[i]?.text.startsWith('-')) i++;\n } else if (name === 'sudo') {\n while (words[i]?.text.startsWith('-')) i += SUDO_VALUES.has(words[i]?.text ?? '') ? 2 : 1;\n } else if (name === 'xargs') {\n while (words[i]?.text.startsWith('-')) i += XARGS_VALUES.has(words[i]?.text ?? '') ? 2 : 1;\n } else {\n return words;\n }\n words = words.slice(i);\n }\n }\n\n private cd(name: string, args: Word[], cwd: string | undefined): string | undefined {\n if (name !== 'cd') return undefined;\n const target = args.find((word) => !/^-[LPe@]+$/.test(word.text));\n if (!target) return homedir();\n if (target.dynamic || target.text === '-') return undefined;\n if (isAbsolute(target.text) || target.text.startsWith('~')) return absolute(target.text, '/');\n return cwd === undefined ? undefined : absolute(target.text, cwd);\n }\n\n private nested(script: string, state: State): void {\n new Reader(script, this.depth + 1, this.out).walk(state, null);\n }\n}\n\nfunction commandsOf(command: string, cwd: string | undefined, depth: number): ShellCommand[] {\n const out: ShellCommand[] = [];\n new Reader(command, depth, out).walk({ cwd, env: new Map() }, null);\n return out;\n}\n\nexport function shellCommands(command: string, cwd: string | undefined): ShellCommand[] {\n return commandsOf(command, cwd, 0);\n}\n\nfunction gitCall(cmd: ShellCommand): GitCall[] {\n const words = cmd.words;\n let base = cmd.cwd;\n const paths: (Word | undefined)[] = [];\n const aliases = new Map<string, string>();\n let i = 1;\n while (i < words.length && words[i]?.text.startsWith('-')) {\n const word = words[i] as Word;\n const at = word.text.startsWith('--') ? word.text.indexOf('=') : -1;\n const option = at === -1 ? word.text : word.text.slice(0, at);\n let value: Word | undefined;\n if (at !== -1) {\n value = { text: word.text.slice(at + 1), dynamic: word.dynamic };\n i++;\n } else if (GIT_VALUES.has(option)) {\n value = words[i + 1];\n i += 2;\n } else {\n i++;\n }\n if (option === '-C') {\n base = !value || value.dynamic || base === undefined ? undefined : absolute(value.text, base);\n } else if (option === '--git-dir' || option === '--work-tree') {\n paths.push(value);\n } else if (option === '-c' && value?.text.startsWith('alias.')) {\n const eq = value.text.indexOf('=');\n if (eq !== -1) aliases.set(value.text.slice(6, eq), value.text.slice(eq + 1));\n }\n }\n const verbWord = words[i];\n if (!verbWord) return [];\n let rest = words.slice(i + 1);\n let verb = verbWord.text;\n const alias = aliases.get(verb);\n if (alias !== undefined) {\n if (alias.startsWith('!')) return gitCallsIn(commandsOf(alias.slice(1), base, MAX_DEPTH));\n const [first = '', ...more] = alias.trim().split(/\\s+/);\n verb = first;\n rest = [...more.map((text) => ({ text, dynamic: false })), ...rest];\n }\n const resolved = (path: string | undefined) =>\n path === undefined || base === undefined ? undefined : absolute(path, base);\n const dirs: (string | undefined)[] = [base];\n for (const path of paths) dirs.push(!path || path.dynamic ? undefined : resolved(path.text));\n for (const name of GIT_ENV) if (cmd.env.has(name)) dirs.push(resolved(cmd.env.get(name)));\n const first = rest[0]?.text;\n const sub = first === undefined || first.startsWith('-') ? undefined : first;\n return [{ verb, sub, dirs }];\n}\n\nfunction gitCallsIn(commands: ShellCommand[]): GitCall[] {\n return commands\n .filter((cmd) => basename(cmd.words[0]?.text ?? '') === 'git')\n .flatMap((cmd) => gitCall(cmd));\n}\n\nexport function gitCalls(command: string, cwd: string | undefined): GitCall[] {\n return gitCallsIn(shellCommands(command, cwd));\n}\n","import { realpathSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport type { AgentKind } from './agents.ts';\nimport { type GitCall, gitCalls } from './shell.ts';\n\nexport const GUARDED_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'Bash']);\nconst FILE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit']);\n\nexport interface GuardInput {\n kind: AgentKind;\n toolName: string;\n filePath?: string | undefined;\n command?: string | undefined;\n cwd?: string | undefined;\n worktree?: string | null | undefined;\n // A research or plan agent's throwaway folder, where it may write, install and commit.\n sandbox?: string | null | undefined;\n // Claude Code's per-user temporary folders, where agents write their reports.\n scratchRoots: string[];\n}\n\nconst PUBLISHING = new Set(['commit', 'push', 'stash']);\n// stash list and show only read.\nconst READ_ONLY_STASH = new Set(['list', 'show']);\n\n// The real path of the longest existing prefix, since a file about to be written doesn't exist yet\n// and /tmp is a symlink on macOS.\nfunction realish(path: string): string {\n const full = resolve(path);\n const parent = dirname(full);\n try {\n return realpathSync(full);\n } catch {\n return parent === full ? full : join(realish(parent), basename(full));\n }\n}\n\nfunction inside(path: string, folder: string): boolean {\n const rest = relative(realish(folder), realish(path));\n return rest === '' || (!rest.startsWith('..') && !isAbsolute(rest));\n}\n\nfunction absolute(path: string, cwd: string | undefined): string {\n if (path === '~' || path.startsWith('~/')) return join(homedir(), path.slice(1));\n return isAbsolute(path) ? path : resolve(cwd ?? '/', path);\n}\n\nfunction inScratch(path: string, input: GuardInput): boolean {\n return input.scratchRoots.some((root) => inside(path, root));\n}\n\nfunction writable(path: string, input: GuardInput): boolean {\n return inScratch(path, input) || (!!input.sandbox && inside(path, input.sandbox));\n}\n\nfunction publishing(call: GitCall): boolean {\n return (\n PUBLISHING.has(call.verb) && !(call.verb === 'stash' && READ_ONLY_STASH.has(call.sub ?? ''))\n );\n}\n\nfunction fileToolViolation(input: GuardInput, contract: string): string | undefined {\n if (input.kind === 'implement') {\n if (!input.worktree || !input.filePath) return undefined;\n const path = absolute(input.filePath, input.cwd);\n if (inside(path, input.worktree) || inScratch(path, input)) return undefined;\n return `${contract} limits writes to its worktree ${input.worktree}`;\n }\n if (input.filePath && writable(absolute(input.filePath, input.cwd), input)) return undefined;\n return input.sandbox\n ? `${contract} limits writes to its sandbox ${input.sandbox} and the scratchpad`\n : `${contract} is read-only: write only the report in the scratchpad`;\n}\n\n// Only exact checks: file paths and git publishing. Other shell writes are left to the contract,\n// since no pattern catches them all.\nexport function guardToolCall(input: GuardInput): string | undefined {\n const contract = `the ${input.kind} contract`;\n if (FILE_TOOLS.has(input.toolName)) return fileToolViolation(input, contract);\n if (input.toolName !== 'Bash') return undefined;\n const calls = gitCalls(input.command ?? '', input.cwd).filter(publishing);\n if (calls.length === 0) return undefined;\n const sandbox = input.sandbox;\n if (!sandbox || input.kind === 'implement') {\n return `${contract} forbids git commit, push and stash: the human commits`;\n }\n if (calls.some((call) => call.verb === 'push')) return `${contract} forbids git push`;\n // A directory that can't be known can't be shown to be inside the sandbox.\n const confined = (dir: string | undefined) => dir !== undefined && inside(dir, sandbox);\n if (calls.every((call) => call.dirs.every(confined))) return undefined;\n return `${contract} allows git commit and stash only in its sandbox ${sandbox}`;\n}\n\n// Cold plugin agents may run without a Carnet row; their type names the kind.\nexport function kindOfAgentType(agentType: string | undefined): AgentKind | undefined {\n const match = /^rucher[\\w-]*:(research|review)$/.exec(agentType ?? '');\n return match?.[1] as AgentKind | undefined;\n}\n","import type { Agent, AgentKind } from './agents.ts';\n\nexport const LAUNCH_TOOLS: ReadonlySet<string> = new Set(['Agent', 'Task', 'EnterPlanMode']);\n\nexport const BUILT_IN_PLAN_DENIED =\n 'In a Rucher session a plan agent is a Rucher fork, never the built-in Plan subagent: use /rucher:start:plan (agent_start with kind plan, then Agent with subagent_type fork and the agent name as description). For a question with no change, use /rucher:start:research.';\n\nconst EXPECTED_TYPES: Readonly<Record<AgentKind, string>> = {\n research: 'fork, or the rucher research agent with --cold',\n plan: 'fork',\n implement: 'fork',\n review: 'the rucher review agent',\n};\n\nfunction fitsKind(kind: AgentKind, subagentType: string | undefined): boolean {\n const type = subagentType ?? '';\n if (kind === 'plan' || kind === 'implement') return type === 'fork';\n if (kind === 'research') return type === 'fork' || /(^|:)research$/.test(type);\n return /(^|:)review$/.test(type);\n}\n\nexport interface LaunchCall {\n toolName: string;\n subagentType?: string | undefined;\n named?: Agent | undefined;\n // A plan agent registered but not launched yet.\n pendingPlan?: Agent | undefined;\n}\n\nexport function guardLaunch(call: LaunchCall): string | undefined {\n if (call.toolName === 'EnterPlanMode') {\n const pending = call.pendingPlan;\n if (!pending) return undefined;\n return `${pending.name} is a Rucher plan agent waiting for its fork: launch it with Agent, subagent_type fork and description ${pending.name}, instead of plan mode.`;\n }\n if (call.subagentType === 'Plan') return BUILT_IN_PLAN_DENIED;\n const named = call.named;\n if (!named || fitsKind(named.kind, call.subagentType)) return undefined;\n return `${named.name} is a Rucher ${named.kind} agent: launch it with subagent_type ${EXPECTED_TYPES[named.kind]}, not ${call.subagentType ?? 'no subagent_type'}.`;\n}\n","import type { Carnet } from '../carnet.ts';\nimport { guardToolCall, kindOfAgentType } from '../guard.ts';\nimport { guardLaunch } from '../launch.ts';\nimport { repoNameFor } from '../workspace/locate.ts';\nimport type { HostToolPayload } from '../hosts/host.ts';\nimport { memoryMaxCharacters } from '../memory.ts';\nimport { memoryHalfLife } from '../notes.ts';\nimport type { HookEnv } from '../sessions.ts';\nimport type { TurnOptions } from '../turn.ts';\n\nexport function handleToolUse(\n carnet: Carnet,\n payload: HostToolPayload,\n env: HookEnv,\n options: TurnOptions = {},\n): string | undefined {\n // session_repos and the turn track the main conversation; a subagent's context is not it.\n if (payload.agent_id) return undefined;\n if (options.trackTurn ?? true) carnet.turn.start(payload.session_id);\n const repo = repoNameFor(carnet.workspace, payload.path);\n if (!repo) return undefined;\n const session = carnet.sessions.ensure(payload.session_id, payload.cwd);\n return carnet.memory.forRepo(session, repo, {\n maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),\n halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS),\n });\n}\n\nexport const WAITING_TOOL = 'AskUserQuestion';\n\n// The turn is still running, but blocked on the human's answer.\nexport function handleToolStart(carnet: Carnet, payload: HostToolPayload): void {\n if (payload.agent_id || payload.tool_name !== WAITING_TOOL) return;\n carnet.turn.wait(payload.session_id);\n}\n\nexport function guardSubagentCall(\n carnet: Carnet,\n payload: HostToolPayload,\n scratchRoots: string[],\n): string | undefined {\n if (!payload.agent_id || !payload.tool_name) return undefined;\n const agent = carnet.agents.byHostAgentId(payload.session_id, payload.agent_id);\n const kind = agent?.kind ?? kindOfAgentType(payload.agent_type);\n if (!kind) return undefined;\n return guardToolCall({\n kind,\n toolName: payload.tool_name,\n filePath: payload.file_path,\n command: payload.command,\n cwd: payload.cwd,\n worktree: agent?.worktree,\n sandbox: agent?.sandbox,\n scratchRoots,\n });\n}\n\n// The main agent's launches: the built-in Plan subagent and plan mode never stand in for a Rucher\n// plan agent, and an Agent call naming a registered agent must use that kind's subagent type.\nexport function guardMainLaunch(carnet: Carnet, payload: HostToolPayload): string | undefined {\n if (payload.agent_id || !payload.tool_name) return undefined;\n if (!carnet.sessions.get(payload.session_id)) return undefined;\n const named = carnet.agents.unpaired(payload.session_id, payload.launched_names ?? []);\n const reason = guardLaunch({\n toolName: payload.tool_name,\n subagentType: payload.subagent_type,\n named,\n pendingPlan:\n payload.tool_name === 'EnterPlanMode'\n ? carnet.agents.pendingPlan(payload.session_id)\n : undefined,\n });\n if (!reason && named && payload.tool_name !== 'EnterPlanMode') {\n carnet.agents.requestLaunch(payload.session_id, named.name);\n }\n return reason;\n}\n","import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Carnet } from '../carnet.ts';\nimport { rucherPaths } from '../paths.ts';\nimport { EMOJI, kindTag } from './model.ts';\nimport type { StatusLine, StatusView } from './view.ts';\n\nexport const STATUS_LINE_LABEL = 'rucher';\n\nconst TURN_LABELS = {\n working: '⚙️ working',\n waiting: '⏸ waiting on you',\n failed: '⚠ turn failed',\n} as const;\n\nfunction counts(lines: readonly StatusLine[]): string {\n const byEmoji = new Map<string, number>();\n for (const line of lines) byEmoji.set(line.emoji, (byEmoji.get(line.emoji) ?? 0) + 1);\n return [...byEmoji].map(([emoji, count]) => `${emoji}${count}`).join(' ');\n}\n\n// One line for Claude Code: what the main agent does, the next thing waiting on the human, then counts.\n// Bare, since Claude Code already names the plugin before a mod's line.\nexport function renderStatusLine(view: StatusView, lag: string | null = null): string {\n if (lag) return lag;\n const parts: string[] = [];\n if (view.turn) parts.push(TURN_LABELS[view.turn]);\n const [next] = view.waiting;\n if (next) {\n const action = next.action ? ` ${next.action}` : '';\n parts.push(`next: ${next.emoji} ${kindTag(next.kind)} ${next.name}${action}`);\n parts.push(counts(view.waiting));\n }\n if (view.running.length > 0) parts.push(`${EMOJI.running}${view.running.length}`);\n if (view.blocked.length > 0) parts.push(`⛓${view.blocked.length}`);\n return parts.join(' · ');\n}\n\nexport function labelStatusLine(line: string): string {\n return line ? `${STATUS_LINE_LABEL} · ${line}` : '';\n}\n\nexport function statusLinePath(sessionId: string, env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).state, 'status', `${sessionId}.txt`);\n}\n\nexport interface StatusLineOptions {\n env?: NodeJS.ProcessEnv | undefined;\n lag?: string | null | undefined;\n}\n\n// Claude Code reads this file on every refresh, so it is written once per change instead of\n// computed by a process per refresh.\nexport function writeStatusLine(\n carnet: Carnet,\n sessionId: string,\n options: StatusLineOptions = {},\n): void {\n const path = statusLinePath(sessionId, options.env);\n const session = carnet.sessions.get(sessionId);\n if (!session || session.status === 'archived') {\n rmSync(path, { force: true });\n return;\n }\n const line = renderStatusLine(carnet.status.view(session), options.lag ?? null);\n mkdirSync(join(path, '..'), { recursive: true });\n const temporary = `${path}.${process.pid}.tmp`;\n writeFileSync(temporary, line ? `${line}\\n` : '');\n renameSync(temporary, path);\n}\n"],"mappings":";;;;;;AAmBA,SAAS,MAAM,QAAgB,KAAa,GAAG,YAA8B;CAC3E,OAAO,OAAQ,OAAO,GAAG,QAAQ,GAAG,CAAC,CAAC,IAAI,GAAG,UAAU,CAAC,CAAuB,KAAK;AACtF;AAEA,SAAS,WAAW,QAAgB,SAA2B;CAC7D,OACE,OAAO,GACJ,QAAQ,sEAAsE,CAAC,CAC/E,IAAI,OAAO,CAAC,CACf,KAAK,QAAQ,IAAI,IAAI;AACzB;AAEA,SAAS,aAAa,QAAgB,WAAmB,MAA8B;CACrF,MAAM,MAAM,OAAO,GAChB,QAAQ,0DAA0D,CAAC,CACnE,IAAI,WAAW,IAAI;CACtB,OAAO,MAAM,OAAO,SAAS,QAAQ,IAAI,EAAE,IAAI;AACjD;AAIA,SAAgB,YACd,QACA,WACA,iBACA,UAAuB,CAAC,GACZ;CACZ,MAAM,UAAU,OAAO,SAAS,QAAQ,SAAS;CACjD,IAAI,QAAQ,eAAe,OAAO,WAAW,QAAQ,OACnD,MAAM,IAAI,YAAY,qBAAqB,mBAAmB,WAAW;CAE3E,IAAI,QAAQ,cAAc,iBACxB,MAAM,IAAI,YAAY,wBAAwB,0CAA0C;CAE1F,MAAM,OAAO,QAAQ,OAAO,aAAa,QAAQ,iBAAiB,QAAQ,IAAI,IAAI;CAClF,IA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d,QACA,WACA,UAA6B,CAAC,GACxB;CACN,MAAM,OAAO,eAAe,WAAW,QAAQ,GAAG;CAClD,MAAM,UAAU,OAAO,SAAS,IAAI,SAAS;CAC7C,IAAI,CAAC,WAAW,QAAQ,WAAW,YAAY;EAC7C,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;EAC5B;CACF;CACA,MAAM,OAAO,iBAAiB,OAAO,OAAO,KAAK,OAAO,GAAG,QAAQ,OAAO,IAAI;CAC9E,UAAU,KAAK,MAAM,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC/C,MAAM,YAAY,GAAG,KAAK,GAAG,QAAQ,IAAI;CACzC,cAAc,WAAW,OAAO,GAAG,KAAK,MAAM,EAAE;CAChD,WAAW,WAAW,IAAI;AAC5B"}
1
+ {"version":3,"file":"index.mjs","names":["absolute","sessionLabel"],"sources":["../src/move.ts","../src/render.ts","../src/workspace/backup.ts","../src/workspace/git-trees.ts","../src/workspace/rename.ts","../src/workspace/merge.ts","../src/hook/session-end.ts","../src/hook/session-start.ts","../src/hook/user-prompt-submit.ts","../src/launch.ts","../src/shell.ts","../src/guard.ts","../src/hook/post-tool-use.ts","../src/launch-plan.ts","../src/status/line.ts"],"sourcesContent":["import type { Carnet } from './carnet.ts';\nimport { CarnetError } from './errors.ts';\nimport { agentMergePlan } from './merge.ts';\nimport type { Session } from './sessions.ts';\n\nexport interface MoveOptions {\n merge?: boolean | undefined;\n dryRun?: boolean | undefined;\n}\n\nexport interface MoveResult {\n session: Session;\n into: Session | null;\n movedAgents: string[];\n skippedAgents: string[];\n movedEvents: number;\n movedTable: boolean;\n keptNotes: number;\n}\n\nfunction count(carnet: Carnet, sql: string, ...parameters: string[]): number {\n return Number((carnet.db.prepare(sql).get(...parameters) as { total: number }).total);\n}\n\nfunction agentNames(carnet: Carnet, session: string): string[] {\n return [\n ...new Set(\n (\n carnet.db\n .prepare('SELECT name FROM agents WHERE session = ? ORDER BY started_at, id')\n .all(session) as unknown as { name: string }[]\n ).map((row) => row.name),\n ),\n ];\n}\n\nfunction sessionNamed(carnet: Carnet, workspace: string, name: string): Session | null {\n const row = carnet.db\n .prepare('SELECT id FROM sessions WHERE workspace = ? AND name = ?')\n .get(workspace, name) as { id: string } | undefined;\n return row ? carnet.sessions.require(row.id) : null;\n}\n\n// One database holds every workspace: moving a session only changes its workspace, and its agents,\n// events and Main line follow its id. Notes stay in the workspace they were written in.\nexport function moveSession(\n carnet: Carnet,\n sessionId: string,\n targetWorkspace: string,\n options: MoveOptions = {},\n): MoveResult {\n const session = carnet.sessions.require(sessionId);\n if (session.workspace !== (carnet.workspace?.name ?? null)) {\n throw new CarnetError('SESSION_NOT_FOUND', `Unknown session ${sessionId}`);\n }\n if (session.workspace === targetWorkspace) {\n throw new CarnetError('SESSION_MOVE_INVALID', 'The session is already in this workspace');\n }\n const into = session.name ? sessionNamed(carnet, targetWorkspace, session.name) : null;\n if (into && !options.merge) {\n throw new CarnetError(\n 'SESSION_NAME_TAKEN',\n `Workspace ${targetWorkspace} already has session ${into.name}: pass --merge to merge into it`,\n );\n }\n const plan = into ? agentMergePlan(carnet.db, session.id, into.id) : undefined;\n const hasTable = (id: string) =>\n carnet.db.prepare('SELECT 1 FROM table_items WHERE session = ?').get(id) !== undefined;\n const result: MoveResult = {\n session,\n into,\n movedAgents: plan?.moved ?? agentNames(carnet, session.id),\n skippedAgents: plan?.closed.map((agent) => agent.name) ?? [],\n movedEvents: count(\n carnet,\n 'SELECT COUNT(*) AS total FROM events WHERE session = ?',\n session.id,\n ),\n movedTable: hasTable(session.id) && !(into && hasTable(into.id)),\n keptNotes: count(\n carnet,\n 'SELECT COUNT(*) AS total FROM notes WHERE session = ? OR dropped_session = ?',\n session.id,\n session.id,\n ),\n };\n if (options.dryRun) return result;\n if (into) carnet.sessions.merge(session.id, into.id);\n carnet.db\n .prepare('UPDATE sessions SET workspace = ? WHERE id = ?')\n .run(targetWorkspace, session.id);\n return result;\n}\n","import { mkdirSync } from 'node:fs';\nimport {\n AGENTS_FILE,\n INSTRUCTIONS_FILE,\n migrateInstructions,\n type Workspace,\n workspaceHosts,\n} from './workspace/workspace.ts';\nimport { hostById } from './hosts/host.ts';\nimport { reportsDirectory } from './paths.ts';\n\nexport interface RenderResult {\n runDirectory: string;\n written: string[];\n removed: string[];\n // Changes to the definition itself, for the human to see.\n notices: string[];\n}\n\nexport interface RunDirectoryRenderOptions {\n env?: NodeJS.ProcessEnv | undefined;\n host?: string | undefined;\n}\n\nexport function renderRunDirectory(\n workspace: Workspace,\n options: RunDirectoryRenderOptions = {},\n): RenderResult {\n mkdirSync(workspace.runDirectory, { recursive: true });\n mkdirSync(reportsDirectory(workspace), { recursive: true });\n const result: RenderResult = {\n runDirectory: workspace.runDirectory,\n written: [],\n removed: [],\n notices: [],\n };\n if (migrateInstructions(workspace)) {\n result.notices.push(\n `renamed ${INSTRUCTIONS_FILE} to ${AGENTS_FILE} in the definition of ${workspace.name}`,\n );\n }\n for (const id of options.host ? [options.host] : workspaceHosts(workspace)) {\n const rendered = hostById(id).renderRunDirectory(workspace);\n result.written.push(...rendered.written);\n result.removed.push(...rendered.removed);\n }\n return result;\n}\n","import { mkdirSync, writeFileSync } from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { join } from 'node:path';\nimport { rucherPaths } from '../paths.ts';\n\nexport function backupsDirectory(env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).state, 'backups');\n}\n\nexport function backupFolder(\n operation: string,\n name: string,\n at: Date,\n env?: NodeJS.ProcessEnv,\n): string {\n const stamp = at\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.\\d+Z$/, 'Z');\n return join(backupsDirectory(env), `${stamp}-${operation}-${name}`);\n}\n\nexport function writeBackup(db: DatabaseSync, folder: string, plan: unknown): void {\n mkdirSync(folder, { recursive: true });\n db.prepare('VACUUM INTO ?').run(join(folder, 'carnet.db'));\n writeFileSync(join(folder, 'plan.json'), `${JSON.stringify(plan, null, 2)}\\n`);\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, lstatSync, readdirSync, readFileSync, renameSync } from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { shellQuote, type UndoList } from './undo.ts';\n\nexport type GitTreeKind = 'worktree' | 'orphan' | 'clone';\n\nexport interface GitTree {\n path: string;\n kind: GitTreeKind;\n // The repo a linked worktree belongs to.\n repo?: string | undefined;\n}\n\nexport interface GitTreeHolder {\n session: string;\n name: string;\n}\n\nexport interface TreeMove extends GitTree {\n to: string;\n holders: GitTreeHolder[];\n}\n\nfunction adminFolder(tree: string): string | undefined {\n const match = /^gitdir:\\s*(.+)$/m.exec(readFileSync(join(tree, '.git'), 'utf8'));\n if (!match?.[1]) return undefined;\n const admin = match[1].trim();\n return isAbsolute(admin) ? admin : resolve(tree, admin);\n}\n\nfunction classify(tree: string): GitTree {\n if (lstatSync(join(tree, '.git')).isDirectory()) return { path: tree, kind: 'clone' };\n const admin = adminFolder(tree);\n if (!admin || !existsSync(admin)) return { path: tree, kind: 'orphan' };\n const common = join(admin, 'commondir');\n const gitDirectory = existsSync(common)\n ? resolve(admin, readFileSync(common, 'utf8').trim())\n : dirname(dirname(admin));\n return { path: tree, kind: 'worktree', repo: dirname(gitDirectory) };\n}\n\n// A folder holding a .git entry moves as one unit: its files are never listed one by one.\nexport function findGitTrees(root: string, skip: readonly string[] = []): GitTree[] {\n const trees: GitTree[] = [];\n const visit = (folder: string) => {\n if (!existsSync(folder)) return;\n for (const name of readdirSync(folder).sort()) {\n const path = join(folder, name);\n if (skip.includes(relative(root, path))) continue;\n if (!lstatSync(path).isDirectory()) continue;\n if (existsSync(join(path, '.git'))) trees.push(classify(path));\n else visit(path);\n }\n };\n visit(root);\n return trees;\n}\n\nexport function treeHolders(db: DatabaseSync, path: string): GitTreeHolder[] {\n return db\n .prepare(\n `SELECT session, name FROM agents WHERE status != 'closed' AND worktree = ?\n ORDER BY session, name`,\n )\n .all(path) as unknown as GitTreeHolder[];\n}\n\nexport function repairWorktree(path: string): void {\n try {\n execFileSync('git', ['-C', path, 'worktree', 'repair'], { stdio: 'pipe', timeout: 30_000 });\n } catch (error) {\n const stderr = (error as { stderr?: Buffer }).stderr?.toString().trim();\n throw new CarnetError(\n 'WORKSPACE_RELOCATE_FAILED',\n `git worktree repair failed in ${path}${stderr ? `: ${stderr}` : ''}`,\n );\n }\n}\n\nfunction repairCommand(path: string): string {\n return `git -C ${shellQuote(path)} worktree repair`;\n}\n\n// The repo's admin folder names the worktree by absolute path, so a moved worktree is repaired\n// from its new place, and undone by moving back then repairing there.\nexport function moveWithTrees(\n undo: UndoList,\n move: { from: string; to: string },\n trees: readonly GitTree[],\n): void {\n const linked = trees.filter((tree) => tree.kind === 'worktree');\n const at = (base: string, tree: GitTree) => join(base, relative(move.from, tree.path));\n renameSync(move.from, move.to);\n undo.push({\n command: [\n `mv ${shellQuote(move.to)} ${shellQuote(move.from)}`,\n ...linked.map((tree) => repairCommand(tree.path)),\n ].join(' && '),\n run: () => {\n renameSync(move.to, move.from);\n for (const tree of linked) repairWorktree(tree.path);\n },\n });\n for (const tree of linked) repairWorktree(at(move.to, tree));\n}\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { join, relative } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { hostById } from '../hosts/host.ts';\nimport { defaultRunDirectory, workspaceDefinition } from '../paths.ts';\nimport { renderRunDirectory } from '../render.ts';\nimport {\n realPathOf,\n renameWorkspaceRows,\n runningWorkspaceSessions,\n workspaceRowCounts,\n type RunningSessionRow,\n type WorkspaceRowCounts,\n} from '../workspace-rows.ts';\nimport { backupFolder, writeBackup } from './backup.ts';\nimport { findGitTrees, moveWithTrees, treeHolders, type TreeMove } from './git-trees.ts';\nimport { moveTracked, relocateFailed, UndoList } from './undo.ts';\nimport {\n isWorkspaceName,\n loadWorkspace,\n serializeWorkspaceFile,\n WORKSPACE_FILE,\n type WorkspaceFile,\n workspaceExists,\n workspaceHosts,\n} from './workspace.ts';\n\nexport interface RenameWorkspaceOptions {\n env?: NodeJS.ProcessEnv | undefined;\n dryRun?: boolean | undefined;\n isAlive: (processId: number) => boolean;\n now?: (() => Date) | undefined;\n}\n\nexport interface FolderMove {\n what: string;\n from: string;\n to: string;\n}\n\nexport interface RenamePlan {\n from: string;\n to: string;\n moves: FolderMove[];\n // Git trees inside the run directory, which move with it.\n trees: TreeMove[];\n rows: WorkspaceRowCounts;\n running: RunningSessionRow[];\n}\n\nexport interface RenameResult extends RenamePlan {\n backup: string;\n paths: number;\n trustMoved: boolean;\n warnings: string[];\n}\n\nfunction requireFree(db: DatabaseSync, name: string, env: NodeJS.ProcessEnv): void {\n const rows = workspaceRowCounts(db, name);\n const taken = [\n workspaceExists(name, env) ? 'a definition' : null,\n existsSync(workspaceDefinition(name, env)) && !workspaceExists(name, env)\n ? 'a definition folder'\n : null,\n existsSync(defaultRunDirectory(name, env)) ? 'a run directory' : null,\n rows.sessions + rows.notes + rows.activeDays > 0 ? 'sessions or notes kept after a drop' : null,\n ].filter((reason): reason is string => reason !== null);\n if (taken.length) {\n throw new CarnetError(\n 'WORKSPACE_EXISTS',\n `Workspace ${name} already has ${taken.join(', ')}: pick another name`,\n );\n }\n}\n\nexport function planWorkspaceRename(\n db: DatabaseSync,\n from: string,\n to: string,\n options: RenameWorkspaceOptions,\n): RenamePlan {\n const env = options.env ?? process.env;\n if (!isWorkspaceName(to)) {\n throw new CarnetError(\n 'WORKSPACE_NAME_INVALID',\n `Invalid workspace name ${JSON.stringify(to)}: use lowercase letters, digits and dashes`,\n );\n }\n const workspace = loadWorkspace(from, env);\n if (from === to) {\n throw new CarnetError('WORKSPACE_EXISTS', `Workspace ${from} already has this name`);\n }\n requireFree(db, to, env);\n const moves: FolderMove[] = [\n { what: 'definition', from: workspace.definition, to: workspaceDefinition(to, env) },\n ];\n const runDirectory = defaultRunDirectory(to, env);\n if (existsSync(workspace.runDirectory)) {\n moves.push({ what: 'run directory', from: workspace.runDirectory, to: runDirectory });\n }\n const trees = findGitTrees(workspace.runDirectory).map((tree) => ({\n ...tree,\n to: join(runDirectory, relative(workspace.runDirectory, tree.path)),\n holders: treeHolders(db, tree.path),\n }));\n return {\n from,\n to,\n moves,\n trees,\n rows: workspaceRowCounts(db, from),\n running: runningWorkspaceSessions(db, from).filter((row) => options.isAlive(row.hostPid)),\n };\n}\n\nfunction rewriteName(definition: string, name: string): void {\n const file = join(definition, WORKSPACE_FILE);\n const content = JSON.parse(readFileSync(file, 'utf8')) as WorkspaceFile;\n if (!('name' in content)) return;\n writeFileSync(file, serializeWorkspaceFile({ ...content, name }));\n}\n\n// The folders move first and the database last: a failure undoes the moves, the database never changed.\nexport function renameWorkspace(\n db: DatabaseSync,\n from: string,\n to: string,\n options: RenameWorkspaceOptions,\n): RenamePlan | RenameResult {\n const env = options.env ?? process.env;\n const plan = planWorkspaceRename(db, from, to, options);\n if (options.dryRun) return plan;\n if (plan.running.length) {\n throw new CarnetError(\n 'WORKSPACE_BUSY',\n `${plan.running.length} session${plan.running.length === 1 ? '' : 's'} of ${from} still running: ${plan.running.map((row) => row.name ?? row.id.slice(0, 8)).join(', ')}`,\n );\n }\n const workspace = loadWorkspace(from, env);\n const runDirectories = { from: workspace.runDirectory, to: defaultRunDirectory(to, env) };\n const backup = backupFolder('rename', from, (options.now ?? (() => new Date()))(), env);\n writeBackup(db, backup, plan);\n const hosts = workspaceHosts(workspace).map((id) => hostById(id));\n const undo = new UndoList();\n let paths = 0;\n const realFrom = realPathOf(runDirectories.from);\n try {\n for (const move of plan.moves) {\n if (move.what === 'run directory') moveWithTrees(undo, move, plan.trees);\n else moveTracked(undo, move);\n }\n rewriteName(workspaceDefinition(to, env), to);\n for (const host of hosts) {\n const relocation = host.relocateProject?.(runDirectories.from, runDirectories.to, env);\n if (!relocation) continue;\n for (const moved of relocation.moves) {\n plan.moves.push({ what: `${host.displayName} project folder`, ...moved });\n }\n for (const step of relocation.undo) undo.push(step);\n }\n paths = renameWorkspaceRows(db, { from, to }, runDirectories, realFrom).paths;\n } catch (error) {\n relocateFailed(error, undo, backup);\n }\n const warnings: string[] = [];\n let trustMoved = false;\n for (const host of hosts) {\n try {\n trustMoved = host.moveTrust?.(runDirectories.from, runDirectories.to, env) || trustMoved;\n } catch (error) {\n warnings.push(`${host.displayName} trust entry not moved: ${(error as Error).message}`);\n }\n }\n try {\n renderRunDirectory(loadWorkspace(to, env), { env });\n } catch (error) {\n warnings.push(`run directory not synced: ${(error as Error).message}`);\n }\n return { ...plan, backup, paths, trustMoved, warnings };\n}\n","import {\n cpSync,\n existsSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { basename, dirname, join, relative } from 'node:path';\nimport { isLeaf } from '../config/schema.ts';\nimport { CarnetError } from '../errors.ts';\nimport { hostById } from '../hosts/host.ts';\nimport { renderRunDirectory } from '../render.ts';\nimport { GENERATED_MARKER, mergeSettings } from '../run-directory-files.ts';\nimport {\n mergeWorkspaceRows,\n realPathOf,\n nextNoteNumber,\n runningWorkspaceSessions,\n workspaceRowCounts,\n type RunningSessionRow,\n type WorkspaceRowCounts,\n} from '../workspace-rows.ts';\nimport { backupFolder, writeBackup } from './backup.ts';\nimport { findGitTrees, moveWithTrees, treeHolders, type TreeMove } from './git-trees.ts';\nimport { moveTracked, relocateFailed, UndoList } from './undo.ts';\nimport {\n AGENTS_FILE,\n definitionInstructions,\n loadWorkspace,\n migrateInstructions,\n repoInstructionFiles,\n repoInstructionsPath,\n type Workspace,\n WORKSPACE_FILE,\n type WorkspaceFile,\n workspaceFileHosts,\n workspaceHosts,\n serializeWorkspaceFile,\n} from './workspace.ts';\n\nexport interface MergeWorkspacesOptions {\n env?: NodeJS.ProcessEnv | undefined;\n isAlive: (processId: number) => boolean;\n now?: (() => Date) | undefined;\n}\n\nexport interface FileMove {\n from: string;\n to: string;\n}\n\nexport interface MergePlan {\n from: string;\n into: string;\n rows: WorkspaceRowCounts;\n // from's notes are shifted to start at firstNumber in into, keeping their order.\n firstNumber: number;\n lastNumber: number;\n running: RunningSessionRow[];\n reposAdded: string[];\n reposRenamed: [string, string][];\n settingsConflicts: string[];\n reports: FileMove[];\n sandboxes: FileMove[];\n trees: TreeMove[];\n files: FileMove[];\n // from's instruction file, appended to into's AGENTS.md.\n instructions: string;\n repoInstructions: FileMove[];\n}\n\nexport interface MergeResult extends MergePlan {\n backup: string;\n projectMoves: number;\n trustDropped: boolean;\n instructionsPath: string;\n warnings: string[];\n}\n\nconst BACKENDS_NOTES = join('backends', 'claude.md');\nconst REPORT_FAMILY = /(\\.plan\\.md|\\.research\\.md|\\.md)$/;\n\nfunction readFile(workspace: Workspace): WorkspaceFile {\n return JSON.parse(\n readFileSync(join(workspace.definition, WORKSPACE_FILE), 'utf8'),\n ) as WorkspaceFile;\n}\n\nfunction entries(folder: string): string[] {\n return existsSync(folder) ? readdirSync(folder).sort() : [];\n}\n\nfunction busy(db: DatabaseSync, names: string[], isAlive: MergeWorkspacesOptions['isAlive']) {\n return names.flatMap((name) =>\n runningWorkspaceSessions(db, name).filter((row) => isAlive(row.hostPid)),\n );\n}\n\nfunction sessionNameConflicts(db: DatabaseSync, from: string, into: string): string[] {\n return (\n db\n .prepare(\n `SELECT name FROM sessions WHERE workspace = ? AND name IS NOT NULL\n AND name IN (SELECT name FROM sessions WHERE workspace = ? AND name IS NOT NULL)\n ORDER BY name`,\n )\n .all(from, into) as { name: string }[]\n ).map((row) => row.name);\n}\n\nfunction repoPlan(from: Workspace, into: Workspace) {\n const added: string[] = [];\n const renamed: [string, string][] = [];\n for (const repo of from.repos) {\n const samePath = into.repos.find((existing) => existing.path === repo.path);\n if (samePath) {\n if (samePath.name !== repo.name) renamed.push([repo.name, samePath.name]);\n continue;\n }\n if (into.repos.some((existing) => existing.name === repo.name)) {\n throw new CarnetError(\n 'REPO_NAME_TAKEN',\n `${into.name} already has a repo named ${repo.name} at another path than ${repo.path}: rename one of them first`,\n );\n }\n added.push(repo.path);\n }\n return { added, renamed };\n}\n\nfunction conflicts(base: unknown, extra: unknown, path: string[] = []): string[] {\n const isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n if (isObject(base) && isObject(extra)) {\n return Object.keys(extra).flatMap((key) =>\n key in base ? conflicts(base[key], extra[key], [...path, key]) : [],\n );\n }\n if (Array.isArray(base) && Array.isArray(extra)) return [];\n return JSON.stringify(base) === JSON.stringify(extra) ? [] : [path.join('.')];\n}\n\n// An older backends key compares and merges as hosts.\nfunction settingsOf(file: WorkspaceFile): Record<string, unknown> {\n const { name: _name, repos: _repos, backends: _backends, ...rest } = file;\n const hosts = workspaceFileHosts(file);\n return Object.keys(hosts).length ? { ...rest, hosts } : rest;\n}\n\n// A report and the plan or research it kept travel together, so keptReportPath still finds them.\nfunction reportMoves(from: Workspace, into: Workspace): FileMove[] {\n const source = join(from.runDirectory, 'reports');\n const target = join(into.runDirectory, 'reports');\n const families = new Map<string, string[]>();\n for (const file of entries(source)) {\n const family = file.replace(REPORT_FAMILY, '');\n families.set(family, [...(families.get(family) ?? []), file]);\n }\n return [...families].flatMap(([family, files]) => {\n const taken = files.some((file) => existsSync(join(target, file)));\n return files.map((file) => ({\n from: join(source, file),\n to: join(target, taken ? `${from.name}-${family}${file.slice(family.length)}` : file),\n }));\n });\n}\n\nfunction sandboxMoves(from: Workspace, into: Workspace): FileMove[] {\n const source = join(from.runDirectory, 'sandboxes');\n const target = join(into.runDirectory, 'sandboxes');\n return entries(source).map((name) => ({\n from: join(source, name),\n to: join(target, existsSync(join(target, name)) ? `${from.name}-${name}` : name),\n }));\n}\n\nfunction generated(path: string): boolean {\n if (!lstatSync(path).isFile()) return false;\n return readFileSync(path, 'utf8').includes(GENERATED_MARKER);\n}\n\nconst OWN_FOLDERS = ['reports', 'sandboxes'];\n\n// A git tree keeps its place (where worktrees are looked for), with the from- prefix if taken.\nfunction treeMoves(db: DatabaseSync, from: Workspace, into: Workspace): TreeMove[] {\n return findGitTrees(from.runDirectory, OWN_FOLDERS).map((tree) => {\n const rest = relative(from.runDirectory, tree.path);\n const target = join(into.runDirectory, rest);\n return {\n ...tree,\n to: existsSync(target) ? join(dirname(target), `${from.name}-${basename(target)}`) : target,\n holders: treeHolders(db, tree.path),\n };\n });\n}\n\n// Hand-written files of the run directory; the generated ones are rendered again for into.\nfunction fileMoves(from: Workspace, into: Workspace, trees: readonly TreeMove[]): FileMove[] {\n const moves: FileMove[] = [];\n const treePaths = new Set(trees.map((tree) => tree.path));\n const visit = (folder: string) => {\n for (const name of entries(folder)) {\n const path = join(folder, name);\n const rest = relative(from.runDirectory, path);\n if (OWN_FOLDERS.includes(rest) || treePaths.has(path)) continue;\n if (lstatSync(path).isDirectory()) {\n visit(path);\n continue;\n }\n if (generated(path)) continue;\n const target = join(into.runDirectory, rest);\n moves.push({\n from: path,\n to: existsSync(target) ? join(into.runDirectory, `merged-${from.name}`, rest) : target,\n });\n }\n };\n visit(from.runDirectory);\n return moves;\n}\n\nexport function planWorkspaceMerge(\n db: DatabaseSync,\n fromName: string,\n intoName: string,\n options: MergeWorkspacesOptions,\n): MergePlan {\n const env = options.env ?? process.env;\n if (fromName === intoName) {\n throw new CarnetError('WORKSPACE_EXISTS', 'Cannot merge a workspace into itself');\n }\n const from = loadWorkspace(fromName, env);\n const into = loadWorkspace(intoName, env);\n const names = sessionNameConflicts(db, fromName, intoName);\n if (names.length) {\n throw new CarnetError(\n 'SESSION_NAME_TAKEN',\n `${intoName} already has sessions named ${names.join(', ')}: rename them in ${fromName} first (rucher sessions rename <name> <new> --ws ${fromName})`,\n );\n }\n const repos = repoPlan(from, into);\n const instructions = definitionInstructions(from);\n definitionInstructions(into);\n const rows = workspaceRowCounts(db, fromName);\n const firstNumber = nextNoteNumber(db, intoName);\n const trees = treeMoves(db, from, into);\n const top = db\n .prepare('SELECT COALESCE(MAX(number), 0) AS top FROM notes WHERE workspace = ?')\n .get(fromName) as { top: number };\n return {\n from: fromName,\n into: intoName,\n rows,\n firstNumber,\n lastNumber: firstNumber - 1 + Number(top.top),\n running: busy(db, [fromName, intoName], options.isAlive),\n reposAdded: repos.added,\n reposRenamed: repos.renamed,\n settingsConflicts: conflicts(settingsOf(readFile(into)), settingsOf(readFile(from))),\n reports: reportMoves(from, into),\n sandboxes: sandboxMoves(from, into),\n trees,\n files: fileMoves(from, into, trees),\n instructions,\n repoInstructions: repoInstructionMoves(from, into, repos.renamed),\n };\n}\n\n// A repo both workspaces hold under different names takes into's name, like in the notes.\nfunction repoInstructionMoves(\n from: Workspace,\n into: Workspace,\n renamed: readonly [string, string][],\n): FileMove[] {\n const names = new Map(renamed);\n return repoInstructionFiles(from).map((file) => ({\n from: file.path,\n to: repoInstructionsPath(into, names.get(file.repo) ?? file.repo),\n }));\n}\n\nfunction appendUnder(target: string, source: string, heading: string): void {\n if (!existsSync(source)) return;\n const added = readFileSync(source, 'utf8').trim();\n if (!added) return;\n mkdirSync(dirname(target), { recursive: true });\n const current = existsSync(target) ? readFileSync(target, 'utf8').trimEnd() : '';\n writeFileSync(target, `${current ? `${current}\\n\\n` : ''}${heading}\\n\\n${added}\\n`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// Flatten lets run.kinds win over run.<kind>. Both files are written as kinds first, so the\n// destination leaf is the only one merge can keep.\nfunction normalizeRun(settings: Record<string, unknown>): Record<string, unknown> {\n const run = settings.run;\n if (!isRecord(run)) return settings;\n const { default: fallback, kinds, ...shorthand } = run;\n const named = isRecord(kinds) ? kinds : {};\n const mergedKinds = { ...shorthand, ...named };\n const next: Record<string, unknown> = {};\n if (fallback !== undefined) next.default = fallback;\n if (Object.keys(mergedKinds).length > 0) next.kinds = mergedKinds;\n return { ...settings, run: next };\n}\n\nfunction writeDefinition(from: Workspace, into: Workspace, plan: MergePlan): void {\n const fromFile = readFile(from);\n const intoFile = readFile(into);\n const merged: WorkspaceFile = {\n ...mergeSettings(\n normalizeRun(settingsOf(fromFile)),\n normalizeRun(settingsOf(intoFile)),\n isLeaf,\n ),\n name: into.name,\n repos: [\n ...(intoFile.repos ?? []),\n // loadWorkspace resolves the repos in file order.\n ...(fromFile.repos ?? []).filter((_, index) =>\n plan.reposAdded.includes(from.repos[index]?.path ?? ''),\n ),\n ],\n };\n writeFileSync(join(into.definition, WORKSPACE_FILE), serializeWorkspaceFile(merged));\n const heading = `## Ex-workspace ${from.name}`;\n migrateInstructions(into);\n appendUnder(\n join(into.definition, AGENTS_FILE),\n join(from.definition, plan.instructions),\n heading,\n );\n for (const move of plan.repoInstructions) appendUnder(move.to, move.from, heading);\n appendUnder(\n join(into.definition, BACKENDS_NOTES),\n join(from.definition, BACKENDS_NOTES),\n heading,\n );\n}\n\nfunction moveAway(from: string, to: string): void {\n if (!existsSync(from)) return;\n mkdirSync(dirname(to), { recursive: true });\n try {\n renameSync(from, to);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;\n cpSync(from, to, { recursive: true });\n rmSync(from, { recursive: true, force: true });\n }\n}\n\n// Files move first and the database last: a failure undoes the moves, the database never changed.\n// The definition is rewritten only after the commit, from the plan the human saw.\nexport function mergeWorkspaces(\n db: DatabaseSync,\n fromName: string,\n intoName: string,\n options: MergeWorkspacesOptions,\n): MergeResult {\n const env = options.env ?? process.env;\n const plan = planWorkspaceMerge(db, fromName, intoName, options);\n if (plan.running.length) {\n throw new CarnetError(\n 'WORKSPACE_BUSY',\n `${plan.running.length} session${plan.running.length === 1 ? '' : 's'} still running in ${fromName} or ${intoName}: ${plan.running.map((row) => row.name ?? row.id.slice(0, 8)).join(', ')}`,\n );\n }\n const from = loadWorkspace(fromName, env);\n const into = loadWorkspace(intoName, env);\n const backup = backupFolder('merge', fromName, (options.now ?? (() => new Date()))(), env);\n writeBackup(db, backup, plan);\n const hosts = workspaceHosts(from).map((id) => hostById(id));\n const undo = new UndoList();\n let projectMoves = 0;\n const realFrom = realPathOf(from.runDirectory);\n try {\n for (const host of hosts) {\n const relocation = host.relocateProject?.(from.runDirectory, into.runDirectory, env, 'merge');\n if (!relocation) continue;\n projectMoves += relocation.moves.length;\n for (const step of relocation.undo) undo.push(step);\n }\n for (const tree of plan.trees) {\n mkdirSync(dirname(tree.to), { recursive: true });\n moveWithTrees(undo, { from: tree.path, to: tree.to }, [tree]);\n }\n for (const move of [...plan.reports, ...plan.sandboxes, ...plan.files]) {\n mkdirSync(dirname(move.to), { recursive: true });\n moveTracked(undo, move);\n }\n const renamed = new Map(\n [\n ...plan.reports,\n ...plan.sandboxes,\n ...plan.trees.map((tree) => ({ ...tree, from: tree.path })),\n ]\n .filter(\n (move) => move.to !== join(into.runDirectory, relative(from.runDirectory, move.from)),\n )\n .map((move) => [move.from, move.to]),\n );\n mergeWorkspaceRows(db, {\n names: { from: fromName, into: intoName },\n runDirectories: { from: from.runDirectory, into: into.runDirectory },\n paths: renamed,\n repos: new Map(plan.reposRenamed),\n realFrom,\n });\n } catch (error) {\n relocateFailed(error, undo, backup);\n }\n const warnings: string[] = [];\n const attempt = (what: string, run: () => void) => {\n try {\n run();\n } catch (error) {\n warnings.push(`${what}: ${(error as Error).message}`);\n }\n };\n attempt('definition not merged', () => writeDefinition(from, into, plan));\n attempt('definition of the merged workspace not moved to the backup', () => {\n moveAway(from.definition, join(backup, 'definition'));\n moveAway(from.runDirectory, join(backup, 'run-directory'));\n });\n let trustDropped = false;\n for (const host of hosts) {\n attempt(`${host.displayName} trust entry not dropped`, () => {\n trustDropped = host.moveTrust?.(from.runDirectory, null, env) || trustDropped;\n });\n }\n attempt('run directory not synced', () => {\n renderRunDirectory(loadWorkspace(intoName, env), { env });\n });\n return {\n ...plan,\n backup,\n projectMoves,\n trustDropped,\n instructionsPath: join(into.definition, AGENTS_FILE),\n warnings,\n };\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { HostSessionEndPayload, HostStopPayload } from '../hosts/host.ts';\nimport type { Session } from '../sessions.ts';\n\nexport function handleSessionEnd(\n carnet: Carnet,\n payload: HostSessionEndPayload,\n): Session | undefined {\n if (!carnet.sessions.get(payload.session_id)) return undefined;\n carnet.turn.end(payload.session_id);\n return carnet.sessions.end(payload.session_id);\n}\n\n// A failed turn stays visible until the next one starts, so the human sees it went wrong.\nexport function handleStop(carnet: Carnet, payload: HostStopPayload): void {\n if (payload.failed) carnet.turn.fail(payload.session_id);\n else carnet.turn.end(payload.session_id);\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { SessionEventType } from '../events.ts';\nimport {\n compactReminder,\n outsideRucherContext,\n OUTSIDE_RUCHER_NOTICE,\n RULES_UPDATED_NOTICE,\n rulesVersion,\n} from '../prompt/prompt.ts';\nimport { hostById } from '../hosts/host.ts';\nimport { memoryMaxCharacters } from '../memory.ts';\nimport { memoryHalfLife } from '../notes.ts';\nimport { purgeDays } from '../purge.ts';\nimport { resumeSummary } from '../resume.ts';\nimport { type Reference, referenceLine } from '../references.ts';\nimport type { HookEnv, HookSessionPayload, Session } from '../sessions.ts';\n\nexport interface SessionStartResult {\n session: Session;\n additionalContext?: string;\n contextParts: string[];\n notices: string[];\n}\n\nconst SOURCE_EVENTS: Readonly<Record<string, SessionEventType>> = {\n startup: 'session.started',\n resume: 'session.resumed',\n fork: 'session.forked',\n};\n\n// A fork gets a new id from the host; the launcher's env still carries the parent's.\nfunction adoptFork(carnet: Carnet, session: Session, env: HookEnv): Session {\n const parentId = env.RUCHER_SESSION_ID;\n if (!parentId || parentId === session.id || !carnet.sessions.get(parentId)) return session;\n let fork = carnet.sessions.setParent(session.id, parentId);\n const kind = env.RUCHER_SESSION_KIND;\n if (kind === 'active' || kind === 'temp') {\n fork = carnet.sessions.setKind(session.id, kind, env.RUCHER_SESSION_NAME || null);\n }\n return fork;\n}\n\n// Claude Code carrying the conversation on under a new id is the same session, not a fork:\n// the new id takes the parent's name, agents, Main line and journal.\nfunction adoptContinuation(carnet: Carnet, session: Session, env: HookEnv): Session | undefined {\n const parentId = env.RUCHER_SESSION_ID;\n const parent = parentId && parentId !== session.id ? carnet.sessions.get(parentId) : undefined;\n if (!parent) return undefined;\n const hostEnv = env.CLAUDE_CONFIG_DIR ? { CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR } : {};\n const launch = hostById(session.host).launch;\n if (!launch?.continues(parent, session.id, hostEnv)) return undefined;\n let merged = carnet.sessions.merge(parent.id, session.id).session;\n merged = carnet.sessions.recordPromptVersion(merged.id, parent.promptVersion);\n return parent.parentId ? carnet.sessions.setParent(merged.id, parent.parentId) : merged;\n}\n\n// A fork inherits its parent's conversation, notes included; a resumed transcript still holds them.\nfunction startMemory(\n carnet: Carnet,\n session: Session,\n source: string,\n env: HookEnv,\n): string | undefined {\n const options = {\n maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),\n halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS),\n };\n if (source === 'startup' || source === 'clear' || source === 'compact') {\n return carnet.memory.atStart(session, options);\n }\n return undefined;\n}\n\nexport function invalidConfigNotice(problem: string): string {\n return `rucher: workspace config ignored, cold agents refused until it is fixed (rucher config check): ${problem}`;\n}\n\nconst LISTED_REFERENCES = 10;\n\n// The documents are a hint; the resume line, notes and notices must still reach the session.\nfunction listedReferences(carnet: Carnet, session: string): Reference[] {\n try {\n return carnet.references.list(session);\n } catch {\n return [];\n }\n}\n\nfunction referencesContext(carnet: Carnet, session: string): string | undefined {\n const references = listedReferences(carnet, session);\n if (!references.length) return undefined;\n const more = references.length > LISTED_REFERENCES ? ', ref_list for the rest' : '';\n return [\n `Reference documents of this session (${references.length}${more}), read them when the work needs them:`,\n ...references.slice(0, LISTED_REFERENCES).map((reference) => ` ${referenceLine(reference)}`),\n ].join('\\n');\n}\n\nexport function handleSessionStart(\n carnet: Carnet,\n payload: HookSessionPayload,\n env: HookEnv,\n): SessionStartResult {\n let session = carnet.sessions.upsertFromHook(payload, env);\n let source = payload.source ?? '';\n if (source === 'fork') {\n const continued = adoptContinuation(carnet, session, env);\n if (continued) {\n session = continued;\n source = 'resume';\n } else {\n session = adoptFork(carnet, session, env);\n }\n }\n const event = SOURCE_EVENTS[source];\n if (event) carnet.events.log(session.id, { type: event });\n session = carnet.sessions.setStatus(session.id, 'running');\n // A compaction happens inside a turn; any other start follows a turn that may have died unseen.\n if (source !== 'compact') carnet.turn.end(session.id);\n carnet.sessions.purge(session.id, purgeDays(env.RUCHER_PURGE_DAYS));\n\n const promptEnv = { RUCHER_HOME: env.RUCHER_HOME };\n const launchedVersion = env.RUCHER_PROMPT_VERSION || null;\n const contextParts: string[] = [];\n const notices: string[] = [];\n if (hostById(session.host).hooks?.rendersSystemPrompt(source)) {\n session = carnet.sessions.recordPromptVersion(session.id, launchedVersion);\n }\n if (source === 'resume') contextParts.push(resumeSummary(carnet, session));\n const memory = startMemory(carnet, session, source, env);\n if (memory) contextParts.push(memory);\n const references = referencesContext(carnet, session.id);\n if (references) contextParts.push(references);\n if (source === 'compact' && !launchedVersion) {\n contextParts.push(compactReminder(carnet.workspace, promptEnv));\n } else if (!env.RUCHER_SESSION_ID && !session.promptVersion) {\n contextParts.push(outsideRucherContext(carnet.workspace, promptEnv));\n notices.push(OUTSIDE_RUCHER_NOTICE);\n } else if (\n session.promptVersion &&\n session.promptVersion !== rulesVersion(carnet.workspace, promptEnv)\n ) {\n notices.push(RULES_UPDATED_NOTICE);\n }\n const configProblem = carnet.workspace?.configProblem;\n if (configProblem) notices.push(invalidConfigNotice(configProblem));\n const additionalContext = contextParts.length ? contextParts.join('\\n\\n') : undefined;\n return { session, contextParts, notices, ...(additionalContext ? { additionalContext } : {}) };\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { HookHost, HostPromptPayload } from '../hosts/host.ts';\nimport type { Session } from '../sessions.ts';\nimport type { TurnOptions } from '../turn.ts';\n\nexport function handleUserPromptSubmit(\n carnet: Carnet,\n host: HookHost,\n payload: HostPromptPayload,\n options: TurnOptions = {},\n): Session {\n carnet.sessions.ensure(payload.session_id, payload.cwd);\n if (options.trackTurn ?? true) carnet.turn.start(payload.session_id);\n carnet.notes.recordActiveDay();\n return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));\n}\n","import type { Agent, AgentKind } from './agents.ts';\nimport type { Verdict } from './guard.ts';\n\nexport const LAUNCH_TOOLS: ReadonlySet<string> = new Set(['Agent', 'Task', 'EnterPlanMode']);\n\nexport const BUILT_IN_PLAN_DENIED =\n 'In a Rucher session a plan agent is a Rucher fork, never the built-in Plan subagent: use /rucher:start:plan (agent_start with kind plan, then Agent with subagent_type fork and the agent name as description). For a question with no change, use /rucher:start:research.';\n\nconst EXPECTED_TYPES: Readonly<Record<AgentKind, string>> = {\n research: 'fork, or the rucher research agent with --cold',\n plan: 'fork, or the rucher plan agent with --cold',\n implement: 'fork, or the rucher implement agent with --cold',\n review: 'the rucher review agent',\n};\n\n// The mode chosen at agent_start must be the one launched: a cold agent has its brief, not the\n// conversation, and a fork has no brief.\nfunction fitsKind(agent: Agent, subagentType: string | undefined): boolean {\n const type = subagentType ?? '';\n const cold = new RegExp(`(^|:)${agent.kind}$`).test(type);\n if (agent.kind === 'review') return cold;\n if (agent.context === 'cold') return cold;\n if (agent.context === 'fork') return type === 'fork';\n return type === 'fork' || cold;\n}\n\nfunction expectedType(agent: Agent): string {\n if (agent.kind === 'review' || agent.context === null) return EXPECTED_TYPES[agent.kind];\n return agent.context === 'cold' ? `the rucher ${agent.kind} agent (it started cold)` : 'fork';\n}\n\nexport interface LaunchCall {\n toolName: string;\n subagentType?: string | undefined;\n named?: Agent | undefined;\n // A plan agent registered but not launched yet.\n pendingPlan?: Agent | undefined;\n}\n\nexport function launchVerdict(call: LaunchCall): Verdict {\n if (call.toolName === 'EnterPlanMode') {\n const pending = call.pendingPlan;\n if (!pending) return { allow: true };\n return {\n allow: false,\n rule: 'plan-mode',\n reason: `${pending.name} is a Rucher plan agent waiting for its fork: launch it with Agent, subagent_type fork and description ${pending.name}, instead of plan mode.`,\n };\n }\n if (call.subagentType === 'Plan') {\n return { allow: false, rule: 'built-in-plan', reason: BUILT_IN_PLAN_DENIED };\n }\n const named = call.named;\n if (!named || fitsKind(named, call.subagentType)) return { allow: true };\n return {\n allow: false,\n rule: 'launch-type',\n reason: `${named.name} is a Rucher ${named.kind} agent: launch it with subagent_type ${expectedType(named)}, not ${call.subagentType ?? 'no subagent_type'}.`,\n };\n}\n","import { homedir } from 'node:os';\nimport { basename, isAbsolute, join, resolve } from 'node:path';\n\n// A reading of Bash just deep enough to find real git calls and where they run: quotes, comments\n// and heredoc bodies are text, not commands.\n\nexport interface Word {\n text: string;\n // Holds an expansion or a glob, so its value is not known before the shell runs it.\n dynamic: boolean;\n}\n\nexport interface ShellCommand {\n words: Word[];\n // undefined when it can't be known, like after cd - or cd $DIR.\n cwd: string | undefined;\n env: Map<string, string | undefined>;\n}\n\nexport interface GitCall {\n verb: string;\n sub: string | undefined;\n // Every directory the call acts on; undefined for one that can't be known.\n dirs: (string | undefined)[];\n}\n\ninterface State {\n cwd: string | undefined;\n env: Map<string, string | undefined>;\n}\n\nconst GIT_ENV = new Set(['GIT_DIR', 'GIT_WORK_TREE']);\nconst KEYWORDS = new Set(['!', '{', '}', 'if', 'then', 'else', 'elif', 'do', 'while', 'until']);\nconst SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);\nconst PLAIN_WRAPPERS = new Set(['command', 'builtin', 'exec', 'nohup', 'time']);\nconst SUDO_VALUES = new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U']);\nconst XARGS_VALUES = new Set(['-I', '-L', '-n', '-P', '-d', '-E', '-s', '-a']);\nconst GIT_VALUES = new Set([\n '-C',\n '-c',\n '--git-dir',\n '--work-tree',\n '--namespace',\n '--config-env',\n '--super-prefix',\n '--exec-path',\n '--list-cmds',\n '--attr-source',\n]);\n// sh -c strings and eval are read one level deep, no further.\nconst MAX_DEPTH = 1;\n\nfunction absolute(path: string, cwd: string): string {\n if (path === '~' || path.startsWith('~/')) return join(homedir(), path.slice(1));\n return isAbsolute(path) ? path : resolve(cwd, path);\n}\n\nfunction copy(state: State): State {\n return { cwd: state.cwd, env: new Map(state.env) };\n}\n\nclass Reader {\n private pos = 0;\n private heredocs: { delimiter: string; strip: boolean }[] = [];\n\n constructor(\n private readonly src: string,\n private readonly depth: number,\n private readonly out: ShellCommand[],\n ) {}\n\n walk(state: State, closer: ')' | '`' | null): void {\n let words: Word[] = [];\n let text = '';\n let dynamic = false;\n let started = false;\n let skipTarget = false;\n let previous: string | null = null;\n\n const endWord = () => {\n if (started) {\n if (skipTarget) skipTarget = false;\n else words.push({ text, dynamic });\n }\n text = '';\n dynamic = false;\n started = false;\n };\n const endCommand = (separator: string | null) => {\n endWord();\n const piped = previous === '|' || separator === '|';\n this.command(words, state, piped);\n words = [];\n skipTarget = false;\n previous = separator;\n };\n const nested = (until: ')' | '`') => {\n this.walk(copy(state), until);\n dynamic = true;\n started = true;\n };\n\n while (this.pos < this.src.length) {\n const c = this.src[this.pos] ?? '';\n const next = this.src[this.pos + 1] ?? '';\n if (closer !== null && c === closer) {\n this.pos++;\n endCommand(null);\n return;\n }\n if (c === ' ' || c === '\\t') {\n endWord();\n this.pos++;\n } else if (c === '\\n') {\n this.pos++;\n endCommand('\\n');\n this.skipHeredocs();\n } else if (c === '#' && !started) {\n while (this.pos < this.src.length && this.src[this.pos] !== '\\n') this.pos++;\n } else if (c === '\\\\') {\n if (next !== '\\n') {\n text += next;\n started = true;\n }\n this.pos += 2;\n } else if (c === \"'\") {\n const end = this.src.indexOf(\"'\", this.pos + 1);\n const stop = end === -1 ? this.src.length : end;\n text += this.src.slice(this.pos + 1, stop);\n started = true;\n this.pos = stop + 1;\n } else if (c === '\"') {\n this.pos++;\n started = true;\n while (this.pos < this.src.length && this.src[this.pos] !== '\"') {\n const d = this.src[this.pos] ?? '';\n if (d === '\\\\' && '\"\\\\$`'.includes(this.src[this.pos + 1] ?? '')) {\n text += this.src[this.pos + 1];\n this.pos += 2;\n } else if (d === '$' && this.src[this.pos + 1] === '(') {\n this.pos += 2;\n nested(')');\n } else if (d === '`') {\n this.pos++;\n nested('`');\n } else {\n if (d === '$') dynamic = true;\n text += d;\n this.pos++;\n }\n }\n this.pos++;\n } else if (c === '$' && next === '(' && this.src[this.pos + 2] === '(') {\n const end = this.src.indexOf('))', this.pos);\n this.pos = end === -1 ? this.src.length : end + 2;\n dynamic = true;\n started = true;\n } else if (c === '$' && next === '(') {\n this.pos += 2;\n nested(')');\n } else if (c === '$' && next === \"'\") {\n this.pos += 2;\n while (this.pos < this.src.length && this.src[this.pos] !== \"'\") {\n if (this.src[this.pos] === '\\\\') this.pos++;\n text += this.src[this.pos] ?? '';\n this.pos++;\n }\n this.pos++;\n started = true;\n } else if (c === '$') {\n text += c;\n dynamic = true;\n started = true;\n this.pos++;\n } else if (c === '`') {\n this.pos++;\n nested('`');\n } else if (c === ';') {\n this.pos += next === ';' ? 2 : 1;\n endCommand(';');\n } else if (c === '&' && next === '&') {\n this.pos += 2;\n endCommand('&&');\n } else if (c === '&' && next === '>') {\n endWord();\n this.pos += this.src[this.pos + 2] === '>' ? 3 : 2;\n skipTarget = true;\n } else if (c === '&') {\n this.pos++;\n endCommand('&');\n } else if (c === '|' && next === '|') {\n this.pos += 2;\n endCommand('||');\n } else if (c === '|') {\n this.pos += next === '&' ? 2 : 1;\n endCommand('|');\n } else if (c === '(' && !started && words.length === 0) {\n this.pos++;\n this.walk(copy(state), ')');\n } else if ((c === '<' || c === '>') && next === '(') {\n endWord();\n this.pos += 2;\n this.walk(copy(state), ')');\n } else if (c === '<' || c === '>') {\n if (started && /^\\d+$/.test(text)) {\n text = '';\n started = false;\n }\n endWord();\n skipTarget = this.redirect();\n } else {\n if (c === '*' || c === '?' || c === '[') dynamic = true;\n text += c;\n started = true;\n this.pos++;\n }\n }\n endCommand(null);\n }\n\n // Whether a target word follows; a heredoc's delimiter is read here.\n private redirect(): boolean {\n if (this.src.startsWith('<<<', this.pos)) {\n this.pos += 3;\n return true;\n }\n if (this.src.startsWith('<<', this.pos)) {\n this.pos += 2;\n const strip = this.src[this.pos] === '-';\n if (strip) this.pos++;\n while (this.src[this.pos] === ' ' || this.src[this.pos] === '\\t') this.pos++;\n const match = /^(?:'([^']*)'|\"([^\"]*)\"|([^\\s;&|<>()]+))/.exec(this.src.slice(this.pos));\n if (match) {\n this.heredocs.push({ delimiter: match[1] ?? match[2] ?? match[3] ?? '', strip });\n this.pos += match[0].length;\n }\n return false;\n }\n this.pos++;\n if ('>&|'.includes(this.src[this.pos] ?? '')) this.pos++;\n return true;\n }\n\n private skipHeredocs(): void {\n for (const { delimiter, strip } of this.heredocs) {\n while (this.pos < this.src.length) {\n const end = this.src.indexOf('\\n', this.pos);\n const stop = end === -1 ? this.src.length : end;\n let line = this.src.slice(this.pos, stop);\n if (strip) line = line.replace(/^\\t+/, '');\n this.pos = stop + 1;\n if (line === delimiter) break;\n }\n }\n this.heredocs = [];\n }\n\n private command(all: Word[], state: State, piped: boolean): void {\n let words = all;\n while (words[0] && KEYWORDS.has(words[0].text)) words = words.slice(1);\n const env = new Map(state.env);\n const assigned = new Map<string, string | undefined>();\n const assign = (word: Word) => {\n const at = word.text.indexOf('=');\n const name = word.text.slice(0, at);\n if (GIT_ENV.has(name)) assigned.set(name, word.dynamic ? undefined : word.text.slice(at + 1));\n };\n while (words[0] && /^[A-Za-z_]\\w*=/.test(words[0].text)) {\n assign(words[0]);\n words = words.slice(1);\n }\n if (words.length === 0) {\n if (!piped) for (const [name, value] of assigned) state.env.set(name, value);\n return;\n }\n words = this.unwrap(words, assign);\n for (const [name, value] of assigned) env.set(name, value);\n const name = words[0]?.text ?? '';\n const args = words.slice(1);\n\n if (name === 'cd' || name === 'pushd' || name === 'popd') {\n if (!piped) state.cwd = this.cd(name, args, state.cwd);\n return;\n }\n if (name === 'export') {\n for (const word of args) if (word.text.includes('=')) assign(word);\n if (!piped) for (const [key, value] of assigned) state.env.set(key, value);\n return;\n }\n if (this.depth < MAX_DEPTH && SHELLS.has(basename(name))) {\n const flag = args.findIndex((word) => /^-[a-z]*c[a-z]*$/.test(word.text));\n const script = flag === -1 ? undefined : args[flag + 1];\n if (script) this.nested(script.text, { cwd: state.cwd, env });\n return;\n }\n if (this.depth < MAX_DEPTH && name === 'eval') {\n this.nested(args.map((word) => word.text).join(' '), { cwd: state.cwd, env });\n return;\n }\n if (words.length > 0) this.out.push({ words, cwd: state.cwd, env });\n }\n\n private unwrap(start: Word[], assign: (word: Word) => void): Word[] {\n let words = start;\n for (;;) {\n const name = words[0]?.text ?? '';\n let i = 1;\n if (name === 'env') {\n while (words[i] && (words[i]?.text.startsWith('-') || words[i]?.text.includes('='))) {\n const word = words[i] as Word;\n if (word.text.includes('=') && !word.text.startsWith('-')) assign(word);\n i += word.text === '-u' || word.text === '-C' ? 2 : 1;\n }\n } else if (PLAIN_WRAPPERS.has(name)) {\n while (words[i]?.text.startsWith('-')) i++;\n } else if (name === 'sudo') {\n while (words[i]?.text.startsWith('-')) i += SUDO_VALUES.has(words[i]?.text ?? '') ? 2 : 1;\n } else if (name === 'xargs') {\n while (words[i]?.text.startsWith('-')) i += XARGS_VALUES.has(words[i]?.text ?? '') ? 2 : 1;\n } else {\n return words;\n }\n words = words.slice(i);\n }\n }\n\n private cd(name: string, args: Word[], cwd: string | undefined): string | undefined {\n if (name !== 'cd') return undefined;\n const target = args.find((word) => !/^-[LPe@]+$/.test(word.text));\n if (!target) return homedir();\n if (target.dynamic || target.text === '-') return undefined;\n if (isAbsolute(target.text) || target.text.startsWith('~')) return absolute(target.text, '/');\n return cwd === undefined ? undefined : absolute(target.text, cwd);\n }\n\n private nested(script: string, state: State): void {\n new Reader(script, this.depth + 1, this.out).walk(state, null);\n }\n}\n\nfunction commandsOf(command: string, cwd: string | undefined, depth: number): ShellCommand[] {\n const out: ShellCommand[] = [];\n new Reader(command, depth, out).walk({ cwd, env: new Map() }, null);\n return out;\n}\n\nexport function shellCommands(command: string, cwd: string | undefined): ShellCommand[] {\n return commandsOf(command, cwd, 0);\n}\n\nfunction gitCall(cmd: ShellCommand): GitCall[] {\n const words = cmd.words;\n let base = cmd.cwd;\n const paths: (Word | undefined)[] = [];\n const aliases = new Map<string, string>();\n let i = 1;\n while (i < words.length && words[i]?.text.startsWith('-')) {\n const word = words[i] as Word;\n const at = word.text.startsWith('--') ? word.text.indexOf('=') : -1;\n const option = at === -1 ? word.text : word.text.slice(0, at);\n let value: Word | undefined;\n if (at !== -1) {\n value = { text: word.text.slice(at + 1), dynamic: word.dynamic };\n i++;\n } else if (GIT_VALUES.has(option)) {\n value = words[i + 1];\n i += 2;\n } else {\n i++;\n }\n if (option === '-C') {\n base = !value || value.dynamic || base === undefined ? undefined : absolute(value.text, base);\n } else if (option === '--git-dir' || option === '--work-tree') {\n paths.push(value);\n } else if (option === '-c' && value?.text.startsWith('alias.')) {\n const eq = value.text.indexOf('=');\n if (eq !== -1) aliases.set(value.text.slice(6, eq), value.text.slice(eq + 1));\n }\n }\n const verbWord = words[i];\n if (!verbWord) return [];\n let rest = words.slice(i + 1);\n let verb = verbWord.text;\n const alias = aliases.get(verb);\n if (alias !== undefined) {\n if (alias.startsWith('!')) return gitCallsIn(commandsOf(alias.slice(1), base, MAX_DEPTH));\n const [first = '', ...more] = alias.trim().split(/\\s+/);\n verb = first;\n rest = [...more.map((text) => ({ text, dynamic: false })), ...rest];\n }\n const resolved = (path: string | undefined) =>\n path === undefined || base === undefined ? undefined : absolute(path, base);\n const dirs: (string | undefined)[] = [base];\n for (const path of paths) dirs.push(!path || path.dynamic ? undefined : resolved(path.text));\n for (const name of GIT_ENV) if (cmd.env.has(name)) dirs.push(resolved(cmd.env.get(name)));\n const first = rest[0]?.text;\n const sub = first === undefined || first.startsWith('-') ? undefined : first;\n return [{ verb, sub, dirs }];\n}\n\nfunction gitCallsIn(commands: ShellCommand[]): GitCall[] {\n return commands\n .filter((cmd) => basename(cmd.words[0]?.text ?? '') === 'git')\n .flatMap((cmd) => gitCall(cmd));\n}\n\nexport function gitCalls(command: string, cwd: string | undefined): GitCall[] {\n return gitCallsIn(shellCommands(command, cwd));\n}\n","import { realpathSync } from 'node:fs';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport type { Agent, AgentKind } from './agents.ts';\nimport { LAUNCH_TOOLS, launchVerdict } from './launch.ts';\nimport { type GitCall, gitCalls } from './shell.ts';\n\nexport const GUARDED_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'Bash']);\nconst FILE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit']);\n\n// read-only writes only its scratchpad and sandbox, worktree only its worktree, and main is the\n// human's own session, where only launches are checked.\nexport type Access = 'read-only' | 'worktree' | 'main';\n\nexport const KIND_ACCESS: Readonly<Record<AgentKind, Access>> = {\n research: 'read-only',\n plan: 'read-only',\n review: 'read-only',\n implement: 'worktree',\n};\n\nexport interface ToolCall {\n tool: string;\n filePath?: string | undefined;\n command?: string | undefined;\n cwd?: string | undefined;\n subagentType?: string | undefined;\n}\n\nexport interface CallContext {\n // Names the broken rule in deny reasons, like \"the plan contract\".\n label: string;\n worktree?: string | null | undefined;\n // A read-only agent's throwaway folder, where it may write, install and commit.\n sandbox?: string | null | undefined;\n // Claude Code's per-user temporary folders, where agents write their reports.\n scratchRoots: string[];\n // A cold implement has no Carnet row. A paired implement with no worktree works in the main repo.\n unpaired?: boolean | undefined;\n launch?: { named?: Agent | undefined; pendingPlan?: Agent | undefined } | undefined;\n}\n\nexport type DenyRule =\n | 'write-read-only'\n | 'write-outside-sandbox'\n | 'write-outside-worktree'\n | 'git-publish'\n | 'git-push'\n | 'git-outside-sandbox'\n | 'plan-mode'\n | 'built-in-plan'\n | 'launch-type';\n\nexport type Verdict = { allow: true } | { allow: false; rule: DenyRule; reason: string };\n\nexport const ALLOW: Verdict = { allow: true };\n\nexport function deny(rule: DenyRule, reason: string): Verdict {\n return { allow: false, rule, reason };\n}\n\nexport function denyReason(verdict: Verdict): string | undefined {\n return verdict.allow ? undefined : verdict.reason;\n}\n\nconst PUBLISHING = new Set(['commit', 'push', 'stash']);\n// stash list and show only read.\nconst READ_ONLY_STASH = new Set(['list', 'show']);\n\n// The real path of the longest existing prefix, since a file about to be written doesn't exist yet\n// and /tmp is a symlink on macOS.\nfunction realish(path: string): string {\n const full = resolve(path);\n const parent = dirname(full);\n try {\n return realpathSync(full);\n } catch {\n return parent === full ? full : join(realish(parent), basename(full));\n }\n}\n\nfunction inside(path: string, folder: string): boolean {\n const rest = relative(realish(folder), realish(path));\n return rest === '' || (!rest.startsWith('..') && !isAbsolute(rest));\n}\n\nfunction absolute(path: string, cwd: string | undefined): string {\n if (path === '~' || path.startsWith('~/')) return join(homedir(), path.slice(1));\n return isAbsolute(path) ? path : resolve(cwd ?? '/', path);\n}\n\nfunction inScratch(path: string, ctx: CallContext): boolean {\n return ctx.scratchRoots.some((root) => inside(path, root));\n}\n\nfunction writable(path: string, ctx: CallContext): boolean {\n return inScratch(path, ctx) || (!!ctx.sandbox && inside(path, ctx.sandbox));\n}\n\nfunction publishing(call: GitCall): boolean {\n return (\n PUBLISHING.has(call.verb) && !(call.verb === 'stash' && READ_ONLY_STASH.has(call.sub ?? ''))\n );\n}\n\nfunction fileToolVerdict(access: Access, call: ToolCall, ctx: CallContext): Verdict {\n if (access === 'worktree') {\n if (!ctx.worktree) {\n if (ctx.unpaired && call.filePath && !inScratch(absolute(call.filePath, call.cwd), ctx)) {\n return deny(\n 'write-read-only',\n `${ctx.label} is read-only: write only the report in the scratchpad`,\n );\n }\n return ALLOW;\n }\n if (!call.filePath) return ALLOW;\n const path = absolute(call.filePath, call.cwd);\n if (inside(path, ctx.worktree) || inScratch(path, ctx)) return ALLOW;\n return deny(\n 'write-outside-worktree',\n `${ctx.label} limits writes to its worktree ${ctx.worktree}`,\n );\n }\n if (call.filePath && writable(absolute(call.filePath, call.cwd), ctx)) return ALLOW;\n return ctx.sandbox\n ? deny(\n 'write-outside-sandbox',\n `${ctx.label} limits writes to its sandbox ${ctx.sandbox} and the scratchpad`,\n )\n : deny('write-read-only', `${ctx.label} is read-only: write only the report in the scratchpad`);\n}\n\n// Only exact checks: file paths and git publishing. Other shell writes are left to the contract,\n// since no pattern catches them all.\nfunction bashVerdict(access: Access, call: ToolCall, ctx: CallContext): Verdict {\n const calls = gitCalls(call.command ?? '', call.cwd).filter(publishing);\n if (calls.length === 0) return ALLOW;\n const sandbox = ctx.sandbox;\n if (!sandbox || access === 'worktree') {\n return deny(\n 'git-publish',\n `${ctx.label} forbids git commit, push and stash: the human commits`,\n );\n }\n if (calls.some((git) => git.verb === 'push')) {\n return deny('git-push', `${ctx.label} forbids git push`);\n }\n // A directory that can't be known can't be shown to be inside the sandbox.\n const confined = (dir: string | undefined) => dir !== undefined && inside(dir, sandbox);\n if (calls.every((git) => git.dirs.every(confined))) return ALLOW;\n return deny(\n 'git-outside-sandbox',\n `${ctx.label} allows git commit and stash only in its sandbox ${sandbox}`,\n );\n}\n\nexport function checkToolCall(access: Access, call: ToolCall, ctx: CallContext): Verdict {\n if (access === 'main') {\n if (!LAUNCH_TOOLS.has(call.tool) || !ctx.launch) return ALLOW;\n return launchVerdict({ toolName: call.tool, subagentType: call.subagentType, ...ctx.launch });\n }\n if (FILE_TOOLS.has(call.tool)) return fileToolVerdict(access, call, ctx);\n if (call.tool === 'Bash') return bashVerdict(access, call, ctx);\n return ALLOW;\n}\n\nfunction text(fields: Record<string, unknown>, key: string): string | undefined {\n const value = fields[key];\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\n// A tool call from its name and raw input, as hosts and SDK permission callbacks hand them over.\nexport function toolCallOf(tool: string, input: unknown, cwd?: string): ToolCall {\n const fields =\n typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {};\n return {\n tool,\n filePath: text(fields, 'file_path') ?? text(fields, 'notebook_path'),\n command: text(fields, 'command'),\n cwd,\n subagentType: text(fields, 'subagent_type'),\n };\n}\n\n// Claude Code's versions and platforms differ on the parent of its per-user folder, so each known\n// one is accepted.\nexport function scratchRoots(env: { CLAUDE_CODE_TMPDIR?: string | undefined }): string[] {\n const folder = `claude-${process.getuid?.() ?? 0}`;\n const parents = [\n env.CLAUDE_CODE_TMPDIR,\n process.platform === 'win32' ? undefined : '/tmp',\n tmpdir(),\n ].filter((parent): parent is string => Boolean(parent));\n return [...new Set(parents.map((parent) => join(parent, folder)))];\n}\n\n// Cold plugin agents may run without a Carnet row; their type names the kind.\nexport function kindOfAgentType(agentType: string | undefined): AgentKind | undefined {\n const match = /^rucher[\\w-]*:(research|plan|implement|review)$/.exec(agentType ?? '');\n return match?.[1] as AgentKind | undefined;\n}\n","import type { Carnet } from '../carnet.ts';\nimport {\n ALLOW,\n checkToolCall,\n deny,\n KIND_ACCESS,\n kindOfAgentType,\n type Verdict,\n} from '../guard.ts';\nimport type { HostToolPayload } from '../hosts/host.ts';\nimport { launchVerdict } from '../launch.ts';\nimport type { TurnOptions } from '../turn.ts';\n\nexport function handleToolUse(\n carnet: Carnet,\n payload: HostToolPayload,\n options: TurnOptions = {},\n): void {\n // The turn tracks the main conversation; a subagent's context is not it.\n if (payload.agent_id) return;\n if (options.trackTurn ?? true) carnet.turn.start(payload.session_id);\n}\n\nexport const WAITING_TOOL = 'AskUserQuestion';\n\n// The turn is still running, but blocked on the human's answer.\nexport function handleToolStart(carnet: Carnet, payload: HostToolPayload): void {\n if (payload.agent_id || payload.tool_name !== WAITING_TOOL) return;\n carnet.turn.wait(payload.session_id);\n}\n\nexport function subagentVerdict(\n carnet: Carnet,\n payload: HostToolPayload,\n scratchRoots: string[],\n names: string[] = [],\n namedUnreadable = false,\n): Verdict {\n if (!payload.agent_id || !payload.tool_name) return ALLOW;\n const agent = carnet.agents.confirmSubagent(payload.session_id, payload.agent_id, names);\n const kind = agent?.kind ?? kindOfAgentType(payload.agent_type);\n // No row and no cold kind. Only a fork, and only when the workspace named by RUCHER_WS or\n // --ws cannot be opened: a helper, or a recorded session whose own file broke, stays untouched.\n if (!kind) {\n if (namedUnreadable && payload.agent_type === 'fork') {\n return deny(\n 'write-read-only',\n 'The named workspace cannot be opened, so writes stay closed.',\n );\n }\n return ALLOW;\n }\n return checkToolCall(\n KIND_ACCESS[kind],\n {\n tool: payload.tool_name,\n filePath: payload.file_path,\n command: payload.command,\n cwd: payload.cwd,\n },\n {\n label: `the ${kind} contract`,\n worktree: agent?.worktree,\n sandbox: agent?.sandbox,\n scratchRoots,\n unpaired: !agent,\n },\n );\n}\n\n// The main agent's launches: the built-in Plan subagent and plan mode never stand in for a Rucher\n// plan agent, and an Agent call naming a registered agent must use that kind's subagent type.\nexport function mainLaunchVerdict(\n carnet: Carnet,\n payload: HostToolPayload,\n namedUnreadable = false,\n): Verdict {\n if (payload.agent_id || !payload.tool_name) return ALLOW;\n if (!carnet.sessions.get(payload.session_id)) {\n if (!namedUnreadable) return ALLOW;\n // The session was never recorded, so a waiting plan cannot be seen. Plan launches stay closed.\n if (payload.tool_name === 'EnterPlanMode') {\n return deny('plan-mode', 'The named workspace cannot be opened, so plan mode stays closed.');\n }\n return launchVerdict({\n toolName: payload.tool_name,\n subagentType: payload.subagent_type,\n });\n }\n const named = carnet.agents.unpaired(payload.session_id, payload.launched_names ?? []);\n const planMode = payload.tool_name === 'EnterPlanMode';\n const verdict = checkToolCall(\n 'main',\n { tool: payload.tool_name, subagentType: payload.subagent_type },\n {\n label: 'the main session',\n scratchRoots: [],\n launch: {\n named,\n pendingPlan: planMode ? carnet.agents.pendingPlan(payload.session_id) : undefined,\n },\n },\n );\n if (verdict.allow && named && !planMode) {\n carnet.agents.requestLaunch(payload.session_id, named.name);\n }\n return verdict;\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport type { Carnet } from './carnet.ts';\nimport { CarnetError } from './errors.ts';\nimport { type Host, hostById, launchHost, type Orchestration } from './hosts/host.ts';\nimport { appendPromptFile } from './prompt/prompt.ts';\nimport { renderRunDirectory } from './render.ts';\nimport type { Session, SessionKind } from './sessions.ts';\nimport { repoNameFor } from './workspace/locate.ts';\nimport { isWorkspaceName, loadWorkspace, type Workspace } from './workspace/workspace.ts';\n\nexport type LaunchMode = 'new' | 'resume' | 'fork' | 'agent';\n\nexport interface SystemAppend {\n path: string;\n version: string;\n}\n\nexport interface McpServerEntry {\n command: string;\n args: string[];\n env: Record<string, string>;\n}\n\nexport interface LaunchPlan {\n mode: LaunchMode;\n host: string;\n orchestration: Orchestration;\n sessionId?: string;\n parentId?: string;\n agentId?: string;\n name: string | null;\n cwd: string;\n dirs: string[];\n systemAppend: SystemAppend;\n env: Record<string, string>;\n model?: string;\n // A server-run agent gets Carnet from the server, never from the rucher plugin.\n mcp?: { carnet: McpServerEntry };\n rucherPlugin: 'load' | 'exclude';\n knownChildren?: string[];\n}\n\nexport interface LaunchPlanInput {\n mode: LaunchMode;\n host: Host;\n workspace: Workspace | null;\n // The parent of a fork.\n session: Pick<Session, 'id' | 'name' | 'promptVersion'>;\n cwd: string;\n dirs: string[];\n systemAppend: SystemAppend;\n kind?: SessionKind | undefined;\n name?: string | null | undefined;\n agentId?: string | undefined;\n model?: string | undefined;\n knownChildren?: string[] | undefined;\n}\n\n// Hints are run from anywhere, where the directory no longer picks the workspace.\nexport function withWorkspace(command: string, workspace: string | null | undefined): string {\n return workspace ? `${command} --ws ${workspace}` : command;\n}\n\nfunction launchEnv(\n workspace: Workspace | null,\n session: Pick<Session, 'id' | 'name'>,\n promptVersion: string,\n kind?: SessionKind,\n): Record<string, string> {\n return {\n RUCHER_SESSION_ID: session.id,\n RUCHER_PROMPT_VERSION: promptVersion,\n RUCHER_SESSION_NAME: session.name ?? '',\n ...(workspace ? { RUCHER_WS: workspace.name } : {}),\n ...(kind ? { RUCHER_SESSION_KIND: kind } : {}),\n };\n}\n\nfunction carnetServer(input: LaunchPlanInput): McpServerEntry {\n return {\n command: 'rucher',\n args: ['mcp'],\n env: {\n RUCHER_SESSION_ID: input.session.id,\n ...(input.agentId ? { RUCHER_AGENT_ID: input.agentId } : {}),\n ...(input.workspace ? { RUCHER_WS: input.workspace.name } : {}),\n },\n };\n}\n\nexport function buildLaunchPlan(input: LaunchPlanInput): LaunchPlan {\n const { mode, host, session } = input;\n if (mode === 'agent' && !input.agentId) throw new TypeError('An agent launch needs an agent id');\n const fork = mode === 'fork';\n const name = input.name === undefined ? session.name : input.name;\n // A fork keeps its parent's system prompt snapshot, so the parent's rules are the ones in effect.\n const env = fork\n ? {\n ...launchEnv(input.workspace, session, session.promptVersion ?? '', input.kind),\n RUCHER_SESSION_NAME: name ?? '',\n }\n : launchEnv(input.workspace, session, input.systemAppend.version, input.kind);\n const server = host.orchestration === 'server';\n return {\n mode,\n host: host.id,\n orchestration: host.orchestration,\n ...(fork ? { parentId: session.id } : { sessionId: session.id }),\n ...(input.agentId ? { agentId: input.agentId } : {}),\n name,\n cwd: input.cwd,\n dirs: input.dirs,\n systemAppend: input.systemAppend,\n env,\n ...(input.model ? { model: input.model } : {}),\n ...(server ? { mcp: { carnet: carnetServer(input) } } : {}),\n rucherPlugin: server ? 'exclude' : 'load',\n ...(input.knownChildren ? { knownChildren: input.knownChildren } : {}),\n };\n}\n\n// Settings directories apply only once the run directory is trusted, and never load the repos' CLAUDE.md.\nfunction repoDirectories(workspace: Workspace | null): string[] {\n return (workspace?.repos ?? []).map((repo) => repo.path).filter((path) => existsSync(path));\n}\n\nfunction sessionWorkspace(\n carnet: Carnet,\n session: Session,\n env: NodeJS.ProcessEnv,\n): Workspace | null {\n if (!isWorkspaceName(session.workspace)) return null;\n return carnet.workspace?.name === session.workspace\n ? carnet.workspace\n : loadWorkspace(session.workspace, env);\n}\n\n// Rendering first recreates a missing run directory, the usual cwd of a workspace session.\nfunction prepareSession(\n carnet: Carnet,\n session: Session,\n env: NodeJS.ProcessEnv,\n): Workspace | null {\n const workspace = sessionWorkspace(carnet, session, env);\n if (workspace) renderRunDirectory(workspace, { env, host: session.host });\n return workspace;\n}\n\nfunction sessionLabel(session: Pick<Session, 'id' | 'name'>): string {\n return session.name ?? session.id.slice(0, 8);\n}\n\n// Hosts store conversations per project directory, so a session only reopens from its original cwd.\nfunction sessionDirectory(session: Session): string {\n if (session.cwd && existsSync(session.cwd)) return session.cwd;\n throw new CarnetError(\n 'SESSION_CWD_MISSING',\n `The directory of session ${sessionLabel(session)} no longer exists: ${session.cwd ?? 'none recorded'}`,\n );\n}\n\nexport interface PrepareNewOptions {\n kind: SessionKind;\n name?: string | undefined;\n // Where the launch was asked from, to record the repo it belongs to.\n repoCwd: string;\n env: NodeJS.ProcessEnv;\n model?: string | undefined;\n}\n\nexport function prepareNew(carnet: Carnet, options: PrepareNewOptions): LaunchPlan {\n if (options.kind === 'active' && !options.name) {\n throw new CarnetError(\n 'SESSION_NAME_REQUIRED',\n 'An active session needs a name',\n withWorkspace('rucher new <name>', carnet.workspace?.name),\n );\n }\n const workspace = carnet.requireWorkspace();\n const session = carnet.sessions.create({\n id: randomUUID(),\n kind: options.kind,\n name: options.name,\n cwd: workspace.runDirectory,\n repo: repoNameFor(workspace, options.repoCwd),\n });\n const host = hostById(session.host);\n renderRunDirectory(workspace, { env: options.env, host: session.host });\n return buildLaunchPlan({\n mode: 'new',\n host,\n workspace,\n session,\n cwd: workspace.runDirectory,\n dirs: repoDirectories(workspace),\n systemAppend: appendPromptFile(workspace, session, options.env),\n model: options.model,\n });\n}\n\nexport interface PreparedResume {\n plan: LaunchPlan;\n notices: string[];\n}\n\nexport function prepareResume(\n carnet: Carnet,\n session: Session,\n env: NodeJS.ProcessEnv,\n options: { model?: string | undefined } = {},\n): PreparedResume {\n const workspace = prepareSession(carnet, session, env);\n const cwd = sessionDirectory(session);\n const systemAppend = appendPromptFile(workspace, session, env);\n const host = hostById(session.host);\n const fresh = !launchHost(host.id).hasConversation(session, env);\n return {\n plan: buildLaunchPlan({\n mode: fresh ? 'new' : 'resume',\n host,\n workspace,\n session,\n cwd,\n dirs: repoDirectories(workspace),\n systemAppend,\n model: options.model,\n }),\n notices: fresh ? [`no conversation yet for ${sessionLabel(session)}: starting it\\n`] : [],\n };\n}\n\nexport interface PrepareForkOptions {\n name?: string | undefined;\n active?: boolean | undefined;\n env: NodeJS.ProcessEnv;\n model?: string | undefined;\n}\n\nexport function checkForkOptions(\n carnet: Carnet,\n options: Pick<PrepareForkOptions, 'name' | 'active'>,\n): void {\n if (options.active && !options.name) {\n throw new CarnetError(\n 'SESSION_NAME_REQUIRED',\n 'An active fork needs a name',\n withWorkspace('rucher fork <session> <name> --active', carnet.workspace?.name),\n );\n }\n if (options.name && carnet.sessions.byName(options.name)) {\n throw new CarnetError('SESSION_NAME_TAKEN', `A session named \"${options.name}\" already exists`);\n }\n}\n\nfunction childrenOf(carnet: Carnet, parentId: string): Session[] {\n return carnet.sessions\n .list({ includeTemp: true, includeArchived: true })\n .filter((session) => session.parentId === parentId);\n}\n\nexport function prepareFork(\n carnet: Carnet,\n parent: Session,\n options: PrepareForkOptions,\n): LaunchPlan {\n checkForkOptions(carnet, options);\n const host = hostById(parent.host);\n if (!launchHost(host.id).hasConversation(parent, options.env)) {\n const label = sessionLabel(parent);\n throw new CarnetError(\n 'NO_CONVERSATION',\n `Session ${label} has no conversation yet, nothing to fork`,\n withWorkspace(`rucher resume ${label}`, parent.workspace),\n );\n }\n const workspace = prepareSession(carnet, parent, options.env);\n const cwd = sessionDirectory(parent);\n return buildLaunchPlan({\n mode: 'fork',\n host,\n workspace,\n session: parent,\n cwd,\n dirs: repoDirectories(workspace),\n systemAppend: appendPromptFile(workspace, parent, options.env),\n kind: options.active ? 'active' : 'temp',\n name: options.name ?? null,\n model: options.model,\n knownChildren: childrenOf(carnet, parent.id).map((session) => session.id),\n });\n}\n\n// The host picks a fork's id, so the launcher finds it as the parent's new child.\nfunction forkChild(carnet: Carnet, plan: LaunchPlan): Session | undefined {\n if (!plan.parentId) return undefined;\n const known = new Set(plan.knownChildren);\n return childrenOf(carnet, plan.parentId).find((session) => !known.has(session.id));\n}\n\nexport function launchStarted(carnet: Carnet, plan: LaunchPlan): void {\n if (plan.sessionId) carnet.sessions.setStatus(plan.sessionId, 'running');\n}\n\nexport function launchEnded(carnet: Carnet, plan: LaunchPlan): void {\n const id = plan.sessionId ?? forkChild(carnet, plan)?.id;\n if (id && carnet.sessions.get(id)) carnet.sessions.end(id);\n}\n","import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Carnet } from '../carnet.ts';\nimport { rucherPaths } from '../paths.ts';\nimport { EMOJI, kindTag } from './model.ts';\nimport type { StatusLine, StatusView } from './view.ts';\n\nexport const STATUS_LINE_LABEL = 'rucher';\n\nconst TURN_LABELS = {\n working: '⚙️ working',\n waiting: '⏸ waiting on you',\n failed: '⚠ turn failed',\n} as const;\n\nfunction counts(lines: readonly StatusLine[]): string {\n const byEmoji = new Map<string, number>();\n for (const line of lines) byEmoji.set(line.emoji, (byEmoji.get(line.emoji) ?? 0) + 1);\n return [...byEmoji].map(([emoji, count]) => `${emoji}${count}`).join(' ');\n}\n\n// One line for Claude Code: what the main agent does, the next thing waiting on the human, then counts.\n// Bare, since Claude Code already names the plugin before a mod's line.\nexport function renderStatusLine(view: StatusView, lag: string | null = null): string {\n if (lag) return lag;\n const parts: string[] = [];\n if (view.turn) parts.push(TURN_LABELS[view.turn]);\n const [next] = view.waiting;\n if (next) {\n const action = next.action ? ` ${next.action}` : '';\n parts.push(`next: ${next.emoji} ${kindTag(next.kind)} ${next.name}${action}`);\n parts.push(counts(view.waiting));\n }\n if (view.running.length > 0) parts.push(`${EMOJI.running}${view.running.length}`);\n if (view.blocked.length > 0) parts.push(`⛓${view.blocked.length}`);\n return parts.join(' · ');\n}\n\nexport function labelStatusLine(line: string): string {\n return line ? `${STATUS_LINE_LABEL} · ${line}` : '';\n}\n\nexport function statusLinePath(sessionId: string, env?: NodeJS.ProcessEnv): string {\n return join(rucherPaths(env).state, 'status', `${sessionId}.txt`);\n}\n\nexport interface StatusLineOptions {\n env?: NodeJS.ProcessEnv | undefined;\n lag?: string | null | undefined;\n}\n\n// Claude Code reads this file on every refresh, so it is written once per change instead of\n// computed by a process per refresh.\nexport function writeStatusLine(\n carnet: Carnet,\n sessionId: string,\n options: StatusLineOptions = {},\n): void {\n const path = statusLinePath(sessionId, options.env);\n const session = carnet.sessions.get(sessionId);\n if (!session || session.status === 'archived') {\n rmSync(path, { force: true });\n return;\n }\n const line = renderStatusLine(carnet.status.view(session), options.lag ?? null);\n mkdirSync(join(path, '..'), { recursive: true });\n const temporary = `${path}.${process.pid}.tmp`;\n writeFileSync(temporary, line ? `${line}\\n` : '');\n renameSync(temporary, path);\n}\n"],"mappings":";;;;;;;AAoBA,SAAS,MAAM,QAAgB,KAAa,GAAG,YAA8B;CAC3E,OAAO,OAAQ,OAAO,GAAG,QAAQ,GAAG,CAAC,CAAC,IAAI,GAAG,UAAU,CAAC,CAAuB,KAAK;AACtF;AAEA,SAAS,WAAW,QAAgB,SAA2B;CAC7D,OAAO,CACL,GAAG,IAAI,IAEH,OAAO,GACJ,QAAQ,mEAAmE,CAAC,CAC5E,IAAI,OAAO,CAAC,CACf,KAAK,QAAQ,IAAI,IAAI,CACzB,CACF;AACF;AAEA,SAAS,aAAa,QAAgB,WAAmB,MAA8B;CACrF,MAAM,MAAM,OAAO,GAChB,QAAQ,0DAA0D,CAAC,CACnE,IAAI,WAAW,IAAI;CACtB,OAAO,MAAM,OAAO,SAAS,QAAQ,IAAI,EAAE,IAAI;AACjD;AAIA,SAAgB,YACd,QACA,WACA,iBACA,UAAuB,CAAC,GACZ;CACZ,MAAM,UAAU,OAAO,SAAS,QAAQ,SAAS;CACjD,IAAI,QAAQ,eAAe,OAAO,WAAW,QAAQ,OACnD,MAAM,IAAI,YAAY,qBAAqB,mBAAmB,WAAW;CAE3E,IAAI,QAAQ,cAAc,iBACxB,MAAM,IAAI,YAAY,wBAAwB,0CAA0C;CAE1F,MAAM,OAAO,Q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C7C,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;EAC5B;CACF;CACA,MAAM,OAAO,iBAAiB,OAAO,OAAO,KAAK,OAAO,GAAG,QAAQ,OAAO,IAAI;CAC9E,UAAU,KAAK,MAAM,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC/C,MAAM,YAAY,GAAG,KAAK,GAAG,QAAQ,IAAI;CACzC,cAAc,WAAW,OAAO,GAAG,KAAK,MAAM,EAAE;CAChD,WAAW,WAAW,IAAI;AAC5B"}
package/dist/mcp.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { St as Host, i as OpenCarnetOptions, t as Carnet } from "./carnet-D3zpKpdn.mjs";
1
+ import { i as OpenCarnetOptions, qt as Host, t as Carnet } from "./carnet-B9opMp0K.mjs";
2
+ import * as z from "zod/v4";
2
3
  import { McpServer } from "@modelcontextprotocol/server";
3
4
  import { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
4
- import * as z from "zod/v4";
5
- export declare const INSTRUCTIONS = "Carnet holds the forks, the Main line, sessions, the journal and the workspace memory that the `rucher` CLI renders. The session is resolved automatically; pass `session` only to target another one. The workflow rules are in the system prompt and the rucher skill: load the skill before launching agents or handling their results.\n\nWhich tool, when:\n- Launch: agent_start with the agent's kind (research, plan, implement, review), then launch it in a later message with Agent, subagent_type fork (or the kind's cold agent), description = the agent name, which names the task, never the kind. A plan agent is always a Rucher fork, never the built-in Plan subagent or plan mode.\n- Each step of a fork's work: agent_step (answered, applying, applied, tested, committed, dropped).\n- Next actions, only when the human asks (/rucher:next): agent_report, then agent_inject or agent_promote (research), agent_questions then agent_answer then agent_promote (plan), review_findings then review_decide, then review_brief for each agent started from the findings (review). review_context before launching a review.\n- Main line text for work of your own: table_set, table_clear.\n- Other moves: agent_update, agent_drop, queue_reorder. Recall: agent_list, log_read, session_resume_info, session_list.\n- Memory: note_list before an approach, note_add and note_drop at the end of a step (main agent), note_cite when a note changed what you did.\n- Session: session_new when the human names it, session_drop only when asked.\n- Fork: agent_update (running, short note) at progress, agent_done last.\n\nStatuses (the NEXT action): running ⏳ · discussing 💬 · answer ❓ · review 👀 · apply 📥 · test 🧪. Notes and table text: under 60 characters, no paths, no backticks.";
5
+ export declare const INSTRUCTIONS = "Carnet tracks forks, the Main line, sessions, the journal and the workspace notes. The session is resolved automatically. Load the rucher skill before launching agents or handling their results.\n\n- Launch: agent_start (kind research, plan, implement or review; a cold agent gets a mission and attachments, never pasted context), then Agent in a later message, subagent_type fork or the kind's cold agent, description = agent name. A plan agent is a Rucher fork, never the built-in Plan subagent or plan mode.\n- Fork steps: agent_step. Next actions, only when the human asks (/rucher:next): agent_report, then the kind's tools.\n- Main line for your own work: table_set, table_clear. Recall: agent_list, log_read, session_resume_info.\n- Notes: note_list before an approach; note_add, note_drop at the end of a step (main only); note_cite when one changed what you did.\n- Agents: agent_brief first when the prompt says so, agent_update at progress, agent_done last.\n\nStatuses name the NEXT action: running ⏳ · discussing 💬 · answer ❓ · review 👀 · apply 📥 · test 🧪. Notes and Main line: under 60 characters, no paths, no backticks.";
6
6
  interface SessionResolverOptions {
7
7
  carnet: Carnet;
8
8
  env?: NodeJS.ProcessEnv | undefined;
@@ -34,7 +34,7 @@ interface ToolDefinition<Schema extends z.ZodObject = z.ZodObject> {
34
34
  name: string;
35
35
  description: string;
36
36
  schema: Schema;
37
- run: (carnet: Carnet, sessionId: string, args: z.infer<Schema>) => ToolOutput;
37
+ run: (carnet: Carnet, sessionId: string, args: z.infer<Schema>, currentId?: () => string | undefined) => ToolOutput;
38
38
  }
39
39
  export declare const TOOLS: readonly ToolDefinition[];
40
40
  export type { CarnetServerOptions, ServeCarnetOptions, SessionResolver, SessionResolverOptions, ToolDefinition, ToolOutput };
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp/instructions.ts","../src/mcp/session.ts","../src/mcp/server.ts","../src/mcp/tools.ts"],"mappings":";;;;qBAAa;UCMI;EACf,QAAQ;EACR,MAAM,OAAO;EACb;EACA;EACA,OAAO;;UAGQ;EACf,QAAQ;;wBAGM,wBACd,QACA,KACA,MACA,KACA,QACC,yBAAyB;qBCXf;qBACA;UAEI,4BAA4B,KAAK;EAChD,QAAQ,gBAAgB;EACxB,cAAc,QAAQ,QAAQ;;wBAOhB,mBAAmB,SAAS,sBAAsB;UAiCjD,2BAA2B;EAC1C,SAAS;EACT;EACA,YAAY;;wBAGE,YAAY,UAAS,qBAA0B;UC5B9C;EACf;;UAGe,eAAe,eAAe,EAAE,YAAY,EAAE;EAC7D;EACA;EACA,QAAQ;EACR,MAAM,QAAQ,QAAQ,mBAAmB,MAAM,EAAE,MAAM,YAAY;;qBAyoBxD,gBAAgB"}
1
+ {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp/instructions.ts","../src/mcp/session.ts","../src/mcp/server.ts","../src/mcp/tools.ts"],"mappings":";;;;qBAAa;UCMI;EACf,QAAQ;EACR,MAAM,OAAO;EACb;EACA;EACA,OAAO;;UAGQ;EACf,QAAQ;;wBAGM,wBACd,QACA,KACA,MACA,KACA,QACC,yBAAyB;qBCVf;qBACA;UAEI,4BAA4B,KAAK;EAChD,QAAQ,gBAAgB;EACxB,cAAc,QAAQ,QAAQ;;wBAuDhB,mBAAmB,SAAS,sBAAsB;UAkDjD,2BAA2B;EAC1C,SAAS;EACT;EACA,YAAY;;wBAGE,YAAY,UAAS,qBAA0B;UCtF9C;EACf;;UAGe,eAAe,eAAe,EAAE,YAAY,EAAE;EAC7D;EACA;EACA,QAAQ;EACR,MACE,QAAQ,QACR,mBACA,MAAM,EAAE,MAAM,SACd,yCACG;;qBA0tBM,gBAAgB"}