@rucher/carnet 0.1.0 → 0.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
- import { $ as schemaVersion, A as repoNameFor, B as hostById, C as GROUP_FILE, D as isInside, E as isGroupRoot, F as registerGroup, G as groupSettings, H as REPOS_START, I as rucherHome, J as transcriptTitle, K as replaceReposBlock, L as unregisterGroups, M as reportPathFor, N as reportsDirectoryOf, O as loadGroup, P as readRegistry, Q as migrations, R as DEFAULT_HOST, S as GROUP_DIRECTORY, T as findGroupRoot, U as claudeCode, V as REPOS_END, W as groupInstructions, X as openDatabase, Y as MEMORY_DB, Z as migrate, _ as DEFAULT_PURGE_DAYS, a as sessionLabel, at as EMOJI, b as shortId, c as PAIRING_WINDOW_MILLISECONDS, d as formatClock, dt as isUserActionStatus, et as PUBLISH_FALLBACK_MILLISECONDS, f as MAIN_WORKING_SUFFIX, ft as EVENT_TYPES, g as renderTableLine, h as renderStatus, i as resumeContext, it as AGENT_STATUSES, j as repoPathFor, k as locateGroup, l as STOPPED_NOTE, lt as USER_ACTION_STATUSES, m as renderSections, mt as CarnetError, n as RESUME_MAX_CHARACTERS, nt as NOTE_MAX, o as Carnet, ot as LEGEND, p as renderAgentLine, pt as isEventType, q as reposBlock, r as formatEventLine, rt as sanitizeNote, s as openCarnet, st as MAIN_WORKING_EMOJI, t as RESUME_EVENTS, tt as REPORTING_NOTE, u as buildStatusView, ut as isAgentStatus, v as purgeDays, w as REPORTS_DIRECTORY, x as DB_FILE, y as MINIMUM_ID_PREFIX, z as allHosts } from "./resume-Daotqfdq.mjs";
2
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
1
+ import { $ as reportsDirectoryOf, A as DEFAULT_HALF_LIFE_DAYS, At as isAgentStatus, B as similarity, C as DEFAULT_PURGE_DAYS, Ct as sanitizeNote, D as MEMORY_MAX_CHARACTERS, Dt as MAIN_WORKING_EMOJI, E as shortId, Et as LEGEND, F as groupRepoNames, Ft as CarnetError, G as findGroupRoot, H as GROUP_DIRECTORY, I as isNoteKind, J as loadGroup, K as isGroupRoot, L as localDay, M as NOTE_KINDS, Mt as EVENT_TYPES, N as NOTE_TEXT_LIMIT, Nt as SESSION_EVENT_TYPES, O as memoryMaxCharacters, P as STALE_AFTER_ACTIVE_DAYS, Pt as isEventType, Q as reportPathFor, R as memoryHalfLife, S as renderTableLine, St as NOTE_MAX, T as MINIMUM_ID_PREFIX, Tt as EMOJI, U as GROUP_FILE, V as DB_FILE, W as REPORTS_DIRECTORY, X as repoNameFor, Y as locateGroup, Z as repoPathFor, _ as renderNoteLine, _t as migrate, a as sessionLabel, at as allHosts, b as renderSections, bt as PUBLISH_FALLBACK_MILLISECONDS, c as PAIRING_WINDOW_MILLISECONDS, ct as REPOS_START, d as formatClock, dt as groupSettings, et as readRegistry, f as MAIN_WORKING_SUFFIX, ft as replaceReposBlock, g as renderAgentLine, gt as openDatabase, h as SIMILAR_PREFIX, ht as MEMORY_DB, i as resumeContext, it as DEFAULT_HOST, j as DUPLICATE_SIMILARITY, jt as isUserActionStatus, k as renderMemory, kt as USER_ACTION_STATUSES, l as STOPPED_NOTE, lt as claudeCode, m as NOTES_HEADER, mt as transcriptTitle, n as RESUME_MAX_CHARACTERS, nt as rucherHome, o as Carnet, ot as hostById, p as NOTES_FOLD_LINES, pt as reposBlock, q as isInside, r as formatEventLine, rt as unregisterGroups, s as openCarnet, st as REPOS_END, t as RESUME_EVENTS, tt as registerGroup, u as buildStatusView, ut as groupInstructions, v as renderNotes, vt as migrations, w as purgeDays, wt as AGENT_STATUSES, x as renderStatus, xt as REPORTING_NOTE, y as renderNotesSummary, yt as schemaVersion, z as sessionNoteActivity } from "./resume-CQRf2jIa.mjs";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { basename, join, resolve } from "node:path";
4
+ import { createHash } from "node:crypto";
4
5
  // src/group/init.ts
