@rucher/cli 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.mjs +1100 -206
  3. package/package.json +2 -2
package/dist/cli.mjs CHANGED
@@ -1,18 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from "citty";
3
- import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { basename, dirname, join, resolve } from "node:path";
5
5
  import tab from "@bomb.sh/tab/citty";
6
- import { AGENT_KINDS, BLOCKED_HEADER, CarnetError, GUARDED_TOOLS, KIND_LEGEND, KIND_TAG_PATTERN, LAUNCH_TOOLS, LEGEND, MAIN_HEADER, MAIN_IDLE, NOTES_HEADER, NOTE_KINDS, SIMILAR_PREFIX, SUBAGENT_RULES, WAITING_TOOL, WORKSPACE_FILE, addWorkspaceRepo, appendPromptFile, archiveWorkspaceSessions, claudeCode, createWorkspace, definitionInstructions, deleteWorkspaceNotes, dropWorkspace, formatClock, guardMainLaunch, guardSubagentCall, handleSessionEnd, handleSessionStart, handleStop, handleToolStart, handleToolUse, handleUserPromptSubmit, hostById, isAgentKind, isWorkspaceName, kindTag, labelStatusLine, listWorkspaces, loadWorkspace, locateAgent, memoryHalfLife, mergeWorkspaces, moveSession, openCarnet, openResolvedCarnet, openWorkspaceCarnet, planWorkspaceMerge, removeWorkspaceRepo, renameWorkspace, renderRunDirectory, renderSections, repoNameFor, repoPathFor, reportDocument, requireWorkspace, resolveWorkspace, shortId, statusLinePath, workspaceExists, workspaceLabel, workspaceLastActive, workspaceRepoNames, workspaceSessionCounts, writeStatusLine } from "@rucher/carnet";
7
- import { tmpdir } from "node:os";
6
+ import { AGENT_BRIEF_HINT, AGENT_KINDS, BLOCKED_HEADER, CLAUDE_BACKEND_NOTES, CLAUDE_NATIVE_FILES, CarnetError, GUARDED_TOOLS, KIND_LEGEND, KIND_TAG_PATTERN, LAUNCH_TOOLS, LEGEND, MAIN_HEADER, MAIN_IDLE, NOTES_HEADER, NOTE_KINDS, SIMILAR_PREFIX, SNIPPET_CLOSE, SNIPPET_OPEN, SUBAGENT_RULES, WAITING_TOOL, WORKSPACE_FILE, addWorkspaceRepo, archiveWorkspaceSessions, checkForkOptions, claudeCode, claudeCodeHooks, claudeTranscriptUsage, createWorkspace, definitionInstructions, deleteWorkspaceNotes, dropWorkspace, effectiveRun, eventUsage, forkStartContext, formatClock, formatUsage, globalConfigPath, handleSessionEnd, handleSessionStart, handleStop, handleToolStart, handleToolUse, handleUserPromptSubmit, hostById, isAgentKind, kindTag, labelStatusLine, launchEnded, launchHost, launchStarted, listWorkspaces, loadGlobalConfig, loadProfiles, loadWorkspace, locateAgent, mainLaunchVerdict, memoryHalfLife, mergeWorkspaces, migrateInstructions, moveSession, openCarnet, openResolvedCarnet, openWorkspaceCarnet, planWorkspaceMerge, prepareFork, prepareNew, prepareResume, profileLookup, referenceLine, removeWorkspaceRepo, renameWorkspace, renderAgentLine, renderMainLine, renderRunDirectory, renderSections, repoInstructionFiles, repoInstructionsPath, repoPathFor, reportDocument, requireWorkspace, resolveConfig, resolveWorkspace, rucherPaths, scratchRoots, serializeWorkspaceFile, shortId, sourceLabel, statusLinePath, subagentVerdict, withWorkspace, withWorkspace as withWorkspace$1, workspaceContext, workspaceExists, workspaceLabel, workspaceLastActive, workspaceRepoNames, workspaceSessionCounts, workspacesDirectory, writeStatusLine } from "@rucher/carnet";
8
7
  import { stripVTControlCharacters, styleText } from "node:util";
9
8
  import { spawnSync } from "node:child_process";
10
- import { randomUUID } from "node:crypto";
11
9
  import { createInterface } from "node:readline/promises";
12
10
  import { serveCarnet } from "@rucher/carnet/mcp";
13
11
  import { emitKeypressEvents } from "node:readline";
14
12
  // src/completion.ts
