@rucher/cli 0.1.0 → 0.2.0-beta.1

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 (3) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.mjs +1266 -149
  3. package/package.json +2 -2
package/dist/cli.mjs CHANGED
@@ -1,12 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from "citty";
3
- import { existsSync, readdirSync } from "node:fs";
3
+ import { existsSync, readdirSync, rmSync } from "node:fs";
4
4
  import { basename, dirname, join, resolve } from "node:path";
5
5
  import tab from "@bomb.sh/tab/citty";
6
- import { CarnetError, LEGEND, addGroupRepo, claudeCode, formatClock, handleSessionStart, handleUserPromptSubmit, hostById, initGroup, isGroupRoot, locateGroup, openCarnet, readRegistry, removeGroupRepo, renderSections, repoPathFor, shortId, unregisterGroups } from "@rucher/carnet";
6
+ import { CarnetError, LEGEND, NOTES_HEADER, NOTE_KINDS, SIMILAR_PREFIX, SUBAGENT_RULES, addGroupRepo, ambiguousGroupContext, appendPromptFile, claudeCode, formatClock, groupRepoNames, handleSessionEnd, handleSessionStart, handleToolUse, handleUserPromptSubmit, hostById, initGroup, isGroupRoot, loadGroup, locateGroup, memoryHalfLife, moveSession, openCarnet, openGroupCarnet, readRegistry, removeGroupRepo, renderSections, repoNameFor, repoPathFor, shortId, unregisterGroups } from "@rucher/carnet";
7
7
  import { styleText } from "node:util";
8
8
  import { spawnSync } from "node:child_process";
9
+ import { randomUUID } from "node:crypto";
10
+ import { createInterface } from "node:readline/promises";
9
11
  import { serveCarnet } from "@rucher/carnet/mcp";
12
+ import { emitKeypressEvents } from "node:readline";
10
13
  // src/completion.ts
11
14
  const hiddenCommands = /* @__PURE__ */ new Set(["hook", "serve"]);