5
6
  function writeGroupFile(root, file) {
6
7
  writeFileSync(join(root, GROUP_DIRECTORY, GROUP_FILE), `${JSON.stringify(file, null, 2)}\n`);
@@ -15,7 +16,10 @@ function initGroup(directory, options = {}) {
15
16
  const groupDirectory = join(root, GROUP_DIRECTORY);
16
17
  if (existsSync(groupDirectory)) throw new CarnetError("GROUP_EXISTS", `${root} is already a Rucher group`);
17
18
  const name = options.name ?? basename(root);
18
- const repos = (options.repos ?? []).map((repo) => resolveRepo(root, repo));
19
+ const repos = [...new Set((options.repos ?? []).map((repo) => resolveRepo(root, repo)))];
20
+ const names = repos.map((repo) => basename(repo));
21
+ const shared = names.find((repoName, index) => names.indexOf(repoName) !== index);
22
+ if (shared) throw new CarnetError("REPO_NAME_TAKEN", `Two repos are named ${shared}: give them distinct names`);
19
23
  const hosts = (options.hosts?.length ? options.hosts : [DEFAULT_HOST]).map((id) => hostById(id).id);
20
24
  mkdirSync(join(groupDirectory, REPORTS_DIRECTORY), { recursive: true });
21
25
  writeGroupFile(root, {
@@ -33,6 +37,8 @@ function initGroup(directory, options = {}) {
33
37
  function addGroupRepo(root, repo) {
34
38
  const group = loadGroup(resolve(root));
35
39
  const path = resolveRepo(group.root, repo);
40
+ const sameName = group.repos.find((existing) => existing !== path && basename(existing) === basename(path));
41
+ if (sameName) throw new CarnetError("REPO_NAME_TAKEN", `${group.name} already has a repo named ${basename(path)}: ${sameName}`);
36
42
  if (!group.repos.includes(path)) writeGroupFile(group.root, {
37
43
  name: group.name,
38
44
  repos: [...group.repos, path],
@@ -51,21 +57,133 @@ function removeGroupRepo(root, repo) {
51
57
  });
52
58
  return loadGroup(group.root);
53
59
  }
60
+ // src/hook/session-end.ts
61
+ function handleSessionEnd(carnet, payload) {
62
+ if (!carnet.sessions.get(payload.session_id)) return void 0;
63
+ return carnet.sessions.end(payload.session_id);
64
+ }
65
+ // src/prompt/core-rules.ts
66
+ const CORE_RULES = `- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.
67
+ - The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.
68
+ - Status lives in Carnet: agent statuses, the "On the table" line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.
69
+ - When a fork finishes, say only "<name> finished, report ready". Never summarise, quote or act on its report or final message until the human asks for that fork's report, even when answering about something else.
70
+ - Forks never commit, push, stash or record notes. A fork writes its report to a file, ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as "<name> done, report written". Only the main agent records notes, at the end of a step.
71
+ - To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.`;
72
+ // src/prompt/prompt.ts
73
+ const PROMPT_FILE = "prompt.md";
74
+ const PROMPTS_DIRECTORY = "prompts";
75
+ function readIfPresent(path) {
76
+ if (!existsSync(path)) return void 0;
77
+ return readFileSync(path, "utf8").trim() || void 0;
78
+ }
79
+ function baseRules(env = process.env) {
80
+ return readIfPresent(join(rucherHome(env), "prompt.md")) ?? "- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the \"On the table\" line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When a fork finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that fork's report, even when answering about something else.\n- Forks never commit, push, stash or record notes. A fork writes its report to a file, ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.";
81
+ }
82
+ function groupRules(group) {
83
+ return readIfPresent(join(group.root, GROUP_DIRECTORY, PROMPT_FILE));
84
+ }
85
+ function rulesText(group, env = process.env) {
86
+ const extra = groupRules(group);
87
+ const base = `Rucher rules:\n${baseRules(env)}`;
88
+ return extra ? `${base}\n\nRules of the ${group.name} group:\n${extra}` : base;
89
+ }
90
+ function rulesVersion(group, env = process.env) {
91
+ return createHash("sha256").update(rulesText(group, env)).digest("hex").slice(0, 12);
92
+ }
93
+ function assemblePrompt(group, session, env = process.env) {
94
+ const identity = `This is the Rucher session ${session.name ?? shortId(session.id)} (${session.kind}) of the ${group.name} group.`;
95
+ return {
96
+ text: `${rulesText(group, env)}\n\n${identity}\n`,
97
+ version: rulesVersion(group, env)
98
+ };
99
+ }
100
+ function appendPromptFile(group, session, env = process.env) {
101
+ const { text, version } = assemblePrompt(group, session, env);
102
+ const directory = join(group.root, GROUP_DIRECTORY, PROMPTS_DIRECTORY);
103
+ mkdirSync(directory, { recursive: true });
104
+ const path = join(directory, `${session.id}.md`);
105
+ writeFileSync(path, text);
106
+ return {
107
+ path,
108
+ version
109
+ };
110
+ }
111
+ function compactReminder(group, env = process.env) {
112
+ return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${rulesText(group, env)}`;
113
+ }
114
+ const OUTSIDE_RUCHER_CONTEXT = "This session was started without rucher, so the Rucher rules are not in its system prompt. Follow the Carnet server instructions and load the rucher skill before dispatching or applying forks.";
115
+ const OUTSIDE_RUCHER_NOTICE = "rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)";
116
+ const RULES_UPDATED_NOTICE = "rucher: rules updated, will apply after the next compaction or in a new session";
117
+ const SUBAGENT_RULES = "Rucher rules for sub-agents: never commit, push or stash. When your task asks for a report, write it to the file it names. If your prompt names you as a Carnet agent, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.";
54
118
  // src/hook/session-start.ts
119
+ const SOURCE_EVENTS = {
120
+ startup: "session.started",
121
+ resume: "session.resumed",
122
+ fork: "session.forked"
123
+ };
124
+ function adoptFork(carnet, session, env) {
125
+ const parentId = env.RUCHER_SESSION_ID;
126
+ if (!parentId || parentId === session.id || !carnet.sessions.get(parentId)) return session;
127
+ let fork = carnet.sessions.setParent(session.id, parentId);
128
+ carnet.memory.copyRepos(parentId, session.id);
129
+ const kind = env.RUCHER_SESSION_KIND;
130
+ if (kind === "active" || kind === "temp") fork = carnet.sessions.setKind(session.id, kind, env.RUCHER_SESSION_NAME || null);
131
+ return fork;
132
+ }
133
+ function startMemory(carnet, session, source, env) {
134
+ const options = {
135
+ maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),
136
+ halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS)
137
+ };
138
+ if (source === "startup" || source === "clear") return carnet.memory.atStart(session, options);
139
+ if (source === "resume" || source === "compact") return carnet.memory.ofSession(session, options);
140
+ }
55
141
  function handleSessionStart(carnet, payload, env) {
56
- const session = carnet.sessions.upsertFromHook(payload, env);
142
+ let session = carnet.sessions.upsertFromHook(payload, env);
143
+ const source = payload.source ?? "";
144
+ if (source === "fork") session = adoptFork(carnet, session, env);
145
+ const event = SOURCE_EVENTS[source];
146
+ if (event) carnet.events.log(session.id, { type: event });
147
+ session = carnet.sessions.setStatus(session.id, "running");
57
148
  carnet.sessions.purge(session.id, purgeDays(env.RUCHER_PURGE_DAYS));
58
- if (payload.source !== "resume") return { session };
149
+ const promptEnv = { RUCHER_HOME: env.RUCHER_HOME };
150
+ const launchedVersion = env.RUCHER_PROMPT_VERSION || null;
151
+ const contextParts = [];
152
+ const notices = [];
153
+ if (hostById(session.host).rendersSystemPrompt(source)) session = carnet.sessions.recordPromptVersion(session.id, launchedVersion);
154
+ if (source === "resume") contextParts.push(resumeContext(carnet, session));
155
+ const memory = startMemory(carnet, session, source, env);
156
+ if (memory) contextParts.push(memory);
157
+ if (source === "compact" && !launchedVersion) contextParts.push(compactReminder(carnet.group, promptEnv));
158
+ else if (!env.RUCHER_SESSION_ID && !session.promptVersion) {
159
+ contextParts.push(OUTSIDE_RUCHER_CONTEXT);
160
+ notices.push(OUTSIDE_RUCHER_NOTICE);
161
+ } else if (session.promptVersion && session.promptVersion !== rulesVersion(carnet.group, promptEnv)) notices.push(RULES_UPDATED_NOTICE);
162
+ const additionalContext = contextParts.length ? contextParts.join("\n\n") : void 0;
59
163
  return {
60
164
  session,
61
- additionalContext: resumeContext(carnet, session)
165
+ contextParts,
166
+ notices,
167
+ ...additionalContext ? { additionalContext } : {}
62
168
  };
63
169
  }
64
170
  // src/hook/user-prompt-submit.ts
65
171
  function handleUserPromptSubmit(carnet, host, payload) {
66
172
  carnet.sessions.ensure(payload.session_id, payload.cwd);
173
+ carnet.notes.recordActiveDay();
67
174
  return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));
68
175
  }
69
- export { AGENT_STATUSES, Carnet, CarnetError, DB_FILE, DEFAULT_HOST, DEFAULT_PURGE_DAYS, EMOJI, EVENT_TYPES, GROUP_DIRECTORY, GROUP_FILE, LEGEND, MAIN_WORKING_EMOJI, MAIN_WORKING_SUFFIX, MEMORY_DB, MINIMUM_ID_PREFIX, NOTE_MAX, PAIRING_WINDOW_MILLISECONDS, PUBLISH_FALLBACK_MILLISECONDS, REPORTING_NOTE, REPORTS_DIRECTORY, REPOS_END, REPOS_START, RESUME_EVENTS, RESUME_MAX_CHARACTERS, STOPPED_NOTE, USER_ACTION_STATUSES, addGroupRepo, allHosts, buildStatusView, claudeCode, findGroupRoot, formatClock, formatEventLine, groupInstructions, groupSettings, handleSessionStart, handleUserPromptSubmit, hostById, initGroup, isAgentStatus, isEventType, isGroupRoot, isInside, isUserActionStatus, loadGroup, locateGroup, migrate, migrations, openCarnet, openDatabase, purgeDays, readRegistry, registerGroup, removeGroupRepo, renderAgentLine, renderSections, renderStatus, renderTableLine, replaceReposBlock, repoNameFor, repoPathFor, reportPathFor, reportsDirectoryOf, reposBlock, resumeContext, rucherHome, sanitizeNote, schemaVersion, sessionLabel, shortId, transcriptTitle, unregisterGroups };
176
+ // src/hook/post-tool-use.ts
177
+ function handleToolUse(carnet, payload, env) {
178
+ if (payload.agent_id) return void 0;
179
+ const repo = repoNameFor(carnet.group, payload.path);
180
+ if (!repo) return void 0;
181
+ const session = carnet.sessions.ensure(payload.session_id, payload.cwd);
182
+ return carnet.memory.forRepo(session, repo, {
183
+ maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),
184
+ halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS)
185
+ });
186
+ }
187
+ export { AGENT_STATUSES, CORE_RULES, Carnet, CarnetError, DB_FILE, DEFAULT_HALF_LIFE_DAYS, DEFAULT_HOST, DEFAULT_PURGE_DAYS, DUPLICATE_SIMILARITY, EMOJI, EVENT_TYPES, GROUP_DIRECTORY, GROUP_FILE, LEGEND, MAIN_WORKING_EMOJI, MAIN_WORKING_SUFFIX, MEMORY_DB, MEMORY_MAX_CHARACTERS, MINIMUM_ID_PREFIX, NOTES_FOLD_LINES, NOTES_HEADER, NOTE_KINDS, NOTE_MAX, NOTE_TEXT_LIMIT, OUTSIDE_RUCHER_CONTEXT, OUTSIDE_RUCHER_NOTICE, PAIRING_WINDOW_MILLISECONDS, PROMPTS_DIRECTORY, PROMPT_FILE, PUBLISH_FALLBACK_MILLISECONDS, REPORTING_NOTE, REPORTS_DIRECTORY, REPOS_END, REPOS_START, RESUME_EVENTS, RESUME_MAX_CHARACTERS, RULES_UPDATED_NOTICE, SESSION_EVENT_TYPES, SIMILAR_PREFIX, STALE_AFTER_ACTIVE_DAYS, STOPPED_NOTE, SUBAGENT_RULES, USER_ACTION_STATUSES, addGroupRepo, allHosts, appendPromptFile, assemblePrompt, baseRules, buildStatusView, claudeCode, compactReminder, findGroupRoot, formatClock, formatEventLine, groupInstructions, groupRepoNames, groupRules, groupSettings, handleSessionEnd, handleSessionStart, handleToolUse, handleUserPromptSubmit, hostById, initGroup, isAgentStatus, isEventType, isGroupRoot, isInside, isNoteKind, isUserActionStatus, loadGroup, localDay, locateGroup, memoryHalfLife, memoryMaxCharacters, migrate, migrations, openCarnet, openDatabase, purgeDays, readRegistry, registerGroup, removeGroupRepo, renderAgentLine, renderMemory, renderNoteLine, renderNotes, renderNotesSummary, renderSections, renderStatus, renderTableLine, replaceReposBlock, repoNameFor, repoPathFor, reportPathFor, reportsDirectoryOf, reposBlock, resumeContext, rucherHome, rulesText, rulesVersion, sanitizeNote, schemaVersion, sessionLabel, sessionNoteActivity, shortId, similarity, transcriptTitle, unregisterGroups };
70
188
 
71
189
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/group/init.ts","../src/hook/session-start.ts","../src/hook/user-prompt-submit.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { basename, join, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { openDatabase } from '../db/open.ts';\nimport { DEFAULT_HOST, hostById } from '../hosts/host.ts';\nimport {\n DB_FILE,\n GROUP_DIRECTORY,\n GROUP_FILE,\n REPORTS_DIRECTORY,\n type Group,\n type GroupFile,\n loadGroup,\n} from './locate.ts';\nimport { registerGroup } from './registry.ts';\n\nexport interface InitOptions {\n name?: string | undefined;\n repos?: string[] | undefined;\n hosts?: string[] | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nfunction writeGroupFile(root: string, file: GroupFile): void {\n writeFileSync(join(root, GROUP_DIRECTORY, GROUP_FILE), `${JSON.stringify(file, null, 2)}\\n`);\n}\n\nfunction resolveRepo(root: string, repo: string): string {\n const path = resolve(root, repo);\n if (!existsSync(path))\n throw new CarnetError('REPO_NOT_FOUND', `Repo path does not exist: ${path}`);\n return path;\n}\n\nexport function initGroup(directory: string, options: InitOptions = {}): Group {\n const root = resolve(directory);\n const groupDirectory = join(root, GROUP_DIRECTORY);\n if (existsSync(groupDirectory)) {\n throw new CarnetError('GROUP_EXISTS', `${root} is already a Rucher group`);\n }\n const name = options.name ?? basename(root);\n const repos = (options.repos ?? []).map((repo) => resolveRepo(root, repo));\n const hosts = (options.hosts?.length ? options.hosts : [DEFAULT_HOST]).map(\n (id) => hostById(id).id,\n );\n mkdirSync(join(groupDirectory, REPORTS_DIRECTORY), { recursive: true });\n writeGroupFile(root, { name, repos, hosts });\n openDatabase(join(groupDirectory, DB_FILE)).close();\n registerGroup({ name, path: root }, options.env);\n return loadGroup(root);\n}\n\nexport function addGroupRepo(root: string, repo: string): Group {\n const group = loadGroup(resolve(root));\n const path = resolveRepo(group.root, repo);\n if (!group.repos.includes(path)) {\n writeGroupFile(group.root, {\n name: group.name,\n repos: [...group.repos, path],\n hosts: group.hosts,\n });\n }\n return loadGroup(group.root);\n}\n\nexport function removeGroupRepo(root: string, repo: string): Group {\n const group = loadGroup(resolve(root));\n const path = resolve(group.root, repo);\n if (!group.repos.includes(path)) {\n throw new CarnetError('REPO_NOT_FOUND', `${path} is not a repo of ${group.name}`);\n }\n writeGroupFile(group.root, {\n name: group.name,\n repos: group.repos.filter((repo) => repo !== path),\n hosts: group.hosts,\n });\n return loadGroup(group.root);\n}\n","import type { Carnet } from '../carnet.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}\n\nexport function handleSessionStart(\n carnet: Carnet,\n payload: HookSessionPayload,\n env: HookEnv,\n): SessionStartResult {\n const session = carnet.sessions.upsertFromHook(payload, env);\n carnet.sessions.purge(session.id, purgeDays(env.RUCHER_PURGE_DAYS));\n if (payload.source !== 'resume') return { session };\n return { session, additionalContext: resumeContext(carnet, session) };\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { Host, HostPromptPayload } from '../hosts/host.ts';\nimport type { Session } from '../sessions.ts';\n\nexport function handleUserPromptSubmit(\n carnet: Carnet,\n host: Host,\n payload: HostPromptPayload,\n): Session {\n carnet.sessions.ensure(payload.session_id, payload.cwd);\n return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));\n}\n"],"mappings":";;;;AAuBA,SAAS,eAAe,MAAc,MAAuB;CAC3D,cAAc,KAAK,MAAM,iBAAiB,UAAU,GAAG,GAAG,KAAK,UAAU,MAAM,M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B,MAAc,MAAqB;CACjE,MAAM,QAAQ,UAAU,QAAQ,IAAI,CAAC;CACrC,MAAM,OAAO,QAAQ,MAAM,MAAM,IAAI;CACrC,IAAI,CAAC,MAAM,MAAM,SAAS,IAAI,GAC5B,MAAM,IAAI,YAAY,kBAAkB,GAAG,KAAK,oBAAoB,MAAM,MAAM;CAElF,eAAe,MAAM,MAAM;EACzB,MAAM,MAAM;EACZ,OAAO,MAAM,MAAM,QAAQ,SAAS,SAAS,IAAI;EACjD,OAAO,MAAM;CACf,CAAC;CACD,OAAO,UAAU,MAAM,IAAI;AAC7B;;ACnEA,SAAgB,mBACd,QACA,SACA,KACoB;CACpB,MAAM,UAAU,OAAO,SAAS,eAAe,SAAS,GAAG;CAC3D,OAAO,SAAS,MAAM,QAAQ,IAAI,UAAU,IAAI,iBAAiB,CAAC;CAClE,IAAI,QAAQ,WAAW,UAAU,OAAO,EAAE,QAAQ;CAClD,OAAO;EAAE;EAAS,mBAAmB,cAAc,QAAQ,OAAO;CAAE;AACtE;;ACfA,SAAgB,uBACd,QACA,MACA,SACS;CACT,OAAO,SAAS,OAAO,QAAQ,YAAY,QAAQ,GAAG;CACtD,OAAO,OAAO,SAAS,WAAW,QAAQ,YAAY,KAAK,YAAY,OAAO,CAAC;AACjF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/group/init.ts","../src/hook/session-end.ts","../src/prompt/core-rules.ts","../src/prompt/prompt.ts","../src/hook/session-start.ts","../src/hook/user-prompt-submit.ts","../src/hook/post-tool-use.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { basename, join, resolve } from 'node:path';\nimport { CarnetError } from '../errors.ts';\nimport { openDatabase } from '../db/open.ts';\nimport { DEFAULT_HOST, hostById } from '../hosts/host.ts';\nimport {\n DB_FILE,\n GROUP_DIRECTORY,\n GROUP_FILE,\n REPORTS_DIRECTORY,\n type Group,\n type GroupFile,\n loadGroup,\n} from './locate.ts';\nimport { registerGroup } from './registry.ts';\n\nexport interface InitOptions {\n name?: string | undefined;\n repos?: string[] | undefined;\n hosts?: string[] | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n}\n\nfunction writeGroupFile(root: string, file: GroupFile): void {\n writeFileSync(join(root, GROUP_DIRECTORY, GROUP_FILE), `${JSON.stringify(file, null, 2)}\\n`);\n}\n\nfunction resolveRepo(root: string, repo: string): string {\n const path = resolve(root, repo);\n if (!existsSync(path))\n throw new CarnetError('REPO_NOT_FOUND', `Repo path does not exist: ${path}`);\n return path;\n}\n\nexport function initGroup(directory: string, options: InitOptions = {}): Group {\n const root = resolve(directory);\n const groupDirectory = join(root, GROUP_DIRECTORY);\n if (existsSync(groupDirectory)) {\n throw new CarnetError('GROUP_EXISTS', `${root} is already a Rucher group`);\n }\n const name = options.name ?? basename(root);\n const repos = [...new Set((options.repos ?? []).map((repo) => resolveRepo(root, repo)))];\n const names = repos.map((repo) => basename(repo));\n const shared = names.find((repoName, index) => names.indexOf(repoName) !== index);\n if (shared) {\n throw new CarnetError(\n 'REPO_NAME_TAKEN',\n `Two repos are named ${shared}: give them distinct names`,\n );\n }\n const hosts = (options.hosts?.length ? options.hosts : [DEFAULT_HOST]).map(\n (id) => hostById(id).id,\n );\n mkdirSync(join(groupDirectory, REPORTS_DIRECTORY), { recursive: true });\n writeGroupFile(root, { name, repos, hosts });\n openDatabase(join(groupDirectory, DB_FILE)).close();\n registerGroup({ name, path: root }, options.env);\n return loadGroup(root);\n}\n\nexport function addGroupRepo(root: string, repo: string): Group {\n const group = loadGroup(resolve(root));\n const path = resolveRepo(group.root, repo);\n const sameName = group.repos.find(\n (existing) => existing !== path && basename(existing) === basename(path),\n );\n // Notes reference repos by name, so two repos cannot share one.\n if (sameName) {\n throw new CarnetError(\n 'REPO_NAME_TAKEN',\n `${group.name} already has a repo named ${basename(path)}: ${sameName}`,\n );\n }\n if (!group.repos.includes(path)) {\n writeGroupFile(group.root, {\n name: group.name,\n repos: [...group.repos, path],\n hosts: group.hosts,\n });\n }\n return loadGroup(group.root);\n}\n\nexport function removeGroupRepo(root: string, repo: string): Group {\n const group = loadGroup(resolve(root));\n const path = resolve(group.root, repo);\n if (!group.repos.includes(path)) {\n throw new CarnetError('REPO_NOT_FOUND', `${path} is not a repo of ${group.name}`);\n }\n writeGroupFile(group.root, {\n name: group.name,\n repos: group.repos.filter((repo) => repo !== path),\n hosts: group.hosts,\n });\n return loadGroup(group.root);\n}\n","import type { Carnet } from '../carnet.ts';\nimport type { HostSessionEndPayload } 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 return carnet.sessions.end(payload.session_id);\n}\n","// Generated from docs/workflow.md by pnpm run build. Do not edit.\nexport const CORE_RULES = `- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the \"On the table\" line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When a fork finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that fork's report, even when answering about something else.\n- Forks never commit, push, stash or record notes. A fork writes its report to a file, ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.`;\n","import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { GROUP_DIRECTORY, type Group } from '../group/locate.ts';\nimport { rucherHome } from '../group/registry.ts';\nimport { shortId, type SessionKind } from '../sessions.ts';\nimport { CORE_RULES } from './core-rules.ts';\n\nexport const PROMPT_FILE = 'prompt.md';\nexport const PROMPTS_DIRECTORY = 'prompts';\n\nexport interface PromptSession {\n id: string;\n name: string | null;\n kind: SessionKind;\n}\n\nexport interface AssembledPrompt {\n text: string;\n version: string;\n}\n\nexport interface AppendPromptFile {\n path: string;\n version: string;\n}\n\nfunction readIfPresent(path: string): string | undefined {\n if (!existsSync(path)) return undefined;\n const content = readFileSync(path, 'utf8').trim();\n return content || undefined;\n}\n\nexport function baseRules(env: NodeJS.ProcessEnv = process.env): string {\n return readIfPresent(join(rucherHome(env), PROMPT_FILE)) ?? CORE_RULES;\n}\n\nexport function groupRules(group: Group): string | undefined {\n return readIfPresent(join(group.root, GROUP_DIRECTORY, PROMPT_FILE));\n}\n\nexport function rulesText(group: Group, env: NodeJS.ProcessEnv = process.env): string {\n const extra = groupRules(group);\n const base = `Rucher rules:\\n${baseRules(env)}`;\n return extra ? `${base}\\n\\nRules of the ${group.name} group:\\n${extra}` : base;\n}\n\n// The identity block is left out so that renaming a session doesn't read as a rules change.\nexport function rulesVersion(group: Group, env: NodeJS.ProcessEnv = process.env): string {\n return createHash('sha256').update(rulesText(group, env)).digest('hex').slice(0, 12);\n}\n\nexport function assemblePrompt(\n group: Group,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AssembledPrompt {\n const label = session.name ?? shortId(session.id);\n const identity = `This is the Rucher session ${label} (${session.kind}) of the ${group.name} group.`;\n return { text: `${rulesText(group, env)}\\n\\n${identity}\\n`, version: rulesVersion(group, env) };\n}\n\nexport function appendPromptFile(\n group: Group,\n session: PromptSession,\n env: NodeJS.ProcessEnv = process.env,\n): AppendPromptFile {\n const { text, version } = assemblePrompt(group, session, env);\n const directory = join(group.root, GROUP_DIRECTORY, PROMPTS_DIRECTORY);\n mkdirSync(directory, { recursive: true });\n const path = join(directory, `${session.id}.md`);\n writeFileSync(path, text);\n return { path, version };\n}\n\nexport function compactReminder(group: Group, env: NodeJS.ProcessEnv = process.env): string {\n return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${rulesText(group, env)}`;\n}\n\nexport const OUTSIDE_RUCHER_CONTEXT =\n 'This session was started without rucher, so the Rucher rules are not in its system prompt. Follow the Carnet server instructions and load the rucher skill before dispatching or applying forks.';\n\nexport const OUTSIDE_RUCHER_NOTICE =\n 'rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)';\n\nexport const RULES_UPDATED_NOTICE =\n 'rucher: rules updated, will apply after the next compaction or in a new session';\n\nexport const SUBAGENT_RULES =\n 'Rucher rules for sub-agents: never commit, push or stash. When your task asks for a report, write it to the file it names. If your prompt names you as a Carnet agent, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.';\n","import type { Carnet } from '../carnet.ts';\nimport type { SessionEventType } from '../events.ts';\nimport {\n compactReminder,\n OUTSIDE_RUCHER_CONTEXT,\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// 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 const source = payload.source ?? '';\n if (source === 'fork') session = adoptFork(carnet, session, env);\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 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.group, promptEnv));\n } else if (!env.RUCHER_SESSION_ID && !session.promptVersion) {\n contextParts.push(OUTSIDE_RUCHER_CONTEXT);\n notices.push(OUTSIDE_RUCHER_NOTICE);\n } else if (\n session.promptVersion &&\n session.promptVersion !== rulesVersion(carnet.group, 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';\n\nexport function handleUserPromptSubmit(\n carnet: Carnet,\n host: Host,\n payload: HostPromptPayload,\n): Session {\n carnet.sessions.ensure(payload.session_id, payload.cwd);\n carnet.notes.recordActiveDay();\n return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));\n}\n","import type { Carnet } from '../carnet.ts';\nimport { repoNameFor } from '../group/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';\n\nexport function handleToolUse(\n carnet: Carnet,\n payload: HostToolPayload,\n env: HookEnv,\n): string | undefined {\n // session_repos tracks the main conversation; a subagent's context is not it.\n if (payload.agent_id) return undefined;\n const repo = repoNameFor(carnet.group, 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"],"mappings":";;;;;AAuBA,SAAS,eAAe,MAAc,MAAuB;CAC3D,cAAc,KAAK,MAAM,iBAAiB,UAAU,GAAG,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,EAAE,GAAG;AAC7F;AAEA,SAAS,YAAY,MAAc,MAAsB;CACvD,MAAM,OAAO,QAAQ,MAAM,IAAI;CAC/B,IAAI,CAAC,WAAW,IAAI,GAClB,MAAM,IAAI,YAAY,kBAAkB,6BAA6B,MAAM;CAC7E,OAAO;AACT;AAEA,SAAgB,UAAU,WAAmB,UAAuB,CAAC,GAAU;CAC7E,MAAM,OAAO,QAAQ,SAAS;CAC9B,MAAM,iBAAiB,KAAK,MAAM,eAAe;CACjD,IAAI,WAAW,cAAc,GAC3B,MAAM,IAAI,YAAY,gBAAgB,GAAG,KAAK,2BAA2B;CAE3E,MAAM,OAAO,Q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,KAAK,sBAAsB;EACxC,QAAQ,KAAK,qBAAqB;CACpC,OAAO,IACL,QAAQ,iBACR,QAAQ,kBAAkB,aAAa,OAAO,OAAO,SAAS,GAE9D,QAAQ,KAAK,oBAAoB;CAEnC,MAAM,oBAAoB,aAAa,SAAS,aAAa,KAAK,MAAM,IAAI,KAAA;CAC5E,OAAO;EAAE;EAAS;EAAc;EAAS,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;CAAG;AAC/F;;AC1FA,SAAgB,uBACd,QACA,MACA,SACS;CACT,OAAO,SAAS,OAAO,QAAQ,YAAY,QAAQ,GAAG;CACtD,OAAO,MAAM,gBAAgB;CAC7B,OAAO,OAAO,SAAS,WAAW,QAAQ,YAAY,KAAK,YAAY,OAAO,CAAC;AACjF;;ACLA,SAAgB,cACd,QACA,SACA,KACoB;CAEpB,IAAI,QAAQ,UAAU,OAAO,KAAA;CAC7B,MAAM,OAAO,YAAY,OAAO,OAAO,QAAQ,IAAI;CACnD,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,MAAM,UAAU,OAAO,SAAS,OAAO,QAAQ,YAAY,QAAQ,GAAG;CACtE,OAAO,OAAO,OAAO,QAAQ,SAAS,MAAM;EAC1C,eAAe,oBAAoB,IAAI,4BAA4B;EACnE,cAAc,eAAe,IAAI,4BAA4B;CAC/D,CAAC;AACH"}
package/dist/mcp.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { D as Host, r as OpenCarnetOptions, t as Carnet } from "./carnet-CSdqWDas.mjs";
1
+ import { r as OpenCarnetOptions, t as Carnet, vt as Host } from "./carnet-CsFtIv2C.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 tracks the status of sub-agents (forks) for the human, in a shared database. Views are rendered by the `rucher` CLI.\n\nRules:\n- Never write status files (agents-status.md or similar) and never describe status updates in the chat. When a fork finishes, the main agent says only \"<name> finished, report ready\".\n- Update BEFORE and AFTER each piece of work, never batched at the end of a turn.\n- Your session is resolved automatically. Pass `session` only to target another session.\n\nMain agent:\n- agent_start before dispatching a fork (name, task), in an earlier message than the launch; launch parallel forks in the same order. Names are short, no paths.\n- table_set with main_working=true before applying, testing or fixing yourself; table_set with a status (or table_clear) when done.\n- log_event when a step is answered, applied, tested, committed or dropped.\n- When a fork finishes: say one line \"<name> finished, report ready\", copy its report to the report destination agent_start gave (.rucher/reports/<name>.md in the group meta directory) and call agent_update with that report_path. Present the report only when asked.\n- For dispatching, applying or reviewing forks, load the rucher skill: it holds the full workflow.\n- agent_drop when a fork's work is committed or abandoned. queue_reorder to change the handling order.\n- agent_list to recall where things stand.\n- Sessions: session_new when the human names this session (then ask them to /rename it the same way); session_list, session_resume_info and log_read to recall other sessions or the journal; session_drop only when the human asks.\n\nForks:\n- agent_update (status running, short note) at meaningful progress.\n- agent_done with the report path as your LAST tool action; has_questions=true when the report asks the human something. Then reply with one line only: the report holds the detail.\n- Never agent_start, never table_set.\n\nStatuses (emoji shown to the human = the NEXT action): running ⏳ fork working · discussing 💬 · answer ❓ human must answer · review 👀 human must review · apply 📥 · test 🧪 · commit ✅ · branch 🌿. Only the human applies, tests and commits.\n\nNotes and table text: under 60 characters, no paths, no backticks.";
5
+ export declare const INSTRUCTIONS = "Carnet tracks sub-agents (forks), the \"On the table\" line, sessions, the journal and the group memory, in a shared database the `rucher` CLI renders. Status goes through these tools only: never status files, never status updates in the chat. Your session is resolved automatically; pass `session` only to target another one. The full workflow is the rucher skill: load it before dispatching, applying or reviewing forks.\n\nMain agent:\n- agent_start before dispatching a fork (name, task), in an earlier message than the launch. Launch it with the agent name as the Agent description and a prompt starting with \"You are fork `<name>`.\" Names are short, no paths.\n- table_set with main_working=true before applying, testing or fixing yourself; table_set with a status, or table_clear, when done.\n- log_event when a step is answered, applied, tested, committed or dropped.\n- When a fork finishes: say only \"<name> finished, report ready\", copy its report to the destination agent_start gave and call agent_update with that report_path. Present a fork's report only when the human asks for it: never summarise or act on it, or on the fork's final message, before.\n- agent_update to move an agent to the next human action; agent_drop once committed or abandoned; queue_reorder to change the order; agent_list to recall where things stand.\n- note_add at the end of a step for what was learned, decided or ruled out; note_drop with the reason when a note proves wrong; promote the Learnings of fork reports.\n- session_new when the human names this session; session_list, session_resume_info and log_read to recall sessions or the journal; session_drop only when the human asks.\n\nForks:\n- agent_update (status running, short note) at meaningful progress.\n- agent_done with the report path as your LAST tool action, has_questions=true when the report asks the human something, then reply with one line that carries no results (\"<name> done, report written\").\n- Never agent_start, table_set or note_add: end the report with a Learnings section. Both roles: note_cite when a note changed what you did.\n\nStatuses (the NEXT action): running ⏳ fork working · discussing 💬 · answer ❓ · review 👀 · apply 📥 · test 🧪 · commit ✅ · branch 🌿. 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;;wBAOV,mBAAmB,SAAS,sBAAsB;UAgCjD,2BAA2B;EAC1C,SAAS;EACT;;wBAGc,YAAY,UAAS,qBAA0B;UCnD9C;EACf;EACA,OAAO;;UAGQ,eAAe,eAAe,EAAE,YAAY,EAAE;EAC7D;EACA;EACA,QAAQ;EACR,MAAM,QAAQ,QAAQ,mBAAmB,MAAM,EAAE,MAAM,YAAY;;qBAoSxD,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;;wBAOV,mBAAmB,SAAS,sBAAsB;UAgCjD,2BAA2B;EAC1C,SAAS;EACT;;wBAGc,YAAY,UAAS,qBAA0B;UClD9C;EACf;EACA,OAAO;;UAGQ,eAAe,eAAe,EAAE,YAAY,EAAE;EAC7D;EACA;EACA,QAAQ;EACR,MAAM,QAAQ,QAAQ,mBAAmB,MAAM,EAAE,MAAM,YAAY;;qBA+YxD,gBAAgB"}
package/dist/mcp.mjs CHANGED
@@ -1,34 +1,26 @@
1
- import { B as hostById, M as reportPathFor, N as reportsDirectoryOf, R as DEFAULT_HOST, a as sessionLabel, at as EMOJI, ct as OPEN_AGENT_STATUSES, ft as EVENT_TYPES, g as renderTableLine, i as resumeContext, lt as USER_ACTION_STATUSES, mt as CarnetError, p as renderAgentLine, r as formatEventLine, s as openCarnet } from "./resume-Daotqfdq.mjs";
1
+ import { $ as reportsDirectoryOf, Ft as CarnetError, M as NOTE_KINDS, Mt as EVENT_TYPES, Ot as OPEN_AGENT_STATUSES, Q as reportPathFor, R as memoryHalfLife, S as renderTableLine, Tt as EMOJI, a as sessionLabel, g as renderAgentLine, i as resumeContext, it as DEFAULT_HOST, kt as USER_ACTION_STATUSES, ot as hostById, r as formatEventLine, s as openCarnet } from "./resume-CQRf2jIa.mjs";
2
2
  import { mkdirSync } from "node:fs";
3
3
  import { McpServer } from "@modelcontextprotocol/server";
4
4
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
5
5
  import * as z from "zod/v4";
6
6
  // src/mcp/instructions.ts
7
- const INSTRUCTIONS = `Carnet tracks the status of sub-agents (forks) for the human, in a shared database. Views are rendered by the \`rucher\` CLI.
8
-
9
- Rules:
10
- - Never write status files (agents-status.md or similar) and never describe status updates in the chat. When a fork finishes, the main agent says only "<name> finished, report ready".
11
- - Update BEFORE and AFTER each piece of work, never batched at the end of a turn.
12
- - Your session is resolved automatically. Pass \`session\` only to target another session.
7
+ const INSTRUCTIONS = `Carnet tracks sub-agents (forks), the "On the table" line, sessions, the journal and the group memory, in a shared database the \`rucher\` CLI renders. Status goes through these tools only: never status files, never status updates in the chat. Your session is resolved automatically; pass \`session\` only to target another one. The full workflow is the rucher skill: load it before dispatching, applying or reviewing forks.
13
8
 
14
9
  Main agent:
15
- - agent_start before dispatching a fork (name, task), in an earlier message than the launch; launch parallel forks in the same order. Names are short, no paths.
16
- - table_set with main_working=true before applying, testing or fixing yourself; table_set with a status (or table_clear) when done.
10
+ - agent_start before dispatching a fork (name, task), in an earlier message than the launch. Launch it with the agent name as the Agent description and a prompt starting with "You are fork \`<name>\`." Names are short, no paths.
11
+ - table_set with main_working=true before applying, testing or fixing yourself; table_set with a status, or table_clear, when done.
17
12
  - log_event when a step is answered, applied, tested, committed or dropped.
18
- - When a fork finishes: say one line "<name> finished, report ready", copy its report to the report destination agent_start gave (.rucher/reports/<name>.md in the group meta directory) and call agent_update with that report_path. Present the report only when asked.
19
- - For dispatching, applying or reviewing forks, load the rucher skill: it holds the full workflow.
20
- - agent_drop when a fork's work is committed or abandoned. queue_reorder to change the handling order.
21
- - agent_list to recall where things stand.
22
- - Sessions: session_new when the human names this session (then ask them to /rename it the same way); session_list, session_resume_info and log_read to recall other sessions or the journal; session_drop only when the human asks.
13
+ - When a fork finishes: say only "<name> finished, report ready", copy its report to the destination agent_start gave and call agent_update with that report_path. Present a fork's report only when the human asks for it: never summarise or act on it, or on the fork's final message, before.
14
+ - agent_update to move an agent to the next human action; agent_drop once committed or abandoned; queue_reorder to change the order; agent_list to recall where things stand.
15
+ - note_add at the end of a step for what was learned, decided or ruled out; note_drop with the reason when a note proves wrong; promote the Learnings of fork reports.
16
+ - session_new when the human names this session; session_list, session_resume_info and log_read to recall sessions or the journal; session_drop only when the human asks.
23
17
 
24
18
  Forks:
25
19
  - agent_update (status running, short note) at meaningful progress.
26
- - agent_done with the report path as your LAST tool action; has_questions=true when the report asks the human something. Then reply with one line only: the report holds the detail.
27
- - Never agent_start, never table_set.
28
-
29
- Statuses (emoji shown to the human = the NEXT action): running ⏳ fork working · discussing 💬 · answer ❓ human must answer · review 👀 human must review · apply 📥 · test 🧪 · commit ✅ · branch 🌿. Only the human applies, tests and commits.
20
+ - agent_done with the report path as your LAST tool action, has_questions=true when the report asks the human something, then reply with one line that carries no results ("<name> done, report written").
21
+ - Never agent_start, table_set or note_add: end the report with a Learnings section. Both roles: note_cite when a note changed what you did.
30
22
 
31
- Notes and table text: under 60 characters, no paths, no backticks.`;
23
+ Statuses (the NEXT action): running ⏳ fork working · discussing 💬 · answer ❓ · review 👀 · apply 📥 · test 🧪 · commit ✅ · branch 🌿. Notes and table text: under 60 characters, no paths, no backticks.`;
32
24
  // src/mcp/session.ts
33
25
  const FULL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
34
26
  function createSessionResolver({ carnet, env = process.env, ppid = process.ppid, cwd = process.cwd(), host = hostById(DEFAULT_HOST) }) {
@@ -117,7 +109,7 @@ const agentUpdate = defineTool({
117
109
  });
118
110
  const agentDone = defineTool({
119
111
  name: "agent_done",
120
- description: "Forks call this as their LAST tool action, then reply with one line. Records the report path and the outcome: ❓ answer (has_questions=true) or 👀 review, shown once the fork has really stopped. Logs a `finished` event then.",
112
+ description: "Forks call this as their LAST tool action, then reply with one line that carries no results (the report holds them). Records the report path and the outcome: ❓ answer (has_questions=true) or 👀 review, shown once the fork has really stopped. Logs a `finished` event then.",
121
113
  schema: z.object({
122
114
  name: agentName,
123
115
  report_path: z.string().min(1).describe("Absolute path of the markdown report"),
@@ -131,7 +123,7 @@ const agentDone = defineTool({
131
123
  });
132
124
  const outcome = args.has_questions ? `${EMOJI.answer} ${agent.name} needs answers` : `${EMOJI.review} ${agent.name} ready for review`;
133
125
  return {
134
- text: agent.status === "running" ? `${outcome} once you stop; reply with one line now` : outcome,
126
+ text: agent.status === "running" ? `${outcome} once you stop; reply now with one line that carries no results` : outcome,
135
127
  data: { agent }
136
128
  };
137
129
  }
@@ -250,7 +242,7 @@ const logEvent = defineTool({
250
242
  const sessionName = z.string().trim().min(1).describe("Short session name, used by rucher resume");
251
243
  const sessionNew = defineTool({
252
244
  name: "session_new",
253
- description: "Name the current session (or rename it) so it can be resumed later with `rucher resume <name>`. Promotes a temporary session to active.",
245
+ 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.",
254
246
  schema: z.object({
255
247
  name: sessionName,
256
248
  purpose: z.string().optional().describe("One line: what this session is for"),
@@ -266,20 +258,20 @@ const sessionNew = defineTool({
266
258
  });
267
259
  const sessionList = defineTool({
268
260
  name: "session_list",
269
- description: "List the group's sessions, most recently active first. Temporary and dropped ones are hidden unless asked.",
261
+ description: "List the group's sessions, most recently active first. Temp and archived ones are hidden unless asked.",
270
262
  schema: z.object({
271
- include_temporary: z.boolean().optional(),
272
- include_dropped: z.boolean().optional(),
263
+ include_temp: z.boolean().optional(),
264
+ include_archived: z.boolean().optional(),
273
265
  session
274
266
  }),
275
267
  run: (carnet, sessionId, args) => {
276
268
  const sessions = carnet.sessions.list({
277
- includeTemporary: args.include_temporary,
278
- includeDropped: args.include_dropped
269
+ includeTemp: args.include_temp,
270
+ includeArchived: args.include_archived
279
271
  });
280
272
  const lines = sessions.map((listed) => {
281
273
  const current = listed.id === sessionId ? " (current)" : "";
282
- return `${sessionLabel(listed)} [${listed.status}]${current}`;
274
+ return `${sessionLabel(listed)} [${listed.kind}, ${listed.status}]${current}`;
283
275
  });
284
276
  return {
285
277
  text: lines.length ? lines.join("\n") : "no sessions",
@@ -289,7 +281,7 @@ const sessionList = defineTool({
289
281
  });
290
282
  const sessionDrop = defineTool({
291
283
  name: "session_drop",
292
- description: "Main agent only. Drop a session by name, id or id prefix: its open agents are closed and it leaves the lists. History stays in the journal.",
284
+ 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.",
293
285
  schema: z.object({
294
286
  name: z.string().trim().min(1).describe("Session name, id or id prefix"),
295
287
  session
@@ -297,7 +289,7 @@ const sessionDrop = defineTool({
297
289
  run: (carnet, _sessionId, args) => {
298
290
  const dropped = carnet.sessions.drop(carnet.sessions.find(args.name).id);
299
291
  return {
300
- text: `Session ${sessionLabel(dropped)} dropped`,
292
+ text: `Session ${sessionLabel(dropped)} archived`,
301
293
  data: { session: dropped }
302
294
  };
303
295
  }
@@ -321,6 +313,26 @@ const sessionResumeInfo = defineTool({
321
313
  };
322
314
  }
323
315
  });
316
+ const logRead = defineTool({
317
+ name: "log_read",
318
+ description: "Read the last journal events of the session, oldest first.",
319
+ schema: z.object({
320
+ limit: z.number().int().min(1).max(200).optional().describe("Number of events, default 20"),
321
+ session
322
+ }),
323
+ run: (carnet, sessionId, args) => {
324
+ const events = carnet.events.read(sessionId, args.limit ?? 20);
325
+ return {
326
+ text: events.length ? events.map(formatEventLine).join("\n") : "no events yet",
327
+ data: { events }
328
+ };
329
+ }
330
+ });
331
+ const noteId = z.number().int().positive().describe("Note id, as shown by note_list (#14 is 14)");
332
+ function noteLine(note) {
333
+ const repos = note.repos.length ? ` [${note.repos.join(", ")}]` : "";
334
+ return `#${note.id} ${note.kind}${repos} ${note.text}`;
335
+ }
324
336
  const TOOLS = [
325
337
  agentStart,
326
338
  agentUpdate,
@@ -331,25 +343,109 @@ const TOOLS = [
331
343
  tableSet,
332
344
  tableClear,
333
345
  logEvent,
346
+ logRead,
347
+ sessionNew,
348
+ sessionList,
349
+ sessionDrop,
350
+ sessionResumeInfo,
334
351
  defineTool({
335
- name: "log_read",
336
- description: "Read the last journal events of the session, oldest first.",
352
+ name: "note_add",
353
+ description: "Main agent only. Record what the group 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 group's repos; omit it for a general note. A result listing similar notes means a likely duplicate: drop or replace instead of piling up.",
337
354
  schema: z.object({
338
- limit: z.number().int().min(1).max(200).optional().describe("Number of events, default 20"),
355
+ kind: z.enum(NOTE_KINDS),
356
+ text: z.string().min(1).describe("One claim with its reason, under 200 characters"),
357
+ repos: z.array(z.string().min(1)).optional().describe("Repo names of the group; omit for a general note"),
358
+ agent: z.string().optional().describe("Fork the note comes from"),
339
359
  session
340
360
  }),
341
361
  run: (carnet, sessionId, args) => {
342
- const events = carnet.events.read(sessionId, args.limit ?? 20);
362
+ const { note, similar } = carnet.notes.add({
363
+ kind: args.kind,
364
+ text: args.text,
365
+ repos: args.repos,
366
+ agent: args.agent,
367
+ session: sessionId
368
+ });
369
+ const warning = similar.length ? `\nSimilar active notes, possible duplicate:\n${similar.map(noteLine).join("\n")}` : "";
343
370
  return {
344
- text: events.length ? events.map(formatEventLine).join("\n") : "no events yet",
345
- data: { events }
371
+ text: `added ${noteLine(note)}${warning}`,
372
+ data: {
373
+ note,
374
+ similar
375
+ }
346
376
  };
347
377
  }
348
378
  }),
349
- sessionNew,
350
- sessionList,
351
- sessionDrop,
352
- sessionResumeInfo
379
+ defineTool({
380
+ name: "note_list",
381
+ description: "The group'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.",
382
+ schema: z.object({
383
+ kind: z.enum(NOTE_KINDS).optional(),
384
+ repo: z.string().optional().describe("Notes of this repo"),
385
+ general: z.boolean().optional().describe("Only notes without repo"),
386
+ query: z.string().optional().describe("Substring of the text"),
387
+ include_dropped: z.boolean().optional(),
388
+ session
389
+ }),
390
+ run: (carnet, _sessionId, args) => {
391
+ const notes = carnet.notes.list({
392
+ kind: args.kind,
393
+ repo: args.repo,
394
+ general: args.general,
395
+ query: args.query,
396
+ includeDropped: args.include_dropped,
397
+ halfLifeDays: memoryHalfLife(process.env["RUCHER_MEMORY_HALF_LIFE_DAYS"])
398
+ });
399
+ const lines = notes.map((note) => `${noteLine(note)}${note.droppedAt ? ` (dropped: ${note.droppedReason})` : ""}`);
400
+ return {
401
+ text: lines.length ? lines.join("\n") : "no notes",
402
+ data: { notes }
403
+ };
404
+ }
405
+ }),
406
+ defineTool({
407
+ name: "note_drop",
408
+ 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.",
409
+ schema: z.object({
410
+ id: noteId,
411
+ reason: z.string().min(1).describe("Why the note is no longer true"),
412
+ replaced_by: z.number().int().positive().optional().describe("Id of the note replacing it"),
413
+ session
414
+ }),
415
+ run: (carnet, sessionId, args) => {
416
+ const note = carnet.notes.drop(args.id, {
417
+ reason: args.reason,
418
+ replacedBy: args.replaced_by,
419
+ session: sessionId
420
+ });
421
+ const replaced = note.replacedBy ? `, replaced by #${note.replacedBy}` : "";
422
+ return {
423
+ text: `dropped #${note.id}${replaced}`,
424
+ data: { note }
425
+ };
426
+ }
427
+ }),
428
+ defineTool({
429
+ name: "note_cite",
430
+ 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.",
431
+ schema: z.object({
432
+ id: noteId,
433
+ why: z.string().min(1).describe("What the note changed, short"),
434
+ agent: z.string().optional().describe("Fork citing it, when not the main agent"),
435
+ session
436
+ }),
437
+ run: (carnet, sessionId, args) => {
438
+ const citation = carnet.notes.cite(args.id, {
439
+ why: args.why,
440
+ agent: args.agent,
441
+ session: sessionId
442
+ });
443
+ return {
444
+ text: `cited #${citation.note}: ${citation.why}`,
445
+ data: { citation }
446
+ };
447
+ }
448
+ })
353
449
  ];
354
450
  // src/mcp/server.ts
355
451
  const SERVER_NAME = "carnet";