@rucher/cli 0.0.0-stage → 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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/dist/cli.mjs +2065 -0
  4. package/package.json +52 -3
package/dist/cli.mjs ADDED
@@ -0,0 +1,2065 @@
1
+ #!/usr/bin/env node
2
+ import { defineCommand, runMain } from "citty";
3
+ import { existsSync, readdirSync, rmSync } from "node:fs";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import tab from "@bomb.sh/tab/citty";
6
+ import { CarnetError, LEGEND, NOTES_HEADER, NOTE_KINDS, SIMILAR_PREFIX, SUBAGENT_RULES, addGroupRepo, appendPromptFile, claudeCode, formatClock, groupRepoNames, handleSessionEnd, handleSessionStart, handleToolUse, handleUserPromptSubmit, hostById, initGroup, isGroupRoot, locateGroup, memoryHalfLife, openCarnet, readRegistry, removeGroupRepo, renderSections, repoNameFor, repoPathFor, shortId, unregisterGroups } from "@rucher/carnet";
7
+ import { styleText } from "node:util";
8
+ import { spawnSync } from "node:child_process";
9
+ import { randomUUID } from "node:crypto";
10
+ import { createInterface } from "node:readline/promises";
11
+ import { serveCarnet } from "@rucher/carnet/mcp";
12
+ import { emitKeypressEvents } from "node:readline";
13
+ // src/completion.ts
14
+ const hiddenCommands = /* @__PURE__ */ new Set(["hook", "serve"]);
15
+ function quietly(suggest) {
16
+ try {
17
+ suggest();
18
+ } catch {}
19
+ }
20
+ function suggestSessions(context, complete) {
21
+ quietly(() => {
22
+ const carnet = openCarnet(context);
23
+ try {
24
+ const sessions = carnet.sessions.list({ includeTemp: true });
25
+ const suggestions = [...sessions.flatMap((session) => session.name ? [{
26
+ value: session.name,
27
+ description: session.purpose ?? session.status
28
+ }] : []), ...sessions.flatMap((session) => session.name ? [] : [{
29
+ value: shortId(session.id),
30
+ description: session.status
31
+ }])];
32
+ for (const suggestion of suggestions) if (!context.typedWords.slice(0, -1).includes(suggestion.value)) complete(suggestion.value, suggestion.description);
33
+ } finally {
34
+ carnet.close();
35
+ }
36
+ });
37
+ }
38
+ function suggestGroups(context, complete) {
39
+ quietly(() => {
40
+ const groups = readRegistry(context.env);
41
+ for (const group of groups) complete(groups.filter((other) => other.name === group.name).length > 1 ? group.path : group.name, group.path);
42
+ });
43
+ }
44
+ function suggestRepos(context, complete) {
45
+ quietly(() => {
46
+ for (const repo of locateGroup(context).repos) complete(repo, "");
47
+ });
48
+ }
49
+ function suggestRepoNames(context, complete) {
50
+ quietly(() => {
51
+ for (const repo of groupRepoNames(locateGroup(context))) complete(repo, "");
52
+ });
53
+ }
54
+ function suggestNoteKinds(complete) {
55
+ for (const kind of NOTE_KINDS) complete(kind, "");
56
+ }
57
+ function suggestNotes(context, complete) {
58
+ quietly(() => {
59
+ const carnet = openCarnet(context);
60
+ try {
61
+ for (const note of carnet.notes.list()) complete(String(note.id), note.text.slice(0, 60));
62
+ } finally {
63
+ carnet.close();
64
+ }
65
+ });
66
+ }
67
+ function suggestDirectories(context, complete) {
68
+ quietly(() => {
69
+ const partial = context.typedWords.at(-1) ?? "";
70
+ const base = partial.endsWith("/") ? partial : dirname(partial) === "." ? "" : `${dirname(partial)}/`;
71
+ for (const entry of readdirSync(resolve(context.cwd, base || "."), { withFileTypes: true })) if (entry.isDirectory() && !entry.name.startsWith(".")) complete(join(base, entry.name), "");
72
+ });
73
+ }
74
+ function processContext() {
75
+ const separator = process.argv.indexOf("--");
76
+ const typedWords = separator === -1 ? [] : process.argv.slice(separator + 1);
77
+ return {
78
+ cwd: process.cwd(),
79
+ env: process.env,
80
+ typedWords
81
+ };
82
+ }
83
+ const sessions = (complete) => suggestSessions(processContext(), complete);
84
+ const groups = (complete) => suggestGroups(processContext(), complete);
85
+ const repos = (complete) => suggestRepos(processContext(), complete);
86
+ const directories = (complete) => suggestDirectories(processContext(), complete);
87
+ const repoNames = (complete) => suggestRepoNames(processContext(), complete);
88
+ const noteKinds = (complete) => suggestNoteKinds(complete);
89
+ const notes = (complete) => suggestNotes(processContext(), complete);
90
+ const completionConfig = { subCommands: {
91
+ status: { options: { session: sessions } },
92
+ log: { options: { session: sessions } },
93
+ init: { args: { directory: directories } },
94
+ resume: { args: { session: sessions } },
95
+ fork: { args: { session: sessions } },
96
+ sessions: { subCommands: {
97
+ merge: { args: {
98
+ from: sessions,
99
+ into: sessions
100
+ } },
101
+ rename: { args: { session: sessions } },
102
+ promote: { args: { session: sessions } },
103
+ demote: { args: { session: sessions } },
104
+ drop: { args: { session: sessions } }
105
+ } },
106
+ notes: {
107
+ options: {
108
+ kind: noteKinds,
109
+ repo: repoNames
110
+ },
111
+ subCommands: {
112
+ list: { options: {
113
+ kind: noteKinds,
114
+ repo: repoNames
115
+ } },
116
+ show: { args: { id: notes } },
117
+ add: {
118
+ args: { kind: noteKinds },
119
+ options: { repo: repoNames }
120
+ },
121
+ drop: {
122
+ args: { id: notes },
123
+ options: { "replaced-by": notes }
124
+ }
125
+ }
126
+ },
127
+ groups: { subCommands: { forget: { args: { reference: groups } } } },
128
+ group: { subCommands: {
129
+ add: { args: { path: directories } },
130
+ remove: { args: { path: repos } }
131
+ } }
132
+ } };
133
+ async function setupCompletion(main) {
134
+ const subCommands = await (typeof main.subCommands === "function" ? main.subCommands() : main.subCommands);
135
+ const visible = Object.fromEntries(Object.entries(subCommands ?? {}).filter(([name]) => !hiddenCommands.has(name)));
136
+ await tab({
137
+ ...main,
138
+ subCommands: visible
139
+ }, completionConfig);
140
+ const complete = visible["complete"];
141
+ if (complete) main.subCommands = {
142
+ ...subCommands,
143
+ complete
144
+ };
145
+ }
146
+ // package.json
147
+ var version = "0.2.0-beta.0";
148
+ // src/color.ts
149
+ function paint(io) {
150
+ const style = (name) => (text) => io.color ? styleText(name, text, { validateStream: false }) : text;
151
+ return {
152
+ bold: style("bold"),
153
+ dim: style("dim"),
154
+ yellow: style("yellow"),
155
+ red: style("red"),
156
+ cyan: style("cyan")
157
+ };
158
+ }
159
+ // src/commands/init.ts
160
+ function syncContextFiles(group, mode) {
161
+ return group.hosts.flatMap((id) => hostById(id).contextFiles.map((file) => ({
162
+ path: file.path,
163
+ result: file.sync(group, mode)
164
+ })));
165
+ }
166
+ function init(options, io) {
167
+ const colors = paint(io);
168
+ const root = resolve(io.cwd, options.directory ?? ".");
169
+ let group;
170
+ try {
171
+ group = initGroup(root, {
172
+ name: options.name,
173
+ repos: options.repos?.map((repo) => resolve(io.cwd, repo)),
174
+ env: io.env
175
+ });
176
+ } catch (error) {
177
+ if (error instanceof CarnetError) {
178
+ io.stderr(`error: ${error.message}\n`);
179
+ return 1;
180
+ }
181
+ throw error;
182
+ }
183
+ const lines = [
184
+ `${colors.bold(group.name)} initialised in ${group.root}`,
185
+ ` repos: ${group.repos.length ? group.repos.join(", ") : "none yet, add them with `rucher group add <path>`"}`,
186
+ ` database: ${group.dbPath}`
187
+ ];
188
+ for (const { path, result } of syncContextFiles(group, "merge")) {
189
+ if (result === "unchanged") continue;
190
+ lines.push(result === "no-markers" ? ` kept existing ${path} ${colors.dim("(add the rucher:repos markers to keep its repo list in sync, and a line: multi-agent work uses the rucher tools)")}` : ` ${result} ${path}`);
191
+ }
192
+ const hosts = group.hosts.map((id) => hostById(id).displayName).join(" or ");
193
+ lines.push("", `Next: start ${hosts} in this directory, then \`rucher status --watch\` in a side pane.`);
194
+ io.stdout(`${lines.join("\n")}\n`);
195
+ return 0;
196
+ }
197
+ // src/commands/group.ts
198
+ function groupShow(io) {
199
+ const colors = paint(io);
200
+ const group = locateGroup({
201
+ cwd: io.cwd,
202
+ env: io.env
203
+ });
204
+ const repos = group.repos.length ? group.repos.map((r) => ` ${basename(r)} ${colors.dim(r)}`).join("\n") : ` ${colors.dim("none")}`;
205
+ io.stdout(`${colors.bold(group.name)} ${colors.dim(group.root)}\nrepos:\n${repos}\n`);
206
+ return 0;
207
+ }
208
+ function syncNotes(group, mode) {
209
+ return syncContextFiles(group, mode).filter(({ result }) => result !== "unchanged").map(({ path, result }) => result === "no-markers" ? `${path} has no rucher:repos markers, update its repo list yourself` : `${result} ${path}`);
210
+ }
211
+ function withNotes(line, notes) {
212
+ return `${line}${notes.length ? ` (${notes.join(", ")})` : ""}\n`;
213
+ }
214
+ function carnetErrors(io, run) {
215
+ try {
216
+ return run();
217
+ } catch (error) {
218
+ if (error instanceof CarnetError) {
219
+ io.stderr(`error: ${error.message}\n`);
220
+ return 1;
221
+ }
222
+ throw error;
223
+ }
224
+ }
225
+ function groupAdd(repo, io) {
226
+ const found = locateGroup({
227
+ cwd: io.cwd,
228
+ env: io.env
229
+ });
230
+ return carnetErrors(io, () => {
231
+ const path = resolve(io.cwd, repo);
232
+ const group = addGroupRepo(found.root, path);
233
+ io.stdout(withNotes(`added ${basename(path)} to ${group.name}`, syncNotes(group, "merge")));
234
+ return 0;
235
+ });
236
+ }
237
+ function groupRemove(repo, io) {
238
+ const found = locateGroup({
239
+ cwd: io.cwd,
240
+ env: io.env
241
+ });
242
+ return carnetErrors(io, () => {
243
+ const path = resolve(io.cwd, repo);
244
+ const group = removeGroupRepo(found.root, path);
245
+ io.stdout(withNotes(`removed ${basename(path)} from ${group.name}`, syncNotes(group, "exact")));
246
+ return 0;
247
+ });
248
+ }
249
+ function groupSync(io) {
250
+ const group = locateGroup({
251
+ cwd: io.cwd,
252
+ env: io.env
253
+ });
254
+ const notes = syncNotes(group, "exact");
255
+ io.stdout(notes.length ? withNotes(`synced ${group.name}`, notes) : `${group.name} already in sync\n`);
256
+ return 0;
257
+ }
258
+ // src/commands/groups.ts
259
+ function missing(reference) {
260
+ return !isGroupRoot(reference.path);
261
+ }
262
+ function groupsList(io) {
263
+ const colors = paint(io);
264
+ const groups = readRegistry(io.env);
265
+ if (groups.length === 0) {
266
+ io.stdout(`${colors.dim("no registered group")}\n`);
267
+ return 0;
268
+ }
269
+ const width = Math.max(...groups.map((group) => group.name.length));
270
+ const lines = groups.map((group) => `${colors.bold(group.name.padEnd(width))} ${group.path}${missing(group) ? ` ${colors.yellow("missing")}` : ""}`);
271
+ io.stdout(`${lines.join("\n")}\n`);
272
+ return 0;
273
+ }
274
+ function groupsForget(reference, io) {
275
+ const groups = readRegistry(io.env);
276
+ const byPath = groups.filter((group) => group.path === resolve(io.cwd, reference));
277
+ const matches = byPath.length ? byPath : groups.filter((group) => group.name === reference);
278
+ const [match] = matches;
279
+ if (!match) {
280
+ io.stderr(`error: no registered group named or located at "${reference}"\n`);
281
+ return 1;
282
+ }
283
+ if (matches.length > 1) {
284
+ io.stderr(`error: several groups are named "${reference}", forget one by path:\n${matches.map((group) => ` ${group.path}`).join("\n")}\n`);
285
+ return 1;
286
+ }
287
+ unregisterGroups([match.path], io.env);
288
+ io.stdout(`forgot ${match.name} (${match.path}); its meta directory is untouched\n`);
289
+ return 0;
290
+ }
291
+ function groupsPrune(io) {
292
+ const gone = readRegistry(io.env).filter(missing);
293
+ if (gone.length === 0) {
294
+ io.stdout("nothing to prune\n");
295
+ return 0;
296
+ }
297
+ unregisterGroups(gone.map((group) => group.path), io.env);
298
+ io.stdout(`pruned ${gone.length}:\n${gone.map((g) => ` ${g.name} ${g.path}`).join("\n")}\n`);
299
+ return 0;
300
+ }
301
+ // src/commands/hook.ts
302
+ const host = claudeCode;
303
+ function runHook(io, run) {
304
+ try {
305
+ run();
306
+ } catch (error) {
307
+ if (error instanceof CarnetError && error.code === "NO_GROUP") return 0;
308
+ io.stderr(`rucher hook: ${error instanceof Error ? error.message : String(error)}\n`);
309
+ }
310
+ return 0;
311
+ }
312
+ function withCarnet$1(cwd, io, use) {
313
+ const carnet = openCarnet({
314
+ cwd: cwd ?? io.cwd,
315
+ env: io.env
316
+ });
317
+ try {
318
+ use(carnet);
319
+ } finally {
320
+ carnet.close();
321
+ }
322
+ }
323
+ function sessionStart(stdinText, io) {
324
+ return runHook(io, () => {
325
+ const payload = host.parseSessionPayload(stdinText);
326
+ withCarnet$1(payload.cwd, io, (carnet) => {
327
+ const { additionalContext, notices } = handleSessionStart(carnet, payload, {
328
+ host: host.id,
329
+ processId: host.processId(io.env),
330
+ RUCHER_PURGE_DAYS: io.env.RUCHER_PURGE_DAYS,
331
+ RUCHER_HOME: io.env.RUCHER_HOME,
332
+ RUCHER_SESSION_ID: io.env.RUCHER_SESSION_ID,
333
+ RUCHER_SESSION_KIND: io.env.RUCHER_SESSION_KIND,
334
+ RUCHER_SESSION_NAME: io.env.RUCHER_SESSION_NAME,
335
+ RUCHER_PROMPT_VERSION: io.env.RUCHER_PROMPT_VERSION,
336
+ RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
337
+ RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
338
+ });
339
+ for (const notice of notices) io.stderr(`${notice}\n`);
340
+ if (additionalContext) {
341
+ const hookSpecificOutput = {
342
+ hookEventName: "SessionStart",
343
+ additionalContext
344
+ };
345
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
346
+ }
347
+ });
348
+ });
349
+ }
350
+ function subagentStart(stdinText, io) {
351
+ return runHook(io, () => {
352
+ const payload = host.parseSubagentPayload(stdinText);
353
+ withCarnet$1(payload.cwd, io, (carnet) => {
354
+ carnet.agents.pairSubagent(payload.session_id, payload.agent_id);
355
+ });
356
+ if (host.subagentInheritsContext(payload)) return;
357
+ const hookSpecificOutput = {
358
+ hookEventName: "SubagentStart",
359
+ additionalContext: SUBAGENT_RULES
360
+ };
361
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
362
+ });
363
+ }
364
+ function subagentStop(stdinText, io) {
365
+ return runHook(io, () => {
366
+ const payload = host.parseSubagentPayload(stdinText);
367
+ withCarnet$1(payload.cwd, io, (carnet) => {
368
+ carnet.agents.stopSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload));
369
+ });
370
+ });
371
+ }
372
+ function userPromptSubmit(stdinText, io) {
373
+ return runHook(io, () => {
374
+ const payload = host.parsePromptPayload(stdinText);
375
+ withCarnet$1(payload.cwd, io, (carnet) => {
376
+ handleUserPromptSubmit(carnet, host, payload);
377
+ });
378
+ });
379
+ }
380
+ function postToolUse(stdinText, io) {
381
+ return runHook(io, () => {
382
+ const payload = host.parseToolPayload(stdinText);
383
+ if (payload.agent_id || !payload.path) return;
384
+ withCarnet$1(payload.cwd, io, (carnet) => {
385
+ const additionalContext = handleToolUse(carnet, payload, {
386
+ RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
387
+ RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
388
+ });
389
+ if (!additionalContext) return;
390
+ const hookSpecificOutput = {
391
+ hookEventName: "PostToolUse",
392
+ additionalContext
393
+ };
394
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
395
+ });
396
+ });
397
+ }
398
+ function sessionEnd(stdinText, io) {
399
+ return runHook(io, () => {
400
+ const payload = host.parseSessionEndPayload(stdinText);
401
+ withCarnet$1(payload.cwd, io, (carnet) => {
402
+ handleSessionEnd(carnet, payload);
403
+ });
404
+ });
405
+ }
406
+ // src/session.ts
407
+ var CliError = class extends Error {
408
+ hint;
409
+ constructor(message, hint) {
410
+ super(message);
411
+ this.hint = hint;
412
+ this.name = "CliError";
413
+ }
414
+ };
415
+ function findSession(carnet, reference) {
416
+ try {
417
+ return carnet.sessions.find(reference);
418
+ } catch (error) {
419
+ if (!(error instanceof CarnetError) || error.code !== "SESSION_NOT_FOUND") throw error;
420
+ const known = carnet.sessions.list().map((session) => session.name).filter(Boolean);
421
+ throw new CliError(error.message, known.length ? `known sessions: ${known.join(", ")}` : "pass a session name, id or id prefix, see rucher sessions --all");
422
+ }
423
+ }
424
+ function resolveSession(carnet, reference) {
425
+ if (reference) return findSession(carnet, reference);
426
+ const session = carnet.sessions.default();
427
+ if (!session) throw new CliError("No session in this group yet", "start a Claude Code session inside the group");
428
+ return session;
429
+ }
430
+ // src/commands/log.ts
431
+ function formatEvents(events, io) {
432
+ const colors = paint(io);
433
+ if (events.length === 0) return colors.dim("no events yet");
434
+ return events.map((event) => {
435
+ return [
436
+ colors.dim(formatClock(new Date(event.at))),
437
+ colors.bold(event.type.padEnd(9)),
438
+ event.agent ?? "",
439
+ event.link ?? event.note ?? "",
440
+ event.commit ? colors.cyan(event.commit.slice(0, 7)) : ""
441
+ ].filter(Boolean).join(" ");
442
+ }).join("\n");
443
+ }
444
+ function formatDay(date) {
445
+ const month = String(date.getMonth() + 1).padStart(2, "0");
446
+ const day = String(date.getDate()).padStart(2, "0");
447
+ return `${date.getFullYear()}-${month}-${day}`;
448
+ }
449
+ function markdownEvent(event) {
450
+ const parts = [`${formatClock(new Date(event.at))} **${event.type}**`];
451
+ if (event.agent) parts.push(`\`${event.agent}\``);
452
+ const detail = [
453
+ event.note,
454
+ event.link ? `[report](${event.link})` : null,
455
+ event.commit ? `\`${event.commit.slice(0, 7)}\`` : null
456
+ ].filter(Boolean).join(" · ");
457
+ return `- ${parts.join(" ")}${detail ? `: ${detail}` : ""}`;
458
+ }
459
+ function formatEventsMarkdown(events, title) {
460
+ const lines = [`# Journal: ${title}`];
461
+ if (events.length === 0) return `${lines[0]}\n\nNo events yet.`;
462
+ let day = "";
463
+ for (const event of events) {
464
+ const current = formatDay(new Date(event.at));
465
+ if (current !== day) {
466
+ day = current;
467
+ lines.push("", `## ${day}`, "");
468
+ }
469
+ lines.push(markdownEvent(event));
470
+ }
471
+ return lines.join("\n");
472
+ }
473
+ function sessionTitle(carnet, session) {
474
+ return `${carnet.group.name} · ${session.name ?? session.id.slice(0, 8)}`;
475
+ }
476
+ function logOnce(carnet, io, options) {
477
+ const session = resolveSession(carnet, options.session);
478
+ const events = carnet.events.read(session.id, options.count, options.agents);
479
+ io.stdout(`${options.md ? formatEventsMarkdown(events, sessionTitle(carnet, session)) : formatEvents(events, io)}\n`);
480
+ }
481
+ // src/commands/notes.ts
482
+ const KIND_TITLES = {
483
+ dead_end: "Dead ends",
484
+ decision: "Decisions",
485
+ learning: "Learnings"
486
+ };
487
+ function repoList(rawArguments) {
488
+ const values = [];
489
+ for (let index = 0; index < rawArguments.length; index++) {
490
+ const argument = rawArguments[index] ?? "";
491
+ if (argument === "--repo") values.push(rawArguments[++index] ?? "");
492
+ else if (argument.startsWith("--repo=")) values.push(argument.slice(7));
493
+ }
494
+ return values.flatMap((value) => value.split(",")).map((repo) => repo.trim()).filter(Boolean);
495
+ }
496
+ function parseNoteId(value) {
497
+ const id = Number(value.replace(/^#/, ""));
498
+ if (!Number.isInteger(id) || id <= 0) throw new CliError(`Invalid note id "${value}"`, "use the number shown by rucher notes, e.g. 14");
499
+ return id;
500
+ }
501
+ function halfLife(io) {
502
+ return memoryHalfLife(io.env["RUCHER_MEMORY_HALF_LIFE_DAYS"]);
503
+ }
504
+ function reposLabel(note) {
505
+ return note.repos.length ? `[${note.repos.join(", ")}] ` : "";
506
+ }
507
+ function noteLine(io, note) {
508
+ const colors = paint(io);
509
+ const extras = [
510
+ note.citationCount ? `cited ${note.citationCount}` : "",
511
+ note.similarNotes.length ? colors.yellow(`similar to ${note.similarNotes.map((id) => `#${id}`).join(", ")}`) : "",
512
+ note.droppedAt ? colors.dim(`dropped: ${note.droppedReason ?? ""}`) : ""
513
+ ].filter(Boolean);
514
+ const text = `${reposLabel(note)}${note.text}`;
515
+ const line = ` ${colors.bold(`#${note.id}`.padEnd(5))} ${note.droppedAt ? colors.dim(text) : text}`;
516
+ return extras.length ? `${line} ${colors.dim("·")} ${extras.join(colors.dim(" · "))}` : line;
517
+ }
518
+ function grouped(notes) {
519
+ return NOTE_KINDS.map((kind) => [kind, notes.filter((note) => note.kind === kind)]).filter(([, kindNotes]) => kindNotes.length > 0);
520
+ }
521
+ function markdown(carnet, notes) {
522
+ const sections = grouped(notes).map(([kind, kindNotes]) => {
523
+ const lines = kindNotes.map((note) => {
524
+ const dropped = note.droppedAt ? ` (dropped: ${note.droppedReason ?? ""})` : "";
525
+ return `- #${note.id} ${reposLabel(note)}${note.text}${dropped}`;
526
+ });
527
+ return `## ${KIND_TITLES[kind]}\n\n${lines.join("\n")}`;
528
+ });
529
+ return `# Memory: ${carnet.group.name}\n\n${sections.join("\n\n") || "No notes."}\n`;
530
+ }
531
+ function notesList(carnet, io, options = {}) {
532
+ const notes = options.stale ? carnet.notes.stale(halfLife(io)) : carnet.notes.list({
533
+ kind: options.kind,
534
+ repo: options.repo,
535
+ general: options.general,
536
+ includeDropped: options.all,
537
+ halfLifeDays: halfLife(io)
538
+ });
539
+ if (options.markdown) {
540
+ io.stdout(markdown(carnet, notes));
541
+ return;
542
+ }
543
+ const colors = paint(io);
544
+ if (notes.length === 0) {
545
+ io.stdout(`${colors.dim(options.stale ? "no note to review" : "no notes")}\n`);
546
+ return;
547
+ }
548
+ const blocks = grouped(notes).map(([kind, kindNotes]) => `${colors.bold(KIND_TITLES[kind])}\n${kindNotes.map((note) => noteLine(io, note)).join("\n")}`);
549
+ io.stdout(`${blocks.join("\n\n")}\n`);
550
+ }
551
+ function sessionLabel$1(carnet, id) {
552
+ if (!id) return "-";
553
+ return carnet.sessions.get(id)?.name ?? shortId(id);
554
+ }
555
+ function when(at) {
556
+ const date = new Date(at);
557
+ return `${at.slice(0, 10)} ${formatClock(date)}`;
558
+ }
559
+ function notesShow(carnet, io, id) {
560
+ const colors = paint(io);
561
+ const note = carnet.notes.show(id, halfLife(io));
562
+ const lines = [
563
+ `${colors.bold(`#${note.id}`)} ${note.kind}${note.droppedAt ? colors.dim(" (dropped)") : ""}`,
564
+ note.text,
565
+ `repos: ${note.repos.length ? note.repos.join(", ") : "general"}`,
566
+ `added: ${when(note.createdAt)} in ${sessionLabel$1(carnet, note.session)}${note.agent ? `, from ${note.agent}` : ""}`,
567
+ `weight: ${note.weight.toFixed(2)} · ${note.citationCount} citation${note.citationCount === 1 ? "" : "s"}`
568
+ ];
569
+ if (note.similarNotes.length) lines.push(colors.yellow(`similar to: ${note.similarNotes.map((other) => `#${other}`).join(", ")}`));
570
+ if (note.droppedAt) {
571
+ const replaced = note.replacedBy ? `, replaced by #${note.replacedBy}` : "";
572
+ lines.push(`dropped: ${when(note.droppedAt)}: ${note.droppedReason ?? ""}${replaced}`);
573
+ }
574
+ if (note.citations.length) {
575
+ lines.push("citations:");
576
+ for (const citation of note.citations) {
577
+ const by = citation.agent ? ` ${citation.agent}` : "";
578
+ lines.push(` ${when(citation.at)} ${sessionLabel$1(carnet, citation.session)}${by} ${citation.why}`);
579
+ }
580
+ }
581
+ io.stdout(`${lines.join("\n")}\n`);
582
+ }
583
+ function notesAdd(carnet, io, input) {
584
+ const { note, similar } = carnet.notes.add({
585
+ kind: input.kind,
586
+ text: input.text,
587
+ repos: input.repos
588
+ });
589
+ io.stdout(`added #${note.id} ${note.kind} ${reposLabel(note)}${note.text}\n`);
590
+ if (similar.length) {
591
+ const colors = paint(io);
592
+ io.stdout(`${colors.yellow("similar active notes, possible duplicate:")}\n${similar.map((other) => ` #${other.id} ${reposLabel(other)}${other.text}`).join("\n")}\n`);
593
+ }
594
+ }
595
+ function notesDrop(carnet, io, id, input) {
596
+ const note = carnet.notes.drop(id, input);
597
+ const replaced = note.replacedBy ? `, replaced by #${note.replacedBy}` : "";
598
+ io.stdout(`dropped #${note.id}${replaced}\n`);
599
+ }
600
+ // src/commands/launch.ts
601
+ function splitPassthrough(rawArgs) {
602
+ const separator = rawArgs.indexOf("--");
603
+ if (separator === -1) return {
604
+ own: [...rawArgs],
605
+ passthrough: []
606
+ };
607
+ return {
608
+ own: rawArgs.slice(0, separator),
609
+ passthrough: rawArgs.slice(separator + 1)
610
+ };
611
+ }
612
+ function positionals(own) {
613
+ return own.filter((argument) => !argument.startsWith("-"));
614
+ }
615
+ function launchEnv(carnet, session, promptVersion, kind) {
616
+ return {
617
+ RUCHER_SESSION_ID: session.id,
618
+ RUCHER_PROMPT_VERSION: promptVersion,
619
+ RUCHER_SESSION_NAME: session.name ?? "",
620
+ RUCHER_GROUP: carnet.group.name,
621
+ ...kind ? { RUCHER_SESSION_KIND: kind } : {}
622
+ };
623
+ }
624
+ function planNew(carnet, io, options) {
625
+ if (options.kind === "active" && !options.name) throw new CliError("An active session needs a name", "rucher new <name>");
626
+ const session = carnet.sessions.create({
627
+ id: randomUUID(),
628
+ kind: options.kind,
629
+ name: options.name,
630
+ cwd: carnet.group.root,
631
+ repo: repoNameFor(carnet.group, io.cwd)
632
+ });
633
+ const host = hostById(session.host);
634
+ const prompt = appendPromptFile(carnet.group, session, io.env);
635
+ return {
636
+ ...host.launchCommand(session.id, {
637
+ name: session.name,
638
+ appendPromptFile: prompt.path,
639
+ passthrough: options.passthrough
640
+ }),
641
+ cwd: carnet.group.root,
642
+ env: launchEnv(carnet, session, prompt.version),
643
+ sessionId: session.id
644
+ };
645
+ }
646
+ function sessionDirectory(session, io) {
647
+ return session.cwd && existsSync(session.cwd) ? session.cwd : io.cwd;
648
+ }
649
+ function planResume(carnet, io, reference, passthrough = []) {
650
+ const session = findSession(carnet, reference);
651
+ if (session.status === "archived") io.stderr(`warning: session ${reference} is archived\n`);
652
+ const prompt = appendPromptFile(carnet.group, session, io.env);
653
+ return {
654
+ ...hostById(session.host).resumeCommand(session, {
655
+ appendPromptFile: prompt.path,
656
+ passthrough
657
+ }),
658
+ cwd: sessionDirectory(session, io),
659
+ env: launchEnv(carnet, session, prompt.version),
660
+ sessionId: session.id
661
+ };
662
+ }
663
+ function planFork(carnet, io, reference, options = {}) {
664
+ if (options.active && !options.name) throw new CliError("An active fork needs a name", "rucher fork <session> <name> --active");
665
+ if (options.name && carnet.sessions.byName(options.name)) throw new CliError(`A session named "${options.name}" already exists`);
666
+ const parent = findSession(carnet, reference);
667
+ const kind = options.active ? "active" : "temp";
668
+ return {
669
+ ...hostById(parent.host).forkCommand(parent, {
670
+ name: options.name,
671
+ appendPromptFile: appendPromptFile(carnet.group, parent, io.env).path,
672
+ passthrough: options.passthrough
673
+ }),
674
+ cwd: sessionDirectory(parent, io),
675
+ env: {
676
+ ...launchEnv(carnet, parent, parent.promptVersion ?? "", kind),
677
+ RUCHER_SESSION_NAME: options.name ?? ""
678
+ },
679
+ parentId: parent.id,
680
+ knownChildren: childrenOf(carnet, parent.id).map((session) => session.id)
681
+ };
682
+ }
683
+ function childrenOf(carnet, parentId) {
684
+ return carnet.sessions.list({
685
+ includeTemp: true,
686
+ includeArchived: true
687
+ }).filter((session) => session.parentId === parentId);
688
+ }
689
+ function forkChild(carnet, plan) {
690
+ if (!plan.parentId) return void 0;
691
+ const known = new Set(plan.knownChildren);
692
+ return childrenOf(carnet, plan.parentId).find((session) => !known.has(session.id));
693
+ }
694
+ function finishLaunch(carnet, plan) {
695
+ const id = plan.sessionId ?? forkChild(carnet, plan)?.id;
696
+ if (id && carnet.sessions.get(id)) carnet.sessions.end(id);
697
+ }
698
+ function startLaunch(carnet, plan) {
699
+ if (plan.sessionId) carnet.sessions.setStatus(plan.sessionId, "running");
700
+ }
701
+ function spawnLaunch(plan, env) {
702
+ const result = spawnSync(plan.command, plan.args, {
703
+ cwd: plan.cwd,
704
+ stdio: "inherit",
705
+ env: {
706
+ ...env,
707
+ ...plan.env
708
+ }
709
+ });
710
+ if (result.error) throw result.error;
711
+ return result.status ?? 1;
712
+ }
713
+ // src/commands/picker.ts
714
+ function pickerSessions(carnet) {
715
+ const sessions = carnet.sessions.list({ includeTemp: true });
716
+ return [...sessions.filter((session) => session.name), ...sessions.filter((session) => !session.name)];
717
+ }
718
+ function lastUse(at, now) {
719
+ const date = new Date(at);
720
+ return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
721
+ }
722
+ function pickerLines(sessions, now = /* @__PURE__ */ new Date()) {
723
+ const rows = sessions.map((session, index) => [
724
+ String(index + 1),
725
+ session.name ?? shortId(session.id),
726
+ session.kind,
727
+ session.status,
728
+ lastUse(session.lastActiveAt, now),
729
+ shortId(session.id)
730
+ ]);
731
+ const widths = (rows[0] ?? []).map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
732
+ return rows.map((row) => row.map((cell, column) => column < row.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell).join(" "));
733
+ }
734
+ function hasFzf() {
735
+ return spawnSync("fzf", ["--version"], { stdio: "ignore" }).status === 0;
736
+ }
737
+ function pickWithFzf(sessions, lines) {
738
+ const result = spawnSync("fzf", [
739
+ "--with-nth=2..",
740
+ "--no-sort",
741
+ "--prompt=session> "
742
+ ], {
743
+ input: lines.join("\n"),
744
+ stdio: [
745
+ "pipe",
746
+ "pipe",
747
+ "inherit"
748
+ ],
749
+ encoding: "utf8"
750
+ });
751
+ return sessions[Number(result.stdout?.trim().split(/\s+/)[0]) - 1];
752
+ }
753
+ async function pickFromList(sessions, lines) {
754
+ process.stderr.write(`${lines.join("\n")}\n`);
755
+ const prompt = createInterface({
756
+ input: process.stdin,
757
+ output: process.stderr
758
+ });
759
+ try {
760
+ const answer = await prompt.question("session number> ");
761
+ return sessions[Number(answer.trim()) - 1];
762
+ } finally {
763
+ prompt.close();
764
+ }
765
+ }
766
+ async function pickSession(carnet) {
767
+ const sessions = pickerSessions(carnet);
768
+ if (sessions.length === 0) throw new CliError("No session to resume in this group", "rucher new <name>");
769
+ if (!process.stdin.isTTY) throw new CliError("No session given", "rucher resume <name, id or id prefix>");
770
+ const lines = pickerLines(sessions);
771
+ const picked = hasFzf() ? pickWithFzf(sessions, lines) : await pickFromList(sessions, lines);
772
+ if (!picked) throw new CliError("No session picked");
773
+ return picked;
774
+ }
775
+ // src/commands/serve.ts
776
+ function serve(io) {
777
+ serveCarnet({
778
+ cwd: io.cwd,
779
+ env: io.env
780
+ });
781
+ }
782
+ // src/commands/watch-keys.ts
783
+ const INITIAL_WATCH_STATE = {
784
+ notesOpen: false,
785
+ selected: 0,
786
+ detail: false,
787
+ reason: null,
788
+ message: null
789
+ };
790
+ function clamp(index, count) {
791
+ return Math.min(Math.max(index, 0), Math.max(count - 1, 0));
792
+ }
793
+ function typeReason(state, key) {
794
+ const reason = state.reason ?? "";
795
+ if (key.name === "escape") return { state: {
796
+ ...state,
797
+ reason: null,
798
+ message: null
799
+ } };
800
+ if (key.name === "return" || key.name === "enter") {
801
+ const trimmed = reason.trim();
802
+ if (!trimmed) return { state: {
803
+ ...state,
804
+ message: "a reason is required"
805
+ } };
806
+ return {
807
+ state: {
808
+ ...state,
809
+ reason: null,
810
+ detail: false,
811
+ message: null
812
+ },
813
+ action: {
814
+ type: "drop",
815
+ index: state.selected,
816
+ reason: trimmed
817
+ }
818
+ };
819
+ }
820
+ if (key.name === "backspace") return { state: {
821
+ ...state,
822
+ reason: reason.slice(0, -1)
823
+ } };
824
+ const character = key.sequence ?? "";
825
+ if (character.length === 1 && character >= " " && !key.ctrl) return { state: {
826
+ ...state,
827
+ reason: reason + character,
828
+ message: null
829
+ } };
830
+ return { state };
831
+ }
832
+ function pressKey(state, key, noteCount) {
833
+ if (key.ctrl && key.name === "c") return {
834
+ state,
835
+ action: { type: "quit" }
836
+ };
837
+ if (state.reason !== null) return typeReason(state, key);
838
+ const next = {
839
+ ...state,
840
+ message: null
841
+ };
842
+ switch (key.name) {
843
+ case "q": return {
844
+ state: next,
845
+ action: { type: "quit" }
846
+ };
847
+ case "n": return { state: {
848
+ ...next,
849
+ notesOpen: !state.notesOpen && noteCount > 0,
850
+ detail: false
851
+ } };
852
+ case "escape": return { state: {
853
+ ...next,
854
+ detail: false
855
+ } };
856
+ }
857
+ if (!state.notesOpen || noteCount === 0) return { state: next };
858
+ const selected = clamp(state.selected, noteCount);
859
+ switch (key.name) {
860
+ case "up": return { state: {
861
+ ...next,
862
+ selected: clamp(selected - 1, noteCount),
863
+ detail: false
864
+ } };
865
+ case "down": return { state: {
866
+ ...next,
867
+ selected: clamp(selected + 1, noteCount),
868
+ detail: false
869
+ } };
870
+ case "return":
871
+ case "enter": return { state: {
872
+ ...next,
873
+ selected,
874
+ detail: !state.detail
875
+ } };
876
+ case "d": return { state: {
877
+ ...next,
878
+ selected,
879
+ detail: false,
880
+ reason: ""
881
+ } };
882
+ }
883
+ return { state: {
884
+ ...next,
885
+ selected
886
+ } };
887
+ }
888
+ // src/commands/status.ts
889
+ const SECTION_HEADERS = /* @__PURE__ */ new Set([
890
+ "On the table",
891
+ "Waiting on you",
892
+ "Running",
893
+ NOTES_HEADER
894
+ ]);
895
+ function truncate(line, columns) {
896
+ const chars = Array.from(line);
897
+ return chars.length > columns ? `${chars.slice(0, Math.max(columns - 1, 1)).join("")}…` : line;
898
+ }
899
+ function colorizeLine(line, io) {
900
+ const colors = paint(io);
901
+ if (line === LEGEND) return colors.dim(line);
902
+ const cut = truncate(line, io.columns);
903
+ if (SECTION_HEADERS.has(line)) return colors.bold(cut);
904
+ if (line.startsWith(" ⚙️")) return colors.yellow(cut);
905
+ if (line === " nothing") return colors.dim(cut);
906
+ if (cut.startsWith(`${NOTES_HEADER} `)) return `${colors.bold(NOTES_HEADER)}${cut.slice(NOTES_HEADER.length)}`;
907
+ const marker = /^ {2}\+ #\d+ +\S+ {2}(similar to [^·]*·)/.exec(cut);
908
+ if (marker?.[1]) {
909
+ const start = cut.indexOf(SIMILAR_PREFIX);
910
+ const end = start + marker[1].length;
911
+ return `${cut.slice(0, start)}${colors.yellow(cut.slice(start, end))}${cut.slice(end)}`;
912
+ }
913
+ return cut;
914
+ }
915
+ function sessionWhere(carnet, session) {
916
+ return repoPathFor(carnet.group, session.cwd) ?? session.repo;
917
+ }
918
+ function sessionLabel(carnet, session, columns) {
919
+ const name = session.name ?? session.id.slice(0, 8);
920
+ const where = sessionWhere(carnet, session);
921
+ if (!where) return name;
922
+ const room = columns - Array.from(name).length - 3;
923
+ return room > 1 ? `${name} · ${truncate(where, room)}` : name;
924
+ }
925
+ function sessionHeader(carnet, session, io) {
926
+ return paint(io).cyan(sessionLabel(carnet, session, io.columns));
927
+ }
928
+ function sessionLines(session, view, io, notes = "full") {
929
+ if (session.status === "archived") return [paint(io).dim(" archived, see rucher sessions --all")];
930
+ return renderSections(view, { notes }).split("\n").map((line) => colorizeLine(line, io));
931
+ }
932
+ const KEYS_HINT = "n fold · ↑↓ select · enter detail · d drop · q quit";
933
+ function noteDetailLines(carnet, id) {
934
+ const note = carnet.notes.show(id);
935
+ const lines = [` ${note.text}`];
936
+ if (note.repos.length > 0) lines.push(` repos: ${note.repos.join(", ")}`);
937
+ const status = note.droppedAt ? `dropped: ${note.droppedReason ?? ""}` : "active";
938
+ lines.push(` ${status} · weight ${note.weight.toFixed(2)} · ${note.citationCount} cited`);
939
+ for (const citation of note.citations) lines.push(` ★ ${citation.at.slice(0, 10)} ${citation.why}`);
940
+ return lines;
941
+ }
942
+ function interactiveLines(carnet, session, view, io, state) {
943
+ if (!state.notesOpen || session.status === "archived") return sessionLines(session, view, io);
944
+ const colors = paint(io);
945
+ const raw = renderSections(view, { notes: "expanded" }).split("\n");
946
+ const header = raw.indexOf(NOTES_HEADER);
947
+ const selected = Math.min(state.selected, view.notes.length - 1);
948
+ return raw.flatMap((line, index) => {
949
+ const position = index - header - 1;
950
+ if (header === -1 || position !== selected) return [colorizeLine(line, io)];
951
+ const marked = colors.cyan(truncate(`›${line.slice(1)}`, io.columns));
952
+ const note = view.notes[selected];
953
+ if (!state.detail || !note) return [marked];
954
+ return [marked, ...noteDetailLines(carnet, note.note).map((detail) => truncate(detail, io.columns))];
955
+ });
956
+ }
957
+ function footerLine(view, io, state) {
958
+ if (!state) return null;
959
+ const colors = paint(io);
960
+ if (state.reason !== null) {
961
+ const note = view.notes[Math.min(state.selected, view.notes.length - 1)];
962
+ return colors.yellow(`drop #${note?.note ?? "?"}, reason: ${state.reason}`);
963
+ }
964
+ if (state.message) return colors.red(state.message);
965
+ return state.notesOpen ? colors.dim(KEYS_HINT) : null;
966
+ }
967
+ function hasSomethingToShow(carnet, session) {
968
+ return carnet.agents.list(session.id).length > 0 || carnet.table.get(session.id) !== void 0 || carnet.notes.activity(session.id).length > 0;
969
+ }
970
+ function sessionBlock(carnet, session, view, io) {
971
+ return [sessionHeader(carnet, session, io), ...sessionLines(session, view, io, "summary")].join("\n");
972
+ }
973
+ function singleView(carnet, session, io, state) {
974
+ const colors = paint(io);
975
+ const view = carnet.status.view(session);
976
+ const separator = " - ";
977
+ const label = sessionLabel(carnet, session, io.columns - view.time.length - 3);
978
+ const title = `${colors.dim(view.time)}${separator}${colors.cyan(label)}`;
979
+ const body = state ? interactiveLines(carnet, session, view, io, state) : sessionLines(session, view, io);
980
+ const footer = footerLine(view, io, state);
981
+ return [
982
+ title,
983
+ "",
984
+ ...body,
985
+ "",
986
+ ...footer ? [footer] : [],
987
+ colors.dim(LEGEND)
988
+ ].join("\n");
989
+ }
990
+ function renderStatusView(carnet, io, options) {
991
+ const sessions = options.all ? carnet.sessions.list({ includeTemp: true }).filter((session) => hasSomethingToShow(carnet, session)) : [];
992
+ if (sessions.length === 0) return singleView(carnet, resolveSession(carnet, options.session), io, options.interaction);
993
+ let time = "";
994
+ const blocks = sessions.map((session) => {
995
+ const view = carnet.status.view(session);
996
+ time ||= view.time;
997
+ return sessionBlock(carnet, session, view, io);
998
+ });
999
+ return [
1000
+ paint(io).dim(time),
1001
+ "",
1002
+ blocks.join("\n\n"),
1003
+ "",
1004
+ paint(io).dim(LEGEND)
1005
+ ].join("\n");
1006
+ }
1007
+ function statusOnce(carnet, io, options) {
1008
+ io.stdout(`${renderStatusView(carnet, io, options)}\n`);
1009
+ }
1010
+ function dropSelected(carnet, options, index, reason) {
1011
+ const session = resolveSession(carnet, options.session);
1012
+ const item = carnet.notes.activity(session.id)[index];
1013
+ if (!item) return "no note selected";
1014
+ try {
1015
+ carnet.notes.drop(item.note, {
1016
+ reason,
1017
+ session: session.id
1018
+ });
1019
+ return null;
1020
+ } catch (error) {
1021
+ return error instanceof Error ? error.message : String(error);
1022
+ }
1023
+ }
1024
+ function noteCount(carnet, options) {
1025
+ try {
1026
+ return carnet.notes.activity(resolveSession(carnet, options.session).id).length;
1027
+ } catch {
1028
+ return 0;
1029
+ }
1030
+ }
1031
+ const CLEAR = "\x1B[H\x1B[2J";
1032
+ const HIDE_CURSOR = "\x1B[?25l";
1033
+ const SHOW_CURSOR = "\x1B[?25h";
1034
+ function statusWatch(carnet, io, options) {
1035
+ return new Promise((resolve) => {
1036
+ let last = "";
1037
+ const interactive = options.keys !== void 0 && !options.all;
1038
+ let state = INITIAL_WATCH_STATE;
1039
+ const repaint = () => {
1040
+ let text;
1041
+ try {
1042
+ text = renderStatusView(carnet, io, {
1043
+ ...options,
1044
+ interaction: interactive ? state : void 0
1045
+ });
1046
+ } catch (error) {
1047
+ text = paint(io).dim(error instanceof Error ? error.message : String(error));
1048
+ }
1049
+ if (text === last) return;
1050
+ last = text;
1051
+ io.stdout(`${CLEAR}${text}\n`);
1052
+ };
1053
+ const timer = setInterval(() => {
1054
+ if (state.reason === null) repaint();
1055
+ }, options.intervalMilliseconds);
1056
+ let stopped = false;
1057
+ const stop = () => {
1058
+ if (stopped) return;
1059
+ stopped = true;
1060
+ clearInterval(timer);
1061
+ options.keys?.close();
1062
+ io.stdout(SHOW_CURSOR);
1063
+ resolve();
1064
+ };
1065
+ options.keys?.onKey((key) => {
1066
+ const result = pressKey(state, key, interactive ? noteCount(carnet, options) : 0);
1067
+ state = result.state;
1068
+ if (result.action?.type === "quit") return stop();
1069
+ if (result.action?.type === "drop") state = {
1070
+ ...state,
1071
+ message: dropSelected(carnet, options, result.action.index, result.action.reason)
1072
+ };
1073
+ repaint();
1074
+ });
1075
+ options.signal?.addEventListener("abort", stop, { once: true });
1076
+ io.stdout(HIDE_CURSOR);
1077
+ repaint();
1078
+ });
1079
+ }
1080
+ // src/commands/sessions.ts
1081
+ function lastActive(at, now) {
1082
+ const date = new Date(at);
1083
+ return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
1084
+ }
1085
+ function row(carnet, session, now) {
1086
+ const open = carnet.agents.list(session.id).length;
1087
+ return [
1088
+ session.name ?? session.id.slice(0, 8),
1089
+ session.kind,
1090
+ session.status,
1091
+ sessionWhere(carnet, session) ?? "",
1092
+ lastActive(session.lastActiveAt, now),
1093
+ open ? `${open} agent${open > 1 ? "s" : ""}` : "",
1094
+ session.purpose ?? ""
1095
+ ];
1096
+ }
1097
+ function sessionsOnce(carnet, io, options = {}) {
1098
+ const colors = paint(io);
1099
+ const sessions = carnet.sessions.list({
1100
+ includeTemp: options.all,
1101
+ includeArchived: options.all
1102
+ });
1103
+ if (sessions.length === 0) {
1104
+ const hint = options.all ? "" : " (temp and archived ones are hidden, use --all)";
1105
+ io.stdout(`${colors.dim(`no active session yet${hint}`)}\n`);
1106
+ return;
1107
+ }
1108
+ const now = options.now ?? /* @__PURE__ */ new Date();
1109
+ const rows = sessions.map((session) => ({
1110
+ session,
1111
+ cells: row(carnet, session, now)
1112
+ }));
1113
+ const widths = rows.reduce((current, { cells }) => cells.map((cell, column) => Math.max(current[column] ?? 0, cell.length)), []);
1114
+ const lines = rows.map(({ session, cells }) => {
1115
+ return cells.map((cell, column) => {
1116
+ const padded = column < cells.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell;
1117
+ if (column === 0) return colors.bold(padded);
1118
+ if (column === 1 && session.kind === "temp") return colors.dim(padded);
1119
+ if (column === 2 && session.status === "archived") return colors.dim(padded);
1120
+ return padded;
1121
+ }).join(" ").trimEnd();
1122
+ });
1123
+ io.stdout(`${lines.join("\n")}\n`);
1124
+ }
1125
+ function sessionsMerge(carnet, fromReference, intoReference, io) {
1126
+ const from = findSession(carnet, fromReference);
1127
+ const into = findSession(carnet, intoReference);
1128
+ const result = carnet.sessions.merge(from.id, into.id);
1129
+ const label = (session) => session.name ?? session.id.slice(0, 8);
1130
+ const lines = [
1131
+ `merged ${label(from)} into ${label(result.session)}`,
1132
+ ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
1133
+ ...result.closedAgents.length ? [` agents closed (name already used): ${result.closedAgents.join(", ")}`] : [],
1134
+ ` events moved: ${result.movedEvents}`,
1135
+ ` table line moved: ${result.movedTable ? "yes" : "no"}`
1136
+ ];
1137
+ io.stdout(`${lines.join("\n")}\n`);
1138
+ }
1139
+ function label(session) {
1140
+ return session.name ?? shortId(session.id);
1141
+ }
1142
+ function sessionsRename(carnet, reference, name, io) {
1143
+ const session = carnet.sessions.rename(findSession(carnet, reference).id, name);
1144
+ io.stdout(`renamed to ${session.name}; rucher resume ${session.name} gives Claude the same title\n`);
1145
+ }
1146
+ function sessionsPromote(carnet, reference, name, io) {
1147
+ const session = carnet.sessions.promote(findSession(carnet, reference).id, name);
1148
+ io.stdout(`${label(session)} is now active\n`);
1149
+ }
1150
+ function sessionsDemote(carnet, reference, io) {
1151
+ const session = carnet.sessions.demote(findSession(carnet, reference).id);
1152
+ io.stdout(`${label(session)} is now temp, cleaned by rucher sessions clean once idle\n`);
1153
+ }
1154
+ function purgeTranscripts(session, io) {
1155
+ const files = hostById(session.host).transcriptFiles(session, io.env);
1156
+ for (const file of files) {
1157
+ rmSync(file, {
1158
+ recursive: true,
1159
+ force: true
1160
+ });
1161
+ io.stdout(` deleted ${file}\n`);
1162
+ }
1163
+ if (files.length === 0) io.stdout(" no transcript found\n");
1164
+ }
1165
+ function sessionsDrop(carnet, reference, io, options = {}) {
1166
+ const session = findSession(carnet, reference);
1167
+ if (options.purge && session.status === "running") throw new CliError(`Session ${label(session)} is running`, "drop it with --purge once it has ended");
1168
+ carnet.sessions.drop(session.id);
1169
+ io.stdout(`archived ${label(session)}\n`);
1170
+ if (options.purge) purgeTranscripts(session, io);
1171
+ }
1172
+ const UNIT_MILLISECONDS = {
1173
+ m: 6e4,
1174
+ h: 36e5,
1175
+ d: 864e5
1176
+ };
1177
+ function parseDuration(value) {
1178
+ const match = /^(\d+(?:\.\d+)?)([mhd]?)$/.exec(value.trim());
1179
+ if (!match) throw new CliError(`Invalid duration "${value}"`, "use a number of days, or 30m, 12h, 7d");
1180
+ return Number(match[1]) * (UNIT_MILLISECONDS[match[2] || "d"] ?? 0);
1181
+ }
1182
+ function processIsAlive(processId) {
1183
+ try {
1184
+ process.kill(processId, 0);
1185
+ return true;
1186
+ } catch (error) {
1187
+ return error.code === "EPERM";
1188
+ }
1189
+ }
1190
+ function sessionsClean(carnet, io, options = {}) {
1191
+ const olderThan = parseDuration(options.olderThan ?? "7d");
1192
+ if (!options.dryRun) for (const session of carnet.sessions.resetDead(options.isAlive ?? processIsAlive)) io.stdout(`${label(session)} was marked running but its process is gone: now idle\n`);
1193
+ const stale = carnet.sessions.staleTemp(olderThan);
1194
+ if (stale.length === 0) {
1195
+ io.stdout(`no temp session idle for more than ${options.olderThan ?? "7d"}\n`);
1196
+ return;
1197
+ }
1198
+ for (const session of stale) {
1199
+ if (options.dryRun) {
1200
+ io.stdout(`would archive ${label(session)}${options.purge ? " and delete its transcript" : ""}\n`);
1201
+ continue;
1202
+ }
1203
+ carnet.sessions.drop(session.id);
1204
+ io.stdout(`archived ${label(session)}\n`);
1205
+ if (options.purge) purgeTranscripts(session, io);
1206
+ }
1207
+ }
1208
+ // src/io.ts
1209
+ function processIo(options = {}) {
1210
+ const tty = process.stdout.isTTY === true;
1211
+ const colorWanted = options.color ?? true;
1212
+ return {
1213
+ stdout: (text) => process.stdout.write(text),
1214
+ stderr: (text) => process.stderr.write(text),
1215
+ cwd: process.cwd(),
1216
+ env: process.env,
1217
+ color: tty && colorWanted && !process.env.NO_COLOR,
1218
+ columns: process.stdout.columns ?? 80
1219
+ };
1220
+ }
1221
+ function readStdin() {
1222
+ return new Promise((resolve) => {
1223
+ let data = "";
1224
+ process.stdin.setEncoding("utf8");
1225
+ process.stdin.on("data", (chunk) => {
1226
+ data += chunk;
1227
+ });
1228
+ process.stdin.on("end", () => resolve(data));
1229
+ process.stdin.on("error", () => resolve(data));
1230
+ });
1231
+ }
1232
+ // src/terminal-keys.ts
1233
+ function terminalKeys(input, output, owner = process) {
1234
+ if (!input.isTTY || !output.isTTY || !input.setRawMode) return void 0;
1235
+ emitKeypressEvents(input);
1236
+ let listener;
1237
+ let closed = false;
1238
+ const close = () => {
1239
+ if (closed) return;
1240
+ closed = true;
1241
+ if (listener) input.off("keypress", listener);
1242
+ input.setRawMode?.(false);
1243
+ input.pause();
1244
+ };
1245
+ input.setRawMode(true);
1246
+ input.resume();
1247
+ owner.once("exit", close);
1248
+ return {
1249
+ onKey: (onKey) => {
1250
+ listener = (sequence, key) => onKey(key ?? { sequence });
1251
+ input.on("keypress", listener);
1252
+ },
1253
+ close
1254
+ };
1255
+ }
1256
+ // src/main.ts
1257
+ function fail(io, error) {
1258
+ if (error instanceof CliError) io.stderr(`error: ${error.message}${error.hint ? `\n ${error.hint}` : ""}\n`);
1259
+ else if (error instanceof CarnetError) io.stderr(`error: ${error.message}\n`);
1260
+ else io.stderr(`error: ${error instanceof Error ? error.message : String(error)}\n`);
1261
+ process.exit(1);
1262
+ }
1263
+ const colorArgument = { color: {
1264
+ type: "boolean",
1265
+ default: true,
1266
+ description: "Colored output (--no-color to disable)"
1267
+ } };
1268
+ const sessionArgument = { session: {
1269
+ type: "string",
1270
+ alias: "s",
1271
+ description: "Session name, id or id prefix (default: most recently active)"
1272
+ } };
1273
+ const initCommand = defineCommand({
1274
+ meta: {
1275
+ name: "init",
1276
+ description: "Make the current directory a Rucher group (meta directory)"
1277
+ },
1278
+ args: {
1279
+ directory: {
1280
+ type: "positional",
1281
+ description: "Meta directory (default: current directory)",
1282
+ required: false
1283
+ },
1284
+ name: {
1285
+ type: "string",
1286
+ description: "Group name (default: directory name)"
1287
+ },
1288
+ repos: {
1289
+ type: "string",
1290
+ description: "Comma-separated repo paths (more later with `rucher group add`)"
1291
+ },
1292
+ ...colorArgument
1293
+ },
1294
+ run({ args }) {
1295
+ const io = processIo({ color: args.color });
1296
+ const repos = args.repos ? args.repos.split(",").map((repo) => repo.trim()).filter(Boolean) : void 0;
1297
+ process.exitCode = init({
1298
+ directory: args.directory,
1299
+ name: args.name,
1300
+ repos
1301
+ }, io);
1302
+ }
1303
+ });
1304
+ const statusCommand = defineCommand({
1305
+ meta: {
1306
+ name: "status",
1307
+ description: "Show agent statuses of a session"
1308
+ },
1309
+ args: {
1310
+ ...sessionArgument,
1311
+ all: {
1312
+ type: "boolean",
1313
+ default: false,
1314
+ description: "Every session with activity"
1315
+ },
1316
+ watch: {
1317
+ type: "boolean",
1318
+ alias: "w",
1319
+ default: false,
1320
+ description: "Refresh continuously"
1321
+ },
1322
+ interval: {
1323
+ type: "string",
1324
+ default: "1",
1325
+ description: "Refresh interval in seconds with --watch"
1326
+ },
1327
+ ...colorArgument
1328
+ },
1329
+ async run({ args }) {
1330
+ const io = processIo({ color: args.color });
1331
+ try {
1332
+ const carnet = openCarnet({
1333
+ cwd: io.cwd,
1334
+ env: io.env
1335
+ });
1336
+ const options = {
1337
+ session: args.session,
1338
+ all: args.all
1339
+ };
1340
+ if (!args.watch) {
1341
+ statusOnce(carnet, io, options);
1342
+ return;
1343
+ }
1344
+ const controller = new AbortController();
1345
+ process.on("SIGINT", () => controller.abort());
1346
+ process.on("SIGTERM", () => controller.abort());
1347
+ const intervalMilliseconds = Math.max(Number(args.interval) || 1, .2) * 1e3;
1348
+ await statusWatch(carnet, io, {
1349
+ ...options,
1350
+ intervalMilliseconds,
1351
+ signal: controller.signal,
1352
+ keys: terminalKeys(process.stdin, process.stdout)
1353
+ });
1354
+ } catch (error) {
1355
+ fail(io, error);
1356
+ }
1357
+ }
1358
+ });
1359
+ const logCommand = defineCommand({
1360
+ meta: {
1361
+ name: "log",
1362
+ description: "Show the last journal events of a session"
1363
+ },
1364
+ args: {
1365
+ ...sessionArgument,
1366
+ count: {
1367
+ type: "string",
1368
+ alias: "n",
1369
+ default: "20",
1370
+ description: "Number of events"
1371
+ },
1372
+ md: {
1373
+ type: "boolean",
1374
+ default: false,
1375
+ description: "Markdown output, for archiving"
1376
+ },
1377
+ agents: {
1378
+ type: "boolean",
1379
+ default: false,
1380
+ description: "Agent events only, without session starts and ends"
1381
+ },
1382
+ ...colorArgument
1383
+ },
1384
+ run({ args }) {
1385
+ const io = processIo({ color: args.color });
1386
+ try {
1387
+ logOnce(openCarnet({
1388
+ cwd: io.cwd,
1389
+ env: io.env
1390
+ }), io, {
1391
+ session: args.session,
1392
+ count: Number(args.count) || 20,
1393
+ md: args.md,
1394
+ agents: args.agents
1395
+ });
1396
+ } catch (error) {
1397
+ fail(io, error);
1398
+ }
1399
+ }
1400
+ });
1401
+ const sessionsListCommand = defineCommand({
1402
+ meta: {
1403
+ name: "list",
1404
+ description: "List the named sessions of the group"
1405
+ },
1406
+ args: {
1407
+ all: {
1408
+ type: "boolean",
1409
+ default: false,
1410
+ description: "Include temp and archived sessions"
1411
+ },
1412
+ ...colorArgument
1413
+ },
1414
+ run({ args }) {
1415
+ const io = processIo({ color: args.color });
1416
+ try {
1417
+ sessionsOnce(openCarnet({
1418
+ cwd: io.cwd,
1419
+ env: io.env
1420
+ }), io, { all: args.all });
1421
+ } catch (error) {
1422
+ fail(io, error);
1423
+ }
1424
+ }
1425
+ });
1426
+ const sessionsMergeCommand = defineCommand({
1427
+ meta: {
1428
+ name: "merge",
1429
+ description: "Move the agents, table line and journal of one session into another, then drop it"
1430
+ },
1431
+ args: {
1432
+ from: {
1433
+ type: "positional",
1434
+ description: "Session to empty (name, id or id prefix)",
1435
+ required: true
1436
+ },
1437
+ into: {
1438
+ type: "positional",
1439
+ description: "Session that keeps everything (name, id or id prefix)",
1440
+ required: true
1441
+ }
1442
+ },
1443
+ run({ args }) {
1444
+ const io = processIo();
1445
+ try {
1446
+ const carnet = openCarnet({
1447
+ cwd: io.cwd,
1448
+ env: io.env
1449
+ });
1450
+ sessionsMerge(carnet, args.from, args.into, io);
1451
+ carnet.close();
1452
+ } catch (error) {
1453
+ fail(io, error);
1454
+ }
1455
+ }
1456
+ });
1457
+ const sessionReference = {
1458
+ type: "positional",
1459
+ description: "Session name, id or id prefix",
1460
+ required: true
1461
+ };
1462
+ const sessionsRenameCommand = defineCommand({
1463
+ meta: {
1464
+ name: "rename",
1465
+ description: "Rename a session that is not running"
1466
+ },
1467
+ args: {
1468
+ session: sessionReference,
1469
+ name: {
1470
+ type: "positional",
1471
+ description: "New name",
1472
+ required: true
1473
+ }
1474
+ },
1475
+ run({ args }) {
1476
+ const io = processIo();
1477
+ withCarnet(io, (carnet) => sessionsRename(carnet, args.session, args.name, io));
1478
+ }
1479
+ });
1480
+ const sessionsPromoteCommand = defineCommand({
1481
+ meta: {
1482
+ name: "promote",
1483
+ description: "Make a temp session active (a name is needed)"
1484
+ },
1485
+ args: {
1486
+ session: sessionReference,
1487
+ name: {
1488
+ type: "positional",
1489
+ description: "Name, when the session has none",
1490
+ required: false
1491
+ }
1492
+ },
1493
+ run({ args }) {
1494
+ const io = processIo();
1495
+ withCarnet(io, (carnet) => sessionsPromote(carnet, args.session, args.name, io));
1496
+ }
1497
+ });
1498
+ const sessionsDemoteCommand = defineCommand({
1499
+ meta: {
1500
+ name: "demote",
1501
+ description: "Make an active session temp, keeping its name"
1502
+ },
1503
+ args: { session: sessionReference },
1504
+ run({ args }) {
1505
+ const io = processIo();
1506
+ withCarnet(io, (carnet) => sessionsDemote(carnet, args.session, io));
1507
+ }
1508
+ });
1509
+ const purgeArgument = { purge: {
1510
+ type: "boolean",
1511
+ default: false,
1512
+ description: "Also delete the host transcript"
1513
+ } };
1514
+ const sessionsDropCommand = defineCommand({
1515
+ meta: {
1516
+ name: "drop",
1517
+ description: "Archive a session and close its agents"
1518
+ },
1519
+ args: {
1520
+ session: sessionReference,
1521
+ ...purgeArgument
1522
+ },
1523
+ run({ args }) {
1524
+ const io = processIo();
1525
+ withCarnet(io, (carnet) => sessionsDrop(carnet, args.session, io, { purge: args.purge }));
1526
+ }
1527
+ });
1528
+ const sessionsCleanCommand = defineCommand({
1529
+ meta: {
1530
+ name: "clean",
1531
+ description: "Archive temp sessions idle for a while; reset running ones whose process is gone"
1532
+ },
1533
+ args: {
1534
+ "older-than": {
1535
+ type: "string",
1536
+ default: "7d",
1537
+ description: "Idle time: 30m, 12h, 7d"
1538
+ },
1539
+ ...purgeArgument,
1540
+ "dry-run": {
1541
+ type: "boolean",
1542
+ default: false,
1543
+ description: "Show what would be archived"
1544
+ }
1545
+ },
1546
+ run({ args }) {
1547
+ const io = processIo();
1548
+ withCarnet(io, (carnet) => sessionsClean(carnet, io, {
1549
+ olderThan: args["older-than"],
1550
+ purge: args.purge,
1551
+ dryRun: args["dry-run"]
1552
+ }));
1553
+ }
1554
+ });
1555
+ const sessionsCommand = defineCommand({
1556
+ meta: {
1557
+ name: "sessions",
1558
+ description: "List and manage the sessions of the group"
1559
+ },
1560
+ default: "list",
1561
+ subCommands: {
1562
+ list: sessionsListCommand,
1563
+ merge: sessionsMergeCommand,
1564
+ rename: sessionsRenameCommand,
1565
+ promote: sessionsPromoteCommand,
1566
+ demote: sessionsDemoteCommand,
1567
+ drop: sessionsDropCommand,
1568
+ clean: sessionsCleanCommand
1569
+ }
1570
+ });
1571
+ function withCarnet(io, run) {
1572
+ try {
1573
+ const carnet = openCarnet({
1574
+ cwd: io.cwd,
1575
+ env: io.env
1576
+ });
1577
+ try {
1578
+ run(carnet);
1579
+ } finally {
1580
+ carnet.close();
1581
+ }
1582
+ } catch (error) {
1583
+ fail(io, error);
1584
+ }
1585
+ }
1586
+ const noteFilterArguments = {
1587
+ kind: {
1588
+ type: "string",
1589
+ description: "learning, decision or dead_end"
1590
+ },
1591
+ repo: {
1592
+ type: "string",
1593
+ description: "Only the notes of this repo"
1594
+ }
1595
+ };
1596
+ const notesListCommand = defineCommand({
1597
+ meta: {
1598
+ name: "list",
1599
+ description: "Active notes of the group, by kind"
1600
+ },
1601
+ args: {
1602
+ all: {
1603
+ type: "boolean",
1604
+ default: false,
1605
+ description: "Include dropped notes and their reason"
1606
+ },
1607
+ ...noteFilterArguments,
1608
+ general: {
1609
+ type: "boolean",
1610
+ default: false,
1611
+ description: "Only the notes without repo"
1612
+ },
1613
+ stale: {
1614
+ type: "boolean",
1615
+ default: false,
1616
+ description: "Notes to review: old and never (or no longer) cited"
1617
+ },
1618
+ md: {
1619
+ type: "boolean",
1620
+ default: false,
1621
+ description: "Markdown output, a view only"
1622
+ },
1623
+ ...colorArgument
1624
+ },
1625
+ run({ args }) {
1626
+ const io = processIo({ color: args.color });
1627
+ withCarnet(io, (carnet) => notesList(carnet, io, {
1628
+ all: args.all,
1629
+ kind: args.kind,
1630
+ repo: args.repo,
1631
+ general: args.general,
1632
+ stale: args.stale,
1633
+ markdown: args.md
1634
+ }));
1635
+ }
1636
+ });
1637
+ const notesShowCommand = defineCommand({
1638
+ meta: {
1639
+ name: "show",
1640
+ description: "A note with its repos, weight and citations"
1641
+ },
1642
+ args: {
1643
+ id: {
1644
+ type: "positional",
1645
+ description: "Note id",
1646
+ required: true
1647
+ },
1648
+ ...colorArgument
1649
+ },
1650
+ run({ args }) {
1651
+ const io = processIo({ color: args.color });
1652
+ withCarnet(io, (carnet) => notesShow(carnet, io, parseNoteId(args.id)));
1653
+ }
1654
+ });
1655
+ const notesAddCommand = defineCommand({
1656
+ meta: {
1657
+ name: "add",
1658
+ description: "Add a note by hand"
1659
+ },
1660
+ args: {
1661
+ kind: {
1662
+ type: "positional",
1663
+ description: "learning, decision or dead_end",
1664
+ required: true
1665
+ },
1666
+ text: {
1667
+ type: "positional",
1668
+ description: "One claim with its reason",
1669
+ required: true
1670
+ },
1671
+ repo: {
1672
+ type: "string",
1673
+ description: "Repo the note applies to (repeat for several)"
1674
+ },
1675
+ ...colorArgument
1676
+ },
1677
+ run({ args, rawArgs }) {
1678
+ const io = processIo({ color: args.color });
1679
+ withCarnet(io, (carnet) => notesAdd(carnet, io, {
1680
+ kind: args.kind,
1681
+ text: args.text,
1682
+ repos: repoList(rawArgs)
1683
+ }));
1684
+ }
1685
+ });
1686
+ const notesDropCommand = defineCommand({
1687
+ meta: {
1688
+ name: "drop",
1689
+ description: "Close a note that proved wrong, keeping it in the history"
1690
+ },
1691
+ args: {
1692
+ id: {
1693
+ type: "positional",
1694
+ description: "Note id",
1695
+ required: true
1696
+ },
1697
+ reason: {
1698
+ type: "string",
1699
+ description: "Why it is no longer true",
1700
+ required: true
1701
+ },
1702
+ "replaced-by": {
1703
+ type: "string",
1704
+ description: "Id of the note that replaces it"
1705
+ }
1706
+ },
1707
+ run({ args }) {
1708
+ const io = processIo();
1709
+ const replacement = args["replaced-by"];
1710
+ withCarnet(io, (carnet) => notesDrop(carnet, io, parseNoteId(args.id), {
1711
+ reason: args.reason,
1712
+ replacedBy: replacement === void 0 ? void 0 : parseNoteId(replacement)
1713
+ }));
1714
+ }
1715
+ });
1716
+ const notesCommand = defineCommand({
1717
+ meta: {
1718
+ name: "notes",
1719
+ description: "The group's memory: learnings, decisions and dead ends"
1720
+ },
1721
+ args: noteFilterArguments,
1722
+ default: "list",
1723
+ subCommands: {
1724
+ list: notesListCommand,
1725
+ show: notesShowCommand,
1726
+ add: notesAddCommand,
1727
+ drop: notesDropCommand
1728
+ }
1729
+ });
1730
+ async function launch(io, plan) {
1731
+ try {
1732
+ const carnet = openCarnet({
1733
+ cwd: io.cwd,
1734
+ env: io.env
1735
+ });
1736
+ const launchPlan = await plan(carnet);
1737
+ startLaunch(carnet, launchPlan);
1738
+ carnet.close();
1739
+ const exitCode = spawnLaunch(launchPlan, io.env);
1740
+ const after = openCarnet({
1741
+ cwd: io.cwd,
1742
+ env: io.env
1743
+ });
1744
+ finishLaunch(after, launchPlan);
1745
+ after.close();
1746
+ process.exitCode = exitCode;
1747
+ } catch (error) {
1748
+ fail(io, error);
1749
+ }
1750
+ }
1751
+ const passthroughHelp = "Arguments after -- are passed to Claude Code";
1752
+ const newCommand = defineCommand({
1753
+ meta: {
1754
+ name: "new",
1755
+ description: `Start a named, durable session. ${passthroughHelp}`
1756
+ },
1757
+ args: { name: {
1758
+ type: "positional",
1759
+ description: "Session name",
1760
+ required: true
1761
+ } },
1762
+ async run({ rawArgs }) {
1763
+ const { own, passthrough } = splitPassthrough(rawArgs);
1764
+ await launch(processIo(), (carnet) => planNew(carnet, processIo(), {
1765
+ kind: "active",
1766
+ name: positionals(own)[0],
1767
+ passthrough
1768
+ }));
1769
+ }
1770
+ });
1771
+ const tmpCommand = defineCommand({
1772
+ meta: {
1773
+ name: "tmp",
1774
+ description: `Start a temporary session. ${passthroughHelp}`
1775
+ },
1776
+ args: { name: {
1777
+ type: "positional",
1778
+ description: "Optional session name",
1779
+ required: false
1780
+ } },
1781
+ async run({ rawArgs }) {
1782
+ const { own, passthrough } = splitPassthrough(rawArgs);
1783
+ await launch(processIo(), (carnet) => planNew(carnet, processIo(), {
1784
+ kind: "temp",
1785
+ name: positionals(own)[0],
1786
+ passthrough
1787
+ }));
1788
+ }
1789
+ });
1790
+ const resumeCommand = defineCommand({
1791
+ meta: {
1792
+ name: "resume",
1793
+ description: `Resume a session in its host, or pick one when none is given. ${passthroughHelp}`
1794
+ },
1795
+ args: { session: {
1796
+ type: "positional",
1797
+ description: "Session name, id or id prefix",
1798
+ required: false
1799
+ } },
1800
+ async run({ rawArgs }) {
1801
+ const { own, passthrough } = splitPassthrough(rawArgs);
1802
+ const io = processIo();
1803
+ await launch(io, async (carnet) => {
1804
+ const reference = positionals(own)[0] ?? (await pickSession(carnet)).id;
1805
+ return planResume(carnet, io, reference, passthrough);
1806
+ });
1807
+ }
1808
+ });
1809
+ const forkCommand = defineCommand({
1810
+ meta: {
1811
+ name: "fork",
1812
+ description: `Branch a session into a new one, temporary unless --active. ${passthroughHelp}`
1813
+ },
1814
+ args: {
1815
+ session: {
1816
+ type: "positional",
1817
+ description: "Session to branch from",
1818
+ required: true
1819
+ },
1820
+ name: {
1821
+ type: "positional",
1822
+ description: "Name of the new session",
1823
+ required: false
1824
+ },
1825
+ active: {
1826
+ type: "boolean",
1827
+ default: false,
1828
+ description: "Make the new session durable (needs a name)"
1829
+ }
1830
+ },
1831
+ async run({ rawArgs }) {
1832
+ const { own, passthrough } = splitPassthrough(rawArgs);
1833
+ const [reference, name] = positionals(own);
1834
+ const io = processIo();
1835
+ await launch(io, (carnet) => planFork(carnet, io, reference ?? "", {
1836
+ name,
1837
+ active: own.includes("--active"),
1838
+ passthrough
1839
+ }));
1840
+ }
1841
+ });
1842
+ const groupCommand = defineCommand({
1843
+ meta: {
1844
+ name: "group",
1845
+ description: "Show the current group, add or remove repos, sync its settings"
1846
+ },
1847
+ subCommands: {
1848
+ show: defineCommand({
1849
+ meta: {
1850
+ name: "show",
1851
+ description: "Name, meta directory and repos of the current group"
1852
+ },
1853
+ args: { ...colorArgument },
1854
+ run({ args }) {
1855
+ const io = processIo({ color: args.color });
1856
+ try {
1857
+ process.exitCode = groupShow(io);
1858
+ } catch (error) {
1859
+ fail(io, error);
1860
+ }
1861
+ }
1862
+ }),
1863
+ add: defineCommand({
1864
+ meta: {
1865
+ name: "add",
1866
+ description: "Add a repo path to the current group"
1867
+ },
1868
+ args: {
1869
+ path: {
1870
+ type: "positional",
1871
+ description: "Repo path",
1872
+ required: true
1873
+ },
1874
+ ...colorArgument
1875
+ },
1876
+ run({ args }) {
1877
+ const io = processIo({ color: args.color });
1878
+ try {
1879
+ process.exitCode = groupAdd(args.path, io);
1880
+ } catch (error) {
1881
+ fail(io, error);
1882
+ }
1883
+ }
1884
+ }),
1885
+ remove: defineCommand({
1886
+ meta: {
1887
+ name: "remove",
1888
+ description: "Remove a repo path from the current group"
1889
+ },
1890
+ args: {
1891
+ path: {
1892
+ type: "positional",
1893
+ description: "Repo path",
1894
+ required: true
1895
+ },
1896
+ ...colorArgument
1897
+ },
1898
+ run({ args }) {
1899
+ const io = processIo({ color: args.color });
1900
+ try {
1901
+ process.exitCode = groupRemove(args.path, io);
1902
+ } catch (error) {
1903
+ fail(io, error);
1904
+ }
1905
+ }
1906
+ }),
1907
+ sync: defineCommand({
1908
+ meta: {
1909
+ name: "sync",
1910
+ description: "Rewrite the hosts' context files (repo list, directory access) from group.json"
1911
+ },
1912
+ args: { ...colorArgument },
1913
+ run({ args }) {
1914
+ const io = processIo({ color: args.color });
1915
+ try {
1916
+ process.exitCode = groupSync(io);
1917
+ } catch (error) {
1918
+ fail(io, error);
1919
+ }
1920
+ }
1921
+ })
1922
+ }
1923
+ });
1924
+ const groupsCommand = defineCommand({
1925
+ meta: {
1926
+ name: "groups",
1927
+ description: "Registered groups of this machine"
1928
+ },
1929
+ subCommands: {
1930
+ list: defineCommand({
1931
+ meta: {
1932
+ name: "list",
1933
+ description: "Registered groups, missing ones flagged"
1934
+ },
1935
+ args: { ...colorArgument },
1936
+ run({ args }) {
1937
+ process.exitCode = groupsList(processIo({ color: args.color }));
1938
+ }
1939
+ }),
1940
+ forget: defineCommand({
1941
+ meta: {
1942
+ name: "forget",
1943
+ description: "Unregister a group by name or meta directory path"
1944
+ },
1945
+ args: {
1946
+ reference: {
1947
+ type: "positional",
1948
+ description: "Group name or path",
1949
+ required: true
1950
+ },
1951
+ ...colorArgument
1952
+ },
1953
+ run({ args }) {
1954
+ process.exitCode = groupsForget(args.reference, processIo({ color: args.color }));
1955
+ }
1956
+ }),
1957
+ prune: defineCommand({
1958
+ meta: {
1959
+ name: "prune",
1960
+ description: "Unregister groups whose meta directory is gone"
1961
+ },
1962
+ args: { ...colorArgument },
1963
+ run({ args }) {
1964
+ process.exitCode = groupsPrune(processIo({ color: args.color }));
1965
+ }
1966
+ })
1967
+ }
1968
+ });
1969
+ const hookCommand = defineCommand({
1970
+ meta: {
1971
+ name: "hook",
1972
+ description: "Agent host hook entry points (Claude Code, JSON payload on stdin)"
1973
+ },
1974
+ subCommands: {
1975
+ "session-start": defineCommand({
1976
+ meta: {
1977
+ name: "session-start",
1978
+ description: "SessionStart hook: records the session"
1979
+ },
1980
+ async run() {
1981
+ process.exitCode = sessionStart(await readStdin(), processIo());
1982
+ }
1983
+ }),
1984
+ "session-end": defineCommand({
1985
+ meta: {
1986
+ name: "session-end",
1987
+ description: "SessionEnd hook: marks the session idle"
1988
+ },
1989
+ async run() {
1990
+ process.exitCode = sessionEnd(await readStdin(), processIo());
1991
+ }
1992
+ }),
1993
+ "post-tool-use": defineCommand({
1994
+ meta: {
1995
+ name: "post-tool-use",
1996
+ description: "PostToolUse hook: adds a repo's notes the first time a tool touches it"
1997
+ },
1998
+ async run() {
1999
+ process.exitCode = postToolUse(await readStdin(), processIo());
2000
+ }
2001
+ }),
2002
+ "user-prompt-submit": defineCommand({
2003
+ meta: {
2004
+ name: "user-prompt-submit",
2005
+ description: "UserPromptSubmit hook: names the session after a /rename"
2006
+ },
2007
+ async run() {
2008
+ process.exitCode = userPromptSubmit(await readStdin(), processIo());
2009
+ }
2010
+ }),
2011
+ "subagent-start": defineCommand({
2012
+ meta: {
2013
+ name: "subagent-start",
2014
+ description: "SubagentStart hook: pairs the fork with its agent"
2015
+ },
2016
+ async run() {
2017
+ process.exitCode = subagentStart(await readStdin(), processIo());
2018
+ }
2019
+ }),
2020
+ "subagent-stop": defineCommand({
2021
+ meta: {
2022
+ name: "subagent-stop",
2023
+ description: "SubagentStop hook: flags a fork that never called agent_done"
2024
+ },
2025
+ async run() {
2026
+ process.exitCode = subagentStop(await readStdin(), processIo());
2027
+ }
2028
+ })
2029
+ }
2030
+ });
2031
+ const serveCommand = defineCommand({
2032
+ meta: {
2033
+ name: "serve",
2034
+ description: "Run the Carnet MCP server over stdio"
2035
+ },
2036
+ run() {
2037
+ serve(processIo());
2038
+ }
2039
+ });
2040
+ const main = defineCommand({
2041
+ meta: {
2042
+ name: "rucher",
2043
+ version,
2044
+ description: "Status, journal and sessions of your coding agents (Claude Code today)"
2045
+ },
2046
+ subCommands: {
2047
+ init: initCommand,
2048
+ status: statusCommand,
2049
+ log: logCommand,
2050
+ new: newCommand,
2051
+ tmp: tmpCommand,
2052
+ resume: resumeCommand,
2053
+ fork: forkCommand,
2054
+ sessions: sessionsCommand,
2055
+ notes: notesCommand,
2056
+ group: groupCommand,
2057
+ groups: groupsCommand,
2058
+ hook: hookCommand,
2059
+ serve: serveCommand
2060
+ }
2061
+ });
2062
+ // src/cli.ts
2063
+ await setupCompletion(main);
2064
+ runMain(main);
2065
+ export {};