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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/move.ts","../src/hook/session-end.ts","../src/hook/session-start.ts","../src/hook/user-prompt-submit.ts","../src/guard.ts","../src/hook/post-tool-use.ts","../src/status/line.ts","../src/render.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 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 { isAbsolute, relative, resolve } from 'node:path';\nimport type { AgentKind } from './agents.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 // Claude Code's per-session temporary folder, where agents write their reports.\n scratchRoot: string;\n}\n\nconst READ_ONLY_BASH: { pattern: RegExp; label: string }[] = [\n { pattern: /(^|[^\\w-])(rm|mv|cp|tee|truncate|chmod|chown|ln)\\s/, label: 'file change' },\n { pattern: /\\bsed\\s+(-\\w*\\s+)*-i/, label: 'sed -i' },\n {\n pattern:\n /\\bgit\\s+(add|commit|push|stash|reset|checkout|switch|merge|rebase|cherry-pick|apply|restore|rm|mv|tag)\\b/,\n label: 'git write',\n },\n {\n pattern:\n /\\b(npm|pnpm|yarn|bun)\\s+(i|install|add|remove|rm|uninstall|update|up)\\b|\\bpip3?\\s+install\\b/,\n label: 'package install',\n },\n];\n\nconst PUBLISH_BASH = /\\bgit\\s+(commit|push|stash)\\b/;\n// `=>`, `>=` and `->` are operators of an inline script, not redirects.\nconst REDIRECT = /(?:^|[^<>&\\d=-])\\d?>>?(?!=)\\s*([^\\s;&|)]+)/g;\nconst QUOTED = /'[^']*'|\"(?:[^\"\\\\]|\\\\.)*\"/g;\n\nfunction inside(path: string, folder: string): boolean {\n const rest = relative(resolve(folder), resolve(path));\n return rest === '' || (!rest.startsWith('..') && !isAbsolute(rest));\n}\n\nfunction absolute(path: string, cwd: string | undefined): string {\n return isAbsolute(path) ? path : resolve(cwd ?? '/', path);\n}\n\nfunction writableRedirect(target: string, input: GuardInput): boolean {\n if (target === '/dev/null' || target.startsWith('&')) return true;\n return inside(absolute(target, input.cwd), input.scratchRoot);\n}\n\nfunction readOnlyBashViolation(input: GuardInput): string | undefined {\n const command = input.command ?? '';\n for (const rule of READ_ONLY_BASH) if (rule.pattern.test(command)) return rule.label;\n // A `>` inside quotes is text handed to a program, not a redirect of the shell.\n for (const match of command.replace(QUOTED, \"''\").matchAll(REDIRECT)) {\n if (!writableRedirect(match[1] ?? '', input)) return `redirect to ${match[1]}`;\n }\n return undefined;\n}\n\nexport function guardToolCall(input: GuardInput): string | undefined {\n const contract = `the ${input.kind} contract`;\n if (input.kind === 'implement') {\n if (input.toolName === 'Bash') {\n return PUBLISH_BASH.test(input.command ?? '')\n ? `${contract} forbids git commit, push and stash: the human commits`\n : undefined;\n }\n if (!input.worktree || !input.filePath) return undefined;\n const path = absolute(input.filePath, input.cwd);\n if (inside(path, input.worktree) || inside(path, input.scratchRoot)) return undefined;\n return `${contract} limits writes to its worktree ${input.worktree}`;\n }\n if (FILE_TOOLS.has(input.toolName)) {\n if (input.filePath && inside(absolute(input.filePath, input.cwd), input.scratchRoot)) {\n return undefined;\n }\n return `${contract} is read-only: write only the report in the scratchpad`;\n }\n if (input.toolName === 'Bash') {\n const violation = readOnlyBashViolation(input);\n return violation ? `${contract} is read-only: ${violation} is not allowed` : undefined;\n }\n return undefined;\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 { Carnet } from '../carnet.ts';\nimport { guardToolCall, kindOfAgentType } from '../guard.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 scratchRoot: 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 scratchRoot,\n });\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.\nexport function renderStatusLine(view: StatusView, lag: string | null = null): string {\n if (lag) return `${STATUS_LINE_LABEL} · ${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.length === 0 ? '' : [STATUS_LINE_LABEL, ...parts].join(' · ');\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","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"],"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,YAA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,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;;AChDA,SAAgB,mBACd,WACA,UAAqC,CAAC,GACxB;CACd,UAAU,UAAU,cAAc,EAAE,WAAW,KAAK,CAAC;CACrD,UAAU,iBAAiB,SAAS,GAAG,EAAE,WAAW,KAAK,CAAC;CAC1D,MAAM,SAAuB;EAAE,cAAc,UAAU;EAAc,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CAC9F,KAAK,MAAM,MAAM,QAAQ,OAAO,CAAC,QAAQ,IAAI,IAAI,eAAe,SAAS,GAAG;EAC1E,MAAM,WAAW,SAAS,EAAE,CAAC,CAAC,mBAAmB,SAAS;EAC1D,OAAO,QAAQ,KAAK,GAAG,SAAS,OAAO;EACvC,OAAO,QAAQ,KAAK,GAAG,SAAS,OAAO;CACzC;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/move.ts","../src/hook/session-end.ts","../src/hook/session-start.ts","../src/hook/user-prompt-submit.ts","../src/guard.ts","../src/launch.ts","../src/hook/post-tool-use.ts","../src/status/line.ts","../src/render.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 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 { isAbsolute, join, relative, resolve } from 'node:path';\nimport type { AgentKind } from './agents.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-session temporary folder, where agents write their reports.\n scratchRoot: string;\n}\n\nconst READ_ONLY_BASH: { pattern: RegExp; label: string }[] = [\n { pattern: /(^|[^\\w-])(rm|mv|cp|tee|truncate|chmod|chown|ln)\\s/, label: 'file change' },\n { pattern: /\\bsed\\s+(-\\w*\\s+)*-i/, label: 'sed -i' },\n {\n pattern:\n /\\bgit\\s+(?:-[Cc]\\s+\\S+\\s+)*(add|commit|push|stash|reset|checkout|switch|merge|rebase|cherry-pick|apply|restore|rm|mv|tag)\\b/,\n label: 'git write',\n },\n {\n pattern:\n /\\b(npm|pnpm|yarn|bun)\\s+(i|install|add|remove|rm|uninstall|update|up)\\b|\\bpip3?\\s+install\\b/,\n label: 'package install',\n },\n];\n\nconst PUBLISH_BASH = /\\bgit\\s+(?:-[Cc]\\s+\\S+\\s+)*(commit|push|stash)\\b/;\nconst PUSH_BASH = /\\bgit\\s+(?:-[Cc]\\s+\\S+\\s+)*push\\b/;\nconst GLOBAL_INSTALL = /\\b(npm|pnpm|yarn|bun)\\s[^;&|]*(\\s-g\\b|\\s--global\\b)/;\nconst LEADING_CD = /^\\s*cd\\s+([^\\s;&|]+)\\s*(?:&&|;)/;\nconst SHELL_WORDS = /[\\s;&|()<>]+/;\n// `=>`, `>=` and `->` are operators of an inline script, not redirects.\nconst REDIRECT = /(?:^|[^<>&\\d=-])\\d?>>?(?!=)\\s*([^\\s;&|)]+)/g;\nconst QUOTED = /'[^']*'|\"(?:[^\"\\\\]|\\\\.)*\"/g;\n\nfunction inside(path: string, folder: string): boolean {\n const rest = relative(resolve(folder), resolve(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 writable(path: string, input: GuardInput): boolean {\n return inside(path, input.scratchRoot) || (!!input.sandbox && inside(path, input.sandbox));\n}\n\nfunction writableRedirect(target: string, input: GuardInput): boolean {\n if (target === '/dev/null' || target.startsWith('&')) return true;\n return writable(absolute(target, input.cwd), input);\n}\n\nfunction pathLike(word: string): boolean {\n return word.startsWith('/') || word.startsWith('~') || /(^|\\/)\\.\\.(\\/|$)/.test(word);\n}\n\n// A writing command passes when it runs in the sandbox and names no path outside it.\nfunction confinedToSandbox(input: GuardInput, sandbox: string): boolean {\n const command = input.command ?? '';\n const lead = LEADING_CD.exec(command);\n const directory = lead ? absolute(lead[1] ?? '', input.cwd) : (input.cwd ?? '/');\n if (!inside(directory, sandbox)) return false;\n return command\n .split(SHELL_WORDS)\n .flatMap((word) => word.replace(/^['\"]|['\"]$/g, '').split('='))\n .filter(pathLike)\n .every((word) => word === '/dev/null' || writable(absolute(word, directory), input));\n}\n\nfunction readOnlyBashViolation(input: GuardInput): string | undefined {\n const command = input.command ?? '';\n for (const rule of READ_ONLY_BASH) if (rule.pattern.test(command)) return rule.label;\n // A `>` inside quotes is text handed to a program, not a redirect of the shell.\n for (const match of command.replace(QUOTED, \"''\").matchAll(REDIRECT)) {\n if (!writableRedirect(match[1] ?? '', input)) return `redirect to ${match[1]}`;\n }\n return undefined;\n}\n\nexport function guardToolCall(input: GuardInput): string | undefined {\n const contract = `the ${input.kind} contract`;\n if (input.kind === 'implement') {\n if (input.toolName === 'Bash') {\n return PUBLISH_BASH.test(input.command ?? '')\n ? `${contract} forbids git commit, push and stash: the human commits`\n : undefined;\n }\n if (!input.worktree || !input.filePath) return undefined;\n const path = absolute(input.filePath, input.cwd);\n if (inside(path, input.worktree) || inside(path, input.scratchRoot)) return undefined;\n return `${contract} limits writes to its worktree ${input.worktree}`;\n }\n const sandbox = input.sandbox;\n if (FILE_TOOLS.has(input.toolName)) {\n if (input.filePath && writable(absolute(input.filePath, input.cwd), input)) return undefined;\n return sandbox\n ? `${contract} limits writes to its sandbox ${sandbox} and the scratchpad`\n : `${contract} is read-only: write only the report in the scratchpad`;\n }\n if (input.toolName !== 'Bash') return undefined;\n if (!sandbox) {\n const violation = readOnlyBashViolation(input);\n return violation ? `${contract} is read-only: ${violation} is not allowed` : undefined;\n }\n const command = input.command ?? '';\n if (PUSH_BASH.test(command)) return `${contract} forbids git push`;\n if (GLOBAL_INSTALL.test(command)) return `${contract} forbids global package installs`;\n const violation = readOnlyBashViolation(input);\n if (!violation || confinedToSandbox(input, sandbox)) return undefined;\n return `${contract} limits writing commands to its sandbox ${sandbox}: ${violation} is not allowed here`;\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 scratchRoot: 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 scratchRoot,\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","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"],"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,IAAI,QAAQ,CAAC,QAAQ,OACnB,MAAM,IAAI,YACR,sBACA,aAAa,gBAAgB,uBAAuB,KAAK,KAAK,gCAChE;CAEF,MAAM,SAAS,WAAW,QAAQ,QAAQ,EAAE;CAC5C,MAAM,QAAQ,IAAI,IAAI,OAAO,WAAW,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC;CAC7D,MAAM,YAAY,OAChB,OAAO,GAAG,QAAQ,6CAA6C,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AAK,CAAC;CAC1D,MAAM,SAAuB;EAAE,cAAc,UAAU;EAAc,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CAC9F,KAAK,MAAM,MAAM,QAAQ,OAAO,CAAC,QAAQ,IAAI,IAAI,eAAe,SAAS,GAAG;EAC1E,MAAM,WAAW,SAAS,EAAE,CAAC,CAAC,mBAAmB,SAAS;EAC1D,OAAO,QAAQ,KAAK,GAAG,SAAS,OAAO;EACvC,OAAO,QAAQ,KAAK,GAAG,SAAS,OAAO;CACzC;CACA,OAAO;AACT"}
package/dist/mcp.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { r as OpenCarnetOptions, t as Carnet, xt as Host } from "./carnet-MC9WeQ6h.mjs";
1
+ import { St as Host, i as OpenCarnetOptions, t as Carnet } from "./carnet-DcHESFRd.mjs";
2
2
  import { McpServer } from "@modelcontextprotocol/server";
