@rucher/carnet 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.mjs CHANGED
@@ -1,32 +1,28 @@
1
- import { B as renderAgentLine, Bn as PROMOTE_KIND_REQUIRED, C as openCarnet, Dn as reportPath, Dt as DEFAULT_HOST, On as reportsDirectory, Rn as AGENT_KINDS, Sn as SPAWN_KINDS, X as sandboxRemovedSuffix, Yn as EMOJI, _ as openQuestionsText, a as formatEventLine, b as reportSummary, bn as FINDING_DECISIONS, c as answerQuestionsText, cr as EVENT_TYPES, d as findingsText, dr as CarnetError, f as finishWithItems, g as nextAgent, ir as USER_ACTION_STATUSES, kt as hostById, l as decideText, m as kindAction, n as stepAgent, nt as NOTE_KINDS, o as resumeContext, p as injectReport, q as renderTableLine, rr as OPEN_AGENT_STATUSES, s as sessionLabel, st as memoryHalfLife, t as AGENT_STEPS, u as findingsBrief, v as promoteText, x as reviewContext, xn as FINDING_SEVERITIES, zn as KIND_REQUIRED } from "./steps-DfvHqzF0.mjs";
1
+ import { Ar as reportsDirectory, Br as FINDING_ROUTES, F as findingsText, Fi as attachmentInput, G as reportSummary, H as openQuestionsText, Hi as CarnetError, Hr as SPAWN_KINDS, I as finishWithItems, Kr as KIND_REQUIRED, N as answerQuestionsText, O as formatEventLine, P as decideText, R as injectReport, St as renderTableLine, T as stepAgent, Tt as sandboxRemovedSuffix, U as promoteText, Ur as AGENT_KINDS, V as nextAgent, Vr as FINDING_SEVERITIES, Zr as agentMode, a as loadProfiles, bi as formatBytes, di as OPEN_AGENT_STATUSES, fi as USER_ACTION_STATUSES, g as sourceLabel, gi as EVENT_TYPES, gr as loadGlobalConfig, h as resolveRun, ht as renderAgentLine, in as hostById, j as sessionLabel, k as resumeContext, ki as memoryHalfLife, kr as reportPath, m as resolveConfig, n as formatTokens, q as openCarnet, qr as PROMOTE_KIND_REQUIRED, ri as EMOJI, s as profileLookup, tn as DEFAULT_HOST, ur as usableWorkspaceConfig, w as AGENT_STEPS, wi as NOTE_KINDS, xi as referenceLine, yr as BACKENDS, z as kindAction, zr as FINDING_DECISIONS } from "./usage-D3xjR_RF.mjs";
2
+ import * as z from "zod/v4";
2
3
  import { copyFileSync, existsSync, mkdirSync } from "node:fs";
3
4
  import { resolve } from "node:path";
4
5
  import { McpServer } from "@modelcontextprotocol/server";
5
6
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
6
- import * as z from "zod/v4";
7
7
  // src/mcp/instructions.ts
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.
8
+ 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.
9
9
 
10
- Which tool, when:
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, which names the task, never the kind. A plan agent is always a Rucher fork, never the built-in Plan subagent or plan mode.
12
- - Each step of a fork's work: agent_step (answered, applying, applied, tested, committed, dropped).
13
- - 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.
14
- - Main line text for work of your own: table_set, table_clear.
15
- - Other moves: agent_update, agent_drop, queue_reorder. Recall: agent_list, log_read, session_resume_info, session_list.
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.
17
- - Session: session_new when the human names it, session_drop only when asked.
18
- - Fork: agent_update (running, short note) at progress, agent_done last.
10
+ - 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.
11
+ - Fork steps: agent_step. Next actions, only when the human asks (/rucher:next): agent_report, then the kind's tools.
12
+ - Main line for your own work: table_set, table_clear. Recall: agent_list, log_read, session_resume_info.
13
+ - 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.
14
+ - Agents: agent_brief first when the prompt says so, agent_update at progress, agent_done last.
19
15
 
20
- Statuses (the NEXT action): running ⏳ · discussing 💬 · answer ❓ · review 👀 · apply 📥 · test 🧪. Notes and table text: under 60 characters, no paths, no backticks.`;
16
+ Statuses name the NEXT action: running ⏳ · discussing 💬 · answer ❓ · review 👀 · apply 📥 · test 🧪. Notes and Main line: under 60 characters, no paths, no backticks.`;
21
17
  // src/mcp/session.ts
22
18
  const FULL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
