@rucher/cli 0.1.0 → 0.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.mjs +1108 -70
  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, 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
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,46 @@ 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
+ 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
+ },
75
127
  groups: { subCommands: { forget: { args: { reference: groups } } } },
76
128
  group: { subCommands: {
77
129
  add: { args: { path: directories } },
@@ -92,7 +144,7 @@ async function setupCompletion(main) {
92
144
  };
93
145
  }
94
146
  // package.json
95
- var version = "0.1.0";
147
+ var version = "0.2.0-beta.0";
96
148
  // src/color.ts
97
149
  function paint(io) {
98
150
  const style = (name) => (text) => io.color ? styleText(name, text, { validateStream: false }) : text;
@@ -257,7 +309,7 @@ function runHook(io, run) {
257
309
  }
258
310
  return 0;
259
311
  }
260
- function withCarnet(cwd, io, use) {
312
+ function withCarnet$1(cwd, io, use) {
261
313
  const carnet = openCarnet({
262
314
  cwd: cwd ?? io.cwd,
263
315
  env: io.env
@@ -271,12 +323,20 @@ function withCarnet(cwd, io, use) {
271
323
  function sessionStart(stdinText, io) {
272
324
  return runHook(io, () => {
273
325
  const payload = host.parseSessionPayload(stdinText);
274
- withCarnet(payload.cwd, io, (carnet) => {
275
- const { additionalContext } = handleSessionStart(carnet, payload, {
326
+ withCarnet$1(payload.cwd, io, (carnet) => {
327
+ const { additionalContext, notices } = handleSessionStart(carnet, payload, {
276
328
  host: host.id,
277
329
  processId: host.processId(io.env),
278
- RUCHER_PURGE_DAYS: io.env.RUCHER_PURGE_DAYS
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
279
338
  });
339
+ for (const notice of notices) io.stderr(`${notice}\n`);
280
340
  if (additionalContext) {
281
341
  const hookSpecificOutput = {
282
342
  hookEventName: "SessionStart",
@@ -287,28 +347,62 @@ function sessionStart(stdinText, io) {
287
347
  });
288
348
  });
289
349
  }
290
- function subagentHook(action, stdinText, io) {
350
+ function subagentStart(stdinText, io) {
291
351
  return runHook(io, () => {
292
352
  const payload = host.parseSubagentPayload(stdinText);
293
- withCarnet(payload.cwd, io, (carnet) => {
294
- carnet.agents[action](payload.session_id, payload.agent_id);
353
+ withCarnet$1(payload.cwd, io, (carnet) => {
354
+ carnet.agents.pairSubagent(payload.session_id, payload.agent_id);
295
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`);
296
362
  });
297
363
  }
298
- function subagentStart(stdinText, io) {
299
- return subagentHook("pairSubagent", stdinText, io);
300
- }
301
364
  function subagentStop(stdinText, io) {
302
- return subagentHook("stopSubagent", 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
+ });
303
371
  }
304
372
  function userPromptSubmit(stdinText, io) {
305
373
  return runHook(io, () => {
306
374
  const payload = host.parsePromptPayload(stdinText);
307
- withCarnet(payload.cwd, io, (carnet) => {
375
+ withCarnet$1(payload.cwd, io, (carnet) => {
308
376
  handleUserPromptSubmit(carnet, host, payload);
309
377
  });
310
378
  });
311
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
+ }
312
406
  // src/session.ts
313
407
  var CliError = class extends Error {
314
408
  hint;
@@ -381,27 +475,303 @@ function sessionTitle(carnet, session) {
381
475
  }
382
476
  function logOnce(carnet, io, options) {
383
477
  const session = resolveSession(carnet, options.session);
384
- const events = carnet.events.read(session.id, options.count);
478
+ const events = carnet.events.read(session.id, options.count, options.agents);
385
479
  io.stdout(`${options.md ? formatEventsMarkdown(events, sessionTitle(carnet, session)) : formatEvents(events, io)}\n`);
386
480
  }
387
- // src/commands/resume.ts
388
- function resumeTarget(carnet, reference, io) {
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 = []) {
389
650
  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;
651
+ if (session.status === "archived") io.stderr(`warning: session ${reference} is archived\n`);
652
+ const prompt = appendPromptFile(carnet.group, session, io.env);
392
653
  return {
393
- ...hostById(session.host).resumeCommand(session),
394
- cwd
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
395
661
  };
396
662
  }
397
- function runTarget({ command, args, cwd }) {
398
- const result = spawnSync(command, args, {
399
- cwd,
400
- stdio: "inherit"
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
+ }
401
709
  });
402
710
  if (result.error) throw result.error;
403
711
  return result.status ?? 1;
404
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
+ }
405
775
  // src/commands/serve.ts
406
776
  function serve(io) {
407
777
  serveCarnet({
@@ -409,11 +779,118 @@ function serve(io) {
409
779
  env: io.env
410
780
  });
411
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
+ }
412
888
  // src/commands/status.ts
413
889
  const SECTION_HEADERS = /* @__PURE__ */ new Set([
414
890
  "On the table",
415
891
  "Waiting on you",
416
- "Running"
892
+ "Running",
893
+ NOTES_HEADER
417
894
  ]);
418
895
  function truncate(line, columns) {
419
896
  const chars = Array.from(line);
@@ -426,6 +903,13 @@ function colorizeLine(line, io) {
426
903
  if (SECTION_HEADERS.has(line)) return colors.bold(cut);
427
904
  if (line.startsWith(" ⚙️")) return colors.yellow(cut);
428
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
+ }
429
913
  return cut;
430
914
  }
431
915
  function sessionWhere(carnet, session) {
@@ -441,32 +925,71 @@ function sessionLabel(carnet, session, columns) {
441
925
  function sessionHeader(carnet, session, io) {
442
926
  return paint(io).cyan(sessionLabel(carnet, session, io.columns));
443
927
  }
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));
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;
447
966
  }
448
967
  function hasSomethingToShow(carnet, session) {
449
- return carnet.agents.list(session.id).length > 0 || carnet.table.get(session.id) !== void 0;
968
+ return carnet.agents.list(session.id).length > 0 || carnet.table.get(session.id) !== void 0 || carnet.notes.activity(session.id).length > 0;
450
969
  }
451
970
  function sessionBlock(carnet, session, view, io) {
452
- return [sessionHeader(carnet, session, io), ...sessionLines(carnet, session, view, io)].join("\n");
971
+ return [sessionHeader(carnet, session, io), ...sessionLines(session, view, io, "summary")].join("\n");
453
972
  }
454
- function singleView(carnet, session, io) {
973
+ function singleView(carnet, session, io, state) {
455
974
  const colors = paint(io);
456
975
  const view = carnet.status.view(session);
457
976
  const separator = " - ";
458
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);
459
981
  return [
460
- `${colors.dim(view.time)}${separator}${colors.cyan(label)}`,
982
+ title,
461
983
  "",
462
- ...sessionLines(carnet, session, view, io),
984
+ ...body,
463
985
  "",
986
+ ...footer ? [footer] : [],
464
987
  colors.dim(LEGEND)
465
988
  ].join("\n");
466
989
  }
467
990
  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);
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);
470
993
  let time = "";
471
994
  const blocks = sessions.map((session) => {
472
995
  const view = carnet.status.view(session);
@@ -484,16 +1007,42 @@ function renderStatusView(carnet, io, options) {
484
1007
  function statusOnce(carnet, io, options) {
485
1008
  io.stdout(`${renderStatusView(carnet, io, options)}\n`);
486
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
+ }
487
1031
  const CLEAR = "\x1B[H\x1B[2J";
488
1032
  const HIDE_CURSOR = "\x1B[?25l";
489
1033
  const SHOW_CURSOR = "\x1B[?25h";
490
1034
  function statusWatch(carnet, io, options) {
491
1035
  return new Promise((resolve) => {
492
1036
  let last = "";
1037
+ const interactive = options.keys !== void 0 && !options.all;
1038
+ let state = INITIAL_WATCH_STATE;
493
1039
  const repaint = () => {
494
1040
  let text;
495
1041
  try {
496
- text = renderStatusView(carnet, io, options);
1042
+ text = renderStatusView(carnet, io, {
1043
+ ...options,
1044
+ interaction: interactive ? state : void 0
1045
+ });
497
1046
  } catch (error) {
498
1047
  text = paint(io).dim(error instanceof Error ? error.message : String(error));
499
1048
  }
@@ -501,12 +1050,28 @@ function statusWatch(carnet, io, options) {
501
1050
  last = text;
502
1051
  io.stdout(`${CLEAR}${text}\n`);
503
1052
  };
504
- const timer = setInterval(repaint, options.intervalMilliseconds);
1053
+ const timer = setInterval(() => {
1054
+ if (state.reason === null) repaint();
1055
+ }, options.intervalMilliseconds);
1056
+ let stopped = false;
505
1057
  const stop = () => {
1058
+ if (stopped) return;
1059
+ stopped = true;
506
1060
  clearInterval(timer);
1061
+ options.keys?.close();
507
1062
  io.stdout(SHOW_CURSOR);
508
1063
  resolve();
509
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
+ });
510
1075
  options.signal?.addEventListener("abort", stop, { once: true });
511
1076
  io.stdout(HIDE_CURSOR);
512
1077
  repaint();
@@ -521,6 +1086,7 @@ function row(carnet, session, now) {
521
1086
  const open = carnet.agents.list(session.id).length;
522
1087
  return [
523
1088
  session.name ?? session.id.slice(0, 8),
1089
+ session.kind,
524
1090
  session.status,
525
1091
  sessionWhere(carnet, session) ?? "",
526
1092
  lastActive(session.lastActiveAt, now),
@@ -531,12 +1097,12 @@ function row(carnet, session, now) {
531
1097
  function sessionsOnce(carnet, io, options = {}) {
532
1098
  const colors = paint(io);
533
1099
  const sessions = carnet.sessions.list({
534
- includeTemporary: options.all,
535
- includeDropped: options.all
1100
+ includeTemp: options.all,
1101
+ includeArchived: options.all
536
1102
  });
537
1103
  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`);
1104
+ const hint = options.all ? "" : " (temp and archived ones are hidden, use --all)";
1105
+ io.stdout(`${colors.dim(`no active session yet${hint}`)}\n`);
540
1106
  return;
541
1107
  }
542
1108
  const now = options.now ?? /* @__PURE__ */ new Date();
@@ -549,7 +1115,8 @@ function sessionsOnce(carnet, io, options = {}) {
549
1115
  return cells.map((cell, column) => {
550
1116
  const padded = column < cells.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell;
551
1117
  if (column === 0) return colors.bold(padded);
552
- if (column === 1 && session.status !== "active") return colors.dim(padded);
1118
+ if (column === 1 && session.kind === "temp") return colors.dim(padded);
1119
+ if (column === 2 && session.status === "archived") return colors.dim(padded);
553
1120
  return padded;
554
1121
  }).join(" ").trimEnd();
555
1122
  });
@@ -569,6 +1136,75 @@ function sessionsMerge(carnet, fromReference, intoReference, io) {
569
1136
  ];
570
1137
  io.stdout(`${lines.join("\n")}\n`);
571
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
+ }
572
1208
  // src/io.ts
573
1209
  function processIo(options = {}) {
574
1210
  const tty = process.stdout.isTTY === true;
@@ -593,6 +1229,30 @@ function readStdin() {
593
1229
  process.stdin.on("error", () => resolve(data));
594
1230
  });
595
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
+ }
596
1256
  // src/main.ts
597
1257
  function fail(io, error) {
598
1258
  if (error instanceof CliError) io.stderr(`error: ${error.message}${error.hint ? `\n ${error.hint}` : ""}\n`);
@@ -688,7 +1348,8 @@ const statusCommand = defineCommand({
688
1348
  await statusWatch(carnet, io, {
689
1349
  ...options,
690
1350
  intervalMilliseconds,
691
- signal: controller.signal
1351
+ signal: controller.signal,
1352
+ keys: terminalKeys(process.stdin, process.stdout)
692
1353
  });
693
1354
  } catch (error) {
694
1355
  fail(io, error);
@@ -713,6 +1374,11 @@ const logCommand = defineCommand({
713
1374
  default: false,
714
1375
  description: "Markdown output, for archiving"
715
1376
  },
1377
+ agents: {
1378
+ type: "boolean",
1379
+ default: false,
1380
+ description: "Agent events only, without session starts and ends"
1381
+ },
716
1382
  ...colorArgument
717
1383
  },
718
1384
  run({ args }) {
@@ -724,7 +1390,8 @@ const logCommand = defineCommand({
724
1390
  }), io, {
725
1391
  session: args.session,
726
1392
  count: Number(args.count) || 20,
727
- md: args.md
1393
+ md: args.md,
1394
+ agents: args.agents
728
1395
  });
729
1396
  } catch (error) {
730
1397
  fail(io, error);
@@ -740,7 +1407,7 @@ const sessionsListCommand = defineCommand({
740
1407
  all: {
741
1408
  type: "boolean",
742
1409
  default: false,
743
- description: "Include temporary and dropped sessions"
1410
+ description: "Include temp and archived sessions"
744
1411
  },
745
1412
  ...colorArgument
746
1413
  },
@@ -787,40 +1454,389 @@ const sessionsMergeCommand = defineCommand({
787
1454
  }
788
1455
  }
789
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
+ });
790
1555
  const sessionsCommand = defineCommand({
791
1556
  meta: {
792
1557
  name: "sessions",
793
- description: "List or merge the sessions of the group"
1558
+ description: "List and manage the sessions of the group"
794
1559
  },
795
1560
  default: "list",
796
1561
  subCommands: {
797
1562
  list: sessionsListCommand,
798
- merge: sessionsMergeCommand
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
+ }));
799
1788
  }
800
1789
  });
801
1790
  const resumeCommand = defineCommand({
802
1791
  meta: {
803
1792
  name: "resume",
804
- description: "Resume a named session in its host (Claude Code today)"
1793
+ description: `Resume a session in its host, or pick one when none is given. ${passthroughHelp}`
805
1794
  },
806
- args: { name: {
1795
+ args: { session: {
807
1796
  type: "positional",
808
1797
  description: "Session name, id or id prefix",
809
- required: true
1798
+ required: false
810
1799
  } },
811
- run({ args }) {
1800
+ async run({ rawArgs }) {
1801
+ const { own, passthrough } = splitPassthrough(rawArgs);
812
1802
  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);
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)"
823
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
+ }));
824
1840
  }
825
1841
  });
826
1842
  const groupCommand = defineCommand({
@@ -965,6 +1981,24 @@ const hookCommand = defineCommand({
965
1981
  process.exitCode = sessionStart(await readStdin(), processIo());
966
1982
  }
967
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
+ }),
968
2002
  "user-prompt-submit": defineCommand({
969
2003
  meta: {
970
2004
  name: "user-prompt-submit",
@@ -1013,8 +2047,12 @@ const main = defineCommand({
1013
2047
  init: initCommand,
1014
2048
  status: statusCommand,
1015
2049
  log: logCommand,
1016
- sessions: sessionsCommand,
2050
+ new: newCommand,
2051
+ tmp: tmpCommand,
1017
2052
  resume: resumeCommand,
2053
+ fork: forkCommand,
2054
+ sessions: sessionsCommand,
2055
+ notes: notesCommand,
1018
2056
  group: groupCommand,
1019
2057
  groups: groupsCommand,
1020
2058
  hook: hookCommand,