3
3
  import { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
4
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, analyze, implement, review), then launch it in a later message.\n- Each step of a fork's work: agent_step (answered, applying, applied, tested, committed, dropped).\n- Final actions, only when the human asks: agent_inject (research), agent_questions then agent_answer then agent_promote (analyze), review_findings then review_decide (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 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. 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- Reports, only when the human asks: agent_report, then agent_inject or agent_promote (research), agent_questions then agent_answer then agent_promote (plan), review_findings then review_decide (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.";
6
6
  interface SessionResolverOptions {
7
7
  carnet: Carnet;
8
8
  env?: NodeJS.ProcessEnv | undefined;
@@ -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;UChC9C;EACf;;UAGe,eAAe,eAAe,EAAE,YAAY,EAAE;EAC7D;EACA;EACA,QAAQ;EACR,MAAM,QAAQ,QAAQ,mBAAmB,MAAM,EAAE,MAAM,YAAY;;qBAilBxD,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;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;UC9B9C;EACf;;UAGe,eAAe,eAAe,EAAE,YAAY,EAAE;EAC7D;EACA;EACA,QAAQ;EACR,MAAM,QAAQ,QAAQ,mBAAmB,MAAM,EAAE,MAAM,YAAY;;qBAgnBxD,gBAAgB"}
package/dist/mcp.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { E as renderAgentLine, Jt as renderQuestions, K as memoryHalfLife, N as renderTableLine, Nn as OPEN_AGENT_STATUSES, Pn as USER_ACTION_STATUSES, Qt as renderFindings, Rn as EVENT_TYPES, Tn as EMOJI, V as NOTE_KINDS, Vn as CarnetError, Xt as FINDING_SEVERITIES, Yt as FINDING_DECISIONS, Zt as formatFinding, a as formatEventLine, bn as statusAfterAnswers, hn as FINAL_ACTIONS, in as reportsDirectory, l as openCarnet, lt as hostById, n as stepAgent, o as resumeContext, pn as AGENT_KINDS, rn as reportPath, s as sessionLabel, st as DEFAULT_HOST, t as AGENT_STEPS, yn as mainTargetRange } from "./steps-xzr8iVWn.mjs";
1
+ import { $t as renderFindings, Cn as mainTargetRange, E as renderAgentLine, Gn as CarnetError, H as NOTE_KINDS, Hn as EVENT_TYPES, I as sandboxRemovedSuffix, Ln as OPEN_AGENT_STATUSES, N as renderTableLine, Qt as formatFinding, Rn as USER_ACTION_STATUSES, Vn as kindTag, Xt as FINDING_DECISIONS, Yt as renderQuestions, Zt as FINDING_SEVERITIES, _n as KIND_REQUIRED, a as formatEventLine, an as reportsDirectory, ct as DEFAULT_HOST, gn as KIND_ACTIONS, hn as AGENT_KINDS, in as reportPath, kn as EMOJI, l as openCarnet, n as stepAgent, o as resumeContext, q as memoryHalfLife, s as sessionLabel, t as AGENT_STEPS, ut as hostById, vn as PROMOTE_KIND_REQUIRED, wn as statusAfterAnswers } from "./steps-wNm8GU_c.mjs";
2
2
  import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { McpServer } from "@modelcontextprotocol/server";
@@ -8,9 +8,9 @@ import * as z from "zod/v4";
8
8
  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.
9
9
 
10
10
  Which tool, when:
11
- - Launch: agent_start with the agent's kind (research, analyze, implement, review), then launch it in a later message.
11
+ - 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. A plan agent is always a Rucher fork, never the built-in Plan subagent or plan mode.
12
12
  - Each step of a fork's work: agent_step (answered, applying, applied, tested, committed, dropped).
13
- - Final actions, only when the human asks: agent_inject (research), agent_questions then agent_answer then agent_promote (analyze), review_findings then review_decide (review). review_context before launching a review.
13
+ - Reports, only when the human asks: agent_report, then agent_inject or agent_promote (research), agent_questions then agent_answer then agent_promote (plan), review_findings then review_decide (review). review_context before launching a review.
14
14
  - Main line text for work of your own: table_set, table_clear.
15
15
  - Other moves: agent_update, agent_drop, queue_reorder. Recall: agent_list, log_read, session_resume_info, session_list.
16
16
  - 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.
@@ -72,12 +72,12 @@ function appendToReport(path, markdown) {
72
72
  const separator = current.endsWith("\n\n") ? "" : current.endsWith("\n") ? "\n" : "\n\n";
73
73
  appendFileSync(path, `${separator}${markdown.trimEnd()}\n`);
74
74
  }
75
- function planPath(report) {
76
- return report.replace(/(\.md)?$/, ".plan.md");
75
+ function keptReportPath(report, kind) {
76
+ return report.replace(/(\.md)?$/, kind === "plan" ? ".plan.md" : ".research.md");
77
77
  }
78
78
  // src/kinds.ts
79
- function finalAction(agent) {
80
- return FINAL_ACTIONS[agent.kind];
79
+ function kindAction(agent) {
80
+ return KIND_ACTIONS[agent.kind];
81
81
  }
82
82
  function finishWithItems(carnet, session, name, input) {
83
83
  const agent = requireAgent(carnet, session, name);
@@ -143,34 +143,95 @@ function injectReport(carnet, session, name, input) {
143
143
  const agent = requireAgent(carnet, session, name);
144
144
  const report = readReport(agent.reportPath);
145
145
  if (report === void 0) throw new CarnetError("REPORT_MISSING", `${name} has no report to inject yet`);
146
- const names = input.section ? [input.section] : agent.kind === "analyze" || agent.promotedFrom === "analyze" ? PLAN : FOR_MAIN;
146
+ const names = input.section ? [input.section] : agent.kind === "plan" || agent.promotedFrom === "plan" ? PLAN : FOR_MAIN;
147
147
  const text = input.full ? report.trim() : extractSection(report, names);
148
148
  if (text === void 0) throw new CarnetError("SECTION_NOT_FOUND", `No "## ${names[0]}" section in ${name}'s report; pass section or full`);
149
149
  const lineCount = text.split("\n").length;
150
150
  const note = `${input.full ? "full report" : names[0]}, ${lineCount} lines`;
151
- if (agent.kind === "research" && agent.status !== "closed") carnet.agents.close(session, name, {
151
+ let removed = false;
152
+ if (agent.kind === "research" && agent.status !== "closed") removed = carnet.agents.close(session, name, {
152
153
  type: "injected",
153
154
  note,
154
155
  link: agent.reportPath ?? void 0
155
- });
156
+ }).sandboxRemoved;
156
157
  else carnet.events.log(session, {
157
158
  type: "injected",
158
159
  agent: name,
159
160
  note
160
161
  });
161
- return `${name} injected (${lineCount} lines)\n${text}`;
162
+ const confirmation = `${name} injected (${lineCount} lines)${sandboxRemovedSuffix(removed)}`;
163
+ return input.echo === false ? confirmation : `${confirmation}\n${text}`;
164
+ }
165
+ function firstLines(text, max) {
166
+ if (!text) return [];
167
+ const lines = text.split("\n").filter((line) => line.trim() !== "");
168
+ return lines.length > max ? [...lines.slice(0, max), "…"] : lines;
169
+ }
170
+ function firstParagraph(text, max) {
171
+ return firstLines(text?.split(/\n\s*\n/)[0], max);
172
+ }
173
+ const TOP_LEVEL_ITEM = /^(-|\*|\d+\.)\s|^\*\*/;
174
+ function topLevelItems(text, max) {
175
+ return firstLines(text?.split("\n").filter((line) => TOP_LEVEL_ITEM.test(line)).join("\n"), max);
176
+ }
177
+ function planSteps(plan) {
178
+ if (!plan) return [];
179
+ const headings = plan.split("\n").filter((line) => /^###\s/.test(line));
180
+ return (headings.length > 0 ? headings : plan.split("\n").filter((line) => /^\d+\.\s/.test(line))).map((line) => line.replace(/^###\s+/, "").trim());
181
+ }
182
+ function block(title, lines) {
183
+ return lines.length > 0 ? [`${title}:`, ...lines] : [];
184
+ }
185
+ function reportSummary(carnet, session, name) {
186
+ const agent = requireAgent(carnet, session, name);
187
+ const report = readReport(agent.reportPath);
188
+ if (report === void 0) throw new CarnetError("REPORT_MISSING", `${name} has no report yet`);
189
+ const section = (...names) => extractSection(report, names);
190
+ const emoji = agent.status === "closed" ? "" : `${EMOJI[agent.status]} `;
191
+ const lines = [`${name} ${kindTag(agent.kind)} ${emoji}→ ${kindAction(agent)}`];
192
+ if (agent.kind === "research") lines.push(...block("For the main", firstLines(section(...FOR_MAIN), 15)), ...block("Gaps", firstLines(section("gaps"), 3)));
193
+ else if (agent.kind === "plan") {
194
+ const plan = section(...PLAN);
195
+ const steps = planSteps(plan);
196
+ const open = carnet.questions.list(session, name, true).length;
197
+ const understanding = section("understanding");
198
+ lines.push(...block("Understanding", steps.length > 0 ? firstParagraph(understanding, 5) : firstLines(understanding, 15)), ...steps.length > 0 ? block(`Plan, ${steps.length} steps`, steps) : [`Plan: ${firstLines(plan, 1)[0] ?? "none"}`], `Questions: ${open} open`);
199
+ } else if (agent.kind === "implement") lines.push(...block("Done", topLevelItems(section("done"), 8)), ...block("Deviations", firstLines(section("deviations"), 6)), ...block("Risks", firstLines(section("risks"), 6)), ...block("Commit message", firstLines(section("commit message")?.replace(/```\w*/g, ""), 1)));
200
+ else {
201
+ const pending = carnet.findings.list(session, name, true);
202
+ const bySeverity = [
203
+ "blocking",
204
+ "to_fix",
205
+ "suggestion"
206
+ ].map((severity) => [severity, pending.filter((f) => f.severity === severity).length]).filter(([, count]) => count > 0).map(([severity, count]) => `${count} ${severity.replace("_", " ")}`);
207
+ lines.push(...block("Verdict", firstLines(section("verdict"), 1)), `Findings: ${bySeverity.length > 0 ? bySeverity.join(", ") : "none pending"}`, ...block("Not verified", firstLines(section("not verified"), 3)));
208
+ }
209
+ if (!hasSection(report, [
210
+ ...FOR_MAIN,
211
+ ...PLAN,
212
+ "understanding",
213
+ "done",
214
+ "verdict"
215
+ ])) lines.push(...block("Report", firstLines(report.replace(/^#[^\n]*\n/, ""), 10)));
216
+ lines.push(`report: ${agent.reportPath}`);
217
+ return lines.join("\n");
162
218
  }
163
219
  function promoteText(carnet, session, name, input) {
164
220
  const current = requireAgent(carnet, session, name);
165
221
  const agent = carnet.agents.promote(session, name, input);
166
- const lines = [`${EMOJI.running} ${name} promoted to implement`];
167
- if (current.reportPath && existsSync(current.reportPath)) {
168
- const plan = planPath(current.reportPath);
169
- copyFileSync(current.reportPath, plan);
170
- lines.push(`plan kept: ${plan}`);
222
+ const lines = [`${EMOJI.running} ${name} promoted to ${agent.kind}`];
223
+ const from = current.kind;
224
+ if ((from === "research" || from === "plan") && current.reportPath) {
225
+ if (existsSync(current.reportPath)) {
226
+ const kept = keptReportPath(current.reportPath, from);
227
+ copyFileSync(current.reportPath, kept);
228
+ lines.push(`${from === "plan" ? "plan" : "research"} kept: ${kept}`);
229
+ }
171
230
  }
172
231
  if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);
173
232
  if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);
233
+ if (agent.sandbox) lines.push(`sandbox kept: ${agent.sandbox}`);
234
+ if (agent.sandboxRemoved) lines.push("sandbox removed");
174
235
  return lines.join("\n");
175
236
  }
176
237
  function reviewContext(carnet, session, target) {
@@ -183,7 +244,10 @@ function reviewContext(carnet, session, target) {
183
244
  if (agent.reportPath) lines.push(`report: ${agent.reportPath}`);
184
245
  if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);
185
246
  if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);
186
- if (agent.reportPath && existsSync(planPath(agent.reportPath))) lines.push(`plan: ${planPath(agent.reportPath)}`);
247
+ for (const kind of ["research", "plan"]) {
248
+ const kept = agent.reportPath ? keptReportPath(agent.reportPath, kind) : null;
249
+ if (kept && existsSync(kept)) lines.push(`${kind === "plan" ? "plan" : "research"}: ${kept}`);
250
+ }
187
251
  const answered = carnet.questions.list(session, target).filter((question) => question.answer);
188
252
  if (answered.length) {
189
253
  lines.push("answers:");
@@ -234,10 +298,11 @@ const agentStart = defineTool({
234
298
  schema: z.object({
235
299
  name: agentName,
236
300
  task: z.string().min(1).describe("One-line task given to the fork"),
237
- kind: z.enum(AGENT_KINDS).optional().describe("Agent type, always pass it: research (reads, reports for the main), analyze (plan and questions), implement (writes code), review (reads a diff, reports findings)"),
301
+ kind: z.enum(AGENT_KINDS, { error: KIND_REQUIRED }).describe("Agent type, required: research (reads, reports for the main), plan (plans a wanted change and asks its questions; a Rucher fork, never the built-in Plan subagent), implement (writes code, the only kind with a worktree), review (reads a diff, reports findings)"),
238
302
  target: z.string().optional().describe("Review only, required there: the implement agent it reviews, or main[:<range>]"),
239
303
  base_commit: z.string().optional().describe("Commit the fork starts from"),
240
- worktree: z.string().optional().describe("Worktree path when the fork has one"),
304
+ worktree: z.string().optional().describe("Implement only: worktree path when the fork has one"),
305
+ sandbox: z.string().optional().describe("Research or plan only: throwaway folder under the run directory's sandboxes folder, created empty, writable by the agent, removed when it closes"),
241
306
  session
242
307
  }),
243
308
  run: (carnet, sessionId, args) => {
@@ -248,11 +313,13 @@ const agentStart = defineTool({
248
313
  kind: args.kind,
249
314
  target: args.target,
250
315
  baseCommit: args.base_commit,
251
- worktree: args.worktree
316
+ worktree: args.worktree,
317
+ sandbox: args.sandbox
252
318
  });
253
- if (!workspace) return { text: `${EMOJI.running} ${agent.name} started outside any workspace\nNo report destination: the report stays where the fork writes it` };
319
+ const sandbox = agent.sandbox ? `\nSandbox: ${agent.sandbox}` : "";
320
+ if (!workspace) return { text: `${EMOJI.running} ${agent.name} started outside any workspace\nNo report destination: the report stays where the fork writes it${sandbox}` };
254
321
  mkdirSync(reportsDirectory(workspace), { recursive: true });
255
- return { text: `${EMOJI.running} ${agent.name} started in workspace ${workspace.name}\nReport destination: ${reportPath(workspace, agent.name)}` };
322
+ return { text: `${EMOJI.running} ${agent.name} started in workspace ${workspace.name}\nReport destination: ${reportPath(workspace, agent.name)}${sandbox}` };
256
323
  }
257
324
  });
258
325
  const agentUpdate = defineTool({
@@ -279,7 +346,8 @@ const agentUpdate = defineTool({
279
346
  status: agent.status,
280
347
  action: agent.blockedOn ? `→ ${agent.blockedOn}` : null,
281
348
  emoji: agent.status === "closed" ? "" : EMOJI[agent.status],
282
- note: agent.note
349
+ note: agent.note,
350
+ pinned: agent.queueOrder !== null
283
351
  }) };
284
352
  }
285
353
  });
@@ -343,12 +411,13 @@ const agentDrop = defineTool({
343
411
  session
344
412
  }),
345
413
  run: (carnet, sessionId, args) => {
346
- return { text: `${carnet.agents.drop(sessionId, args.name, args.reason).name} closed` };
414
+ const agent = carnet.agents.drop(sessionId, args.name, args.reason);
415
+ return { text: `${agent.name} closed${sandboxRemovedSuffix(agent.sandboxRemoved)}` };
347
416
  }
348
417
  });
349
418
  const agentList = defineTool({
350
419
  name: "agent_list",
351
- description: "List the open agents of the session: kind, status, final action, note, task and report path.",
420
+ description: "List the open agents of the session: kind, status, next action, note, task and report path.",
352
421
  schema: z.object({
353
422
  kind: z.enum(AGENT_KINDS).optional().describe("Only agents of this kind"),
354
423
  session
@@ -356,12 +425,13 @@ const agentList = defineTool({
356
425
  run: (carnet, sessionId, args) => {
357
426
  const lines = carnet.agents.list(sessionId).filter((agent) => !args.kind || agent.kind === args.kind).map((agent) => {
358
427
  const emoji = agent.status === "closed" ? "" : EMOJI[agent.status];
359
- const action = agent.status === "running" ? "" : ` → ${finalAction(agent)}`;
428
+ const action = agent.status === "running" ? "" : ` → ${kindAction(agent)}`;
360
429
  const target = agent.target ? ` on ${agent.target}` : "";
361
430
  const blocked = agent.blockedOn ? ` blocked on ${agent.blockedOn}` : "";
362
431
  const note = agent.note ? ` — ${agent.note}` : "";
363
432
  const report = agent.reportPath ? ` (report: ${agent.reportPath})` : "";
364
- return `${emoji} ${agent.name} ${agent.kind}${target} [${agent.status}]${blocked}${action}${note}${report}`;
433
+ const sandbox = agent.sandbox ? ` (sandbox: ${agent.sandbox})` : "";
434
+ return `${emoji} ${agent.name} ${agent.kind}${target} [${agent.status}]${blocked}${action}${note}${report}${sandbox}`;
365
435
  });
366
436
  return { text: lines.length ? lines.join("\n") : "no open agents" };
367
437
  }
@@ -377,7 +447,7 @@ const agentQuestions = defineTool({
377
447
  });
378
448
  const agentAnswer = defineTool({
379
449
  name: "agent_answer",
380
- description: "Main agent only. Record the human's answers, one or several at once. Appends them to the report. With the last answer, logs answered and moves the agent on: an analyze to 👀 review with its plan to validate, an implement to 📥 apply.",
450
+ description: "Main agent only. Record the human's answers, one or several at once. Appends them to the report. With the last answer, logs answered and moves the agent on: a plan agent to 👀 review with its plan to validate, an implement to 📥 apply.",
381
451
  schema: z.object({
382
452
  name: agentName,
383
453
  answers: z.array(z.object({
@@ -390,28 +460,41 @@ const agentAnswer = defineTool({
390
460
  });
391
461
  const agentInject = defineTool({
392
462
  name: "agent_inject",
393
- description: "Main agent only, when the human asks. Returns a report section for your context: 'For the main' by default, the plan for an analyze or promoted agent. Logs injected; closes a research agent. Works on closed agents.",
463
+ description: "Main agent only, when the human asks. Returns a report section for your context: 'For the main' by default, the plan for a plan or promoted agent. Logs injected; closes a research agent. Works on closed agents.",
394
464
  schema: z.object({
395
465
  name: agentName,
396
466
  section: z.string().optional().describe("Heading to extract instead of the default"),
397
467
  full: z.boolean().optional().describe("The whole report, only when the human asks"),
468
+ echo: z.boolean().optional().describe("false: only confirm, when agent_report already showed the section"),
398
469
  session
399
470
  }),
400
471
  run: (carnet, sessionId, args) => ({ text: injectReport(carnet, sessionId, args.name, {
401
472
  section: args.section,
402
- full: args.full
473
+ full: args.full,
474
+ echo: args.echo
403
475
  }) })
404
476
  });
477
+ const agentReport = defineTool({
478
+ name: "agent_report",
479
+ description: "Main agent only, when the human asks for an agent's report: a short summary built from its report by kind, read-only. Show it as is, then run the kind's next action.",
480
+ schema: z.object({
481
+ name: agentName,
482
+ session
483
+ }),
484
+ run: (carnet, sessionId, args) => ({ text: reportSummary(carnet, sessionId, args.name) })
485
+ });
405
486
  const agentPromote = defineTool({
406
487
  name: "agent_promote",
407
- description: "Main agent only, when the human validates a plan. Turns an analyze agent into implement (same agent, running) and keeps its plan next to the report. Create the worktree first and pass it, then resume the fork with the answers.",
488
+ description: "Main agent only, when the human asks. Continues the same agent under another kind: a research into plan or implement, a plan into implement, keeping the previous report beside the new one. For implement, create the worktree first and pass it. Then resume the fork under the new kind's contract.",
408
489
  schema: z.object({
409
490
  name: agentName,
491
+ kind: z.enum(["plan", "implement"], { error: PROMOTE_KIND_REQUIRED }).describe("Kind the agent becomes: plan or implement"),
410
492
  worktree: z.string().optional().describe("Worktree created for the implementation"),
411
493
  base_commit: z.string().optional().describe("Commit the worktree starts from"),
412
494
  session
413
495
  }),
414
496
  run: (carnet, sessionId, args) => ({ text: promoteText(carnet, sessionId, args.name, {
497
+ kind: args.kind,
415
498
  worktree: args.worktree,
416
499
  baseCommit: args.base_commit
417
500
  }) })
@@ -451,7 +534,7 @@ const reviewDecide = defineTool({
451
534
  });
452
535
  const queueReorder = defineTool({
453
536
  name: "queue_reorder",
454
- description: "Main agent only. Set the order of the 'Waiting on you' list. Named agents come first in the given order, the others follow the default order (answer, review, rest).",
537
+ description: "Main agent only, when the human asks. Pin the order of 'Waiting on you': the named agents come first in the given order, each pin lasting until that agent's status changes. The others follow the default order: test, answer, validate, triage, apply, inject, the rest, longest waiting first.",
455
538
  schema: z.object({
456
539
  names: z.array(agentName).min(1).describe("Agent names in handling order"),
457
540
  session
@@ -612,6 +695,7 @@ const TOOLS = [
612
695
  agentQuestions,
613
696
  agentAnswer,
614
697
  agentInject,
698
+ agentReport,
615
699
  agentPromote,
616
700
  reviewContextTool,
617
701
  reviewFindings,