19
  function createSessionResolver({ carnet, env = process.env, ppid = process.ppid, cwd = process.cwd(), host = hostById(DEFAULT_HOST) }) {
24
20
  function resolveOwn() {
25
21
  const hooked = carnet.sessions.byHostProcess(host.id, ppid);
26
22
  if (hooked) return hooked.id;
27
- const fromEnvironment = host.sessionIdFromEnvironment(env);
23
+ const fromEnvironment = host.hooks?.sessionIdFromEnvironment(env);
28
24
  if (fromEnvironment) return carnet.sessions.ensure(fromEnvironment, cwd).id;
29
- throw new CarnetError("NO_SESSION", `Cannot tell which ${host.displayName} session this is: pass \`session\`, or install the rucher SessionStart hook`);
25
+ throw new CarnetError("NO_SESSION", `Cannot tell which ${host.displayName} session this is: start it with rucher, or install the rucher SessionStart hook`);
30
26
  }
31
27
  function resolveOverride(override) {
32
28
  try {
@@ -43,52 +39,124 @@ function createSessionResolver({ carnet, env = process.env, ppid = process.ppid,
43
39
  return id;
44
40
  } };
45
41
  }
42
+ // src/mcp/brief.ts
43
+ function partLines(part) {
44
+ const missing = part.missing ? " (missing)" : "";
45
+ if (part.type === "reference") return [`- ${part.title}: ${part.path ?? "?"} · ${formatBytes(part.bytes ?? null)}${missing}`];
46
+ const lines = [`## ${part.title}${missing}`];
47
+ if (part.path) lines.push(`file: ${part.path}${part.bytes != null ? ` · ${formatBytes(part.bytes)}` : ""}`);
48
+ if (part.text) lines.push("", part.text);
49
+ return [...lines, ""];
50
+ }
51
+ function renderBrief(brief) {
52
+ const lines = [`# Brief of ${brief.name} (${brief.kind})`, ""];
53
+ lines.push("## Mission", "", brief.mission ?? brief.task ?? "none given", "");
54
+ if (brief.contract) lines.push("## Contract", "", brief.contract, "");
55
+ const references = brief.parts.filter((part) => part.type === "reference");
56
+ if (references.length) lines.push("## Documents to read", "", ...references.flatMap(partLines), "");
57
+ for (const part of brief.parts.filter((item) => item.type !== "reference")) lines.push(...partLines(part));
58
+ return lines.join("\n").trimEnd();
59
+ }
46
60
  // src/mcp/tools.ts
47
61
  function defineTool(definition) {
48
62
  return definition;
49
63
  }
50
- const session = z.string().optional().describe("Session to target (name, id or id prefix). Omit for the current session.");
64
+ const session = z.string().optional().describe("Another session to read (name or id prefix); omit for this one");
51
65
  const agentName = z.string().min(1).describe("Short agent name, no paths");
66
+ const PLUGIN_UPDATE_HINT = "An older rucher plugin never passes one: update the plugin and restart the session.";
67
+ function mainContextLine(carnet, sessionId, cold) {
68
+ if (cold) return "";
69
+ const session = carnet.sessions.get(sessionId);
70
+ if (!session) return "";
71
+ const launch = hostById(session.host).launch;
72
+ const transcript = launch?.transcriptFiles(session, carnet.env).find((path) => path.endsWith(".jsonl"));
73
+ const tokens = transcript ? launch?.lastContext?.(transcript) : void 0;
74
+ if (!tokens) return "";
75
+ const coldAbove = coldAboveSetting(carnet);
76
+ const above = typeof coldAbove === "number" && tokens > coldAbove;
77
+ return `\nMain context: ${formatTokens(tokens)}${above ? `, above context.coldAbove (${formatTokens(coldAbove)}): suggest --cold to the human` : ""}`;
78
+ }
79
+ function coldAboveSetting(carnet) {
80
+ try {
81
+ const workspace = carnet.workspace;
82
+ return resolveConfig({
83
+ global: loadGlobalConfig(carnet.env),
84
+ workspace: usableWorkspaceConfig(workspace),
85
+ profiles: profileLookup(loadProfiles(carnet.env, workspace))
86
+ }).values.get("context.coldAbove");
87
+ } catch {
88
+ return;
89
+ }
90
+ }
52
91
  const agentStart = defineTool({
53
92
  name: "agent_start",
54
- description: "Main agent only. Register a fork before dispatching it (launch it in a later message). Logs `started`. The result gives the report destination in the workspace, where agent_done copies the report.",
93
+ description: "Main only. Register an agent before launching it in a later message; returns its report destination.",
55
94
  schema: z.object({
56
- name: agentName.describe("Short name for the task, no paths and no kind word (plan, rv, impl…): it stays when the agent is promoted"),
95
+ name: agentName.describe("Short task name, no path, no kind word; kept on promotion"),
57
96
  task: z.string().min(1).describe("One-line task given to the fork"),
58
- 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)"),
59
- target: z.string().optional().describe("Review only, required there: the implement agent it reviews, or main[:<range>]"),
97
+ kind: z.enum(AGENT_KINDS, { error: KIND_REQUIRED }).describe("research (answers a question), plan (plans a change, asks questions), implement (codes in a worktree), review (reads a diff, reports findings)"),
98
+ target: z.string().optional().describe("Review only, required: implement agent name or main[:<range>]"),
60
99
  base_commit: z.string().optional().describe("Commit the fork starts from"),
61
100
  worktree: z.string().optional().describe("Implement only: worktree path when the fork has one"),
62
- 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"),
63
- session
101
+ sandbox: z.string().optional().describe("Research or plan only: throwaway writable folder under the sandboxes folder, removed at close"),
102
+ cold: z.boolean().optional().describe("--cold: launch cold; the default comes from the kind"),
103
+ fork: z.boolean().optional().describe("--fork: launch as a fork when the kind defaults to cold"),
104
+ model: z.string().min(1).optional().describe("Cold agents only: --model override"),
105
+ backend: z.enum(BACKENDS).optional().describe("Cold agents only: --backend override"),
106
+ mission: z.string().optional().describe("A few lines: goal, what was settled, what to return. Required when cold; attach, never paste"),
107
+ attachments: z.array(attachmentInput).optional().describe("By reference, read with agent_brief: doc {path}, ref {id}, deliverable {agent, section}, for_main {agent}, notes {ids|query}; after triage, findings {review, n: [..]} spawned for this name")
64
108
  }),
65
109
  run: (carnet, sessionId, args) => {
66
110
  const workspace = carnet.workspace;
67
- const agent = carnet.agents.start(sessionId, {
111
+ const cold = agentMode(args.kind, {
112
+ cold: args.cold,
113
+ fork: args.fork
114
+ }) === "cold";
115
+ const run = resolveRun({
116
+ kind: args.kind,
117
+ context: cold ? "cold" : "fork",
118
+ override: {
119
+ backend: args.backend,
120
+ model: args.model
121
+ },
122
+ host: "claude-code",
123
+ config: cold ? {
124
+ global: loadGlobalConfig(carnet.env),
125
+ workspace: usableWorkspaceConfig(workspace),
126
+ profiles: profileLookup(loadProfiles(carnet.env, workspace))
127
+ } : void 0
128
+ });
129
+ if (cold && !args.mission?.trim()) throw new CarnetError("MISSION_REQUIRED", `${args.name} runs cold and does not see the conversation: pass a mission. ${PLUGIN_UPDATE_HINT}`);
130
+ const model = cold && run.model ? `\nModel: ${run.model} (${sourceLabel(run.source)})` : "";
131
+ const agent = carnet.agents.startWith(sessionId, {
68
132
  name: args.name,
69
133
  task: args.task,
70
134
  kind: args.kind,
71
135
  target: args.target,
72
136
  baseCommit: args.base_commit,
73
137
  worktree: args.worktree,
74
- sandbox: args.sandbox
75
- });
76
- const sandbox = agent.sandbox ? `\nSandbox: ${agent.sandbox}` : "";
77
- if (!workspace) return { text: `${EMOJI.running} ${agent.name} started outside any workspace\nNo report destination: the report stays where the fork writes it${sandbox}` };
138
+ sandbox: args.sandbox,
139
+ backend: run.backend,
140
+ model: run.model,
141
+ context: cold ? "cold" : "fork",
142
+ mission: args.mission
143
+ }, args.attachments);
144
+ const briefLine = agent.mission || agent.attachments?.length ? `\nBrief: ${agent.attachments?.length ?? 0} attachments, the agent reads it with agent_brief` : "";
145
+ const extra = `${agent.sandbox ? `\nSandbox: ${agent.sandbox}` : ""}${briefLine}${model}${mainContextLine(carnet, sessionId, cold)}`;
146
+ if (!workspace) return { text: `${EMOJI.running} ${agent.name} started outside any workspace\nNo report destination: the report stays where the fork writes it${extra}` };
78
147
  mkdirSync(reportsDirectory(workspace), { recursive: true });
79
- return { text: `${EMOJI.running} ${agent.name} started in workspace ${workspace.name}\nReport destination: ${reportPath(workspace, agent.name)}${sandbox}` };
148
+ return { text: `${EMOJI.running} ${agent.name} started in workspace ${workspace.name}\nReport destination: ${reportPath(workspace, agent.name, agent.id)}${extra}` };
80
149
  }
81
150
  });
82
151
  const agentUpdate = defineTool({
83
152
  name: "agent_update",
84
- description: "Set an agent's status and note. Forks: status running at progress. Main agent: only for moves agent_step does not cover, and blocked_on when an agent waits on another agent (never 💬 discussing for that).",
153
+ description: "Set an agent's status and note. Forks: running at progress. Main: only moves agent_step lacks, and blocked_on when an agent waits on another.",
85
154
  schema: z.object({
86
155
  name: agentName,
87
- status: z.enum(OPEN_AGENT_STATUSES).describe("Next action: running means the fork is working"),
156
+ status: z.enum(OPEN_AGENT_STATUSES).describe("Next action; running while the fork works"),
88
157
  note: z.string().optional().describe("Under 60 characters, no paths, no backticks"),
89
158
  report_path: z.string().optional().describe("New absolute path of the report, when it moved"),
90
- blocked_on: z.string().nullable().optional().describe("Open agent of this session it waits on: it leaves Waiting on you until that agent closes. null clears it"),
91
- session
159
+ blocked_on: z.string().nullable().optional().describe("Open agent it waits on, out of Waiting on you until that one closes; null clears")
92
160
  }),
93
161
  run: (carnet, sessionId, args) => {
94
162
  const agent = carnet.agents.update(sessionId, args.name, {
@@ -108,9 +176,10 @@ const agentUpdate = defineTool({
108
176
  }) };
109
177
  }
110
178
  });
111
- function copyReport(carnet, name, reportFile) {
179
+ function copyReport(carnet, sessionId, name, reportFile) {
112
180
  if (!carnet.workspace) return reportFile;
113
- const destination = reportPath(carnet.workspace, name);
181
+ const agent = carnet.agents.require(sessionId, name);
182
+ const destination = reportPath(carnet.workspace, agent.name, agent.id);
114
183
  if (resolve(reportFile) === destination || !existsSync(reportFile)) return reportFile;
115
184
  mkdirSync(reportsDirectory(carnet.workspace), { recursive: true });
116
185
  copyFileSync(reportFile, destination);
@@ -126,7 +195,8 @@ const findingInput = z.object({
126
195
  severity: z.enum(FINDING_SEVERITIES),
127
196
  location: z.string().optional().describe("file:line"),
128
197
  text: z.string().min(1),
129
- fix: z.string().optional().describe("Proposed fix, short")
198
+ fix: z.string().optional().describe("Proposed fix, short"),
199
+ route: z.enum(FINDING_ROUTES).optional().describe("Your fix route, if any: send back (before apply only), in main, or a new implement, plan or research agent")
130
200
  });
131
201
  const DONE_WORDS = {
132
202
  answer: "needs answers",
@@ -139,18 +209,17 @@ function doneOutcome(name, status) {
139
209
  }
140
210
  const agentDone = defineTool({
141
211
  name: "agent_done",
142
- description: "Forks call this as their LAST tool action, then reply with one line that carries no results. Copies the report to the workspace report destination. Pass questions (and findings for a review) here only, never in the report: Carnet writes them into it. The agent then waits on ❓ answer when questions are open, else 📥 apply (implement) or 👀 review.",
212
+ description: "Forks: LAST tool action, then reply one line without results. Copies the report; questions (and review findings) go here only, never in the report.",
143
213
  schema: z.object({
144
214
  name: agentName,
145
215
  report_path: z.string().min(1).describe("Absolute path of the markdown report"),
146
- questions: z.array(questionInput).optional().describe("Choices left to the human, each with a recommendation"),
216
+ questions: z.array(questionInput).optional().describe("Choices for the human, each with a recommendation"),
147
217
  findings: z.array(findingInput).optional().describe("Review agents only"),
148
- has_questions: z.boolean().optional().describe("Only when the report asks something outside questions"),
149
- session
218
+ has_questions: z.boolean().optional().describe("Only when the report asks outside questions")
150
219
  }),
151
220
  run: (carnet, sessionId, args) => {
152
221
  const agent = finishWithItems(carnet, sessionId, args.name, {
153
- reportPath: copyReport(carnet, args.name, args.report_path),
222
+ reportPath: copyReport(carnet, sessionId, args.name, args.report_path),
154
223
  questions: args.questions,
155
224
  findings: args.findings,
156
225
  hasQuestions: args.has_questions
@@ -161,11 +230,10 @@ const agentDone = defineTool({
161
230
  });
162
231
  const agentDrop = defineTool({
163
232
  name: "agent_drop",
164
- description: "Main agent only. Close an agent once its work is committed or abandoned. It leaves the status view; history stays in the journal.",
233
+ description: "Main only. Close an agent whose work is committed or abandoned.",
165
234
  schema: z.object({
166
235
  name: agentName,
167
- reason: z.string().optional().describe("Why it is closed, for the journal"),
168
- session
236
+ reason: z.string().optional().describe("Why it is closed, for the journal")
169
237
  }),
170
238
  run: (carnet, sessionId, args) => {
171
239
  const agent = carnet.agents.drop(sessionId, args.name, args.reason);
@@ -174,7 +242,7 @@ const agentDrop = defineTool({
174
242
  });
175
243
  const agentList = defineTool({
176
244
  name: "agent_list",
177
- description: "List the open agents of the session: kind, status, next action, note, task and report path.",
245
+ description: "Open agents: kind, status, next action, note, report.",
178
246
  schema: z.object({
179
247
  kind: z.enum(AGENT_KINDS).optional().describe("Only agents of this kind"),
180
248
  session
@@ -195,7 +263,7 @@ const agentList = defineTool({
195
263
  });
196
264
  const agentQuestions = defineTool({
197
265
  name: "agent_questions",
198
- description: "Main agent only. An agent's open questions, numbered n/total, each with its recommendation and alternatives. Ask them one at a time unless the human wants them as text.",
266
+ description: "Main only. An agent's open questions with recommendations and alternatives.",
199
267
  schema: z.object({
200
268
  name: agentName,
201
269
  session
@@ -204,38 +272,38 @@ const agentQuestions = defineTool({
204
272
  });
205
273
  const agentAnswer = defineTool({
206
274
  name: "agent_answer",
207
- 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.",
275
+ description: "Main only. Record the human's answers; the last one moves the agent on.",
208
276
  schema: z.object({
209
277
  name: agentName,
210
278
  answers: z.array(z.object({
211
279
  n: z.number().int().min(1),
212
280
  answer: z.string().min(1)
213
- })).min(1),
214
- session
281
+ })).min(1)
215
282
  }),
216
283
  run: (carnet, sessionId, args) => ({ text: answerQuestionsText(carnet, sessionId, args.name, args.answers) })
217
284
  });
218
285
  const agentInject = defineTool({
219
286
  name: "agent_inject",
220
- 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.",
287
+ description: "Main only, when asked. A report section for your context ('For the main', a plan's outline); closes a research unless session names another.",
221
288
  schema: z.object({
222
289
  name: agentName,
223
290
  section: z.string().optional().describe("Heading to extract instead of the default"),
224
291
  full: z.boolean().optional().describe("The whole report, only when the human asks"),
225
- echo: z.boolean().optional().describe("false: only confirm, when agent_report already showed the section"),
292
+ echo: z.boolean().optional().describe("false: confirm only, agent_report showed it"),
226
293
  session
227
294
  }),
228
- run: (carnet, sessionId, args) => ({ text: injectReport(carnet, sessionId, args.name, {
295
+ run: (carnet, sessionId, args, currentId) => ({ text: injectReport(carnet, sessionId, args.name, {
229
296
  section: args.section,
230
297
  full: args.full,
231
- echo: args.echo
298
+ echo: args.echo,
299
+ close: args.session === void 0 || sessionId === currentId?.()
232
300
  }) })
233
301
  });
234
302
  const agentReport = defineTool({
235
303
  name: "agent_report",
236
- description: "Main agent only, when the human asks to handle an agent (/rucher:next): picks it (the named one, else the first of Waiting on you) and returns a short summary of its report by kind, read-only. Show it as is, then run the kind's next action.",
304
+ description: "Main only, on /rucher:next: summary of an agent's report (named, else first waiting), then the steps of its next action. Show the summary as is, follow the steps.",
237
305
  schema: z.object({
238
- name: z.string().min(1).optional().describe("Agent name or its start; omit for the first agent of Waiting on you"),
306
+ name: z.string().min(1).optional().describe("Name or its start; omit for the first waiting"),
239
307
  session
240
308
  }),
241
309
  run: (carnet, sessionId, args) => {
@@ -245,32 +313,28 @@ const agentReport = defineTool({
245
313
  });
246
314
  const agentPromote = defineTool({
247
315
  name: "agent_promote",
248
- 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.",
316
+ description: "Main only, when asked. Continue an agent as plan or implement (pass the worktree for implement): send the fork the message line it returns, or relaunch it cold.",
249
317
  schema: z.object({
250
318
  name: agentName,
251
- kind: z.enum(["plan", "implement"], { error: PROMOTE_KIND_REQUIRED }).describe("Kind the agent becomes: plan or implement"),
252
- worktree: z.string().optional().describe("Worktree created for the implementation"),
253
- base_commit: z.string().optional().describe("Commit the worktree starts from"),
254
- session
319
+ kind: z.enum(["plan", "implement"], { error: PROMOTE_KIND_REQUIRED }).describe("plan or implement"),
320
+ worktree: z.string().optional().describe("Worktree for implement"),
321
+ base_commit: z.string().optional().describe("Worktree base commit"),
322
+ cold: z.boolean().optional().describe("--cold: relaunch cold with the kept report attached"),
323
+ fork: z.boolean().optional().describe("--fork: resume the fork when the kind defaults to cold"),
324
+ mission: z.string().optional().describe("Required when it continues cold")
255
325
  }),
256
326
  run: (carnet, sessionId, args) => ({ text: promoteText(carnet, sessionId, args.name, {
257
327
  kind: args.kind,
258
328
  worktree: args.worktree,
259
- baseCommit: args.base_commit
329
+ baseCommit: args.base_commit,
330
+ cold: args.cold,
331
+ fork: args.fork,
332
+ mission: args.mission
260
333
  }) })
261
334
  });
262
- const reviewContextTool = defineTool({
263
- name: "review_context",
264
- description: "Main agent only, before launching a review. What the reviewer needs about its target: task, report, worktree, base, plan and answers, or the main repo range.",
265
- schema: z.object({
266
- target: z.string().min(1).describe("Implement agent name, or main[:<range>]"),
267
- session
268
- }),
269
- run: (carnet, sessionId, args) => ({ text: reviewContext(carnet, sessionId, args.target) })
270
- });
271
335
  const reviewFindings = defineTool({
272
336
  name: "review_findings",
273
- description: "Main agent only. A review's open findings, blocking first, numbered n/total, in two groups each with its recommended route (send back, in main, implement, plan, research): to decide (no decision yet) and to route (fix chosen, route pending). The last line names the next pass. Open ones only by default.",
337
+ description: "Main only. A review's open findings with recommended routes (the reviewer's when given): to decide (deferred ones last), then to route; the last line names the next pass.",
274
338
  schema: z.object({
275
339
  name: agentName,
276
340
  all: z.boolean().optional().describe("Also the findings already decided"),
@@ -280,36 +344,51 @@ const reviewFindings = defineTool({
280
344
  });
281
345
  const reviewDecide = defineTool({
282
346
  name: "review_decide",
283
- description: "Main agent only. Record the human's decision on findings, one or several at once: fix (chosen, route decided in a second pass), then sent (back to the implement agent) or fixed (in main, or by a new agent: reason '<kind> agent <name>'); ignored (reason required) at either pass. A finding left for later stays to decide. Once nothing is left to decide or route, logs triaged, closes the review and lists the findings to send to the target.",
347
+ description: "Main only. Record decisions on findings. Pass 1: fix, deferred (review stays open) or ignored (reason required). Pass 2: sent, fixed (in main), spawned (planned agent name and kind) or ignored. A spawn name holding a kind word is refused. Closes the review once no finding is open. An override that leaves a finding open reopens a closed review.",
284
348
  schema: z.object({
285
349
  name: agentName,
286
350
  decisions: z.array(z.object({
287
351
  n: z.number().int().min(1),
288
352
  decision: z.enum(FINDING_DECISIONS),
289
- reason: z.string().optional()
353
+ reason: z.string().optional(),
354
+ agent: z.string().min(1).optional().describe("Spawned only: the name of the agent planned for it"),
355
+ kind: z.enum(SPAWN_KINDS).optional().describe("Spawned only: its kind")
290
356
  })).min(1),
291
- session
357
+ override: z.boolean().optional().describe("Only to correct a mistake: re-decide findings already decided")
292
358
  }),
293
- run: (carnet, sessionId, args) => ({ text: decideText(carnet, sessionId, args.name, args.decisions) })
359
+ run: (carnet, sessionId, args) => ({ text: decideText(carnet, sessionId, args.name, args.decisions, args.override === true) })
294
360
  });
295
- const reviewBrief = defineTool({
296
- name: "review_brief",
297
- description: "Main agent only, after triage. The brief of an agent started for some of a review's findings: the review, its target and the findings with their location and proposed fix. Put it in the agent's prompt as is, after its kind's contract. Read-only.",
298
- schema: z.object({
299
- name: agentName.describe("The review agent"),
300
- findings: z.array(z.number().int().min(1)).min(1).describe("Finding numbers of this agent"),
301
- kind: z.enum(SPAWN_KINDS).describe("Kind of the agent started for them"),
302
- session
303
- }),
304
- run: (carnet, sessionId, args) => ({ text: findingsBrief(carnet, sessionId, args.name, args.findings, args.kind) })
361
+ const agentBrief = defineTool({
362
+ name: "agent_brief",
363
+ description: "Your brief, read first when your prompt says so: mission, a fork's contract, documents to open, what the main attached.",
364
+ schema: z.object({ name: agentName }),
365
+ run: (carnet, sessionId, args) => ({ text: renderBrief(carnet.brief(sessionId, args.name)) })
305
366
  });
367
+ const refList = defineTool({
368
+ name: "ref_list",
369
+ description: "Reference documents of the session, or also of one agent: title, path, size. Read them by path.",
370
+ schema: z.object({ name: agentName.optional().describe("An agent: also its own documents") }),
371
+ run: (carnet, sessionId, args) => {
372
+ const references = carnet.references.list(sessionId, { agent: args.name });
373
+ return { text: references.length ? references.map(referenceLine).join("\n") : "No reference documents" };
374
+ }
375
+ });
376
+ function removedTool(name) {
377
+ return defineTool({
378
+ name,
379
+ description: "Removed.",
380
+ schema: z.looseObject({}),
381
+ run: () => {
382
+ throw new CarnetError("PLUGIN_OUTDATED", `${name} was removed: this plugin is older than the rucher CLI. Update the plugin and restart the session.`);
383
+ }
384
+ });
385
+ }
386
+ const reviewContext = removedTool("review_context");
387
+ const reviewBrief = removedTool("review_brief");
306
388
  const queueReorder = defineTool({
307
389
  name: "queue_reorder",
308
- 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.",
309
- schema: z.object({
310
- names: z.array(agentName).min(1).describe("Agent names in handling order"),
311
- session
312
- }),
390
+ description: "Main only, when asked. Pin agents first in Waiting on you, each until its status changes.",
391
+ schema: z.object({ names: z.array(agentName).min(1).describe("Agent names in handling order") }),
313
392
  run: (carnet, sessionId, args) => {
314
393
  carnet.agents.reorderQueue(sessionId, args.names);
315
394
  const order = carnet.status.view(carnet.sessions.require(sessionId)).waiting.map((line) => line.name).join(", ");
@@ -318,11 +397,10 @@ const queueReorder = defineTool({
318
397
  });
319
398
  const tableSet = defineTool({
320
399
  name: "table_set",
321
- description: "Main agent only. Set the Main line: what the main agent is handling, and the next human action once its turn ends. The hooks show ⚙️ while the main agent works, whatever this line says.",
400
+ description: "Main only. Set the Main line: what you handle, and the next human action once the turn ends.",
322
401
  schema: z.object({
323
402
  text: z.string().min(1).describe("Under 60 characters, no paths, no backticks"),
324
- status: z.enum(USER_ACTION_STATUSES).optional().describe("Next human action once the turn ends; defaults to discussing"),
325
- session
403
+ status: z.enum(USER_ACTION_STATUSES).optional().describe("Default discussing")
326
404
  }),
327
405
  run: (carnet, sessionId, args) => {
328
406
  const item = carnet.table.set(sessionId, {
@@ -334,21 +412,20 @@ const tableSet = defineTool({
334
412
  });
335
413
  const agentStep = defineTool({
336
414
  name: "agent_step",
337
- description: "Main agent only. One call per step of a fork's work: logs the event, moves the agent to the next human action and keeps the Main line in sync; the note replaces the agent's note. answered → apply (implement) or review, applying → Main line (implement only), applied → test, tested (optional) stays on test, committed (commit required) → closed, dropped (note = reason) → closed.",
415
+ description: "Main only. One call per step of a fork's work. answered → apply or review, applying (implement), applied → test, tested, committed (commit required) → closed, dropped (note = reason) → closed.",
338
416
  schema: z.object({
339
417
  name: agentName,
340
418
  step: z.enum(AGENT_STEPS),
341
419
  commit: z.string().optional().describe("Commit sha, for committed"),
342
- note: z.string().optional().describe("Short note for the journal; the reason for dropped"),
343
- next: z.enum(OPEN_AGENT_STATUSES).optional().describe("Override the next status, e.g. running when the fork resumes"),
344
- session
420
+ note: z.string().optional().describe("Journal note; the reason for dropped"),
421
+ next: z.enum(OPEN_AGENT_STATUSES).optional().describe("Override the next status, e.g. running")
345
422
  }),
346
423
  run: (carnet, sessionId, args) => ({ text: stepAgent(carnet, sessionId, args) })
347
424
  });
348
425
  const tableClear = defineTool({
349
426
  name: "table_clear",
350
- description: "Main agent only. Empty the Main line.",
351
- schema: z.object({ session }),
427
+ description: "Main only. Empty the Main line.",
428
+ schema: z.object({}),
352
429
  run: (carnet, sessionId) => {
353
430
  carnet.table.clear(sessionId);
354
431
  return { text: "Main line cleared" };
@@ -356,14 +433,13 @@ const tableClear = defineTool({
356
433
  });
357
434
  const logEvent = defineTool({
358
435
  name: "log_event",
359
- description: "Append a journal event. agent_start, agent_done, agent_drop and agent_step already log theirs: use this only for events outside them.",
436
+ description: "Journal event outside the agent tools, which log their own.",
360
437
  schema: z.object({
361
438
  type: z.enum(EVENT_TYPES),
362
439
  agent: z.string().optional().describe("Agent concerned"),
363
440
  commit: z.string().optional().describe("Commit sha"),
364
441
  link: z.string().optional().describe("Report path or URL"),
365
- note: z.string().optional(),
366
- session
442
+ note: z.string().optional()
367
443
  }),
368
444
  run: (carnet, sessionId, args) => {
369
445
  const event = carnet.events.log(sessionId, {
@@ -384,24 +460,22 @@ const logEvent = defineTool({
384
460
  const sessionName = z.string().trim().min(1).describe("Short session name, used by rucher resume");
385
461
  const sessionNew = defineTool({
386
462
  name: "session_new",
387
- description: "Name the current session (or rename it) so it can be resumed later with `rucher resume <name>`. Makes it an active session, kept by the cleanups.",
463
+ description: "When the human names the session: makes it active and resumable with rucher resume <name>.",
388
464
  schema: z.object({
389
465
  name: sessionName,
390
- purpose: z.string().optional().describe("One line: what this session is for"),
391
- session
466
+ purpose: z.string().optional().describe("One line: what this session is for")
392
467
  }),
393
468
  run: (carnet, sessionId, args) => {
394
469
  const named = carnet.sessions.name(sessionId, args.name, args.purpose);
395
- return { text: `Session named ${named.name}. ${hostById(named.host).renameInstruction(named.name ?? args.name)}` };
470
+ return { text: [`Session named ${named.name}.`, hostById(named.host).launch?.renameInstruction(named.name ?? args.name)].filter(Boolean).join(" ") };
396
471
  }
397
472
  });
398
473
  const sessionList = defineTool({
399
474
  name: "session_list",
400
- description: "List the workspace's sessions, most recently active first. Temp and archived ones are hidden unless asked.",
475
+ description: "The workspace's sessions, latest first; temp and archived on request.",
401
476
  schema: z.object({
402
477
  include_temp: z.boolean().optional(),
403
- include_archived: z.boolean().optional(),
404
- session
478
+ include_archived: z.boolean().optional()
405
479
  }),
406
480
  run: (carnet, sessionId, args) => {
407
481
  const lines = carnet.sessions.list({
@@ -416,11 +490,8 @@ const sessionList = defineTool({
416
490
  });
417
491
  const sessionDrop = defineTool({
418
492
  name: "session_drop",
419
- description: "Main agent only. Archive a session by name, id or id prefix: its open agents are closed and it leaves the lists. History stays in the journal.",
420
- schema: z.object({
421
- name: z.string().trim().min(1).describe("Session name, id or id prefix"),
422
- session
423
- }),
493
+ description: "Main only, when asked. Archive a session and close its open agents.",
494
+ schema: z.object({ name: z.string().trim().min(1).describe("Session name, id or id prefix") }),
424
495
  run: (carnet, _sessionId, args) => {
425
496
  const dropped = carnet.sessions.drop(carnet.sessions.find(args.name).id);
426
497
  return { text: `Session ${sessionLabel(dropped)} archived` };
@@ -428,11 +499,8 @@ const sessionDrop = defineTool({
428
499
  });
429
500
  const sessionResumeInfo = defineTool({
430
501
  name: "session_resume_info",
431
- description: "What a session was doing: its status view and last events, plus the command to resume it. Defaults to the current session.",
432
- schema: z.object({
433
- name: z.string().trim().min(1).optional().describe("Session name, id or id prefix"),
434
- session
435
- }),
502
+ description: "Full state of a session (this one by default): status view, last events, resume command.",
503
+ schema: z.object({ name: z.string().trim().min(1).optional().describe("Session name, id or id prefix") }),
436
504
  run: (carnet, sessionId, args) => {
437
505
  const target = args.name ? carnet.sessions.find(args.name) : carnet.sessions.require(sessionId);
438
506
  const resume = `rucher resume ${target.name ?? target.id} --ws ${target.workspace}`;
@@ -441,7 +509,7 @@ const sessionResumeInfo = defineTool({
441
509
  });
442
510
  const logRead = defineTool({
443
511
  name: "log_read",
444
- description: "Read the last journal events of the session, oldest first.",
512
+ description: "Last journal events, oldest first.",
445
513
  schema: z.object({
446
514
  limit: z.number().int().min(1).max(200).optional().describe("Number of events, default 20"),
447
515
  session
@@ -451,7 +519,7 @@ const logRead = defineTool({
451
519
  return { text: events.length ? events.map(formatEventLine).join("\n") : "no events yet" };
452
520
  }
453
521
  });
454
- const noteId = z.number().int().positive().describe("Note id, as shown by note_list (#14 is 14)");
522
+ const noteId = z.number().int().positive().describe("Note id (#14 is 14)");
455
523
  function noteLine(note) {
456
524
  const repos = note.repos.length ? ` [${note.repos.join(", ")}]` : "";
457
525
  return `#${note.id} ${note.kind}${repos} ${note.text}`;
@@ -468,11 +536,13 @@ const TOOLS = [
468
536
  agentInject,
469
537
  agentReport,
470
538
  agentPromote,
471
- reviewContextTool,
472
539
  reviewFindings,
473
540
  reviewDecide,
474
- reviewBrief,
541
+ agentBrief,
542
+ refList,
475
543
  queueReorder,
544
+ reviewContext,
545
+ reviewBrief,
476
546
  tableSet,
477
547
  tableClear,
478
548
  logEvent,
@@ -483,13 +553,12 @@ const TOOLS = [
483
553
  sessionResumeInfo,
484
554
  defineTool({
485
555
  name: "note_add",
486
- description: "Main agent only. Record what the workspace learned (learning), decided (decision) or tried and gave up (dead_end), at the end of a step. One claim under 200 characters with its reason, no markdown. `repos` only when it applies to some of the workspace's repos; omit it for a general note. A result listing similar notes means a likely duplicate: drop or replace instead of piling up.",
556
+ description: "Main only, end of a step: what no repo's instructions hold. Similar notes in the result: drop or replace rather than pile up.",
487
557
  schema: z.object({
488
558
  kind: z.enum(NOTE_KINDS),
489
- text: z.string().min(1).describe("One claim with its reason, under 200 characters"),
490
- repos: z.array(z.string().min(1)).optional().describe("Repo names of the workspace; omit for a general note"),
491
- agent: z.string().optional().describe("Fork the note comes from"),
492
- session
559
+ text: z.string().min(1).describe("One claim with its reason, under 200 characters, no markdown"),
560
+ repos: z.array(z.string().min(1)).optional().describe("Omit for a general note"),
561
+ agent: z.string().optional().describe("Fork the note comes from")
493
562
  }),
494
563
  run: (carnet, sessionId, args) => {
495
564
  const { note, similar } = carnet.notes.add({
@@ -505,14 +574,13 @@ const TOOLS = [
505
574
  }),
506
575
  defineTool({
507
576
  name: "note_list",
508
- description: "The workspace's active notes, dead ends first, then decisions, then learnings, most cited first. Filter by kind, repo, general (notes without repo) or a substring query. Check it before trying an approach.",
577
+ description: "Active notes, dead ends first. Check before an approach; repo for a repo's notes.",
509
578
  schema: z.object({
510
579
  kind: z.enum(NOTE_KINDS).optional(),
511
580
  repo: z.string().optional().describe("Notes of this repo"),
512
581
  general: z.boolean().optional().describe("Only notes without repo"),
513
582
  query: z.string().optional().describe("Substring of the text"),
514
- include_dropped: z.boolean().optional(),
515
- session
583
+ include_dropped: z.boolean().optional()
516
584
  }),
517
585
  run: (carnet, _sessionId, args) => {
518
586
  const lines = carnet.notes.list({
@@ -528,12 +596,11 @@ const TOOLS = [
528
596
  }),
529
597
  defineTool({
530
598
  name: "note_drop",
531
- description: "Main agent only. Close a note that proved wrong or outdated: it stays in the history, marked dropped with the reason. Pass replaced_by when a corrected note replaces it.",
599
+ description: "Main only. Close a wrong or outdated note.",
532
600
  schema: z.object({
533
601
  id: noteId,
534
602
  reason: z.string().min(1).describe("Why the note is no longer true"),
535
- replaced_by: z.number().int().positive().optional().describe("Id of the note replacing it"),
536
- session
603
+ replaced_by: z.number().int().positive().optional().describe("Id of the note replacing it")
537
604
  }),
538
605
  run: (carnet, sessionId, args) => {
539
606
  const note = carnet.notes.drop(args.id, {
@@ -547,12 +614,11 @@ const TOOLS = [
547
614
  }),
548
615
  defineTool({
549
616
  name: "note_cite",
550
- description: "Cite a note that changed what you did (avoided, followed or adjusted something), with what it changed. Never for a plain read. Citations decide which notes come first.",
617
+ description: "Cite a note that changed what you did, never for a plain read; citations rank notes.",
551
618
  schema: z.object({
552
619
  id: noteId,
553
620
  why: z.string().min(1).describe("What the note changed, short"),
554
- agent: z.string().optional().describe("Fork citing it, when not the main agent"),
555
- session
621
+ agent: z.string().optional().describe("Fork citing it, when not the main agent")
556
622
  }),
557
623
  run: (carnet, sessionId, args) => {
558
624
  const citation = carnet.notes.cite(args.id, {
@@ -567,6 +633,36 @@ const TOOLS = [
567
633
  // src/mcp/server.ts
568
634
  const SERVER_NAME = "carnet";
569
635
  const SERVER_VERSION = "0.0.0";
636
+ function leanJsonSchema(node) {
637
+ if (Array.isArray(node)) return node.map(leanJsonSchema);
638
+ if (!node || typeof node !== "object") return node;
639
+ const out = {};
640
+ for (const [key, value] of Object.entries(node)) {
641
+ if (key === "$schema") continue;
642
+ if (key === "maximum" && value === Number.MAX_SAFE_INTEGER) continue;
643
+ if (key === "minimum" && value === Number.MIN_SAFE_INTEGER) continue;
644
+ if (key === "type" && "const" in node) continue;
645
+ out[key] = leanJsonSchema(value);
646
+ }
647
+ return out;
648
+ }
649
+ function leanInputSchema(advertised, validating) {
650
+ const standard = advertised["~standard"];
651
+ const lean = (convert) => (options) => leanJsonSchema(convert(options));
652
+ return { "~standard": {
653
+ ...validating["~standard"],
654
+ jsonSchema: {
655
+ input: lean(standard.jsonSchema.input),
656
+ output: lean(standard.jsonSchema.output)
657
+ }
658
+ } };
659
+ }
660
+ function takesSession(schema) {
661
+ return "session" in schema.shape;
662
+ }
663
+ function sessionOutdated(name) {
664
+ return new CarnetError("PLUGIN_OUTDATED", `${name} takes no session argument: this plugin is older than the rucher CLI. Update the plugin and restart the session.`);
665
+ }
570
666
  function errorResult(error) {
571
667
  return {
572
668
  isError: true,
@@ -594,24 +690,35 @@ function createCarnetServer(options) {
594
690
  name: SERVER_NAME,
595
691
  version: SERVER_VERSION
596
692
  }, { instructions: INSTRUCTIONS });
597
- for (const tool of TOOLS) server.registerTool(tool.name, {
598
- description: tool.description,
599
- inputSchema: tool.schema
600
- }, (args) => {
601
- try {
602
- const { carnet, resolver } = open();
603
- const sessionId = resolver.resolve(args.session);
604
- const out = tool.run(carnet, sessionId, args);
605
- options.afterTool?.(carnet, sessionId);
606
- return { content: [{
607
- type: "text",
608
- text: out.text
609
- }] };
610
- } catch (error) {
611
- if (error instanceof CarnetError) return errorResult(error);
612
- throw error;
613
- }
614
- });
693
+ for (const tool of TOOLS) {
694
+ const validating = takesSession(tool.schema) ? tool.schema : tool.schema.extend({ session: z.unknown().optional() });
695
+ server.registerTool(tool.name, {
696
+ description: tool.description,
697
+ inputSchema: leanInputSchema(tool.schema, validating)
698
+ }, (args) => {
699
+ try {
700
+ if (!takesSession(tool.schema) && args.session !== void 0) throw sessionOutdated(tool.name);
701
+ const { carnet, resolver } = open();
702
+ const sessionId = takesSession(tool.schema) && args.session !== void 0 ? resolver.resolve(args.session) : resolver.resolve();
703
+ const currentId = () => {
704
+ try {
705
+ return resolver.resolve();
706
+ } catch {
707
+ return;
708
+ }
709
+ };
710
+ const out = tool.run(carnet, sessionId, args, currentId);
711
+ options.afterTool?.(carnet, sessionId);
712
+ return { content: [{
713
+ type: "text",
714
+ text: out.text
715
+ }] };
716
+ } catch (error) {
717
+ if (error instanceof CarnetError) return errorResult(error);
718
+ throw error;
719
+ }
720
+ });
721
+ }
615
722
  return server;
616
723
  }
617
724
  function serveCarnet(options = {}) {