15
- const hiddenCommands = /* @__PURE__ */ new Set(["hook", "serve"]);
13
+ const hiddenCommands = /* @__PURE__ */ new Set([
14
+ "hook",
15
+ "mcp",
16
+ "serve"
17
+ ]);
16
18
  function quietly(suggest) {
17
19
  try {
18
20
  suggest();
@@ -79,6 +81,12 @@ function suggestRepoNames(context, complete) {
79
81
  function suggestNoteKinds(complete) {
80
82
  for (const kind of NOTE_KINDS) complete(kind, "");
81
83
  }
84
+ function suggestProfiles(context, complete) {
85
+ quietly(() => {
86
+ const { workspace } = resolveWorkspace(inWorkspace(context));
87
+ for (const definition of loadProfiles(context.env, workspace).top.values()) complete(definition.name, definition.layer);
88
+ });
89
+ }
82
90
  function suggestAgentKinds(complete) {
83
91
  for (const kind of AGENT_KINDS) complete(kind, "");
84
92
  }
@@ -135,6 +143,7 @@ const noteKinds = (complete) => suggestNoteKinds(complete);
135
143
  const agentKinds = (complete) => suggestAgentKinds(complete);
136
144
  const notes = (complete) => suggestNotes(processContext(), complete);
137
145
  const agents = (complete) => suggestAgents(processContext(), complete);
146
+ const profiles = (complete) => suggestProfiles(processContext(), complete);
138
147
  const workspace = { ws: workspaces };
139
148
  const completionConfig = { subCommands: {
140
149
  status: { options: {
@@ -147,6 +156,7 @@ const completionConfig = { subCommands: {
147
156
  kind: agentKinds,
148
157
  ...workspace
149
158
  } },
159
+ find: { options: workspace },
150
160
  report: {
151
161
  args: { name: agents },
152
162
  options: {
@@ -233,6 +243,25 @@ const completionConfig = { subCommands: {
233
243
  }
234
244
  }
235
245
  },
246
+ ref: {
247
+ options: workspace,
248
+ subCommands: {
249
+ list: { options: {
250
+ agent: agents,
251
+ session: sessions,
252
+ ...workspace
253
+ } },
254
+ add: { options: {
255
+ agent: agents,
256
+ session: sessions,
257
+ ...workspace
258
+ } },
259
+ remove: { options: {
260
+ session: sessions,
261
+ ...workspace
262
+ } }
263
+ }
264
+ },
236
265
  ws: {
237
266
  options: workspace,
238
267
  subCommands: {
@@ -260,14 +289,32 @@ const completionConfig = { subCommands: {
260
289
  },
261
290
  edit: {
262
291
  args: { name: workspaces },
263
- options: workspace
292
+ options: {
293
+ repo: repoNames,
294
+ ...workspace
295
+ }
264
296
  },
265
297
  path: {
266
298
  args: { name: workspaces },
267
299
  options: workspace
268
300
  }
269
301
  }
270
- }
302
+ },
303
+ config: { subCommands: {
304
+ show: { options: {
305
+ kind: agentKinds,
306
+ ...workspace
307
+ } },
308
+ check: { options: workspace }
309
+ } },
310
+ profiles: { subCommands: {
311
+ list: { options: workspace },
312
+ show: {
313
+ args: { name: profiles },
314
+ options: workspace
315
+ },
316
+ check: { options: workspace }
317
+ } }
271
318
  } };
272
319
  async function setupCompletion(main) {
273
320
  const subCommands = await (typeof main.subCommands === "function" ? main.subCommands() : main.subCommands);
@@ -289,7 +336,7 @@ async function setupCompletion(main) {
289
336
  };
290
337
  }
291
338
  // package.json
292
- var version = "0.3.0";
339
+ var version = "0.4.0";
293
340
  // src/plugin.ts
294
341
  const CLI_VERSION = version;
295
342
  function readJson(path) {
@@ -357,7 +404,7 @@ function readStatusLine(sessionId, env) {
357
404
  }
358
405
  }
359
406
  // src/commands/hook.ts
360
- const host = claudeCode;
407
+ const host = claudeCodeHooks;
361
408
  function runHook(io, run) {
362
409
  try {
363
410
  run();
@@ -367,16 +414,18 @@ function runHook(io, run) {
367
414
  }
368
415
  return 0;
369
416
  }
370
- function withCarnet$1(payload, io, use) {
371
- const carnet = openCarnet({
417
+ function withCarnet$1(payload, io, use, { guard = false } = {}) {
418
+ const { carnet, resolution } = openResolvedCarnet({
372
419
  cwd: payload.cwd ?? io.cwd,
373
420
  env: io.env,
374
- sessionId: payload.session_id
421
+ sessionId: payload.session_id,
422
+ tolerant: true
375
423
  });
376
424
  try {
377
425
  const known = payload.session_id ? carnet.sessions.get(payload.session_id) : void 0;
378
- if (!carnet.workspace && !known) return;
379
- use(carnet);
426
+ const named = resolution.origin === "option" || resolution.origin === "env";
427
+ if (!carnet.workspace && !known && !(guard && named)) return;
428
+ use(carnet, resolution);
380
429
  if (payload.session_id) refreshStatusLine(carnet, payload.session_id, io.env);
381
430
  } finally {
382
431
  carnet.close();
@@ -392,7 +441,7 @@ function sessionStart(stdinText, io) {
392
441
  const payload = host.parseSessionPayload(stdinText);
393
442
  withCarnet$1(payload, io, (carnet) => {
394
443
  const { additionalContext, notices } = handleSessionStart(carnet, payload, {
395
- host: host.id,
444
+ host: claudeCode.id,
396
445
  processId: host.processId(io.env),
397
446
  RUCHER_PURGE_DAYS: io.env.RUCHER_PURGE_DAYS,
398
447
  RUCHER_HOME: io.env.RUCHER_HOME,
@@ -421,13 +470,18 @@ function sessionStart(stdinText, io) {
421
470
  function subagentStart(stdinText, io) {
422
471
  return runHook(io, () => {
423
472
  const payload = host.parseSubagentPayload(stdinText);
473
+ let contract;
424
474
  withCarnet$1(payload, io, (carnet) => {
425
- carnet.agents.pairSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload), payload.agent_type);
475
+ const names = host.subagentNames(payload);
476
+ const agent = carnet.agents.pairSubagent(payload.session_id, payload.agent_id, names, payload.agent_type);
477
+ if (!agent) return;
478
+ contract = !names.includes(agent.name) && carnet.agents.fallbackCandidates(payload.session_id) > 0 ? AGENT_BRIEF_HINT : forkStartContext(agent);
426
479
  });
427
- if (host.subagentInheritsContext(payload)) return;
480
+ const inherits = host.subagentInheritsContext(payload);
481
+ if (inherits && !contract) return;
428
482
  const hookSpecificOutput = {
429
483
  hookEventName: "SubagentStart",
430
- additionalContext: SUBAGENT_RULES
484
+ additionalContext: inherits ? contract : SUBAGENT_RULES
431
485
  };
432
486
  io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
433
487
  });
@@ -436,7 +490,8 @@ function subagentStop(stdinText, io) {
436
490
  return runHook(io, () => {
437
491
  const payload = host.parseSubagentPayload(stdinText);
438
492
  withCarnet$1(payload, io, (carnet) => {
439
- carnet.agents.stopSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload));
493
+ const transcript = payload.agent_transcript_path;
494
+ carnet.agents.stopSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload), transcript ? claudeTranscriptUsage(transcript) : void 0);
440
495
  });
441
496
  });
442
497
  }
@@ -457,35 +512,33 @@ function postToolUse(stdinText, io) {
457
512
  withCarnet$1(payload, io, (carnet) => {
458
513
  const plugin = installedPlugin(io.env);
459
514
  syncPluginVersion(carnet, payload.session_id, plugin.version);
460
- const additionalContext = handleToolUse(carnet, payload, {
461
- RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
462
- RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
463
- }, { trackTurn: plugin.endsTurns });
464
- if (!additionalContext) return;
465
- const hookSpecificOutput = {
466
- hookEventName: "PostToolUse",
467
- additionalContext
468
- };
469
- io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
515
+ handleToolUse(carnet, payload, { trackTurn: plugin.endsTurns });
470
516
  });
471
517
  });
472
518
  }
519
+ function indexForSearch(carnet, payload, io) {
520
+ try {
521
+ carnet.search.index(payload.session_id, { transcriptPath: payload.transcript_path });
522
+ } catch (error) {
523
+ io.stderr(`rucher hook: search index: ${error instanceof Error ? error.message : String(error)}\n`);
524
+ }
525
+ }
473
526
  function sessionEnd(stdinText, io) {
474
527
  return runHook(io, () => {
475
528
  const payload = host.parseSessionEndPayload(stdinText);
476
529
  withCarnet$1(payload, io, (carnet) => {
477
530
  handleSessionEnd(carnet, payload);
531
+ indexForSearch(carnet, payload, io);
478
532
  });
479
533
  });
480
534
  }
481
- function scratchRoots(io) {
482
- const folder = `claude-${process.getuid?.() ?? 0}`;
483
- const parents = [
484
- io.env.CLAUDE_CODE_TMPDIR,
485
- process.platform === "win32" ? void 0 : "/tmp",
486
- tmpdir()
487
- ].filter((parent) => Boolean(parent));
488
- return [...new Set(parents.map((parent) => join(parent, folder)))];
535
+ function subagentToolNames(payload) {
536
+ if (!payload.agent_id) return [];
537
+ return host.subagentNames({
538
+ session_id: payload.session_id,
539
+ agent_id: payload.agent_id,
540
+ transcript_path: payload.transcript_path
541
+ });
489
542
  }
490
543
  function denyToolCall(io, reason) {
491
544
  const hookSpecificOutput = {
@@ -502,10 +555,15 @@ function preToolUse(stdinText, io) {
502
555
  const guarded = Boolean(payload.agent_id) && GUARDED_TOOLS.has(tool);
503
556
  const launch = !payload.agent_id && LAUNCH_TOOLS.has(tool);
504
557
  if (!guarded && !launch && (payload.agent_id || tool !== WAITING_TOOL)) return;
505
- withCarnet$1(payload, io, (carnet) => {
506
- const reason = guarded ? guardSubagentCall(carnet, payload, scratchRoots(io)) : launch ? guardMainLaunch(carnet, payload) : handleToolStart(carnet, payload);
507
- if (reason) denyToolCall(io, reason);
508
- });
558
+ withCarnet$1(payload, io, (carnet, resolution) => {
559
+ if (!guarded && !launch) {
560
+ handleToolStart(carnet, payload);
561
+ return;
562
+ }
563
+ const namedUnreadable = !carnet.workspace && (resolution.origin === "option" || resolution.origin === "env");
564
+ const verdict = guarded ? subagentVerdict(carnet, payload, scratchRoots(io.env), subagentToolNames(payload), namedUnreadable) : mainLaunchVerdict(carnet, payload, namedUnreadable);
565
+ if (!verdict.allow) denyToolCall(io, verdict.reason);
566
+ }, { guard: guarded || launch });
509
567
  });
510
568
  }
511
569
  function stopHook(stdinText, io) {
@@ -513,6 +571,7 @@ function stopHook(stdinText, io) {
513
571
  const payload = host.parseStopPayload(stdinText);
514
572
  withCarnet$1(payload, io, (carnet) => {
515
573
  handleStop(carnet, payload);
574
+ indexForSearch(carnet, payload, io);
516
575
  });
517
576
  });
518
577
  }
@@ -527,6 +586,261 @@ function paint(io) {
527
586
  cyan: style("cyan")
528
587
  };
529
588
  }
589
+ // src/commands/profiles.ts
590
+ function carnetErrors$2(io, run) {
591
+ try {
592
+ return run();
593
+ } catch (error) {
594
+ if (error instanceof CarnetError) {
595
+ io.stderr(`error: ${error.message}\n`);
596
+ return 1;
597
+ }
598
+ throw error;
599
+ }
600
+ }
601
+ function currentWorkspace$1(io, name) {
602
+ return resolveWorkspace({
603
+ cwd: io.cwd,
604
+ env: io.env,
605
+ workspace: name
606
+ }).workspace ?? void 0;
607
+ }
608
+ function firstLine(text) {
609
+ return text.split("\n").find((line) => line.trim())?.trim() ?? "";
610
+ }
611
+ function valueText$1(value) {
612
+ if (value && typeof value === "object" && "backend" in value) {
613
+ const pair = value;
614
+ return [pair.backend, pair.model].filter(Boolean).join("/");
615
+ }
616
+ return typeof value === "string" ? value : JSON.stringify(value);
617
+ }
618
+ function profilesList(io, options = {}) {
619
+ return carnetErrors$2(io, () => {
620
+ const colors = paint(io);
621
+ const workspace = currentWorkspace$1(io, options.workspace);
622
+ const profiles = loadProfiles(io.env, workspace);
623
+ const rows = [...profiles.top.values()].map((definition) => ({
624
+ name: definition.name,
625
+ layer: definition.layer,
626
+ extends: definition.extends ?? null,
627
+ path: definition.path ?? null,
628
+ valid: profiles.resolved.has(definition.name),
629
+ notes: firstLine(definition.body)
630
+ }));
631
+ if (options.json) {
632
+ io.stdout(`${JSON.stringify(rows, null, 2)}\n`);
633
+ return 0;
634
+ }
635
+ const width = Math.max(...rows.map((row) => row.name.length));
636
+ const layerWidth = Math.max(...rows.map((row) => row.layer.length));
637
+ for (const row of rows) {
638
+ const base = row.extends ? colors.dim(` extends ${row.extends}`) : "";
639
+ const invalid = row.valid ? "" : colors.yellow(" invalid, see rucher profiles check");
640
+ io.stdout(`${row.name.padEnd(width)} ${colors.dim(row.layer.padEnd(layerWidth))} ${row.notes}${base}${invalid}\n`);
641
+ }
642
+ return 0;
643
+ });
644
+ }
645
+ function profilesShow(io, name, options = {}) {
646
+ return carnetErrors$2(io, () => {
647
+ const colors = paint(io);
648
+ const workspace = currentWorkspace$1(io, options.workspace);
649
+ const profiles = loadProfiles(io.env, workspace);
650
+ const resolved = profiles.resolved.get(name);
651
+ if (!resolved) {
652
+ const problem = profiles.problems.find((candidate) => candidate.name === name);
653
+ io.stderr(problem ? `error: profile ${name} (${problem.path ?? problem.layer}): ${problem.message}\n` : `error: no profile named ${name}: see rucher profiles list\n`);
654
+ return 1;
655
+ }
656
+ const setBy = (key) => resolved.chain.find((definition) => definition.value?.has(key)) ?? resolved;
657
+ const keys = [...resolved.value.keys()].sort();
658
+ if (options.json) {
659
+ io.stdout(`${JSON.stringify({
660
+ name,
661
+ layer: resolved.layer,
662
+ path: resolved.path ?? null,
663
+ chain: resolved.chain.map((definition) => ({
664
+ name: definition.name,
665
+ layer: definition.layer,
666
+ path: definition.path ?? null
667
+ })),
668
+ values: Object.fromEntries(resolved.value),
669
+ sources: Object.fromEntries(keys.map((key) => [key, setBy(key).name])),
670
+ notes: resolved.body
671
+ }, null, 2)}\n`);
672
+ return 0;
673
+ }
674
+ const chain = resolved.chain.map((definition) => `${definition.name} (${definition.layer})`).join(" → ");
675
+ const lines = [colors.bold(`profile ${name}`), colors.dim(` ${chain}`)];
676
+ if (resolved.path) lines.push(colors.dim(` ${resolved.path}`));
677
+ for (const key of keys) {
678
+ const definition = setBy(key);
679
+ const origin = definition === resolved.chain[0] ? "" : ` ${colors.dim(definition.name)}`;
680
+ lines.push(` ${key} = ${valueText$1(resolved.value.get(key))}${origin}`);
681
+ }
682
+ if (resolved.body) lines.push("", resolved.body);
683
+ io.stdout(`${lines.join("\n")}\n`);
684
+ return 0;
685
+ });
686
+ }
687
+ function workspaceNames$1(io, only) {
688
+ if (only) return [only];
689
+ const directory = workspacesDirectory(io.env);
690
+ if (!existsSync(directory)) return [];
691
+ return readdirSync(directory).filter((name) => workspaceExists(name, io.env)).sort();
692
+ }
693
+ /** Problems of the user profiles and of each workspace's, every file reported once. */
694
+ function profileProblems(env, workspaces) {
695
+ const seen = /* @__PURE__ */ new Set();
696
+ const collect = (profiles) => profiles.problems.map((problem) => `${problem.path ?? `built-in ${problem.name}`}: ${problem.message}`).filter((text) => !seen.has(text) && seen.add(text));
697
+ return [...collect(loadProfiles(env)), ...workspaces.flatMap((workspace) => collect(loadProfiles(env, workspace)))];
698
+ }
699
+ function profilesCheck(io, options = {}) {
700
+ const errors = [];
701
+ const workspaces = [];
702
+ for (const name of workspaceNames$1(io, options.workspace)) try {
703
+ workspaces.push(loadWorkspace(name, io.env));
704
+ } catch (error) {
705
+ if (!(error instanceof CarnetError)) throw error;
706
+ errors.push(error.message);
707
+ }
708
+ errors.push(...profileProblems(io.env, workspaces));
709
+ for (const error of errors) io.stderr(`error: ${error}\n`);
710
+ if (errors.length) return 1;
711
+ io.stdout("profiles ok\n");
712
+ return 0;
713
+ }
714
+ // src/commands/config.ts
715
+ function carnetErrors$1(io, run) {
716
+ try {
717
+ return run();
718
+ } catch (error) {
719
+ if (error instanceof CarnetError) {
720
+ io.stderr(`error: ${error.message}\n`);
721
+ return 1;
722
+ }
723
+ throw error;
724
+ }
725
+ }
726
+ function pairText(pair) {
727
+ return pair.model ? `${pair.backend}/${pair.model}` : `${pair.backend} (its default model)`;
728
+ }
729
+ function valueText(key, value) {
730
+ if (key === "run.default" || key.startsWith("run.kinds.")) return pairText(value);
731
+ return typeof value === "string" ? value : JSON.stringify(value);
732
+ }
733
+ function configPath(io) {
734
+ io.stdout(`${globalConfigPath(io.env)}\n`);
735
+ return 0;
736
+ }
737
+ function configShow(io, options = {}) {
738
+ return carnetErrors$1(io, () => {
739
+ const colors = paint(io);
740
+ const workspace = resolveWorkspace({
741
+ cwd: io.cwd,
742
+ env: io.env,
743
+ workspace: options.workspace
744
+ }).workspace;
745
+ const resolved = resolveConfig({
746
+ global: loadGlobalConfig(io.env),
747
+ workspace: workspace?.config,
748
+ profiles: profileLookup(loadProfiles(io.env, workspace))
749
+ });
750
+ const problems = workspace?.configProblem ? [workspace.configProblem, ...resolved.problems] : resolved.problems;
751
+ const kinds = options.kind ? [options.kind] : [...AGENT_KINDS];
752
+ const runs = kinds.map((kind) => ({
753
+ kind,
754
+ ...effectiveRun(resolved, kind)
755
+ }));
756
+ if (options.json) {
757
+ io.stdout(`${JSON.stringify({
758
+ workspace: workspace?.name ?? null,
759
+ values: Object.fromEntries(resolved.values),
760
+ sources: Object.fromEntries(resolved.sources),
761
+ run: Object.fromEntries(runs.map(({ kind, pair, key }) => [kind, {
762
+ ...pair,
763
+ key
764
+ }])),
765
+ problems
766
+ }, null, 2)}\n`);
767
+ return problems.length ? 1 : 0;
768
+ }
769
+ const lines = [colors.bold(workspace ? `config of workspace ${workspace.name}` : "config, no workspace")];
770
+ for (const key of [...resolved.values.keys()].sort()) {
771
+ const source = options.sources ? ` ${colors.dim(sourceLabel(resolved.sources.get(key)))}` : "";
772
+ lines.push(` ${key} = ${valueText(key, resolved.values.get(key))}${source}`);
773
+ }
774
+ lines.push(colors.bold("run, cold agents"));
775
+ const width = Math.max(...kinds.map((kind) => kind.length));
776
+ for (const { kind, pair, key, source } of runs) {
777
+ const unavailable = pair.backend === "claude" ? "" : colors.yellow(" not in claude-code");
778
+ lines.push(` ${kind.padEnd(width)} ${pairText(pair)} ${colors.dim(`${key} · ${sourceLabel(source)}`)}${unavailable}`);
779
+ }
780
+ lines.push(colors.dim("Only run acts in the claude-code host; the other keys are stored for the Rucher server."));
781
+ io.stdout(`${lines.join("\n")}\n`);
782
+ if (workspace?.configProblem) io.stderr(`warning: workspace config ignored: ${workspace.configProblem}\n`);
783
+ for (const problem of resolved.problems) io.stderr(`warning: ${problem}\n`);
784
+ return 0;
785
+ });
786
+ }
787
+ function workspaceNames(io, only) {
788
+ if (only) return [only];
789
+ const directory = workspacesDirectory(io.env);
790
+ if (!existsSync(directory)) return [];
791
+ return readdirSync(directory).filter((name) => workspaceExists(name, io.env)).sort();
792
+ }
793
+ function attempt(errors, run) {
794
+ try {
795
+ return run();
796
+ } catch (error) {
797
+ if (!(error instanceof CarnetError)) throw error;
798
+ errors.push(error.message);
799
+ return;
800
+ }
801
+ }
802
+ function unknownKinds(source, origin) {
803
+ return [...source?.keys() ?? []].filter((key) => key.startsWith("run.kinds.")).map((key) => key.slice(10)).filter((kind) => !AGENT_KINDS.includes(kind)).map((kind) => `${origin}: run.${kind} names no known kind (${AGENT_KINDS.join(", ")})`);
804
+ }
805
+ function configCheck(io, options = {}) {
806
+ const errors = [];
807
+ const warnings = [];
808
+ const globalPath = globalConfigPath(io.env);
809
+ const global = attempt(errors, () => loadGlobalConfig(io.env));
810
+ warnings.push(...unknownKinds(global, globalPath));
811
+ const checked = [globalPath];
812
+ const workspaces = [];
813
+ const reported = /* @__PURE__ */ new Set();
814
+ const resolveFor = (label, workspace) => {
815
+ const resolved = attempt(errors, () => resolveConfig({
816
+ global: global ?? /* @__PURE__ */ new Map(),
817
+ workspace: workspace?.config,
818
+ profiles: profileLookup(loadProfiles(io.env, workspace))
819
+ }));
820
+ for (const problem of resolved?.problems ?? []) {
821
+ if (reported.has(problem)) continue;
822
+ reported.add(problem);
823
+ errors.push(`${label}: ${problem}`);
824
+ }
825
+ };
826
+ resolveFor(globalPath);
827
+ for (const name of workspaceNames(io, options.workspace)) {
828
+ const workspace = attempt(errors, () => loadWorkspace(name, io.env));
829
+ checked.push(`workspace ${name}`);
830
+ if (!workspace) continue;
831
+ workspaces.push(workspace);
832
+ if (workspace.configProblem) errors.push(workspace.configProblem);
833
+ warnings.push(...unknownKinds(workspace.config, `workspace ${name}`));
834
+ resolveFor(`workspace ${name}`, workspace);
835
+ }
836
+ errors.push(...profileProblems(io.env, workspaces));
837
+ checked.push("profiles");
838
+ for (const warning of warnings) io.stderr(`warning: ${warning}\n`);
839
+ for (const error of errors) io.stderr(`error: ${error}\n`);
840
+ if (errors.length) return 1;
841
+ io.stdout(`config ok: ${checked.join(", ")}\n`);
842
+ return 0;
843
+ }
530
844
  // src/session.ts
531
845
  var CliError = class extends Error {
532
846
  hint;
@@ -536,9 +850,6 @@ var CliError = class extends Error {
536
850
  this.name = "CliError";
537
851
  }
538
852
  };
539
- function withWorkspace(command, workspace) {
540
- return workspace ? `${command} --ws ${workspace}` : command;
541
- }
542
853
  function findSession(carnet, reference) {
543
854
  try {
544
855
  return carnet.sessions.find(reference);
@@ -554,9 +865,122 @@ function resolveSession(carnet, reference) {
554
865
  if (!session) throw new CliError("No session in this workspace yet", withWorkspace("start one with rucher new <name>", carnet.workspace?.name));
555
866
  return session;
556
867
  }
868
+ // src/commands/find.ts
869
+ const WAITING_SHOWN = 2;
870
+ const EVENTS_SHOWN = 2;
871
+ function recap(carnet, session) {
872
+ const view = carnet.status.view(session);
873
+ const events = carnet.events.read(session.id, EVENTS_SHOWN, true);
874
+ return {
875
+ main: renderMainLine(view.table, view.turn),
876
+ waiting: view.waiting.slice(0, WAITING_SHOWN).map((line) => renderAgentLine(line)),
877
+ waitingCount: view.waiting.length,
878
+ events: events.map((event) => [
879
+ formatClock(new Date(event.at)),
880
+ event.type,
881
+ event.agent ?? "",
882
+ event.note ?? ""
883
+ ].filter(Boolean).join(" "))
884
+ };
885
+ }
886
+ function sessionReference$1(session) {
887
+ return session.name ?? shortId(session.id);
888
+ }
889
+ function resumeHint(carnet, session) {
890
+ const other = session.workspace !== carnet.workspace?.name;
891
+ return `rucher resume ${sessionReference$1(session)}${other ? ` --ws ${session.workspace}` : ""}`;
892
+ }
893
+ function day(at) {
894
+ return at ? at.slice(0, 10) : "";
895
+ }
896
+ function hitLabel(hit) {
897
+ if (hit.source === "transcript") return `transcript ${day(hit.at)}`.trim();
898
+ if (hit.source === "event") return `journal ${hit.title}`;
899
+ if (hit.source === "report" || hit.source === "agent") return `${hit.source} ${hit.title}`;
900
+ if (hit.source === "note") return `note ${hit.title}`;
901
+ return hit.source;
902
+ }
903
+ function flatten(snippet) {
904
+ return snippet.replace(/\s+/g, " ").trim();
905
+ }
906
+ function highlight(snippet, colors, io) {
907
+ if (!io.color) return flatten(snippet);
908
+ return flatten(snippet).replace(new RegExp(`${SNIPPET_OPEN}([^${SNIPPET_CLOSE}]*)${SNIPPET_CLOSE}`, "g"), (_, word) => colors.bold(word));
909
+ }
910
+ function renderMatch(carnet, match, io, all) {
911
+ const colors = paint(io);
912
+ const { session } = match;
913
+ const summary = recap(carnet, session);
914
+ const lines = [[colors.bold(sessionReference$1(session)), colors.dim([
915
+ session.kind,
916
+ session.status,
917
+ day(session.lastActiveAt),
918
+ all ? session.workspace : ""
919
+ ].filter(Boolean).join(" · "))].join(" "), ` Main: ${summary.main}`];
920
+ if (summary.waitingCount > 0) {
921
+ const more = summary.waitingCount - summary.waiting.length;
922
+ lines.push(` Waiting on you: ${summary.waiting.join(" · ")}${more > 0 ? ` (+${more})` : ""}`);
923
+ }
924
+ if (summary.events.length > 0) lines.push(` Last: ${summary.events.join(" · ")}`);
925
+ for (const hit of match.hits) lines.push(` ${colors.dim(hitLabel(hit))} ${highlight(hit.snippet, colors, io)}`);
926
+ if (match.partial) lines.push(colors.dim(" transcript partly indexed (size cap)"));
927
+ lines.push(` ${colors.cyan(`→ ${resumeHint(carnet, session)}`)}`);
928
+ return lines.join("\n");
929
+ }
930
+ function jsonResults(carnet, results, pending) {
931
+ const plain = (snippet) => flatten(snippet);
932
+ return {
933
+ pending,
934
+ sessions: results.sessions.map((match) => ({
935
+ id: match.session.id,
936
+ name: match.session.name,
937
+ workspace: match.session.workspace,
938
+ kind: match.session.kind,
939
+ status: match.session.status,
940
+ lastActiveAt: match.session.lastActiveAt,
941
+ score: match.score,
942
+ partial: match.partial,
943
+ recap: recap(carnet, match.session),
944
+ hits: match.hits.map((hit) => ({
945
+ ...hit,
946
+ snippet: plain(hit.snippet)
947
+ })),
948
+ resume: resumeHint(carnet, match.session)
949
+ })),
950
+ notes: results.notes.map((note) => ({
951
+ ...note,
952
+ snippet: plain(note.snippet)
953
+ }))
954
+ };
955
+ }
956
+ function findOnce(carnet, io, options) {
957
+ const all = options.all ?? false;
958
+ let pending = false;
959
+ if (options.reindex) {
960
+ const { sessions } = carnet.search.reindex(all);
961
+ if (!options.json) io.stdout(`reindexed ${sessions} session${sessions === 1 ? "" : "s"}\n`);
962
+ if (!options.question) return;
963
+ } else pending = carnet.search.refresh(all).pending;
964
+ const question = options.question?.trim();
965
+ if (!question) throw new CliError("Nothing to search", "rucher find \"which session talked about the cache\"");
966
+ const results = carnet.search.find(question, {
967
+ all,
968
+ limit: options.limit
969
+ });
970
+ if (options.json) {
971
+ io.stdout(`${JSON.stringify(jsonResults(carnet, results, pending), null, 2)}\n`);
972
+ return;
973
+ }
974
+ const colors = paint(io);
975
+ const blocks = results.sessions.map((match) => renderMatch(carnet, match, io, all));
976
+ if (results.notes.length > 0) blocks.push([colors.bold("Notes"), ...results.notes.map((note) => ` ${colors.dim(`#${note.number} ${note.kind}${all ? ` · ${note.workspace}` : ""}`)} ${highlight(note.snippet, colors, io)}`)].join("\n"));
977
+ if (blocks.length === 0) blocks.push(colors.dim(`no session matches "${question}"`));
978
+ if (pending) blocks.push(colors.dim("the index is still catching up: rucher find --reindex reads it all"));
979
+ io.stdout(`${blocks.join("\n\n")}\n`);
980
+ }
557
981
  // src/commands/log.ts
558
982
  function kindOf(event, kinds) {
559
- return event.agent ? kinds.get(event.agent) : void 0;
983
+ return (event.agentId !== null ? kinds.get(event.agentId) : void 0) ?? (event.agent ? kinds.get(event.agent) : void 0);
560
984
  }
561
985
  function formatEvents(events, io, kinds = /* @__PURE__ */ new Map()) {
562
986
  const colors = paint(io);
@@ -569,10 +993,15 @@ function formatEvents(events, io, kinds = /* @__PURE__ */ new Map()) {
569
993
  kind ? colors.dim(kindTag(kind)) : "",
570
994
  event.agent ?? "",
571
995
  event.link ?? event.note ?? "",
572
- event.commit ? colors.cyan(event.commit.slice(0, 7)) : ""
996
+ event.commit ? colors.cyan(event.commit.slice(0, 7)) : "",
997
+ usageText(event, (text) => colors.dim(text))
573
998
  ].filter(Boolean).join(" ");
574
999
  }).join("\n");
575
1000
  }
1001
+ function usageText(event, style = (text) => text) {
1002
+ const usage = eventUsage(event);
1003
+ return usage ? style(formatUsage(usage)) : "";
1004
+ }
576
1005
  function formatDay(date) {
577
1006
  const month = String(date.getMonth() + 1).padStart(2, "0");
578
1007
  const day = String(date.getDate()).padStart(2, "0");
@@ -586,7 +1015,8 @@ function markdownEvent(event, kinds) {
586
1015
  const detail = [
587
1016
  event.note,
588
1017
  event.link ? `[report](${event.link})` : null,
589
- event.commit ? `\`${event.commit.slice(0, 7)}\`` : null
1018
+ event.commit ? `\`${event.commit.slice(0, 7)}\`` : null,
1019
+ usageText(event) || null
590
1020
  ].filter(Boolean).join(" · ");
591
1021
  return `- ${parts.join(" ")}${detail ? `: ${detail}` : ""}`;
592
1022
  }
@@ -610,9 +1040,122 @@ function sessionTitle(carnet, session) {
610
1040
  function logOnce(carnet, io, options) {
611
1041
  const session = resolveSession(carnet, options.session);
612
1042
  const events = carnet.events.read(session.id, options.count, options.agents, options.kind);
613
- const kinds = new Map(carnet.agents.list(session.id, { includeClosed: true }).map((agent) => [agent.name, agent.kind]));
1043
+ const kinds = new Map(carnet.agents.list(session.id, { includeClosed: true }).map((agent) => [agent.id, agent.kind]));
614
1044
  io.stdout(`${options.md ? formatEventsMarkdown(events, sessionTitle(carnet, session), kinds) : formatEvents(events, io, kinds)}\n`);
615
1045
  }
1046
+ // src/hook-debug.ts
1047
+ const HOOK_DEBUG_FILE = "hook-debug.jsonl";
1048
+ function hookDebugPath(env) {
1049
+ return join(rucherPaths(env).state, HOOK_DEBUG_FILE);
1050
+ }
1051
+ function estimatedTokens(bytes) {
1052
+ return Math.ceil(bytes / 4);
1053
+ }
1054
+ function injectedText(output) {
1055
+ const parts = [];
1056
+ for (const line of output.split("\n")) {
1057
+ if (!line.trim()) continue;
1058
+ try {
1059
+ const specific = JSON.parse(line).hookSpecificOutput;
1060
+ const text = specific?.additionalContext ?? specific?.permissionDecisionReason;
1061
+ if (typeof text === "string") parts.push(text);
1062
+ } catch {
1063
+ parts.push(line);
1064
+ }
1065
+ }
1066
+ return parts.join("\n");
1067
+ }
1068
+ function sessionOf(stdinText) {
1069
+ try {
1070
+ const id = JSON.parse(stdinText).session_id;
1071
+ return typeof id === "string" ? id : null;
1072
+ } catch {
1073
+ return null;
1074
+ }
1075
+ }
1076
+ function runHookCommand(hook, run, stdinText, io) {
1077
+ if (io.env.RUCHER_HOOK_DEBUG !== "1") return run(stdinText, io);
1078
+ let output = "";
1079
+ const code = run(stdinText, {
1080
+ ...io,
1081
+ stdout: (text) => {
1082
+ output += text;
1083
+ io.stdout(text);
1084
+ }
1085
+ });
1086
+ const injected = injectedText(output);
1087
+ const bytes = Buffer.byteLength(injected);
1088
+ const entry = {
1089
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1090
+ hook,
1091
+ session: sessionOf(stdinText),
1092
+ injected,
1093
+ bytes,
1094
+ tokens: estimatedTokens(bytes)
1095
+ };
1096
+ try {
1097
+ const path = hookDebugPath(io.env);
1098
+ mkdirSync(dirname(path), { recursive: true });
1099
+ appendFileSync(path, `${JSON.stringify(entry)}\n`);
1100
+ } catch {}
1101
+ return code;
1102
+ }
1103
+ function hookDebugRows(entries) {
1104
+ const rows = /* @__PURE__ */ new Map();
1105
+ for (const entry of entries) {
1106
+ const row = rows.get(entry.hook) ?? {
1107
+ hook: entry.hook,
1108
+ calls: 0,
1109
+ injecting: 0,
1110
+ bytes: 0,
1111
+ tokens: 0
1112
+ };
1113
+ row.calls += 1;
1114
+ if (entry.bytes) row.injecting += 1;
1115
+ row.bytes += entry.bytes;
1116
+ row.tokens += entry.tokens;
1117
+ rows.set(entry.hook, row);
1118
+ }
1119
+ return [...rows.values()].sort((a, b) => b.tokens - a.tokens || a.hook.localeCompare(b.hook));
1120
+ }
1121
+ function readHookDebug(env, session) {
1122
+ const path = hookDebugPath(env);
1123
+ if (!existsSync(path)) return [];
1124
+ return readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)).filter((entry) => !session || entry.session?.startsWith(session));
1125
+ }
1126
+ function renderHookDebug(rows) {
1127
+ if (!rows.length) return "No hook output recorded (set RUCHER_HOOK_DEBUG=1).\n";
1128
+ const header = [
1129
+ "hook",
1130
+ "calls",
1131
+ "injecting",
1132
+ "bytes",
1133
+ "~tokens"
1134
+ ];
1135
+ const total = rows.reduce((sum, row) => ({
1136
+ hook: "total",
1137
+ calls: sum.calls + row.calls,
1138
+ injecting: sum.injecting + row.injecting,
1139
+ bytes: sum.bytes + row.bytes,
1140
+ tokens: sum.tokens + row.tokens
1141
+ }), {
1142
+ hook: "total",
1143
+ calls: 0,
1144
+ injecting: 0,
1145
+ bytes: 0,
1146
+ tokens: 0
1147
+ });
1148
+ const cells = [...rows, total].map((row) => [
1149
+ row.hook,
1150
+ String(row.calls),
1151
+ String(row.injecting),
1152
+ String(row.bytes),
1153
+ String(row.tokens)
1154
+ ]);
1155
+ const widths = header.map((title, i) => Math.max(title.length, ...cells.map((c) => c[i].length)));
1156
+ const line = (values) => values.map((value, i) => i ? value.padStart(widths[i]) : value.padEnd(widths[i])).join(" ");
1157
+ return `${[line(header), ...cells.map(line)].join("\n")}\n`;
1158
+ }
616
1159
  // src/commands/notes.ts
617
1160
  const KIND_TITLES = {
618
1161
  dead_end: "Dead ends",
@@ -633,6 +1176,21 @@ function parseNoteId(value) {
633
1176
  if (!Number.isInteger(id) || id <= 0) throw new CliError(`Invalid note id "${value}"`, "use the number shown by rucher notes, e.g. 14");
634
1177
  return id;
635
1178
  }
1179
+ function parseNoteIds(values) {
1180
+ const ids = [];
1181
+ for (const value of values.flatMap((part) => part.split(",")).filter(Boolean)) {
1182
+ const range = /^#?(\d+)-#?(\d+)$/.exec(value);
1183
+ if (!range) {
1184
+ ids.push(parseNoteId(value));
1185
+ continue;
1186
+ }
1187
+ const from = parseNoteId(range[1] ?? "");
1188
+ const to = parseNoteId(range[2] ?? "");
1189
+ if (to < from) throw new CliError(`Invalid range "${value}"`, "write the lower number first");
1190
+ for (let id = from; id <= to; id++) ids.push(id);
1191
+ }
1192
+ return ids;
1193
+ }
636
1194
  function halfLife(io) {
637
1195
  return memoryHalfLife(io.env["RUCHER_MEMORY_HALF_LIFE_DAYS"]);
638
1196
  }
@@ -683,7 +1241,7 @@ function notesList(carnet, io, options = {}) {
683
1241
  const blocks = grouped(notes).map(([kind, kindNotes]) => `${colors.bold(KIND_TITLES[kind])}\n${kindNotes.map((note) => noteLine(io, note)).join("\n")}`);
684
1242
  io.stdout(`${blocks.join("\n\n")}\n`);
685
1243
  }
686
- function sessionLabel$2(carnet, id) {
1244
+ function sessionLabel$1(carnet, id) {
687
1245
  if (!id) return "-";
688
1246
  return carnet.sessions.get(id)?.name ?? shortId(id);
689
1247
  }
@@ -698,7 +1256,7 @@ function notesShow(carnet, io, id) {
698
1256
  `${colors.bold(`#${note.id}`)} ${note.kind}${note.droppedAt ? colors.dim(" (dropped)") : ""}`,
699
1257
  note.text,
700
1258
  `repos: ${note.repos.length ? note.repos.join(", ") : "general"}`,
701
- `added: ${when(note.createdAt)} in ${sessionLabel$2(carnet, note.session)}${note.agent ? `, from ${note.agent}` : ""}`,
1259
+ `added: ${when(note.createdAt)} in ${sessionLabel$1(carnet, note.session)}${note.agent ? `, from ${note.agent}` : ""}`,
702
1260
  `weight: ${note.weight.toFixed(2)} · ${note.citationCount} citation${note.citationCount === 1 ? "" : "s"}`
703
1261
  ];
704
1262
  if (note.similarNotes.length) lines.push(colors.yellow(`similar to: ${note.similarNotes.map((other) => `#${other}`).join(", ")}`));
@@ -710,7 +1268,7 @@ function notesShow(carnet, io, id) {
710
1268
  lines.push("citations:");
711
1269
  for (const citation of note.citations) {
712
1270
  const by = citation.agent ? ` ${citation.agent}` : "";
713
- lines.push(` ${when(citation.at)} ${sessionLabel$2(carnet, citation.session)}${by} ${citation.why}`);
1271
+ lines.push(` ${when(citation.at)} ${sessionLabel$1(carnet, citation.session)}${by} ${citation.why}`);
714
1272
  }
715
1273
  }
716
1274
  io.stdout(`${lines.join("\n")}\n`);
@@ -727,10 +1285,21 @@ function notesAdd(carnet, io, input) {
727
1285
  io.stdout(`${colors.yellow("similar active notes, possible duplicate:")}\n${similar.map((other) => ` #${other.id} ${reposLabel(other)}${other.text}`).join("\n")}\n`);
728
1286
  }
729
1287
  }
730
- function notesDrop(carnet, io, id, input) {
731
- const note = carnet.notes.drop(id, input);
732
- const replaced = note.replacedBy ? `, replaced by #${note.replacedBy}` : "";
733
- io.stdout(`dropped #${note.id}${replaced}\n`);
1288
+ function notesDrop(carnet, io, ids, input) {
1289
+ if (ids.length === 1 && !input.dryRun) {
1290
+ const note = carnet.notes.drop(ids[0] ?? 0, input);
1291
+ const replaced = note.replacedBy ? `, replaced by #${note.replacedBy}` : "";
1292
+ io.stdout(`dropped #${note.id}${replaced}\n`);
1293
+ return;
1294
+ }
1295
+ if (input.replacedBy !== void 0) throw new CliError("--replaced-by takes a single note", "drop the other notes apart");
1296
+ const { dropped, skipped } = carnet.notes.dropMany(ids, {
1297
+ reason: input.reason,
1298
+ dryRun: input.dryRun
1299
+ });
1300
+ const verb = input.dryRun ? "would drop" : "dropped";
1301
+ const lines = [...dropped.map((note) => `${verb} #${note.id} ${reposLabel(note)}${note.text}`), ...skipped.map((skip) => `skipped #${skip.id}: ${skip.reason}`)];
1302
+ io.stdout(`${lines.join("\n")}\n`);
734
1303
  }
735
1304
  // src/commands/launch.ts
736
1305
  function splitPassthrough(rawArgs) {
@@ -747,142 +1316,73 @@ function splitPassthrough(rawArgs) {
747
1316
  function positionals(own) {
748
1317
  return own.filter((argument) => !argument.startsWith("-"));
749
1318
  }
750
- function launchEnv(workspace, session, promptVersion, kind) {
1319
+ function hostLaunch(plan, passthrough = []) {
1320
+ const command = launchHost(plan.host).command(plan, passthrough);
751
1321
  return {
752
- RUCHER_SESSION_ID: session.id,
753
- RUCHER_PROMPT_VERSION: promptVersion,
754
- RUCHER_SESSION_NAME: session.name ?? "",
755
- CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: "1",
756
- ...workspace ? { RUCHER_WS: workspace.name } : {},
757
- ...kind ? { RUCHER_SESSION_KIND: kind } : {}
1322
+ command: command.command,
1323
+ args: command.args,
1324
+ cwd: plan.cwd,
1325
+ env: {
1326
+ ...plan.env,
1327
+ ...command.env
1328
+ },
1329
+ plan
758
1330
  };
759
1331
  }
760
1332
  function planNew(carnet, io, options) {
761
- if (options.kind === "active" && !options.name) throw new CliError("An active session needs a name", withWorkspace("rucher new <name>", carnet.workspace?.name));
762
- const workspace = carnet.requireWorkspace();
763
- const session = carnet.sessions.create({
764
- id: randomUUID(),
1333
+ return hostLaunch(prepareNew(carnet, {
765
1334
  kind: options.kind,
766
1335
  name: options.name,
767
- cwd: workspace.runDirectory,
768
- repo: repoNameFor(workspace, io.cwd)
769
- });
770
- const host = hostById(session.host);
771
- renderRunDirectory(workspace, {
1336
+ repoCwd: io.cwd,
772
1337
  env: io.env,
773
- host: session.host
774
- });
775
- const prompt = appendPromptFile(workspace, session, io.env);
776
- return {
777
- ...host.launchCommand(session.id, {
778
- name: session.name,
779
- appendPromptFile: prompt.path,
780
- directories: repoDirectories(workspace),
781
- passthrough: options.passthrough
782
- }),
783
- cwd: workspace.runDirectory,
784
- env: launchEnv(workspace, session, prompt.version),
785
- sessionId: session.id
786
- };
787
- }
788
- function repoDirectories(workspace) {
789
- return (workspace?.repos ?? []).map((repo) => repo.path).filter((path) => existsSync(path));
790
- }
791
- function sessionWorkspace(carnet, session, env) {
792
- if (!isWorkspaceName(session.workspace)) return null;
793
- return carnet.workspace?.name === session.workspace ? carnet.workspace : loadWorkspace(session.workspace, env);
794
- }
795
- function prepareSession(carnet, session, env) {
796
- const workspace = sessionWorkspace(carnet, session, env);
797
- if (workspace) renderRunDirectory(workspace, {
798
- env,
799
- host: session.host
800
- });
801
- return workspace;
802
- }
803
- function sessionLabel$1(session) {
804
- return session.name ?? session.id.slice(0, 8);
1338
+ model: options.model
1339
+ }), options.passthrough);
805
1340
  }
806
- function sessionDirectory(session) {
807
- if (session.cwd && existsSync(session.cwd)) return session.cwd;
808
- throw new CarnetError("SESSION_CWD_MISSING", `The directory of session ${sessionLabel$1(session)} no longer exists: ${session.cwd ?? "none recorded"}`);
809
- }
810
- function planResume(carnet, io, reference, passthrough = []) {
1341
+ function planResume(carnet, io, reference, passthrough = [], model) {
811
1342
  const session = findSession(carnet, reference);
812
1343
  if (session.status === "archived") io.stderr(`warning: session ${reference} is archived\n`);
813
- const workspace = prepareSession(carnet, session, io.env);
814
- const cwd = sessionDirectory(session);
815
- const prompt = appendPromptFile(workspace, session, io.env);
816
- const host = hostById(session.host);
817
- const options = {
818
- appendPromptFile: prompt.path,
819
- directories: repoDirectories(workspace),
820
- passthrough
821
- };
822
- const fresh = !host.hasConversation(session, io.env);
823
- if (fresh) io.stderr(`no conversation yet for ${sessionLabel$1(session)}: starting it\n`);
1344
+ const { plan, notices } = prepareResume(carnet, session, io.env, { model });
1345
+ for (const notice of notices) io.stderr(notice);
1346
+ return hostLaunch(plan, passthrough);
1347
+ }
1348
+ function liveAttach(carnet, io, reference, live) {
1349
+ const session = findSession(carnet, reference);
1350
+ const host = launchHost(session.host);
1351
+ const found = (live ?? ((id) => host.liveSession?.(id, io.env)))(session.id);
1352
+ if (!found) return void 0;
1353
+ const label = session.name ?? session.id.slice(0, 8);
1354
+ if (found.kind === "interactive" || !host.attachCommand) throw new CliError(`Session ${label} is already open in another terminal`, `switch to that terminal, or branch a copy: rucher fork ${label}`);
1355
+ const command = host.attachCommand(found.id);
1356
+ io.stderr(`${label} is running in the background: attaching\n`);
824
1357
  return {
825
- ...fresh ? host.launchCommand(session.id, {
826
- name: session.name,
827
- ...options
828
- }) : host.resumeCommand(session, options),
829
- cwd,
830
- env: launchEnv(workspace, session, prompt.version),
831
- sessionId: session.id
1358
+ attach: true,
1359
+ ...command,
1360
+ cwd: io.cwd
832
1361
  };
833
1362
  }
834
1363
  function planFork(carnet, io, reference, options = {}) {
835
- if (options.active && !options.name) throw new CliError("An active fork needs a name", withWorkspace("rucher fork <session> <name> --active", carnet.workspace?.name));
836
- if (options.name && carnet.sessions.byName(options.name)) throw new CliError(`A session named "${options.name}" already exists`);
1364
+ checkForkOptions(carnet, options);
837
1365
  const parent = findSession(carnet, reference);
838
- if (!hostById(parent.host).hasConversation(parent, io.env)) {
839
- const label = sessionLabel$1(parent);
840
- throw new CliError(`Session ${label} has no conversation yet, nothing to fork`, withWorkspace(`rucher resume ${label}`, parent.workspace));
841
- }
842
- const workspace = prepareSession(carnet, parent, io.env);
843
- const cwd = sessionDirectory(parent);
844
- const kind = options.active ? "active" : "temp";
845
- return {
846
- ...hostById(parent.host).forkCommand(parent, {
847
- name: options.name,
848
- appendPromptFile: appendPromptFile(workspace, parent, io.env).path,
849
- directories: repoDirectories(workspace),
850
- passthrough: options.passthrough
851
- }),
852
- cwd,
853
- env: {
854
- ...launchEnv(workspace, parent, parent.promptVersion ?? "", kind),
855
- RUCHER_SESSION_NAME: options.name ?? ""
856
- },
857
- parentId: parent.id,
858
- knownChildren: childrenOf(carnet, parent.id).map((session) => session.id)
859
- };
860
- }
861
- function childrenOf(carnet, parentId) {
862
- return carnet.sessions.list({
863
- includeTemp: true,
864
- includeArchived: true
865
- }).filter((session) => session.parentId === parentId);
866
- }
867
- function forkChild(carnet, plan) {
868
- if (!plan.parentId) return void 0;
869
- const known = new Set(plan.knownChildren);
870
- return childrenOf(carnet, plan.parentId).find((session) => !known.has(session.id));
1366
+ return hostLaunch(prepareFork(carnet, parent, {
1367
+ name: options.name,
1368
+ active: options.active,
1369
+ env: io.env,
1370
+ model: options.model
1371
+ }), options.passthrough);
871
1372
  }
872
- function finishLaunch(carnet, plan) {
873
- const id = plan.sessionId ?? forkChild(carnet, plan)?.id;
874
- if (id && carnet.sessions.get(id)) carnet.sessions.end(id);
1373
+ function startLaunch(carnet, launch) {
1374
+ launchStarted(carnet, launch.plan);
875
1375
  }
876
- function startLaunch(carnet, plan) {
877
- if (plan.sessionId) carnet.sessions.setStatus(plan.sessionId, "running");
1376
+ function finishLaunch(carnet, launch) {
1377
+ launchEnded(carnet, launch.plan);
878
1378
  }
879
- function spawnLaunch(plan, env) {
880
- const result = spawnSync(plan.command, plan.args, {
881
- cwd: plan.cwd,
1379
+ function spawnLaunch(launch, env) {
1380
+ const result = spawnSync(launch.command, launch.args, {
1381
+ cwd: launch.cwd,
882
1382
  stdio: "inherit",
883
1383
  env: {
884
1384
  ...env,
885
- ...plan.env
1385
+ ...launch.env
886
1386
  }
887
1387
  });
888
1388
  if (result.error) throw result.error;
@@ -949,8 +1449,8 @@ function pick(items, lines, label) {
949
1449
  async function pickSession(carnet) {
950
1450
  const sessions = pickerSessions(carnet);
951
1451
  const workspace = carnet.workspace?.name;
952
- if (sessions.length === 0) throw new CliError("No session to resume in this workspace", withWorkspace("rucher new <name>", workspace));
953
- if (!process.stdin.isTTY) throw new CliError("No session given", withWorkspace("rucher resume <name, id or id prefix>", workspace));
1452
+ if (sessions.length === 0) throw new CliError("No session to resume in this workspace", withWorkspace$1("rucher new <name>", workspace));
1453
+ if (!process.stdin.isTTY) throw new CliError("No session given", withWorkspace$1("rucher resume <name, id or id prefix>", workspace));
954
1454
  const picked = await pick(sessions, pickerLines(sessions), "session");
955
1455
  if (!picked) throw new CliError("No session picked");
956
1456
  return picked;
@@ -977,6 +1477,35 @@ function workspaceLines(choices, now = /* @__PURE__ */ new Date()) {
977
1477
  async function pickWorkspace(choices) {
978
1478
  return (await pick(choices, workspaceLines(choices), "workspace"))?.name;
979
1479
  }
1480
+ // src/commands/ref.ts
1481
+ function refAdd(carnet, io, paths, options) {
1482
+ const session = resolveSession(carnet, options.session);
1483
+ for (const path of paths) {
1484
+ const reference = carnet.references.add(session.id, path, {
1485
+ agent: options.agent,
1486
+ cwd: io.cwd
1487
+ });
1488
+ const scope = options.agent ? `agent ${options.agent}` : "the session";
1489
+ io.stdout(`added to ${scope}: ${referenceLine(reference)}\n`);
1490
+ }
1491
+ }
1492
+ function refList(carnet, io, options) {
1493
+ const session = resolveSession(carnet, options.session);
1494
+ const references = carnet.references.list(session.id, {
1495
+ agent: options.agent,
1496
+ all: options.all
1497
+ });
1498
+ if (!references.length) {
1499
+ io.stdout(`${paint(io).dim("no reference documents")}\n`);
1500
+ return;
1501
+ }
1502
+ io.stdout(`${references.map(referenceLine).join("\n")}\n`);
1503
+ }
1504
+ function refRemove(carnet, io, idOrPath, options) {
1505
+ const session = resolveSession(carnet, options.session);
1506
+ const reference = carnet.references.remove(session.id, idOrPath);
1507
+ io.stdout(`removed: ${referenceLine(reference)}\n`);
1508
+ }
980
1509
  // src/commands/report.ts
981
1510
  function runEditor(editor, file) {
982
1511
  return spawnSync(`${editor} "$RUCHER_EDIT_FILE"`, {
@@ -1007,12 +1536,12 @@ function reportOnce(carnet, io, name, options) {
1007
1536
  io.stdout(`${colorHeadings(document.text, io)}\n`);
1008
1537
  return 0;
1009
1538
  }
1010
- // src/commands/serve.ts
1011
- function serve(io) {
1539
+ // src/commands/mcp.ts
1540
+ function runMcp(io) {
1012
1541
  serveCarnet({
1013
1542
  cwd: io.cwd,
1014
1543
  env: io.env,
1015
- sessionId: claudeCode.sessionIdFromEnvironment(io.env),
1544
+ sessionId: claudeCodeHooks.sessionIdFromEnvironment(io.env),
1016
1545
  afterTool: (carnet, sessionId) => refreshStatusLine(carnet, sessionId, io.env)
1017
1546
  });
1018
1547
  }
@@ -1070,7 +1599,7 @@ function sessionsMerge(carnet, fromReference, intoReference, io) {
1070
1599
  const lines = [
1071
1600
  `merged ${label(from)} into ${label(result.session)}`,
1072
1601
  ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
1073
- ...result.closedAgents.length ? [` agents closed (name already used): ${result.closedAgents.join(", ")}`] : [],
1602
+ ...result.closedAgents.length ? [` agents closed (name already open): ${result.closedAgents.join(", ")}`] : [],
1074
1603
  ` events moved: ${result.movedEvents}`,
1075
1604
  ` Main line moved: ${result.movedTable ? "yes" : "no"}`
1076
1605
  ];
@@ -1091,7 +1620,7 @@ function sessionsMove(carnet, reference, workspaceReference, io, options = {}) {
1091
1620
  const lines = [
1092
1621
  `${options.dryRun ? "would move" : "moved"} ${label(session)} from ${workspaceLabel(carnet.workspace)} to ${target}${into}`,
1093
1622
  ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
1094
- ...result.skippedAgents.length ? [` agents left out (name already used): ${result.skippedAgents.join(", ")}`] : [],
1623
+ ...result.skippedAgents.length ? [` agents closed (name already open): ${result.skippedAgents.join(", ")}`] : [],
1095
1624
  ` events moved: ${result.movedEvents}`,
1096
1625
  ` Main line moved: ${result.movedTable ? "yes" : "no"}`,
1097
1626
  ...result.keptNotes ? [` notes kept in ${workspaceLabel(carnet.workspace)}: ${result.keptNotes}`] : []
@@ -1110,8 +1639,9 @@ function sessionsDemote(carnet, reference, io) {
1110
1639
  const session = carnet.sessions.demote(findSession(carnet, reference).id);
1111
1640
  io.stdout(`${label(session)} is now temp, cleaned by rucher sessions clean once idle\n`);
1112
1641
  }
1113
- function purgeTranscripts(session, io) {
1114
- const files = hostById(session.host).transcriptFiles(session, io.env);
1642
+ function purgeTranscripts(carnet, session, io) {
1643
+ carnet.search.forgetTranscript(session.id);
1644
+ const files = hostById(session.host).launch?.transcriptFiles(session, io.env) ?? [];
1115
1645
  for (const file of files) {
1116
1646
  rmSync(file, {
1117
1647
  recursive: true,
@@ -1126,7 +1656,7 @@ function sessionsDrop(carnet, reference, io, options = {}) {
1126
1656
  if (options.purge && session.status === "running") throw new CliError(`Session ${label(session)} is running`, "drop it with --purge once it has ended");
1127
1657
  carnet.sessions.drop(session.id);
1128
1658
  io.stdout(`archived ${label(session)}\n`);
1129
- if (options.purge) purgeTranscripts(session, io);
1659
+ if (options.purge) purgeTranscripts(carnet, session, io);
1130
1660
  }
1131
1661
  const UNIT_MILLISECONDS = {
1132
1662
  m: 6e4,
@@ -1161,7 +1691,7 @@ function sessionsClean(carnet, io, options = {}) {
1161
1691
  }
1162
1692
  carnet.sessions.drop(session.id);
1163
1693
  io.stdout(`archived ${label(session)}\n`);
1164
- if (options.purge) purgeTranscripts(session, io);
1694
+ if (options.purge) purgeTranscripts(carnet, session, io);
1165
1695
  }
1166
1696
  }
1167
1697
  // src/commands/fit.ts
@@ -1651,17 +2181,42 @@ function carnetErrors(io, run) {
1651
2181
  }
1652
2182
  function rendered(workspace, io) {
1653
2183
  const result = renderRunDirectory(workspace, { env: io.env });
1654
- return [...result.written.map((path) => `written ${path}`), ...result.removed.map((path) => `removed ${path}`)];
2184
+ return [
2185
+ ...result.notices,
2186
+ ...result.written.map((path) => `written ${path}`),
2187
+ ...result.removed.map((path) => `removed ${path}`)
2188
+ ];
1655
2189
  }
1656
2190
  function withChanges(line, changes) {
1657
2191
  return `${line}${changes.length ? ` (${changes.join(", ")})` : ""}\n`;
1658
2192
  }
2193
+ const LOADING_LABELS = {
2194
+ native: "loaded by Claude Code",
2195
+ listed: "imported",
2196
+ skipped: "skipped"
2197
+ };
2198
+ function instructionLines(workspace, colors) {
2199
+ const context = workspaceContext(workspace, {
2200
+ nativeFiles: CLAUDE_NATIVE_FILES,
2201
+ workspaceText: false
2202
+ });
2203
+ const dim = (text) => colors.dim(text);
2204
+ const file = definitionInstructions(workspace);
2205
+ const lines = [` workspace: ${existsSync(join(workspace.definition, file)) ? file : dim("none")}`];
2206
+ if (existsSync(join(workspace.definition, CLAUDE_BACKEND_NOTES))) lines.push(` Claude Code only: ${CLAUDE_BACKEND_NOTES}`);
2207
+ for (const repo of context.repos) {
2208
+ const own = repo.own.map((file) => `${file.file} ${dim(`(${LOADING_LABELS[file.loading]})`)}`);
2209
+ lines.push(` ${repo.name}: yours ${repo.personal?.file ?? dim("none")}, the repo's ${own.length ? own.join(", ") : dim("none")}`);
2210
+ }
2211
+ for (const orphan of repoInstructionFiles(workspace).filter((file) => file.orphan)) lines.push(` ${orphan.repo}: ${join("repos", `${orphan.repo}.md`)} ${dim("(no such repo)")}`);
2212
+ return lines;
2213
+ }
1659
2214
  function workspaceShow(io, options = {}) {
1660
2215
  return carnetErrors(io, () => {
1661
2216
  const colors = paint(io);
1662
2217
  const workspace = currentWorkspace(io, options.workspace);
1663
2218
  const repos = workspace.repos.length ? workspace.repos.map((repo) => ` ${repo.name} ${colors.dim(repo.path)}`).join("\n") : ` ${colors.dim("none")}`;
1664
- io.stdout(`${colors.bold(workspace.name)}\ndefinition: ${workspace.definition}\nrun directory: ${workspace.runDirectory}\nrepos:\n${repos}\n`);
2219
+ io.stdout(`${colors.bold(workspace.name)}\ndefinition: ${workspace.definition}\nrun directory: ${workspace.runDirectory}\nrepos:\n${repos}\ninstructions:\n${instructionLines(workspace, colors).join("\n")}\n`);
1665
2220
  return 0;
1666
2221
  });
1667
2222
  }
@@ -1720,12 +2275,24 @@ function invalidWorkspaceFile(name, io) {
1720
2275
  return error instanceof Error ? error.message : String(error);
1721
2276
  }
1722
2277
  }
2278
+ function editedFile(workspace, options, io) {
2279
+ if (options.json) return join(workspace.definition, WORKSPACE_FILE);
2280
+ if (options.repo !== void 0) {
2281
+ if (!workspace.repos.some((repo) => repo.name === options.repo)) throw new CarnetError("REPO_NOT_FOUND", `${options.repo} is not a repo of ${workspace.name}: see "rucher ws show --ws ${workspace.name}"`);
2282
+ const file = repoInstructionsPath(workspace, options.repo);
2283
+ mkdirSync(dirname(file), { recursive: true });
2284
+ if (!existsSync(file)) writeFileSync(file, "");
2285
+ return file;
2286
+ }
2287
+ if (migrateInstructions(workspace)) io.stderr(`renamed CLAUDE.md to AGENTS.md in the definition of ${workspace.name}\n`);
2288
+ return join(workspace.definition, definitionInstructions(workspace));
2289
+ }
1723
2290
  async function workspaceEdit(io, options = {}) {
1724
2291
  let workspace;
1725
2292
  let file;
1726
2293
  try {
1727
2294
  workspace = currentWorkspace(io, options.workspace);
1728
- file = join(workspace.definition, options.json ? WORKSPACE_FILE : definitionInstructions(workspace));
2295
+ file = editedFile(workspace, options, io);
1729
2296
  } catch (error) {
1730
2297
  if (error instanceof CarnetError) {
1731
2298
  io.stderr(`error: ${error.message}\n`);
@@ -1749,8 +2316,13 @@ async function workspaceEdit(io, options = {}) {
1749
2316
  return 1;
1750
2317
  }
1751
2318
  }
2319
+ if (options.json) moveBackendsKey(file);
1752
2320
  return workspaceSync(io, { workspace: workspace.name });
1753
2321
  }
2322
+ function moveBackendsKey(file) {
2323
+ const content = JSON.parse(readFileSync(file, "utf8"));
2324
+ if ("backends" in content) writeFileSync(file, serializeWorkspaceFile(content));
2325
+ }
1754
2326
  function plural(count, word) {
1755
2327
  return `${count} ${word}${count === 1 ? "" : "s"}`;
1756
2328
  }
@@ -1889,7 +2461,8 @@ function mergePlanLines(plan) {
1889
2461
  ...plan.reposAdded.length ? [` repos added: ${plan.reposAdded.join(", ")}`] : [],
1890
2462
  ...plan.reposRenamed.map(([from, into]) => ` repo ${from} is ${into} in ${plan.into}`),
1891
2463
  ...plan.settingsConflicts.length ? [` settings kept from ${plan.into}: ${plan.settingsConflicts.join(", ")}`] : [],
1892
- ` ${plan.instructions} of ${plan.from} appended to ${plan.into}'s under ## Ex-workspace ${plan.from}`,
2464
+ ` ${plan.instructions} of ${plan.from} appended to ${plan.into}'s AGENTS.md under ## Ex-workspace ${plan.from}`,
2465
+ ...plan.repoInstructions.map((move) => ` repos/${basename(move.from)} of ${plan.from} appended to ${plan.into}'s repos/${basename(move.to)}`),
1893
2466
  ` Claude Code project folder of ${plan.from} merged into ${plan.into}'s (conversations, memory), trust entry dropped`,
1894
2467
  ...moveList("reports", plan.reports),
1895
2468
  ...moveList("sandboxes", plan.sandboxes),
@@ -2019,7 +2592,7 @@ function terminalKeys(input, output, owner = process) {
2019
2592
  // src/main.ts
2020
2593
  function fail(io, error) {
2021
2594
  if (error instanceof CliError) io.stderr(`error: ${error.message}${error.hint ? `\n ${error.hint}` : ""}\n`);
2022
- else if (error instanceof CarnetError) io.stderr(`error: ${error.message}\n`);
2595
+ else if (error instanceof CarnetError) io.stderr(`error: ${error.message}${error.hint ? `\n ${error.hint}` : ""}\n`);
2023
2596
  else io.stderr(`error: ${error instanceof Error ? error.message : String(error)}\n`);
2024
2597
  process.exit(1);
2025
2598
  }
@@ -2161,6 +2734,67 @@ const logCommand = defineCommand({
2161
2734
  }
2162
2735
  }
2163
2736
  });
2737
+ const findCommand = defineCommand({
2738
+ meta: {
2739
+ name: "find",
2740
+ description: "Find the sessions that talked about something, with where each one stands"
2741
+ },
2742
+ args: {
2743
+ question: {
2744
+ type: "positional",
2745
+ description: "What to look for",
2746
+ required: false
2747
+ },
2748
+ all: {
2749
+ type: "boolean",
2750
+ default: false,
2751
+ description: "Search every workspace"
2752
+ },
2753
+ limit: {
2754
+ type: "string",
2755
+ default: "5",
2756
+ description: "Number of sessions shown"
2757
+ },
2758
+ json: {
2759
+ type: "boolean",
2760
+ default: false,
2761
+ description: "JSON output"
2762
+ },
2763
+ reindex: {
2764
+ type: "boolean",
2765
+ default: false,
2766
+ description: "Rebuild the index of the workspace (every workspace with --all) first"
2767
+ },
2768
+ ...workspaceArgument,
2769
+ ...colorArgument
2770
+ },
2771
+ async setup({ args }) {
2772
+ if (!args.all) await askWorkspace({ args });
2773
+ },
2774
+ run({ args }) {
2775
+ const io = processIo({ color: args.color });
2776
+ try {
2777
+ const carnet = args.all ? openResolvedCarnet({
2778
+ cwd: io.cwd,
2779
+ env: io.env,
2780
+ workspace: args.ws
2781
+ }).carnet : openCliCarnet(io, args.ws);
2782
+ try {
2783
+ findOnce(carnet, io, {
2784
+ question: args.question,
2785
+ all: args.all,
2786
+ limit: Math.max(1, Number(args.limit) || 5),
2787
+ json: args.json,
2788
+ reindex: args.reindex
2789
+ });
2790
+ } finally {
2791
+ carnet.close();
2792
+ }
2793
+ } catch (error) {
2794
+ fail(io, error);
2795
+ }
2796
+ }
2797
+ });
2164
2798
  const reportCommand = defineCommand({
2165
2799
  meta: {
2166
2800
  name: "report",
@@ -2537,32 +3171,39 @@ const notesAddCommand = defineCommand({
2537
3171
  const notesDropCommand = defineCommand({
2538
3172
  meta: {
2539
3173
  name: "drop",
2540
- description: "Close a note that proved wrong, keeping it in the history"
3174
+ description: "Close notes that proved wrong or moved elsewhere, keeping them in the history"
2541
3175
  },
2542
3176
  args: {
2543
3177
  id: {
2544
3178
  type: "positional",
2545
- description: "Note number",
3179
+ description: "Note numbers or ranges, e.g. 14 or 1-60 101",
2546
3180
  required: true
2547
3181
  },
2548
3182
  reason: {
2549
3183
  type: "string",
2550
- description: "Why it is no longer true",
3184
+ description: "Why they no longer hold here",
2551
3185
  required: true
2552
3186
  },
2553
3187
  "replaced-by": {
2554
3188
  type: "string",
2555
3189
  description: "Number of the note that replaces it"
2556
3190
  },
3191
+ "dry-run": {
3192
+ type: "boolean",
3193
+ default: false,
3194
+ description: "List the notes, drop nothing"
3195
+ },
2557
3196
  ...workspaceArgument
2558
3197
  },
2559
3198
  setup: askWorkspace,
2560
3199
  run({ args }) {
2561
3200
  const io = processIo();
2562
3201
  const replacement = args["replaced-by"];
2563
- withCarnet(io, args.ws, (carnet) => notesDrop(carnet, io, parseNoteId(args.id), {
3202
+ const ids = parseNoteIds(args._.length ? args._ : [args.id]);
3203
+ withCarnet(io, args.ws, (carnet) => notesDrop(carnet, io, ids, {
2564
3204
  reason: args.reason,
2565
- replacedBy: replacement === void 0 ? void 0 : parseNoteId(replacement)
3205
+ replacedBy: replacement === void 0 ? void 0 : parseNoteId(replacement),
3206
+ dryRun: args["dry-run"]
2566
3207
  }));
2567
3208
  }
2568
3209
  });
@@ -2584,10 +3225,105 @@ const notesCommand = defineCommand({
2584
3225
  drop: notesDropCommand
2585
3226
  }
2586
3227
  });
3228
+ const refAddCommand = defineCommand({
3229
+ meta: {
3230
+ name: "add",
3231
+ description: "Attach markdown documents to the session, or to one agent"
3232
+ },
3233
+ args: {
3234
+ paths: {
3235
+ type: "positional",
3236
+ description: "Markdown files",
3237
+ required: true
3238
+ },
3239
+ agent: {
3240
+ type: "string",
3241
+ description: "An open agent: only its brief gets the documents"
3242
+ },
3243
+ ...sessionArgument,
3244
+ ...workspaceArgument
3245
+ },
3246
+ setup: askWorkspace,
3247
+ run({ args }) {
3248
+ const io = processIo();
3249
+ withCarnet(io, args.ws, (carnet) => refAdd(carnet, io, args._, {
3250
+ session: args.session,
3251
+ agent: args.agent
3252
+ }));
3253
+ }
3254
+ });
3255
+ const refListCommand = defineCommand({
3256
+ meta: {
3257
+ name: "list",
3258
+ description: "Reference documents of the session: title, path, size"
3259
+ },
3260
+ args: {
3261
+ agent: {
3262
+ type: "string",
3263
+ description: "Also the documents of this agent"
3264
+ },
3265
+ all: {
3266
+ type: "boolean",
3267
+ default: false,
3268
+ description: "Include removed documents"
3269
+ },
3270
+ ...sessionArgument,
3271
+ ...workspaceArgument,
3272
+ ...colorArgument
3273
+ },
3274
+ setup: askWorkspace,
3275
+ run({ args }) {
3276
+ const io = processIo({ color: args.color });
3277
+ withCarnet(io, args.ws, (carnet) => refList(carnet, io, {
3278
+ session: args.session,
3279
+ agent: args.agent,
3280
+ all: args.all
3281
+ }));
3282
+ }
3283
+ });
3284
+ const refRemoveCommand = defineCommand({
3285
+ meta: {
3286
+ name: "remove",
3287
+ description: "Detach a reference document, by number or path"
3288
+ },
3289
+ args: {
3290
+ ref: {
3291
+ type: "positional",
3292
+ description: "Reference number or path",
3293
+ required: true
3294
+ },
3295
+ ...sessionArgument,
3296
+ ...workspaceArgument
3297
+ },
3298
+ setup: askWorkspace,
3299
+ run({ args }) {
3300
+ const io = processIo();
3301
+ withCarnet(io, args.ws, (carnet) => refRemove(carnet, io, args.ref, { session: args.session }));
3302
+ }
3303
+ });
3304
+ const refCommand = defineCommand({
3305
+ meta: {
3306
+ name: "ref",
3307
+ description: "Reference documents (specs, tickets) agents read by path, never copied"
3308
+ },
3309
+ args: { ...workspaceArgument },
3310
+ setup: forwardWorkspace,
3311
+ default: "list",
3312
+ subCommands: {
3313
+ list: refListCommand,
3314
+ add: refAddCommand,
3315
+ remove: refRemoveCommand
3316
+ }
3317
+ });
2587
3318
  async function launch(io, workspace, plan) {
2588
3319
  try {
2589
3320
  const carnet = openCliCarnet(io, workspace);
2590
3321
  const launchPlan = await plan(carnet);
3322
+ if ("attach" in launchPlan) {
3323
+ carnet.close();
3324
+ process.exitCode = spawnLaunch(launchPlan, io.env);
3325
+ return;
3326
+ }
2591
3327
  startLaunch(carnet, launchPlan);
2592
3328
  carnet.close();
2593
3329
  const exitCode = spawnLaunch(launchPlan, io.env);
@@ -2674,7 +3410,7 @@ const resumeCommand = defineCommand({
2674
3410
  const io = processIo();
2675
3411
  await launch(io, args.ws, async (carnet) => {
2676
3412
  const reference = positionals(withoutWorkspaceOption(own))[0] ?? (await pickSession(carnet)).id;
2677
- return planResume(carnet, io, reference, passthrough);
3413
+ return liveAttach(carnet, io, reference) ?? planResume(carnet, io, reference, passthrough);
2678
3414
  });
2679
3415
  }
2680
3416
  });
@@ -2875,7 +3611,7 @@ const wsCommand = defineCommand({
2875
3611
  show: defineCommand({
2876
3612
  meta: {
2877
3613
  name: "show",
2878
- description: "Name, definition, run directory and repos of the workspace"
3614
+ description: "Name, definition, run directory, repos and instruction files of the workspace"
2879
3615
  },
2880
3616
  args: {
2881
3617
  ...workspaceNameArgument,
@@ -2943,7 +3679,7 @@ const wsCommand = defineCommand({
2943
3679
  edit: defineCommand({
2944
3680
  meta: {
2945
3681
  name: "edit",
2946
- description: "Open the instructions (or workspace.json with --json) in $EDITOR, then sync"
3682
+ description: "Open the instructions (a repo's with --repo, workspace.json with --json) in $EDITOR, then sync"
2947
3683
  },
2948
3684
  args: {
2949
3685
  ...workspaceNameArgument,
@@ -2952,6 +3688,10 @@ const wsCommand = defineCommand({
2952
3688
  default: false,
2953
3689
  description: "Edit workspace.json instead"
2954
3690
  },
3691
+ repo: {
3692
+ type: "string",
3693
+ description: "Edit your own instructions for this repo of the workspace instead"
3694
+ },
2955
3695
  ...workspaceArgument
2956
3696
  },
2957
3697
  setup: askNamedWorkspace,
@@ -2959,6 +3699,7 @@ const wsCommand = defineCommand({
2959
3699
  process.exitCode = await workspaceEdit(processIo(), {
2960
3700
  workspace: namedWorkspace(args),
2961
3701
  json: args.json,
3702
+ repo: args.repo,
2962
3703
  confirm: askYes
2963
3704
  });
2964
3705
  }
@@ -2992,6 +3733,129 @@ const wsCommand = defineCommand({
2992
3733
  })
2993
3734
  }
2994
3735
  });
3736
+ const configCommand = defineCommand({
3737
+ meta: {
3738
+ name: "config",
3739
+ description: "The run configuration: global file path, resolved values and their sources, checks"
3740
+ },
3741
+ default: "show",
3742
+ subCommands: {
3743
+ path: defineCommand({
3744
+ meta: {
3745
+ name: "path",
3746
+ description: "Print the path of the global config file"
3747
+ },
3748
+ run() {
3749
+ process.exitCode = configPath(processIo());
3750
+ }
3751
+ }),
3752
+ show: defineCommand({
3753
+ meta: {
3754
+ name: "show",
3755
+ description: "Resolved config of the workspace, and the backend and model of each kind"
3756
+ },
3757
+ args: {
3758
+ ...workspaceArgument,
3759
+ ...kindArgument,
3760
+ sources: {
3761
+ type: "boolean",
3762
+ default: false,
3763
+ description: "Show the level and source that set each key"
3764
+ },
3765
+ json: {
3766
+ type: "boolean",
3767
+ default: false,
3768
+ description: "Print JSON"
3769
+ },
3770
+ ...colorArgument
3771
+ },
3772
+ run({ args }) {
3773
+ process.exitCode = configShow(processIo({ color: args.color }), {
3774
+ workspace: args.ws,
3775
+ kind: args.kind,
3776
+ sources: args.sources,
3777
+ json: args.json
3778
+ });
3779
+ }
3780
+ }),
3781
+ check: defineCommand({
3782
+ meta: {
3783
+ name: "check",
3784
+ description: "Check the global config and every workspace config (or the one given)"
3785
+ },
3786
+ args: { ...workspaceArgument },
3787
+ run({ args }) {
3788
+ process.exitCode = configCheck(processIo(), { workspace: args.ws });
3789
+ }
3790
+ })
3791
+ }
3792
+ });
3793
+ const profilesCommand = defineCommand({
3794
+ meta: {
3795
+ name: "profiles",
3796
+ description: "Autonomy profiles: built-in, yours and the workspace's, resolved and checked"
3797
+ },
3798
+ default: "list",
3799
+ subCommands: {
3800
+ list: defineCommand({
3801
+ meta: {
3802
+ name: "list",
3803
+ description: "Profiles of the workspace, with their layer and notes"
3804
+ },
3805
+ args: {
3806
+ ...workspaceArgument,
3807
+ json: {
3808
+ type: "boolean",
3809
+ default: false,
3810
+ description: "Print JSON"
3811
+ },
3812
+ ...colorArgument
3813
+ },
3814
+ run({ args }) {
3815
+ process.exitCode = profilesList(processIo({ color: args.color }), {
3816
+ workspace: args.ws,
3817
+ json: args.json
3818
+ });
3819
+ }
3820
+ }),
3821
+ show: defineCommand({
3822
+ meta: {
3823
+ name: "show",
3824
+ description: "Resolved keys of a profile, the definition that set each one, and its notes"
3825
+ },
3826
+ args: {
3827
+ name: {
3828
+ type: "positional",
3829
+ required: true,
3830
+ description: "Profile name"
3831
+ },
3832
+ ...workspaceArgument,
3833
+ json: {
3834
+ type: "boolean",
3835
+ default: false,
3836
+ description: "Print JSON"
3837
+ },
3838
+ ...colorArgument
3839
+ },
3840
+ run({ args }) {
3841
+ process.exitCode = profilesShow(processIo({ color: args.color }), args.name, {
3842
+ workspace: args.ws,
3843
+ json: args.json
3844
+ });
3845
+ }
3846
+ }),
3847
+ check: defineCommand({
3848
+ meta: {
3849
+ name: "check",
3850
+ description: "Check your profiles and every workspace's (or the one given)"
3851
+ },
3852
+ args: { ...workspaceArgument },
3853
+ run({ args }) {
3854
+ process.exitCode = profilesCheck(processIo(), { workspace: args.ws });
3855
+ }
3856
+ })
3857
+ }
3858
+ });
2995
3859
  const hookCommand = defineCommand({
2996
3860
  meta: {
2997
3861
  name: "hook",
@@ -3004,7 +3868,7 @@ const hookCommand = defineCommand({
3004
3868
  description: "SessionStart hook: records the session"
3005
3869
  },
3006
3870
  async run() {
3007
- process.exitCode = sessionStart(await readStdin(), processIo());
3871
+ process.exitCode = runHookCommand("session-start", sessionStart, await readStdin(), processIo());
3008
3872
  }
3009
3873
  }),
3010
3874
  "session-end": defineCommand({
@@ -3013,7 +3877,7 @@ const hookCommand = defineCommand({
3013
3877
  description: "SessionEnd hook: marks the session idle"
3014
3878
  },
3015
3879
  async run() {
3016
- process.exitCode = sessionEnd(await readStdin(), processIo());
3880
+ process.exitCode = runHookCommand("session-end", sessionEnd, await readStdin(), processIo());
3017
3881
  }
3018
3882
  }),
3019
3883
  "pre-tool-use": defineCommand({
@@ -3022,7 +3886,7 @@ const hookCommand = defineCommand({
3022
3886
  description: "PreToolUse hook: marks the main turn as waiting on the human"
3023
3887
  },
3024
3888
  async run() {
3025
- process.exitCode = preToolUse(await readStdin(), processIo());
3889
+ process.exitCode = runHookCommand("pre-tool-use", preToolUse, await readStdin(), processIo());
3026
3890
  }
3027
3891
  }),
3028
3892
  stop: defineCommand({
@@ -3031,7 +3895,7 @@ const hookCommand = defineCommand({
3031
3895
  description: "Stop hook: ends the main agent's turn"
3032
3896
  },
3033
3897
  async run() {
3034
- process.exitCode = stopHook(await readStdin(), processIo());
3898
+ process.exitCode = runHookCommand("stop", stopHook, await readStdin(), processIo());
3035
3899
  }
3036
3900
  }),
3037
3901
  "post-tool-use": defineCommand({
@@ -3040,7 +3904,7 @@ const hookCommand = defineCommand({
3040
3904
  description: "PostToolUse hook: marks the main turn working, adds a repo's notes the first time a tool touches it"
3041
3905
  },
3042
3906
  async run() {
3043
- process.exitCode = postToolUse(await readStdin(), processIo());
3907
+ process.exitCode = runHookCommand("post-tool-use", postToolUse, await readStdin(), processIo());
3044
3908
  }
3045
3909
  }),
3046
3910
  "user-prompt-submit": defineCommand({
@@ -3049,7 +3913,7 @@ const hookCommand = defineCommand({
3049
3913
  description: "UserPromptSubmit hook: starts the main turn, names the session after a /rename"
3050
3914
  },
3051
3915
  async run() {
3052
- process.exitCode = userPromptSubmit(await readStdin(), processIo());
3916
+ process.exitCode = runHookCommand("user-prompt-submit", userPromptSubmit, await readStdin(), processIo());
3053
3917
  }
3054
3918
  }),
3055
3919
  "subagent-start": defineCommand({
@@ -3058,7 +3922,32 @@ const hookCommand = defineCommand({
3058
3922
  description: "SubagentStart hook: pairs the fork with its agent"
3059
3923
  },
3060
3924
  async run() {
3061
- process.exitCode = subagentStart(await readStdin(), processIo());
3925
+ process.exitCode = runHookCommand("subagent-start", subagentStart, await readStdin(), processIo());
3926
+ }
3927
+ }),
3928
+ debug: defineCommand({
3929
+ meta: {
3930
+ name: "debug",
3931
+ description: "What the hooks injected while RUCHER_HOOK_DEBUG=1: calls, bytes and estimated tokens per hook"
3932
+ },
3933
+ args: {
3934
+ session: {
3935
+ type: "string",
3936
+ description: "Only this session (id or id prefix)"
3937
+ },
3938
+ clear: {
3939
+ type: "boolean",
3940
+ description: "Empty the debug log"
3941
+ }
3942
+ },
3943
+ run({ args }) {
3944
+ const io = processIo();
3945
+ if (args.clear) {
3946
+ rmSync(hookDebugPath(io.env), { force: true });
3947
+ return;
3948
+ }
3949
+ io.stdout(renderHookDebug(hookDebugRows(readHookDebug(io.env, args.session))));
3950
+ io.stdout(`log: ${hookDebugPath(io.env)}\n`);
3062
3951
  }
3063
3952
  }),
3064
3953
  "subagent-stop": defineCommand({
@@ -3067,7 +3956,7 @@ const hookCommand = defineCommand({
3067
3956
  description: "SubagentStop hook: flags a fork that never called agent_done"
3068
3957
  },
3069
3958
  async run() {
3070
- process.exitCode = subagentStop(await readStdin(), processIo());
3959
+ process.exitCode = runHookCommand("subagent-stop", subagentStop, await readStdin(), processIo());
3071
3960
  }
3072
3961
  })
3073
3962
  }
@@ -3089,13 +3978,13 @@ const statusLineCommand = defineCommand({
3089
3978
  process.exitCode = statusLine(await readStdin(), processIo());
3090
3979
  }
3091
3980
  });
3092
- const serveCommand = defineCommand({
3981
+ const mcpCommand = defineCommand({
3093
3982
  meta: {
3094
- name: "serve",
3983
+ name: "mcp",
3095
3984
  description: "Run the Carnet MCP server over stdio"
3096
3985
  },
3097
3986
  run() {
3098
- serve(processIo());
3987
+ runMcp(processIo());
3099
3988
  }
3100
3989
  });
3101
3990
  const main = defineCommand({
@@ -3107,6 +3996,7 @@ const main = defineCommand({
3107
3996
  subCommands: {
3108
3997
  status: statusCommand,
3109
3998
  log: logCommand,
3999
+ find: findCommand,
3110
4000
  report: reportCommand,
3111
4001
  new: newCommand,
3112
4002
  tmp: tmpCommand,
@@ -3114,10 +4004,14 @@ const main = defineCommand({
3114
4004
  fork: forkCommand,
3115
4005
  sessions: sessionsCommand,
3116
4006
  notes: notesCommand,
4007
+ ref: refCommand,
3117
4008
  ws: wsCommand,
4009
+ config: configCommand,
4010
+ profiles: profilesCommand,
3118
4011
  hook: hookCommand,
3119
4012
  statusline: statusLineCommand,
3120
- serve: serveCommand
4013
+ mcp: mcpCommand,
4014
+ serve: mcpCommand
3121
4015
  }
3122
4016
  });
3123
4017
  // src/cli.ts