12
15
  function quietly(suggest) {
@@ -18,7 +21,7 @@ function suggestSessions(context, complete) {
18
21
  quietly(() => {
19
22
  const carnet = openCarnet(context);
20
23
  try {
21
- const sessions = carnet.sessions.list({ includeTemporary: true });
24
+ const sessions = carnet.sessions.list({ includeTemp: true });
22
25
  const suggestions = [...sessions.flatMap((session) => session.name ? [{
23
26
  value: session.name,
24
27
  description: session.purpose ?? session.status
@@ -43,6 +46,24 @@ function suggestRepos(context, complete) {
43
46
  for (const repo of locateGroup(context).repos) complete(repo, "");
44
47
  });
45
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
+ }
46
67
  function suggestDirectories(context, complete) {
47
68
  quietly(() => {
48
69
  const partial = context.typedWords.at(-1) ?? "";
@@ -63,15 +84,50 @@ const sessions = (complete) => suggestSessions(processContext(), complete);
63
84
  const groups = (complete) => suggestGroups(processContext(), complete);
64
85
  const repos = (complete) => suggestRepos(processContext(), complete);
65
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);
66
90
  const completionConfig = { subCommands: {
67
91
  status: { options: { session: sessions } },
68
92
  log: { options: { session: sessions } },
69
93
  init: { args: { directory: directories } },
70
- resume: { args: { name: sessions } },
71
- sessions: { subCommands: { merge: { args: {
72
- from: sessions,
73
- into: sessions
74
- } } } },
94
+ resume: { args: { session: sessions } },
95
+ fork: { args: { session: sessions } },
96
+ sessions: { subCommands: {
97
+ merge: { args: {
98
+ from: sessions,
99
+ into: sessions
100
+ } },
101
+ move: {
102
+ args: { session: sessions },
103
+ options: { to: groups }
104
+ },
105
+ rename: { args: { session: sessions } },
106
+ promote: { args: { session: sessions } },
107
+ demote: { args: { session: sessions } },
108
+ drop: { args: { session: sessions } }
109
+ } },
110
+ notes: {
111
+ options: {
112
+ kind: noteKinds,
113
+ repo: repoNames
114
+ },
115
+ subCommands: {
116
+ list: { options: {
117
+ kind: noteKinds,
118
+ repo: repoNames
119
+ } },
120
+ show: { args: { id: notes } },
121
+ add: {
122
+ args: { kind: noteKinds },
123
+ options: { repo: repoNames }
124
+ },
125
+ drop: {
126
+ args: { id: notes },
127
+ options: { "replaced-by": notes }
128
+ }
129
+ }
130
+ },
75
131
  groups: { subCommands: { forget: { args: { reference: groups } } } },
76
132
  group: { subCommands: {
77
133
  add: { args: { path: directories } },
@@ -92,7 +148,7 @@ async function setupCompletion(main) {
92
148
  };
93
149
  }
94
150
  // package.json
95
- var version = "0.1.0";
151
+ var version = "0.2.0-beta.1";
96
152
  // src/color.ts
97
153
  function paint(io) {
98
154
  const style = (name) => (text) => io.color ? styleText(name, text, { validateStream: false }) : text;
@@ -248,19 +304,31 @@ function groupsPrune(io) {
248
304
  }
249
305
  // src/commands/hook.ts
250
306
  const host = claudeCode;
251
- function runHook(io, run) {
307
+ function runHook(io, run, hookEventName) {
252
308
  try {
253
309
  run();
254
310
  } catch (error) {
255
311
  if (error instanceof CarnetError && error.code === "NO_GROUP") return 0;
312
+ if (error instanceof CarnetError && error.code === "GROUP_AMBIGUOUS") {
313
+ if (hookEventName) {
314
+ io.stderr(`rucher: ${error.message}\n`);
315
+ const additionalContext = ambiguousGroupContext(error.message);
316
+ io.stdout(`${JSON.stringify({ hookSpecificOutput: {
317
+ hookEventName,
318
+ additionalContext
319
+ } })}\n`);
320
+ }
321
+ return 0;
322
+ }
256
323
  io.stderr(`rucher hook: ${error instanceof Error ? error.message : String(error)}\n`);
257
324
  }
258
325
  return 0;
259
326
  }
260
- function withCarnet(cwd, io, use) {
327
+ function withCarnet$1(payload, io, use) {
261
328
  const carnet = openCarnet({
262
- cwd: cwd ?? io.cwd,
263
- env: io.env
329
+ cwd: payload.cwd ?? io.cwd,
330
+ env: io.env,
331
+ sessionId: payload.session_id
264
332
  });
265
333
  try {
266
334
  use(carnet);
@@ -271,12 +339,20 @@ function withCarnet(cwd, io, use) {
271
339
  function sessionStart(stdinText, io) {
272
340
  return runHook(io, () => {
273
341
  const payload = host.parseSessionPayload(stdinText);
274
- withCarnet(payload.cwd, io, (carnet) => {
275
- const { additionalContext } = handleSessionStart(carnet, payload, {
342
+ withCarnet$1(payload, io, (carnet) => {
343
+ const { additionalContext, notices } = handleSessionStart(carnet, payload, {
276
344
  host: host.id,
277
345
  processId: host.processId(io.env),
278
- RUCHER_PURGE_DAYS: io.env.RUCHER_PURGE_DAYS
346
+ RUCHER_PURGE_DAYS: io.env.RUCHER_PURGE_DAYS,
347
+ RUCHER_HOME: io.env.RUCHER_HOME,
348
+ RUCHER_SESSION_ID: io.env.RUCHER_SESSION_ID,
349
+ RUCHER_SESSION_KIND: io.env.RUCHER_SESSION_KIND,
350
+ RUCHER_SESSION_NAME: io.env.RUCHER_SESSION_NAME,
351
+ RUCHER_PROMPT_VERSION: io.env.RUCHER_PROMPT_VERSION,
352
+ RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
353
+ RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
279
354
  });
355
+ for (const notice of notices) io.stderr(`${notice}\n`);
280
356
  if (additionalContext) {
281
357
  const hookSpecificOutput = {
282
358
  hookEventName: "SessionStart",
@@ -285,28 +361,62 @@ function sessionStart(stdinText, io) {
285
361
  io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
286
362
  }
287
363
  });
288
- });
364
+ }, "SessionStart");
289
365
  }
290
- function subagentHook(action, stdinText, io) {
366
+ function subagentStart(stdinText, io) {
291
367
  return runHook(io, () => {
292
368
  const payload = host.parseSubagentPayload(stdinText);
293
- withCarnet(payload.cwd, io, (carnet) => {
294
- carnet.agents[action](payload.session_id, payload.agent_id);
369
+ withCarnet$1(payload, io, (carnet) => {
370
+ carnet.agents.pairSubagent(payload.session_id, payload.agent_id);
295
371
  });
372
+ if (host.subagentInheritsContext(payload)) return;
373
+ const hookSpecificOutput = {
374
+ hookEventName: "SubagentStart",
375
+ additionalContext: SUBAGENT_RULES
376
+ };
377
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
296
378
  });
297
379
  }
298
- function subagentStart(stdinText, io) {
299
- return subagentHook("pairSubagent", stdinText, io);
300
- }
301
380
  function subagentStop(stdinText, io) {
302
- return subagentHook("stopSubagent", stdinText, io);
381
+ return runHook(io, () => {
382
+ const payload = host.parseSubagentPayload(stdinText);
383
+ withCarnet$1(payload, io, (carnet) => {
384
+ carnet.agents.stopSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload));
385
+ });
386
+ });
303
387
  }
304
388
  function userPromptSubmit(stdinText, io) {
305
389
  return runHook(io, () => {
306
390
  const payload = host.parsePromptPayload(stdinText);
307
- withCarnet(payload.cwd, io, (carnet) => {
391
+ withCarnet$1(payload, io, (carnet) => {
308
392
  handleUserPromptSubmit(carnet, host, payload);
309
393
  });
394
+ }, "UserPromptSubmit");
395
+ }
396
+ function postToolUse(stdinText, io) {
397
+ return runHook(io, () => {
398
+ const payload = host.parseToolPayload(stdinText);
399
+ if (payload.agent_id || !payload.path) return;
400
+ withCarnet$1(payload, io, (carnet) => {
401
+ const additionalContext = handleToolUse(carnet, payload, {
402
+ RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
403
+ RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
404
+ });
405
+ if (!additionalContext) return;
406
+ const hookSpecificOutput = {
407
+ hookEventName: "PostToolUse",
408
+ additionalContext
409
+ };
410
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
411
+ });
412
+ });
413
+ }
414
+ function sessionEnd(stdinText, io) {
415
+ return runHook(io, () => {
416
+ const payload = host.parseSessionEndPayload(stdinText);
417
+ withCarnet$1(payload, io, (carnet) => {
418
+ handleSessionEnd(carnet, payload);
419
+ });
310
420
  });
311
421
  }
312
422
  // src/session.ts
@@ -381,39 +491,580 @@ function sessionTitle(carnet, session) {
381
491
  }
382
492
  function logOnce(carnet, io, options) {
383
493
  const session = resolveSession(carnet, options.session);
384
- const events = carnet.events.read(session.id, options.count);
494
+ const events = carnet.events.read(session.id, options.count, options.agents);
385
495
  io.stdout(`${options.md ? formatEventsMarkdown(events, sessionTitle(carnet, session)) : formatEvents(events, io)}\n`);
386
496
  }
387
- // src/commands/resume.ts
388
- function resumeTarget(carnet, reference, io) {
497
+ // src/commands/notes.ts
498
+ const KIND_TITLES = {
499
+ dead_end: "Dead ends",
500
+ decision: "Decisions",
501
+ learning: "Learnings"
502
+ };
503
+ function repoList(rawArguments) {
504
+ const values = [];
505
+ for (let index = 0; index < rawArguments.length; index++) {
506
+ const argument = rawArguments[index] ?? "";
507
+ if (argument === "--repo") values.push(rawArguments[++index] ?? "");
508
+ else if (argument.startsWith("--repo=")) values.push(argument.slice(7));
509
+ }
510
+ return values.flatMap((value) => value.split(",")).map((repo) => repo.trim()).filter(Boolean);
511
+ }
512
+ function parseNoteId(value) {
513
+ const id = Number(value.replace(/^#/, ""));
514
+ if (!Number.isInteger(id) || id <= 0) throw new CliError(`Invalid note id "${value}"`, "use the number shown by rucher notes, e.g. 14");
515
+ return id;
516
+ }
517
+ function halfLife(io) {
518
+ return memoryHalfLife(io.env["RUCHER_MEMORY_HALF_LIFE_DAYS"]);
519
+ }
520
+ function reposLabel(note) {
521
+ return note.repos.length ? `[${note.repos.join(", ")}] ` : "";
522
+ }
523
+ function noteLine(io, note) {
524
+ const colors = paint(io);
525
+ const extras = [
526
+ note.citationCount ? `cited ${note.citationCount}` : "",
527
+ note.similarNotes.length ? colors.yellow(`similar to ${note.similarNotes.map((id) => `#${id}`).join(", ")}`) : "",
528
+ note.droppedAt ? colors.dim(`dropped: ${note.droppedReason ?? ""}`) : ""
529
+ ].filter(Boolean);
530
+ const text = `${reposLabel(note)}${note.text}`;
531
+ const line = ` ${colors.bold(`#${note.id}`.padEnd(5))} ${note.droppedAt ? colors.dim(text) : text}`;
532
+ return extras.length ? `${line} ${colors.dim("·")} ${extras.join(colors.dim(" · "))}` : line;
533
+ }
534
+ function grouped(notes) {
535
+ return NOTE_KINDS.map((kind) => [kind, notes.filter((note) => note.kind === kind)]).filter(([, kindNotes]) => kindNotes.length > 0);
536
+ }
537
+ function markdown(carnet, notes) {
538
+ const sections = grouped(notes).map(([kind, kindNotes]) => {
539
+ const lines = kindNotes.map((note) => {
540
+ const dropped = note.droppedAt ? ` (dropped: ${note.droppedReason ?? ""})` : "";
541
+ return `- #${note.id} ${reposLabel(note)}${note.text}${dropped}`;
542
+ });
543
+ return `## ${KIND_TITLES[kind]}\n\n${lines.join("\n")}`;
544
+ });
545
+ return `# Memory: ${carnet.group.name}\n\n${sections.join("\n\n") || "No notes."}\n`;
546
+ }
547
+ function notesList(carnet, io, options = {}) {
548
+ const notes = options.stale ? carnet.notes.stale(halfLife(io)) : carnet.notes.list({
549
+ kind: options.kind,
550
+ repo: options.repo,
551
+ general: options.general,
552
+ includeDropped: options.all,
553
+ halfLifeDays: halfLife(io)
554
+ });
555
+ if (options.markdown) {
556
+ io.stdout(markdown(carnet, notes));
557
+ return;
558
+ }
559
+ const colors = paint(io);
560
+ if (notes.length === 0) {
561
+ io.stdout(`${colors.dim(options.stale ? "no note to review" : "no notes")}\n`);
562
+ return;
563
+ }
564
+ const blocks = grouped(notes).map(([kind, kindNotes]) => `${colors.bold(KIND_TITLES[kind])}\n${kindNotes.map((note) => noteLine(io, note)).join("\n")}`);
565
+ io.stdout(`${blocks.join("\n\n")}\n`);
566
+ }
567
+ function sessionLabel$1(carnet, id) {
568
+ if (!id) return "-";
569
+ return carnet.sessions.get(id)?.name ?? shortId(id);
570
+ }
571
+ function when(at) {
572
+ const date = new Date(at);
573
+ return `${at.slice(0, 10)} ${formatClock(date)}`;
574
+ }
575
+ function notesShow(carnet, io, id) {
576
+ const colors = paint(io);
577
+ const note = carnet.notes.show(id, halfLife(io));
578
+ const lines = [
579
+ `${colors.bold(`#${note.id}`)} ${note.kind}${note.droppedAt ? colors.dim(" (dropped)") : ""}`,
580
+ note.text,
581
+ `repos: ${note.repos.length ? note.repos.join(", ") : "general"}`,
582
+ `added: ${when(note.createdAt)} in ${sessionLabel$1(carnet, note.session)}${note.agent ? `, from ${note.agent}` : ""}`,
583
+ `weight: ${note.weight.toFixed(2)} · ${note.citationCount} citation${note.citationCount === 1 ? "" : "s"}`
584
+ ];
585
+ if (note.similarNotes.length) lines.push(colors.yellow(`similar to: ${note.similarNotes.map((other) => `#${other}`).join(", ")}`));
586
+ if (note.droppedAt) {
587
+ const replaced = note.replacedBy ? `, replaced by #${note.replacedBy}` : "";
588
+ lines.push(`dropped: ${when(note.droppedAt)}: ${note.droppedReason ?? ""}${replaced}`);
589
+ }
590
+ if (note.citations.length) {
591
+ lines.push("citations:");
592
+ for (const citation of note.citations) {
593
+ const by = citation.agent ? ` ${citation.agent}` : "";
594
+ lines.push(` ${when(citation.at)} ${sessionLabel$1(carnet, citation.session)}${by} ${citation.why}`);
595
+ }
596
+ }
597
+ io.stdout(`${lines.join("\n")}\n`);
598
+ }
599
+ function notesAdd(carnet, io, input) {
600
+ const { note, similar } = carnet.notes.add({
601
+ kind: input.kind,
602
+ text: input.text,
603
+ repos: input.repos
604
+ });
605
+ io.stdout(`added #${note.id} ${note.kind} ${reposLabel(note)}${note.text}\n`);
606
+ if (similar.length) {
607
+ const colors = paint(io);
608
+ io.stdout(`${colors.yellow("similar active notes, possible duplicate:")}\n${similar.map((other) => ` #${other.id} ${reposLabel(other)}${other.text}`).join("\n")}\n`);
609
+ }
610
+ }
611
+ function notesDrop(carnet, io, id, input) {
612
+ const note = carnet.notes.drop(id, input);
613
+ const replaced = note.replacedBy ? `, replaced by #${note.replacedBy}` : "";
614
+ io.stdout(`dropped #${note.id}${replaced}\n`);
615
+ }
616
+ // src/commands/launch.ts
617
+ function splitPassthrough(rawArgs) {
618
+ const separator = rawArgs.indexOf("--");
619
+ if (separator === -1) return {
620
+ own: [...rawArgs],
621
+ passthrough: []
622
+ };
623
+ return {
624
+ own: rawArgs.slice(0, separator),
625
+ passthrough: rawArgs.slice(separator + 1)
626
+ };
627
+ }
628
+ function positionals(own) {
629
+ return own.filter((argument) => !argument.startsWith("-"));
630
+ }
631
+ function launchEnv(carnet, session, promptVersion, kind) {
632
+ return {
633
+ RUCHER_SESSION_ID: session.id,
634
+ RUCHER_PROMPT_VERSION: promptVersion,
635
+ RUCHER_SESSION_NAME: session.name ?? "",
636
+ RUCHER_GROUP: carnet.group.name,
637
+ RUCHER_GROUP_ROOT: carnet.group.root,
638
+ ...kind ? { RUCHER_SESSION_KIND: kind } : {}
639
+ };
640
+ }
641
+ function planNew(carnet, io, options) {
642
+ if (options.kind === "active" && !options.name) throw new CliError("An active session needs a name", "rucher new <name>");
643
+ const session = carnet.sessions.create({
644
+ id: randomUUID(),
645
+ kind: options.kind,
646
+ name: options.name,
647
+ cwd: carnet.group.root,
648
+ repo: repoNameFor(carnet.group, io.cwd)
649
+ });
650
+ const host = hostById(session.host);
651
+ const prompt = appendPromptFile(carnet.group, session, io.env);
652
+ return {
653
+ ...host.launchCommand(session.id, {
654
+ name: session.name,
655
+ appendPromptFile: prompt.path,
656
+ passthrough: options.passthrough
657
+ }),
658
+ cwd: carnet.group.root,
659
+ env: launchEnv(carnet, session, prompt.version),
660
+ sessionId: session.id
661
+ };
662
+ }
663
+ function sessionDirectory(session, io) {
664
+ return session.cwd && existsSync(session.cwd) ? session.cwd : io.cwd;
665
+ }
666
+ function planResume(carnet, io, reference, passthrough = []) {
389
667
  const session = findSession(carnet, reference);
390
- if (session.status === "dropped") io.stderr(`warning: session ${reference} was dropped\n`);
391
- const cwd = session.cwd && existsSync(session.cwd) ? session.cwd : io.cwd;
668
+ if (session.status === "archived") io.stderr(`warning: session ${reference} is archived\n`);
669
+ const prompt = appendPromptFile(carnet.group, session, io.env);
392
670
  return {
393
- ...hostById(session.host).resumeCommand(session),
394
- cwd
671
+ ...hostById(session.host).resumeCommand(session, {
672
+ appendPromptFile: prompt.path,
673
+ passthrough
674
+ }),
675
+ cwd: sessionDirectory(session, io),
676
+ env: launchEnv(carnet, session, prompt.version),
677
+ sessionId: session.id
395
678
  };
396
679
  }
397
- function runTarget({ command, args, cwd }) {
398
- const result = spawnSync(command, args, {
399
- cwd,
400
- stdio: "inherit"
680
+ function planFork(carnet, io, reference, options = {}) {
681
+ if (options.active && !options.name) throw new CliError("An active fork needs a name", "rucher fork <session> <name> --active");
682
+ if (options.name && carnet.sessions.byName(options.name)) throw new CliError(`A session named "${options.name}" already exists`);
683
+ const parent = findSession(carnet, reference);
684
+ const kind = options.active ? "active" : "temp";
685
+ return {
686
+ ...hostById(parent.host).forkCommand(parent, {
687
+ name: options.name,
688
+ appendPromptFile: appendPromptFile(carnet.group, parent, io.env).path,
689
+ passthrough: options.passthrough
690
+ }),
691
+ cwd: sessionDirectory(parent, io),
692
+ env: {
693
+ ...launchEnv(carnet, parent, parent.promptVersion ?? "", kind),
694
+ RUCHER_SESSION_NAME: options.name ?? ""
695
+ },
696
+ parentId: parent.id,
697
+ knownChildren: childrenOf(carnet, parent.id).map((session) => session.id)
698
+ };
699
+ }
700
+ function childrenOf(carnet, parentId) {
701
+ return carnet.sessions.list({
702
+ includeTemp: true,
703
+ includeArchived: true
704
+ }).filter((session) => session.parentId === parentId);
705
+ }
706
+ function forkChild(carnet, plan) {
707
+ if (!plan.parentId) return void 0;
708
+ const known = new Set(plan.knownChildren);
709
+ return childrenOf(carnet, plan.parentId).find((session) => !known.has(session.id));
710
+ }
711
+ function finishLaunch(carnet, plan) {
712
+ const id = plan.sessionId ?? forkChild(carnet, plan)?.id;
713
+ if (id && carnet.sessions.get(id)) carnet.sessions.end(id);
714
+ }
715
+ function startLaunch(carnet, plan) {
716
+ if (plan.sessionId) carnet.sessions.setStatus(plan.sessionId, "running");
717
+ }
718
+ function spawnLaunch(plan, env) {
719
+ const result = spawnSync(plan.command, plan.args, {
720
+ cwd: plan.cwd,
721
+ stdio: "inherit",
722
+ env: {
723
+ ...env,
724
+ ...plan.env
725
+ }
401
726
  });
402
727
  if (result.error) throw result.error;
403
728
  return result.status ?? 1;
404
729
  }
730
+ // src/commands/picker.ts
731
+ function pickerSessions(carnet) {
732
+ const sessions = carnet.sessions.list({ includeTemp: true });
733
+ return [...sessions.filter((session) => session.name), ...sessions.filter((session) => !session.name)];
734
+ }
735
+ function lastUse(at, now) {
736
+ const date = new Date(at);
737
+ return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
738
+ }
739
+ function pickerLines(sessions, now = /* @__PURE__ */ new Date()) {
740
+ const rows = sessions.map((session, index) => [
741
+ String(index + 1),
742
+ session.name ?? shortId(session.id),
743
+ session.kind,
744
+ session.status,
745
+ lastUse(session.lastActiveAt, now),
746
+ shortId(session.id)
747
+ ]);
748
+ const widths = (rows[0] ?? []).map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
749
+ return rows.map((row) => row.map((cell, column) => column < row.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell).join(" "));
750
+ }
751
+ function hasFzf() {
752
+ return spawnSync("fzf", ["--version"], { stdio: "ignore" }).status === 0;
753
+ }
754
+ function pickWithFzf(sessions, lines) {
755
+ const result = spawnSync("fzf", [
756
+ "--with-nth=2..",
757
+ "--no-sort",
758
+ "--prompt=session> "
759
+ ], {
760
+ input: lines.join("\n"),
761
+ stdio: [
762
+ "pipe",
763
+ "pipe",
764
+ "inherit"
765
+ ],
766
+ encoding: "utf8"
767
+ });
768
+ return sessions[Number(result.stdout?.trim().split(/\s+/)[0]) - 1];
769
+ }
770
+ async function pickFromList(sessions, lines) {
771
+ process.stderr.write(`${lines.join("\n")}\n`);
772
+ const prompt = createInterface({
773
+ input: process.stdin,
774
+ output: process.stderr
775
+ });
776
+ try {
777
+ const answer = await prompt.question("session number> ");
778
+ return sessions[Number(answer.trim()) - 1];
779
+ } finally {
780
+ prompt.close();
781
+ }
782
+ }
783
+ async function pickSession(carnet) {
784
+ const sessions = pickerSessions(carnet);
785
+ if (sessions.length === 0) throw new CliError("No session to resume in this group", "rucher new <name>");
786
+ if (!process.stdin.isTTY) throw new CliError("No session given", "rucher resume <name, id or id prefix>");
787
+ const lines = pickerLines(sessions);
788
+ const picked = hasFzf() ? pickWithFzf(sessions, lines) : await pickFromList(sessions, lines);
789
+ if (!picked) throw new CliError("No session picked");
790
+ return picked;
791
+ }
405
792
  // src/commands/serve.ts
406
793
  function serve(io) {
407
794
  serveCarnet({
408
795
  cwd: io.cwd,
409
- env: io.env
796
+ env: io.env,
797
+ sessionId: claudeCode.sessionIdFromEnvironment(io.env)
410
798
  });
411
799
  }
800
+ // src/commands/sessions.ts
801
+ function lastActive(at, now) {
802
+ const date = new Date(at);
803
+ return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
804
+ }
805
+ function row(carnet, session, now) {
806
+ const open = carnet.agents.list(session.id).length;
807
+ return [
808
+ session.name ?? session.id.slice(0, 8),
809
+ session.kind,
810
+ session.status,
811
+ repoPathFor(carnet.group, session.cwd) ?? session.repo ?? "",
812
+ lastActive(session.lastActiveAt, now),
813
+ open ? `${open} agent${open > 1 ? "s" : ""}` : "",
814
+ session.purpose ?? ""
815
+ ];
816
+ }
817
+ function sessionsOnce(carnet, io, options = {}) {
818
+ const colors = paint(io);
819
+ const sessions = carnet.sessions.list({
820
+ includeTemp: options.all,
821
+ includeArchived: options.all
822
+ });
823
+ if (sessions.length === 0) {
824
+ const hint = options.all ? "" : " (temp and archived ones are hidden, use --all)";
825
+ io.stdout(`${colors.dim(`no active session yet${hint}`)}\n`);
826
+ return;
827
+ }
828
+ const now = options.now ?? /* @__PURE__ */ new Date();
829
+ const rows = sessions.map((session) => ({
830
+ session,
831
+ cells: row(carnet, session, now)
832
+ }));
833
+ const widths = rows.reduce((current, { cells }) => cells.map((cell, column) => Math.max(current[column] ?? 0, cell.length)), []);
834
+ const lines = rows.map(({ session, cells }) => {
835
+ return cells.map((cell, column) => {
836
+ const padded = column < cells.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell;
837
+ if (column === 0) return colors.bold(padded);
838
+ if (column === 1 && session.kind === "temp") return colors.dim(padded);
839
+ if (column === 2 && session.status === "archived") return colors.dim(padded);
840
+ return padded;
841
+ }).join(" ").trimEnd();
842
+ });
843
+ io.stdout(`${lines.join("\n")}\n`);
844
+ }
845
+ function sessionsMerge(carnet, fromReference, intoReference, io) {
846
+ const from = findSession(carnet, fromReference);
847
+ const into = findSession(carnet, intoReference);
848
+ const result = carnet.sessions.merge(from.id, into.id);
849
+ const label = (session) => session.name ?? session.id.slice(0, 8);
850
+ const lines = [
851
+ `merged ${label(from)} into ${label(result.session)}`,
852
+ ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
853
+ ...result.closedAgents.length ? [` agents closed (name already used): ${result.closedAgents.join(", ")}`] : [],
854
+ ` events moved: ${result.movedEvents}`,
855
+ ` table line moved: ${result.movedTable ? "yes" : "no"}`
856
+ ];
857
+ io.stdout(`${lines.join("\n")}\n`);
858
+ }
859
+ function label(session) {
860
+ return session.name ?? shortId(session.id);
861
+ }
862
+ function groupNamed(reference, io) {
863
+ const groups = readRegistry(io.env).filter((group) => isGroupRoot(group.path));
864
+ const byPath = groups.filter((group) => group.path === resolve(io.cwd, reference));
865
+ const matches = byPath.length ? byPath : groups.filter((group) => group.name === reference);
866
+ const [match] = matches;
867
+ if (!match) throw new CliError(`No registered group named "${reference}"`, "see rucher groups");
868
+ if (matches.length > 1) throw new CliError(`Several groups are named "${reference}"`, "pass the group path");
869
+ return loadGroup(match.path);
870
+ }
871
+ function sessionsMove(carnet, reference, groupReference, io, options = {}) {
872
+ const session = findSession(carnet, reference);
873
+ const target = openGroupCarnet(groupNamed(groupReference, io));
874
+ try {
875
+ const result = moveSession(carnet, session.id, target, options);
876
+ const into = result.into ? ` into ${label(result.into)}` : "";
877
+ const lines = [
878
+ `${options.dryRun ? "would move" : "moved"} ${label(session)} from ${carnet.group.name} to ${target.group.name}${into}`,
879
+ ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
880
+ ...result.skippedAgents.length ? [` agents left out (name already used): ${result.skippedAgents.join(", ")}`] : [],
881
+ ` events moved: ${result.movedEvents}`,
882
+ ` table line moved: ${result.movedTable ? "yes" : "no"}`,
883
+ ...result.unlinkedNotes ? [` notes kept in ${carnet.group.name}, unlinked from the session: ${result.unlinkedNotes}`] : []
884
+ ];
885
+ io.stdout(`${lines.join("\n")}\n`);
886
+ } finally {
887
+ target.close();
888
+ }
889
+ }
890
+ function sessionsRename(carnet, reference, name, io) {
891
+ const session = carnet.sessions.rename(findSession(carnet, reference).id, name);
892
+ io.stdout(`renamed to ${session.name}; rucher resume ${session.name} gives Claude the same title\n`);
893
+ }
894
+ function sessionsPromote(carnet, reference, name, io) {
895
+ const session = carnet.sessions.promote(findSession(carnet, reference).id, name);
896
+ io.stdout(`${label(session)} is now active\n`);
897
+ }
898
+ function sessionsDemote(carnet, reference, io) {
899
+ const session = carnet.sessions.demote(findSession(carnet, reference).id);
900
+ io.stdout(`${label(session)} is now temp, cleaned by rucher sessions clean once idle\n`);
901
+ }
902
+ function purgeTranscripts(session, io) {
903
+ const files = hostById(session.host).transcriptFiles(session, io.env);
904
+ for (const file of files) {
905
+ rmSync(file, {
906
+ recursive: true,
907
+ force: true
908
+ });
909
+ io.stdout(` deleted ${file}\n`);
910
+ }
911
+ if (files.length === 0) io.stdout(" no transcript found\n");
912
+ }
913
+ function sessionsDrop(carnet, reference, io, options = {}) {
914
+ const session = findSession(carnet, reference);
915
+ if (options.purge && session.status === "running") throw new CliError(`Session ${label(session)} is running`, "drop it with --purge once it has ended");
916
+ carnet.sessions.drop(session.id);
917
+ io.stdout(`archived ${label(session)}\n`);
918
+ if (options.purge) purgeTranscripts(session, io);
919
+ }
920
+ const UNIT_MILLISECONDS = {
921
+ m: 6e4,
922
+ h: 36e5,
923
+ d: 864e5
924
+ };
925
+ function parseDuration(value) {
926
+ const match = /^(\d+(?:\.\d+)?)([mhd]?)$/.exec(value.trim());
927
+ if (!match) throw new CliError(`Invalid duration "${value}"`, "use a number of days, or 30m, 12h, 7d");
928
+ return Number(match[1]) * (UNIT_MILLISECONDS[match[2] || "d"] ?? 0);
929
+ }
930
+ function processIsAlive(processId) {
931
+ try {
932
+ process.kill(processId, 0);
933
+ return true;
934
+ } catch (error) {
935
+ return error.code === "EPERM";
936
+ }
937
+ }
938
+ function sessionsClean(carnet, io, options = {}) {
939
+ const olderThan = parseDuration(options.olderThan ?? "7d");
940
+ 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`);
941
+ const stale = carnet.sessions.staleTemp(olderThan);
942
+ if (stale.length === 0) {
943
+ io.stdout(`no temp session idle for more than ${options.olderThan ?? "7d"}\n`);
944
+ return;
945
+ }
946
+ for (const session of stale) {
947
+ if (options.dryRun) {
948
+ io.stdout(`would archive ${label(session)}${options.purge ? " and delete its transcript" : ""}\n`);
949
+ continue;
950
+ }
951
+ carnet.sessions.drop(session.id);
952
+ io.stdout(`archived ${label(session)}\n`);
953
+ if (options.purge) purgeTranscripts(session, io);
954
+ }
955
+ }
956
+ // src/commands/watch-keys.ts
957
+ const INITIAL_WATCH_STATE = {
958
+ notesOpen: false,
959
+ selected: 0,
960
+ detail: false,
961
+ reason: null,
962
+ message: null
963
+ };
964
+ function clamp(index, count) {
965
+ return Math.min(Math.max(index, 0), Math.max(count - 1, 0));
966
+ }
967
+ function typeReason(state, key) {
968
+ const reason = state.reason ?? "";
969
+ if (key.name === "escape") return { state: {
970
+ ...state,
971
+ reason: null,
972
+ message: null
973
+ } };
974
+ if (key.name === "return" || key.name === "enter") {
975
+ const trimmed = reason.trim();
976
+ if (!trimmed) return { state: {
977
+ ...state,
978
+ message: "a reason is required"
979
+ } };
980
+ return {
981
+ state: {
982
+ ...state,
983
+ reason: null,
984
+ detail: false,
985
+ message: null
986
+ },
987
+ action: {
988
+ type: "drop",
989
+ index: state.selected,
990
+ reason: trimmed
991
+ }
992
+ };
993
+ }
994
+ if (key.name === "backspace") return { state: {
995
+ ...state,
996
+ reason: reason.slice(0, -1)
997
+ } };
998
+ const character = key.sequence ?? "";
999
+ if (character.length === 1 && character >= " " && !key.ctrl) return { state: {
1000
+ ...state,
1001
+ reason: reason + character,
1002
+ message: null
1003
+ } };
1004
+ return { state };
1005
+ }
1006
+ function pressKey(state, key, noteCount) {
1007
+ if (key.ctrl && key.name === "c") return {
1008
+ state,
1009
+ action: { type: "quit" }
1010
+ };
1011
+ if (state.reason !== null) return typeReason(state, key);
1012
+ const next = {
1013
+ ...state,
1014
+ message: null
1015
+ };
1016
+ switch (key.name) {
1017
+ case "q": return {
1018
+ state: next,
1019
+ action: { type: "quit" }
1020
+ };
1021
+ case "n": return { state: {
1022
+ ...next,
1023
+ notesOpen: !state.notesOpen && noteCount > 0,
1024
+ detail: false
1025
+ } };
1026
+ case "escape": return { state: {
1027
+ ...next,
1028
+ detail: false
1029
+ } };
1030
+ }
1031
+ if (!state.notesOpen || noteCount === 0) return { state: next };
1032
+ const selected = clamp(state.selected, noteCount);
1033
+ switch (key.name) {
1034
+ case "up": return { state: {
1035
+ ...next,
1036
+ selected: clamp(selected - 1, noteCount),
1037
+ detail: false
1038
+ } };
1039
+ case "down": return { state: {
1040
+ ...next,
1041
+ selected: clamp(selected + 1, noteCount),
1042
+ detail: false
1043
+ } };
1044
+ case "return":
1045
+ case "enter": return { state: {
1046
+ ...next,
1047
+ selected,
1048
+ detail: !state.detail
1049
+ } };
1050
+ case "d": return { state: {
1051
+ ...next,
1052
+ selected,
1053
+ detail: false,
1054
+ reason: ""
1055
+ } };
1056
+ }
1057
+ return { state: {
1058
+ ...next,
1059
+ selected
1060
+ } };
1061
+ }
412
1062
  // src/commands/status.ts
413
1063
  const SECTION_HEADERS = /* @__PURE__ */ new Set([
414
1064
  "On the table",
415
1065
  "Waiting on you",
416
- "Running"
1066
+ "Running",
1067
+ NOTES_HEADER
417
1068
  ]);
418
1069
  function truncate(line, columns) {
419
1070
  const chars = Array.from(line);
@@ -426,148 +1077,180 @@ function colorizeLine(line, io) {
426
1077
  if (SECTION_HEADERS.has(line)) return colors.bold(cut);
427
1078
  if (line.startsWith(" ⚙️")) return colors.yellow(cut);
428
1079
  if (line === " nothing") return colors.dim(cut);
1080
+ if (cut.startsWith(`${NOTES_HEADER} `)) return `${colors.bold(NOTES_HEADER)}${cut.slice(NOTES_HEADER.length)}`;
1081
+ const marker = /^ {2}\+ #\d+ +\S+ {2}(similar to [^·]*·)/.exec(cut);
1082
+ if (marker?.[1]) {
1083
+ const start = cut.indexOf(SIMILAR_PREFIX);
1084
+ const end = start + marker[1].length;
1085
+ return `${cut.slice(0, start)}${colors.yellow(cut.slice(start, end))}${cut.slice(end)}`;
1086
+ }
429
1087
  return cut;
430
1088
  }
431
- function sessionWhere(carnet, session) {
432
- return repoPathFor(carnet.group, session.cwd) ?? session.repo;
1089
+ function sessionName(session) {
1090
+ return session.name ?? session.id.slice(0, 8);
433
1091
  }
434
1092
  function sessionLabel(carnet, session, columns) {
435
- const name = session.name ?? session.id.slice(0, 8);
436
- const where = sessionWhere(carnet, session);
437
- if (!where) return name;
1093
+ const name = sessionName(session);
438
1094
  const room = columns - Array.from(name).length - 3;
439
- return room > 1 ? `${name} · ${truncate(where, room)}` : name;
1095
+ return room > 1 ? `${name} · ${truncate(carnet.group.name, room)}` : name;
1096
+ }
1097
+ function sessionHeader(session, io) {
1098
+ return paint(io).cyan(truncate(sessionName(session), io.columns));
1099
+ }
1100
+ function sessionLines(session, view, io, notes = "full") {
1101
+ if (session.status === "archived") return [paint(io).dim(" archived, see rucher sessions --all")];
1102
+ return renderSections(view, { notes }).split("\n").map((line) => colorizeLine(line, io));
440
1103
  }
441
- function sessionHeader(carnet, session, io) {
442
- return paint(io).cyan(sessionLabel(carnet, session, io.columns));
1104
+ const KEYS_HINT = "n fold · ↑↓ select · enter detail · d drop · q quit";
1105
+ function noteDetailLines(carnet, id) {
1106
+ const note = carnet.notes.show(id);
1107
+ const lines = [` ${note.text}`];
1108
+ if (note.repos.length > 0) lines.push(` repos: ${note.repos.join(", ")}`);
1109
+ const status = note.droppedAt ? `dropped: ${note.droppedReason ?? ""}` : "active";
1110
+ lines.push(` ${status} · weight ${note.weight.toFixed(2)} · ${note.citationCount} cited`);
1111
+ for (const citation of note.citations) lines.push(` ★ ${citation.at.slice(0, 10)} ${citation.why}`);
1112
+ return lines;
443
1113
  }
444
- function sessionLines(carnet, session, view, io) {
445
- if (session.status === "dropped") return [paint(io).dim(" dropped, see rucher sessions --all")];
446
- return renderSections(view).split("\n").map((line) => colorizeLine(line, io));
1114
+ function interactiveLines(carnet, session, view, io, state) {
1115
+ if (!state.notesOpen || session.status === "archived") return sessionLines(session, view, io);
1116
+ const colors = paint(io);
1117
+ const raw = renderSections(view, { notes: "expanded" }).split("\n");
1118
+ const header = raw.indexOf(NOTES_HEADER);
1119
+ const selected = Math.min(state.selected, view.notes.length - 1);
1120
+ return raw.flatMap((line, index) => {
1121
+ const position = index - header - 1;
1122
+ if (header === -1 || position !== selected) return [colorizeLine(line, io)];
1123
+ const marked = colors.cyan(truncate(`›${line.slice(1)}`, io.columns));
1124
+ const note = view.notes[selected];
1125
+ if (!state.detail || !note) return [marked];
1126
+ return [marked, ...noteDetailLines(carnet, note.note).map((detail) => truncate(detail, io.columns))];
1127
+ });
1128
+ }
1129
+ function footerLine(view, io, state) {
1130
+ if (!state) return null;
1131
+ const colors = paint(io);
1132
+ if (state.reason !== null) {
1133
+ const note = view.notes[Math.min(state.selected, view.notes.length - 1)];
1134
+ return colors.yellow(`drop #${note?.note ?? "?"}, reason: ${state.reason}`);
1135
+ }
1136
+ if (state.message) return colors.red(state.message);
1137
+ return state.notesOpen ? colors.dim(KEYS_HINT) : null;
447
1138
  }
448
1139
  function hasSomethingToShow(carnet, session) {
449
- return carnet.agents.list(session.id).length > 0 || carnet.table.get(session.id) !== void 0;
1140
+ return carnet.agents.list(session.id).length > 0 || carnet.table.get(session.id) !== void 0 || carnet.notes.activity(session.id).length > 0;
450
1141
  }
451
- function sessionBlock(carnet, session, view, io) {
452
- return [sessionHeader(carnet, session, io), ...sessionLines(carnet, session, view, io)].join("\n");
1142
+ function sessionBlock(session, view, io) {
1143
+ return [sessionHeader(session, io), ...sessionLines(session, view, io, "summary")].join("\n");
453
1144
  }
454
- function singleView(carnet, session, io) {
1145
+ function singleView(carnet, session, io, state) {
455
1146
  const colors = paint(io);
456
1147
  const view = carnet.status.view(session);
457
1148
  const separator = " - ";
458
1149
  const label = sessionLabel(carnet, session, io.columns - view.time.length - 3);
1150
+ const title = `${colors.dim(view.time)}${separator}${colors.cyan(label)}`;
1151
+ const body = state ? interactiveLines(carnet, session, view, io, state) : sessionLines(session, view, io);
1152
+ const footer = footerLine(view, io, state);
459
1153
  return [
460
- `${colors.dim(view.time)}${separator}${colors.cyan(label)}`,
1154
+ title,
461
1155
  "",
462
- ...sessionLines(carnet, session, view, io),
1156
+ ...body,
463
1157
  "",
1158
+ ...footer ? [footer] : [],
464
1159
  colors.dim(LEGEND)
465
1160
  ].join("\n");
466
1161
  }
467
1162
  function renderStatusView(carnet, io, options) {
468
- const sessions = options.all ? carnet.sessions.list({ includeTemporary: true }).filter((session) => hasSomethingToShow(carnet, session)) : [];
469
- if (sessions.length === 0) return singleView(carnet, resolveSession(carnet, options.session), io);
1163
+ const sessions = options.all ? carnet.sessions.list({ includeTemp: true }).filter((session) => hasSomethingToShow(carnet, session)) : [];
1164
+ if (sessions.length === 0) return singleView(carnet, resolveSession(carnet, options.session), io, options.interaction);
470
1165
  let time = "";
471
1166
  const blocks = sessions.map((session) => {
472
1167
  const view = carnet.status.view(session);
473
1168
  time ||= view.time;
474
- return sessionBlock(carnet, session, view, io);
1169
+ return sessionBlock(session, view, io);
475
1170
  });
1171
+ const colors = paint(io);
1172
+ const separator = " - ";
1173
+ const group = truncate(carnet.group.name, io.columns - time.length - 3);
476
1174
  return [
477
- paint(io).dim(time),
1175
+ `${colors.dim(time)}${separator}${colors.cyan(group)}`,
478
1176
  "",
479
1177
  blocks.join("\n\n"),
480
1178
  "",
481
- paint(io).dim(LEGEND)
1179
+ colors.dim(LEGEND)
482
1180
  ].join("\n");
483
1181
  }
484
1182
  function statusOnce(carnet, io, options) {
485
1183
  io.stdout(`${renderStatusView(carnet, io, options)}\n`);
486
1184
  }
1185
+ function dropSelected(carnet, options, index, reason) {
1186
+ const session = resolveSession(carnet, options.session);
1187
+ const item = carnet.notes.activity(session.id)[index];
1188
+ if (!item) return "no note selected";
1189
+ try {
1190
+ carnet.notes.drop(item.note, {
1191
+ reason,
1192
+ session: session.id
1193
+ });
1194
+ return null;
1195
+ } catch (error) {
1196
+ return error instanceof Error ? error.message : String(error);
1197
+ }
1198
+ }
1199
+ function noteCount(carnet, options) {
1200
+ try {
1201
+ return carnet.notes.activity(resolveSession(carnet, options.session).id).length;
1202
+ } catch {
1203
+ return 0;
1204
+ }
1205
+ }
487
1206
  const CLEAR = "\x1B[H\x1B[2J";
488
1207
  const HIDE_CURSOR = "\x1B[?25l";
489
1208
  const SHOW_CURSOR = "\x1B[?25h";
490
1209
  function statusWatch(carnet, io, options) {
491
1210
  return new Promise((resolve) => {
492
1211
  let last = "";
1212
+ const interactive = options.keys !== void 0 && !options.all;
1213
+ let state = INITIAL_WATCH_STATE;
493
1214
  const repaint = () => {
494
1215
  let text;
495
1216
  try {
496
- text = renderStatusView(carnet, io, options);
1217
+ text = renderStatusView(carnet, io, {
1218
+ ...options,
1219
+ interaction: interactive ? state : void 0
1220
+ });
497
1221
  } catch (error) {
498
1222
  text = paint(io).dim(error instanceof Error ? error.message : String(error));
499
1223
  }
500
1224
  if (text === last) return;
501
1225
  last = text;
502
- io.stdout(`${CLEAR}${text}\n`);
503
- };
504
- const timer = setInterval(repaint, options.intervalMilliseconds);
505
- const stop = () => {
506
- clearInterval(timer);
507
- io.stdout(SHOW_CURSOR);
508
- resolve();
509
- };
510
- options.signal?.addEventListener("abort", stop, { once: true });
511
- io.stdout(HIDE_CURSOR);
512
- repaint();
513
- });
514
- }
515
- // src/commands/sessions.ts
516
- function lastActive(at, now) {
517
- const date = new Date(at);
518
- return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
519
- }
520
- function row(carnet, session, now) {
521
- const open = carnet.agents.list(session.id).length;
522
- return [
523
- session.name ?? session.id.slice(0, 8),
524
- session.status,
525
- sessionWhere(carnet, session) ?? "",
526
- lastActive(session.lastActiveAt, now),
527
- open ? `${open} agent${open > 1 ? "s" : ""}` : "",
528
- session.purpose ?? ""
529
- ];
530
- }
531
- function sessionsOnce(carnet, io, options = {}) {
532
- const colors = paint(io);
533
- const sessions = carnet.sessions.list({
534
- includeTemporary: options.all,
535
- includeDropped: options.all
536
- });
537
- if (sessions.length === 0) {
538
- const hint = options.all ? "" : " (temporary ones are hidden, use --all)";
539
- io.stdout(`${colors.dim(`no named session yet${hint}`)}\n`);
540
- return;
541
- }
542
- const now = options.now ?? /* @__PURE__ */ new Date();
543
- const rows = sessions.map((session) => ({
544
- session,
545
- cells: row(carnet, session, now)
546
- }));
547
- const widths = rows.reduce((current, { cells }) => cells.map((cell, column) => Math.max(current[column] ?? 0, cell.length)), []);
548
- const lines = rows.map(({ session, cells }) => {
549
- return cells.map((cell, column) => {
550
- const padded = column < cells.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell;
551
- if (column === 0) return colors.bold(padded);
552
- if (column === 1 && session.status !== "active") return colors.dim(padded);
553
- return padded;
554
- }).join(" ").trimEnd();
1226
+ io.stdout(`${CLEAR}${text}\n`);
1227
+ };
1228
+ const timer = setInterval(() => {
1229
+ if (state.reason === null) repaint();
1230
+ }, options.intervalMilliseconds);
1231
+ let stopped = false;
1232
+ const stop = () => {
1233
+ if (stopped) return;
1234
+ stopped = true;
1235
+ clearInterval(timer);
1236
+ options.keys?.close();
1237
+ io.stdout(SHOW_CURSOR);
1238
+ resolve();
1239
+ };
1240
+ options.keys?.onKey((key) => {
1241
+ const result = pressKey(state, key, interactive ? noteCount(carnet, options) : 0);
1242
+ state = result.state;
1243
+ if (result.action?.type === "quit") return stop();
1244
+ if (result.action?.type === "drop") state = {
1245
+ ...state,
1246
+ message: dropSelected(carnet, options, result.action.index, result.action.reason)
1247
+ };
1248
+ repaint();
1249
+ });
1250
+ options.signal?.addEventListener("abort", stop, { once: true });
1251
+ io.stdout(HIDE_CURSOR);
1252
+ repaint();
555
1253
  });
556
- io.stdout(`${lines.join("\n")}\n`);
557
- }
558
- function sessionsMerge(carnet, fromReference, intoReference, io) {
559
- const from = findSession(carnet, fromReference);
560
- const into = findSession(carnet, intoReference);
561
- const result = carnet.sessions.merge(from.id, into.id);
562
- const label = (session) => session.name ?? session.id.slice(0, 8);
563
- const lines = [
564
- `merged ${label(from)} into ${label(result.session)}`,
565
- ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
566
- ...result.closedAgents.length ? [` agents closed (name already used): ${result.closedAgents.join(", ")}`] : [],
567
- ` events moved: ${result.movedEvents}`,
568
- ` table line moved: ${result.movedTable ? "yes" : "no"}`
569
- ];
570
- io.stdout(`${lines.join("\n")}\n`);
571
1254
  }
572
1255
  // src/io.ts
573
1256
  function processIo(options = {}) {
@@ -593,6 +1276,30 @@ function readStdin() {
593
1276
  process.stdin.on("error", () => resolve(data));
594
1277
  });
595
1278
  }
1279
+ // src/terminal-keys.ts
1280
+ function terminalKeys(input, output, owner = process) {
1281
+ if (!input.isTTY || !output.isTTY || !input.setRawMode) return void 0;
1282
+ emitKeypressEvents(input);
1283
+ let listener;
1284
+ let closed = false;
1285
+ const close = () => {
1286
+ if (closed) return;
1287
+ closed = true;
1288
+ if (listener) input.off("keypress", listener);
1289
+ input.setRawMode?.(false);
1290
+ input.pause();
1291
+ };
1292
+ input.setRawMode(true);
1293
+ input.resume();
1294
+ owner.once("exit", close);
1295
+ return {
1296
+ onKey: (onKey) => {
1297
+ listener = (sequence, key) => onKey(key ?? { sequence });
1298
+ input.on("keypress", listener);
1299
+ },
1300
+ close
1301
+ };
1302
+ }
596
1303
  // src/main.ts
597
1304
  function fail(io, error) {
598
1305
  if (error instanceof CliError) io.stderr(`error: ${error.message}${error.hint ? `\n ${error.hint}` : ""}\n`);
@@ -688,7 +1395,8 @@ const statusCommand = defineCommand({
688
1395
  await statusWatch(carnet, io, {
689
1396
  ...options,
690
1397
  intervalMilliseconds,
691
- signal: controller.signal
1398
+ signal: controller.signal,
1399
+ keys: terminalKeys(process.stdin, process.stdout)
692
1400
  });
693
1401
  } catch (error) {
694
1402
  fail(io, error);
@@ -713,6 +1421,11 @@ const logCommand = defineCommand({
713
1421
  default: false,
714
1422
  description: "Markdown output, for archiving"
715
1423
  },
1424
+ agents: {
1425
+ type: "boolean",
1426
+ default: false,
1427
+ description: "Agent events only, without session starts and ends"
1428
+ },
716
1429
  ...colorArgument
717
1430
  },
718
1431
  run({ args }) {
@@ -724,7 +1437,8 @@ const logCommand = defineCommand({
724
1437
  }), io, {
725
1438
  session: args.session,
726
1439
  count: Number(args.count) || 20,
727
- md: args.md
1440
+ md: args.md,
1441
+ agents: args.agents
728
1442
  });
729
1443
  } catch (error) {
730
1444
  fail(io, error);
@@ -740,7 +1454,7 @@ const sessionsListCommand = defineCommand({
740
1454
  all: {
741
1455
  type: "boolean",
742
1456
  default: false,
743
- description: "Include temporary and dropped sessions"
1457
+ description: "Include temp and archived sessions"
744
1458
  },
745
1459
  ...colorArgument
746
1460
  },
@@ -787,40 +1501,421 @@ const sessionsMergeCommand = defineCommand({
787
1501
  }
788
1502
  }
789
1503
  });
1504
+ const sessionReference = {
1505
+ type: "positional",
1506
+ description: "Session name, id or id prefix",
1507
+ required: true
1508
+ };
1509
+ const sessionsRenameCommand = defineCommand({
1510
+ meta: {
1511
+ name: "rename",
1512
+ description: "Rename a session that is not running"
1513
+ },
1514
+ args: {
1515
+ session: sessionReference,
1516
+ name: {
1517
+ type: "positional",
1518
+ description: "New name",
1519
+ required: true
1520
+ }
1521
+ },
1522
+ run({ args }) {
1523
+ const io = processIo();
1524
+ withCarnet(io, (carnet) => sessionsRename(carnet, args.session, args.name, io));
1525
+ }
1526
+ });
1527
+ const sessionsPromoteCommand = defineCommand({
1528
+ meta: {
1529
+ name: "promote",
1530
+ description: "Make a temp session active (a name is needed)"
1531
+ },
1532
+ args: {
1533
+ session: sessionReference,
1534
+ name: {
1535
+ type: "positional",
1536
+ description: "Name, when the session has none",
1537
+ required: false
1538
+ }
1539
+ },
1540
+ run({ args }) {
1541
+ const io = processIo();
1542
+ withCarnet(io, (carnet) => sessionsPromote(carnet, args.session, args.name, io));
1543
+ }
1544
+ });
1545
+ const sessionsDemoteCommand = defineCommand({
1546
+ meta: {
1547
+ name: "demote",
1548
+ description: "Make an active session temp, keeping its name"
1549
+ },
1550
+ args: { session: sessionReference },
1551
+ run({ args }) {
1552
+ const io = processIo();
1553
+ withCarnet(io, (carnet) => sessionsDemote(carnet, args.session, io));
1554
+ }
1555
+ });
1556
+ const purgeArgument = { purge: {
1557
+ type: "boolean",
1558
+ default: false,
1559
+ description: "Also delete the host transcript"
1560
+ } };
1561
+ const sessionsDropCommand = defineCommand({
1562
+ meta: {
1563
+ name: "drop",
1564
+ description: "Archive a session and close its agents"
1565
+ },
1566
+ args: {
1567
+ session: sessionReference,
1568
+ ...purgeArgument
1569
+ },
1570
+ run({ args }) {
1571
+ const io = processIo();
1572
+ withCarnet(io, (carnet) => sessionsDrop(carnet, args.session, io, { purge: args.purge }));
1573
+ }
1574
+ });
1575
+ const sessionsMoveCommand = defineCommand({
1576
+ meta: {
1577
+ name: "move",
1578
+ description: "Move a session, its agents, table line and journal to another group"
1579
+ },
1580
+ args: {
1581
+ session: sessionReference,
1582
+ to: {
1583
+ type: "string",
1584
+ required: true,
1585
+ description: "Target group (name or path)"
1586
+ },
1587
+ merge: {
1588
+ type: "boolean",
1589
+ default: false,
1590
+ description: "Merge into the session the target group already has under this id or name"
1591
+ },
1592
+ "dry-run": {
1593
+ type: "boolean",
1594
+ default: false,
1595
+ description: "Show what would move"
1596
+ }
1597
+ },
1598
+ run({ args }) {
1599
+ const io = processIo();
1600
+ withCarnet(io, (carnet) => sessionsMove(carnet, args.session, args.to, io, {
1601
+ merge: args.merge,
1602
+ dryRun: args["dry-run"]
1603
+ }));
1604
+ }
1605
+ });
1606
+ const sessionsCleanCommand = defineCommand({
1607
+ meta: {
1608
+ name: "clean",
1609
+ description: "Archive temp sessions idle for a while; reset running ones whose process is gone"
1610
+ },
1611
+ args: {
1612
+ "older-than": {
1613
+ type: "string",
1614
+ default: "7d",
1615
+ description: "Idle time: 30m, 12h, 7d"
1616
+ },
1617
+ ...purgeArgument,
1618
+ "dry-run": {
1619
+ type: "boolean",
1620
+ default: false,
1621
+ description: "Show what would be archived"
1622
+ }
1623
+ },
1624
+ run({ args }) {
1625
+ const io = processIo();
1626
+ withCarnet(io, (carnet) => sessionsClean(carnet, io, {
1627
+ olderThan: args["older-than"],
1628
+ purge: args.purge,
1629
+ dryRun: args["dry-run"]
1630
+ }));
1631
+ }
1632
+ });
790
1633
  const sessionsCommand = defineCommand({
791
1634
  meta: {
792
1635
  name: "sessions",
793
- description: "List or merge the sessions of the group"
1636
+ description: "List and manage the sessions of the group"
794
1637
  },
795
1638
  default: "list",
796
1639
  subCommands: {
797
1640
  list: sessionsListCommand,
798
- merge: sessionsMergeCommand
1641
+ merge: sessionsMergeCommand,
1642
+ move: sessionsMoveCommand,
1643
+ rename: sessionsRenameCommand,
1644
+ promote: sessionsPromoteCommand,
1645
+ demote: sessionsDemoteCommand,
1646
+ drop: sessionsDropCommand,
1647
+ clean: sessionsCleanCommand
1648
+ }
1649
+ });
1650
+ function withCarnet(io, run) {
1651
+ try {
1652
+ const carnet = openCarnet({
1653
+ cwd: io.cwd,
1654
+ env: io.env
1655
+ });
1656
+ try {
1657
+ run(carnet);
1658
+ } finally {
1659
+ carnet.close();
1660
+ }
1661
+ } catch (error) {
1662
+ fail(io, error);
1663
+ }
1664
+ }
1665
+ const noteFilterArguments = {
1666
+ kind: {
1667
+ type: "string",
1668
+ description: "learning, decision or dead_end"
1669
+ },
1670
+ repo: {
1671
+ type: "string",
1672
+ description: "Only the notes of this repo"
1673
+ }
1674
+ };
1675
+ const notesListCommand = defineCommand({
1676
+ meta: {
1677
+ name: "list",
1678
+ description: "Active notes of the group, by kind"
1679
+ },
1680
+ args: {
1681
+ all: {
1682
+ type: "boolean",
1683
+ default: false,
1684
+ description: "Include dropped notes and their reason"
1685
+ },
1686
+ ...noteFilterArguments,
1687
+ general: {
1688
+ type: "boolean",
1689
+ default: false,
1690
+ description: "Only the notes without repo"
1691
+ },
1692
+ stale: {
1693
+ type: "boolean",
1694
+ default: false,
1695
+ description: "Notes to review: old and never (or no longer) cited"
1696
+ },
1697
+ md: {
1698
+ type: "boolean",
1699
+ default: false,
1700
+ description: "Markdown output, a view only"
1701
+ },
1702
+ ...colorArgument
1703
+ },
1704
+ run({ args }) {
1705
+ const io = processIo({ color: args.color });
1706
+ withCarnet(io, (carnet) => notesList(carnet, io, {
1707
+ all: args.all,
1708
+ kind: args.kind,
1709
+ repo: args.repo,
1710
+ general: args.general,
1711
+ stale: args.stale,
1712
+ markdown: args.md
1713
+ }));
1714
+ }
1715
+ });
1716
+ const notesShowCommand = defineCommand({
1717
+ meta: {
1718
+ name: "show",
1719
+ description: "A note with its repos, weight and citations"
1720
+ },
1721
+ args: {
1722
+ id: {
1723
+ type: "positional",
1724
+ description: "Note id",
1725
+ required: true
1726
+ },
1727
+ ...colorArgument
1728
+ },
1729
+ run({ args }) {
1730
+ const io = processIo({ color: args.color });
1731
+ withCarnet(io, (carnet) => notesShow(carnet, io, parseNoteId(args.id)));
1732
+ }
1733
+ });
1734
+ const notesAddCommand = defineCommand({
1735
+ meta: {
1736
+ name: "add",
1737
+ description: "Add a note by hand"
1738
+ },
1739
+ args: {
1740
+ kind: {
1741
+ type: "positional",
1742
+ description: "learning, decision or dead_end",
1743
+ required: true
1744
+ },
1745
+ text: {
1746
+ type: "positional",
1747
+ description: "One claim with its reason",
1748
+ required: true
1749
+ },
1750
+ repo: {
1751
+ type: "string",
1752
+ description: "Repo the note applies to (repeat for several)"
1753
+ },
1754
+ ...colorArgument
1755
+ },
1756
+ run({ args, rawArgs }) {
1757
+ const io = processIo({ color: args.color });
1758
+ withCarnet(io, (carnet) => notesAdd(carnet, io, {
1759
+ kind: args.kind,
1760
+ text: args.text,
1761
+ repos: repoList(rawArgs)
1762
+ }));
1763
+ }
1764
+ });
1765
+ const notesDropCommand = defineCommand({
1766
+ meta: {
1767
+ name: "drop",
1768
+ description: "Close a note that proved wrong, keeping it in the history"
1769
+ },
1770
+ args: {
1771
+ id: {
1772
+ type: "positional",
1773
+ description: "Note id",
1774
+ required: true
1775
+ },
1776
+ reason: {
1777
+ type: "string",
1778
+ description: "Why it is no longer true",
1779
+ required: true
1780
+ },
1781
+ "replaced-by": {
1782
+ type: "string",
1783
+ description: "Id of the note that replaces it"
1784
+ }
1785
+ },
1786
+ run({ args }) {
1787
+ const io = processIo();
1788
+ const replacement = args["replaced-by"];
1789
+ withCarnet(io, (carnet) => notesDrop(carnet, io, parseNoteId(args.id), {
1790
+ reason: args.reason,
1791
+ replacedBy: replacement === void 0 ? void 0 : parseNoteId(replacement)
1792
+ }));
1793
+ }
1794
+ });
1795
+ const notesCommand = defineCommand({
1796
+ meta: {
1797
+ name: "notes",
1798
+ description: "The group's memory: learnings, decisions and dead ends"
1799
+ },
1800
+ args: noteFilterArguments,
1801
+ default: "list",
1802
+ subCommands: {
1803
+ list: notesListCommand,
1804
+ show: notesShowCommand,
1805
+ add: notesAddCommand,
1806
+ drop: notesDropCommand
1807
+ }
1808
+ });
1809
+ async function launch(io, plan) {
1810
+ try {
1811
+ const carnet = openCarnet({
1812
+ cwd: io.cwd,
1813
+ env: io.env
1814
+ });
1815
+ const launchPlan = await plan(carnet);
1816
+ startLaunch(carnet, launchPlan);
1817
+ carnet.close();
1818
+ const exitCode = spawnLaunch(launchPlan, io.env);
1819
+ const after = openCarnet({
1820
+ cwd: io.cwd,
1821
+ env: io.env
1822
+ });
1823
+ finishLaunch(after, launchPlan);
1824
+ after.close();
1825
+ process.exitCode = exitCode;
1826
+ } catch (error) {
1827
+ fail(io, error);
1828
+ }
1829
+ }
1830
+ const passthroughHelp = "Arguments after -- are passed to Claude Code";
1831
+ const newCommand = defineCommand({
1832
+ meta: {
1833
+ name: "new",
1834
+ description: `Start a named, durable session. ${passthroughHelp}`
1835
+ },
1836
+ args: { name: {
1837
+ type: "positional",
1838
+ description: "Session name",
1839
+ required: true
1840
+ } },
1841
+ async run({ rawArgs }) {
1842
+ const { own, passthrough } = splitPassthrough(rawArgs);
1843
+ await launch(processIo(), (carnet) => planNew(carnet, processIo(), {
1844
+ kind: "active",
1845
+ name: positionals(own)[0],
1846
+ passthrough
1847
+ }));
1848
+ }
1849
+ });
1850
+ const tmpCommand = defineCommand({
1851
+ meta: {
1852
+ name: "tmp",
1853
+ description: `Start a temporary session. ${passthroughHelp}`
1854
+ },
1855
+ args: { name: {
1856
+ type: "positional",
1857
+ description: "Optional session name",
1858
+ required: false
1859
+ } },
1860
+ async run({ rawArgs }) {
1861
+ const { own, passthrough } = splitPassthrough(rawArgs);
1862
+ await launch(processIo(), (carnet) => planNew(carnet, processIo(), {
1863
+ kind: "temp",
1864
+ name: positionals(own)[0],
1865
+ passthrough
1866
+ }));
799
1867
  }
800
1868
  });
801
1869
  const resumeCommand = defineCommand({
802
1870
  meta: {
803
1871
  name: "resume",
804
- description: "Resume a named session in its host (Claude Code today)"
1872
+ description: `Resume a session in its host, or pick one when none is given. ${passthroughHelp}`
805
1873
  },
806
- args: { name: {
1874
+ args: { session: {
807
1875
  type: "positional",
808
1876
  description: "Session name, id or id prefix",
809
- required: true
1877
+ required: false
810
1878
  } },
811
- run({ args }) {
1879
+ async run({ rawArgs }) {
1880
+ const { own, passthrough } = splitPassthrough(rawArgs);
812
1881
  const io = processIo();
813
- try {
814
- const carnet = openCarnet({
815
- cwd: io.cwd,
816
- env: io.env
817
- });
818
- const target = resumeTarget(carnet, args.name, io);
819
- carnet.close();
820
- process.exitCode = runTarget(target);
821
- } catch (error) {
822
- fail(io, error);
1882
+ await launch(io, async (carnet) => {
1883
+ const reference = positionals(own)[0] ?? (await pickSession(carnet)).id;
1884
+ return planResume(carnet, io, reference, passthrough);
1885
+ });
1886
+ }
1887
+ });
1888
+ const forkCommand = defineCommand({
1889
+ meta: {
1890
+ name: "fork",
1891
+ description: `Branch a session into a new one, temporary unless --active. ${passthroughHelp}`
1892
+ },
1893
+ args: {
1894
+ session: {
1895
+ type: "positional",
1896
+ description: "Session to branch from",
1897
+ required: true
1898
+ },
1899
+ name: {
1900
+ type: "positional",
1901
+ description: "Name of the new session",
1902
+ required: false
1903
+ },
1904
+ active: {
1905
+ type: "boolean",
1906
+ default: false,
1907
+ description: "Make the new session durable (needs a name)"
823
1908
  }
1909
+ },
1910
+ async run({ rawArgs }) {
1911
+ const { own, passthrough } = splitPassthrough(rawArgs);
1912
+ const [reference, name] = positionals(own);
1913
+ const io = processIo();
1914
+ await launch(io, (carnet) => planFork(carnet, io, reference ?? "", {
1915
+ name,
1916
+ active: own.includes("--active"),
1917
+ passthrough
1918
+ }));
824
1919
  }
825
1920
  });
826
1921
  const groupCommand = defineCommand({
@@ -965,6 +2060,24 @@ const hookCommand = defineCommand({
965
2060
  process.exitCode = sessionStart(await readStdin(), processIo());
966
2061
  }
967
2062
  }),
2063
+ "session-end": defineCommand({
2064
+ meta: {
2065
+ name: "session-end",
2066
+ description: "SessionEnd hook: marks the session idle"
2067
+ },
2068
+ async run() {
2069
+ process.exitCode = sessionEnd(await readStdin(), processIo());
2070
+ }
2071
+ }),
2072
+ "post-tool-use": defineCommand({
2073
+ meta: {
2074
+ name: "post-tool-use",
2075
+ description: "PostToolUse hook: adds a repo's notes the first time a tool touches it"
2076
+ },
2077
+ async run() {
2078
+ process.exitCode = postToolUse(await readStdin(), processIo());
2079
+ }
2080
+ }),
968
2081
  "user-prompt-submit": defineCommand({
969
2082
  meta: {
970
2083
  name: "user-prompt-submit",
@@ -1013,8 +2126,12 @@ const main = defineCommand({
1013
2126
  init: initCommand,
1014
2127
  status: statusCommand,
1015
2128
  log: logCommand,
1016
- sessions: sessionsCommand,
2129
+ new: newCommand,
2130
+ tmp: tmpCommand,
1017
2131
  resume: resumeCommand,
2132
+ fork: forkCommand,
2133
+ sessions: sessionsCommand,
2134
+ notes: notesCommand,
1018
2135
  group: groupCommand,
1019
2136
  groups: groupsCommand,
1020
2137
  hook: hookCommand,