@rucher/cli 0.2.0 → 0.3.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 +1 -1
  2. package/dist/cli.mjs +790 -137
  3. package/package.json +2 -2
package/dist/cli.mjs CHANGED
@@ -3,8 +3,9 @@ import { defineCommand, runMain } from "citty";
3
3
  import { existsSync, 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 { CarnetError, LEGEND, NOTES_HEADER, NOTE_KINDS, SIMILAR_PREFIX, SUBAGENT_RULES, WORKSPACE_FILE, addWorkspaceRepo, ambiguousWorkspaceContext, appendPromptFile, archiveWorkspaceSessions, claudeCode, createWorkspace, definitionInstructions, deleteWorkspaceNotes, dropWorkspace, formatClock, handleSessionEnd, handleSessionStart, handleToolUse, handleUserPromptSubmit, hostById, isWorkspaceName, listWorkspaces, loadWorkspace, memoryHalfLife, moveSession, openCarnet, openResolvedCarnet, openWorkspaceCarnet, removeWorkspaceRepo, renderRunDirectory, renderSections, repoNameFor, repoPathFor, requireWorkspace, resolveWorkspace, shortId, workspaceExists, workspaceLabel, workspaceRepoNames, workspaceSessionCounts } from "@rucher/carnet";
7
- import { styleText } from "node:util";
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";
8
+ import { stripVTControlCharacters, styleText } from "node:util";
8
9
  import { spawnSync } from "node:child_process";
9
10
  import { randomUUID } from "node:crypto";
10
11
  import { createInterface } from "node:readline/promises";
@@ -78,6 +79,9 @@ function suggestRepoNames(context, complete) {
78
79
  function suggestNoteKinds(complete) {
79
80
  for (const kind of NOTE_KINDS) complete(kind, "");
80
81
  }
82
+ function suggestAgentKinds(complete) {
83
+ for (const kind of AGENT_KINDS) complete(kind, "");
84
+ }
81
85
  function suggestNotes(context, complete) {
82
86
  quietly(() => {
83
87
  const carnet = openCarnet(inWorkspace(context));
@@ -88,6 +92,24 @@ function suggestNotes(context, complete) {
88
92
  }
89
93
  });
90
94
  }
95
+ function suggestAgents(context, complete) {
96
+ quietly(() => {
97
+ const carnet = openCarnet(inWorkspace(context));
98
+ try {
99
+ const seen = /* @__PURE__ */ new Set();
100
+ for (const session of carnet.sessions.list({ includeTemp: true })) {
101
+ const label = session.name ?? shortId(session.id);
102
+ for (const agent of carnet.agents.list(session.id, { includeClosed: true })) {
103
+ if (seen.has(agent.name)) continue;
104
+ seen.add(agent.name);
105
+ complete(agent.name, agent.task ? `${agent.task} · ${label}` : label);
106
+ }
107
+ }
108
+ } finally {
109
+ carnet.close();
110
+ }
111
+ });
112
+ }
91
113
  function suggestDirectories(context, complete) {
92
114
  quietly(() => {
93
115
  const partial = context.typedWords.at(-1) ?? "";
@@ -110,17 +132,28 @@ const repos = (complete) => suggestRepos(processContext(), complete);
110
132
  const directories = (complete) => suggestDirectories(processContext(), complete);
111
133
  const repoNames = (complete) => suggestRepoNames(processContext(), complete);
112
134
  const noteKinds = (complete) => suggestNoteKinds(complete);
135
+ const agentKinds = (complete) => suggestAgentKinds(complete);
113
136
  const notes = (complete) => suggestNotes(processContext(), complete);
137
+ const agents = (complete) => suggestAgents(processContext(), complete);
114
138
  const workspace = { ws: workspaces };
115
139
  const completionConfig = { subCommands: {
116
140
  status: { options: {
117
141
  session: sessions,
142
+ kind: agentKinds,
118
143
  ...workspace
119
144
  } },
120
145
  log: { options: {
121
146
  session: sessions,
147
+ kind: agentKinds,
122
148
  ...workspace
123
149
  } },
150
+ report: {
151
+ args: { name: agents },
152
+ options: {
153
+ session: sessions,
154
+ ...workspace
155
+ }
156
+ },
124
157
  new: { options: workspace },
125
158
  tmp: { options: workspace },
126
159
  resume: {
@@ -203,6 +236,11 @@ const completionConfig = { subCommands: {
203
236
  ws: {
204
237
  options: workspace,
205
238
  subCommands: {
239
+ rename: { args: { old: workspaces } },
240
+ merge: { args: {
241
+ from: workspaces,
242
+ into: workspaces
243
+ } },
206
244
  drop: { args: { name: workspaces } },
207
245
  show: { options: workspace },
208
246
  add: {
@@ -239,25 +277,80 @@ async function setupCompletion(main) {
239
277
  };
240
278
  }
241
279
  // package.json
242
- var version = "0.2.0";
280
+ var version = "0.3.0-beta.0";
281
+ // src/plugin.ts
282
+ const CLI_VERSION = version;
283
+ function readJson(path) {
284
+ try {
285
+ return JSON.parse(readFileSync(path, "utf8"));
286
+ } catch {
287
+ return;
288
+ }
289
+ }
290
+ function installedPlugin(env) {
291
+ const root = env.CLAUDE_PLUGIN_ROOT;
292
+ if (!root) return {
293
+ version: null,
294
+ endsTurns: true
295
+ };
296
+ const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
297
+ const hooks = readJson(join(root, "hooks", "hooks.json"));
298
+ return {
299
+ version: typeof manifest?.version === "string" ? manifest.version : null,
300
+ endsTurns: Boolean(hooks?.hooks && "Stop" in hooks.hooks)
301
+ };
302
+ }
303
+ function parse(version) {
304
+ const [core = "", ...pre] = version.split("-");
305
+ return {
306
+ core: core.split(".").map(Number),
307
+ pre: pre.length > 0 ? pre.join("-") : null
308
+ };
309
+ }
310
+ function isOlderVersion(version, than) {
311
+ const a = parse(version);
312
+ const b = parse(than);
313
+ for (let index = 0; index < 3; index += 1) {
314
+ const diff = (a.core[index] ?? 0) - (b.core[index] ?? 0);
315
+ if (diff !== 0) return diff < 0;
316
+ }
317
+ if (a.pre === b.pre) return false;
318
+ if (a.pre === null) return false;
319
+ if (b.pre === null) return true;
320
+ return a.pre.localeCompare(b.pre, void 0, { numeric: true }) < 0;
321
+ }
322
+ function pluginLagNotice(version) {
323
+ if (!version || !isOlderVersion(version, CLI_VERSION)) return null;
324
+ return `rucher plugin ${version} is behind the CLI ${CLI_VERSION}: update the plugin, then restart the session`;
325
+ }
326
+ // src/status-line.ts
327
+ const LAG_LINE = "plugin behind the CLI: update it";
328
+ function refreshStatusLine(carnet, sessionId, env) {
329
+ try {
330
+ const version = carnet.sessions.get(sessionId)?.pluginVersion ?? null;
331
+ const lag = version && isOlderVersion(version, CLI_VERSION) ? LAG_LINE : null;
332
+ writeStatusLine(carnet, sessionId, {
333
+ env,
334
+ lag
335
+ });
336
+ } catch {
337
+ return;
338
+ }
339
+ }
340
+ function readStatusLine(sessionId, env) {
341
+ try {
342
+ return readFileSync(statusLinePath(sessionId, env), "utf8").trimEnd();
343
+ } catch {
344
+ return "";
345
+ }
346
+ }
243
347
  // src/commands/hook.ts
244
348
  const host = claudeCode;
245
- function runHook(io, run, hookEventName) {
349
+ function runHook(io, run) {
246
350
  try {
247
351
  run();
248
352
  } catch (error) {
249
353
  if (error instanceof CarnetError && error.code === "NO_WORKSPACE") return 0;
250
- if (error instanceof CarnetError && error.code === "WORKSPACE_AMBIGUOUS") {
251
- if (hookEventName) {
252
- io.stderr(`rucher: ${error.message}\n`);
253
- const additionalContext = ambiguousWorkspaceContext(error.message);
254
- io.stdout(`${JSON.stringify({ hookSpecificOutput: {
255
- hookEventName,
256
- additionalContext
257
- } })}\n`);
258
- }
259
- return 0;
260
- }
261
354
  io.stderr(`rucher hook: ${error instanceof Error ? error.message : String(error)}\n`);
262
355
  }
263
356
  return 0;
@@ -270,8 +363,9 @@ function withCarnet$1(payload, io, use) {
270
363
  });
271
364
  try {
272
365
  const known = payload.session_id ? carnet.sessions.get(payload.session_id) : void 0;
273
- if (!carnet.workspace && !io.env.RUCHER_SESSION_ID && !known) return;
366
+ if (!carnet.workspace && !known) return;
274
367
  use(carnet);
368
+ if (payload.session_id) refreshStatusLine(carnet, payload.session_id, io.env);
275
369
  } finally {
276
370
  carnet.close();
277
371
  }
@@ -290,24 +384,28 @@ function sessionStart(stdinText, io) {
290
384
  RUCHER_SESSION_NAME: io.env.RUCHER_SESSION_NAME,
291
385
  RUCHER_PROMPT_VERSION: io.env.RUCHER_PROMPT_VERSION,
292
386
  RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
293
- RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
387
+ RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS,
388
+ CLAUDE_CONFIG_DIR: io.env.CLAUDE_CONFIG_DIR
294
389
  });
295
390
  for (const notice of notices) io.stderr(`${notice}\n`);
296
- if (additionalContext) {
391
+ const { version } = installedPlugin(io.env);
392
+ carnet.sessions.recordPluginVersion(payload.session_id, version);
393
+ const context = [additionalContext, pluginLagNotice(version)].filter(Boolean).join("\n\n");
394
+ if (context) {
297
395
  const hookSpecificOutput = {
298
396
  hookEventName: "SessionStart",
299
- additionalContext
397
+ additionalContext: context
300
398
  };
301
399
  io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
302
400
  }
303
401
  });
304
- }, "SessionStart");
402
+ });
305
403
  }
306
404
  function subagentStart(stdinText, io) {
307
405
  return runHook(io, () => {
308
406
  const payload = host.parseSubagentPayload(stdinText);
309
407
  withCarnet$1(payload, io, (carnet) => {
310
- carnet.agents.pairSubagent(payload.session_id, payload.agent_id);
408
+ carnet.agents.pairSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload), payload.agent_type);
311
409
  });
312
410
  if (host.subagentInheritsContext(payload)) return;
313
411
  const hookSpecificOutput = {
@@ -329,19 +427,19 @@ function userPromptSubmit(stdinText, io) {
329
427
  return runHook(io, () => {
330
428
  const payload = host.parsePromptPayload(stdinText);
331
429
  withCarnet$1(payload, io, (carnet) => {
332
- handleUserPromptSubmit(carnet, host, payload);
430
+ handleUserPromptSubmit(carnet, host, payload, { trackTurn: installedPlugin(io.env).endsTurns });
333
431
  });
334
- }, "UserPromptSubmit");
432
+ });
335
433
  }
336
434
  function postToolUse(stdinText, io) {
337
435
  return runHook(io, () => {
338
436
  const payload = host.parseToolPayload(stdinText);
339
- if (payload.agent_id || !payload.path) return;
437
+ if (payload.agent_id) return;
340
438
  withCarnet$1(payload, io, (carnet) => {
341
439
  const additionalContext = handleToolUse(carnet, payload, {
342
440
  RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
343
441
  RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
344
- });
442
+ }, { trackTurn: installedPlugin(io.env).endsTurns });
345
443
  if (!additionalContext) return;
346
444
  const hookSpecificOutput = {
347
445
  hookEventName: "PostToolUse",
@@ -359,6 +457,44 @@ function sessionEnd(stdinText, io) {
359
457
  });
360
458
  });
361
459
  }
460
+ function scratchRoots(io) {
461
+ const folder = `claude-${process.getuid?.() ?? 0}`;
462
+ const parents = [
463
+ io.env.CLAUDE_CODE_TMPDIR,
464
+ process.platform === "win32" ? void 0 : "/tmp",
465
+ tmpdir()
466
+ ].filter((parent) => Boolean(parent));
467
+ return [...new Set(parents.map((parent) => join(parent, folder)))];
468
+ }
469
+ function denyToolCall(io, reason) {
470
+ const hookSpecificOutput = {
471
+ hookEventName: "PreToolUse",
472
+ permissionDecision: "deny",
473
+ permissionDecisionReason: reason
474
+ };
475
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
476
+ }
477
+ function preToolUse(stdinText, io) {
478
+ return runHook(io, () => {
479
+ const payload = host.parseToolPayload(stdinText);
480
+ const tool = payload.tool_name ?? "";
481
+ const guarded = Boolean(payload.agent_id) && GUARDED_TOOLS.has(tool);
482
+ const launch = !payload.agent_id && LAUNCH_TOOLS.has(tool);
483
+ if (!guarded && !launch && (payload.agent_id || tool !== WAITING_TOOL)) return;
484
+ withCarnet$1(payload, io, (carnet) => {
485
+ const reason = guarded ? guardSubagentCall(carnet, payload, scratchRoots(io)) : launch ? guardMainLaunch(carnet, payload) : handleToolStart(carnet, payload);
486
+ if (reason) denyToolCall(io, reason);
487
+ });
488
+ });
489
+ }
490
+ function stopHook(stdinText, io) {
491
+ return runHook(io, () => {
492
+ const payload = host.parseStopPayload(stdinText);
493
+ withCarnet$1(payload, io, (carnet) => {
494
+ handleStop(carnet, payload);
495
+ });
496
+ });
497
+ }
362
498
  // src/color.ts
363
499
  function paint(io) {
364
500
  const style = (name) => (text) => io.color ? styleText(name, text, { validateStream: false }) : text;
@@ -379,29 +515,37 @@ var CliError = class extends Error {
379
515
  this.name = "CliError";
380
516
  }
381
517
  };
518
+ function withWorkspace(command, workspace) {
519
+ return workspace ? `${command} --ws ${workspace}` : command;
520
+ }
382
521
  function findSession(carnet, reference) {
383
522
  try {
384
523
  return carnet.sessions.find(reference);
385
524
  } catch (error) {
386
525
  if (!(error instanceof CarnetError) || error.code !== "SESSION_NOT_FOUND") throw error;
387
526
  const known = carnet.sessions.list().map((session) => session.name).filter(Boolean);
388
- throw new CliError(error.message, known.length ? `known sessions: ${known.join(", ")}` : "pass a session name, id or id prefix, see rucher sessions --all");
527
+ throw new CliError(error.message, known.length ? `known sessions: ${known.join(", ")}` : `pass a session name, id or id prefix, see ${withWorkspace("rucher sessions --all", carnet.workspace?.name)}`);
389
528
  }
390
529
  }
391
530
  function resolveSession(carnet, reference) {
392
531
  if (reference) return findSession(carnet, reference);
393
532
  const session = carnet.sessions.default();
394
- if (!session) throw new CliError("No session in this workspace yet", "start a Claude Code session inside the workspace");
533
+ if (!session) throw new CliError("No session in this workspace yet", withWorkspace("start one with rucher new <name>", carnet.workspace?.name));
395
534
  return session;
396
535
  }
397
536
  // src/commands/log.ts
398
- function formatEvents(events, io) {
537
+ function kindOf(event, kinds) {
538
+ return event.agent ? kinds.get(event.agent) : void 0;
539
+ }
540
+ function formatEvents(events, io, kinds = /* @__PURE__ */ new Map()) {
399
541
  const colors = paint(io);
400
542
  if (events.length === 0) return colors.dim("no events yet");
401
543
  return events.map((event) => {
544
+ const kind = kindOf(event, kinds);
402
545
  return [
403
546
  colors.dim(formatClock(new Date(event.at))),
404
547
  colors.bold(event.type.padEnd(9)),
548
+ kind ? colors.dim(kindTag(kind)) : "",
405
549
  event.agent ?? "",
406
550
  event.link ?? event.note ?? "",
407
551
  event.commit ? colors.cyan(event.commit.slice(0, 7)) : ""
@@ -413,8 +557,10 @@ function formatDay(date) {
413
557
  const day = String(date.getDate()).padStart(2, "0");
414
558
  return `${date.getFullYear()}-${month}-${day}`;
415
559
  }
416
- function markdownEvent(event) {
560
+ function markdownEvent(event, kinds) {
417
561
  const parts = [`${formatClock(new Date(event.at))} **${event.type}**`];
562
+ const kind = kindOf(event, kinds);
563
+ if (kind) parts.push(kind);
418
564
  if (event.agent) parts.push(`\`${event.agent}\``);
419
565
  const detail = [
420
566
  event.note,
@@ -423,7 +569,7 @@ function markdownEvent(event) {
423
569
  ].filter(Boolean).join(" · ");
424
570
  return `- ${parts.join(" ")}${detail ? `: ${detail}` : ""}`;
425
571
  }
426
- function formatEventsMarkdown(events, title) {
572
+ function formatEventsMarkdown(events, title, kinds = /* @__PURE__ */ new Map()) {
427
573
  const lines = [`# Journal: ${title}`];
428
574
  if (events.length === 0) return `${lines[0]}\n\nNo events yet.`;
429
575
  let day = "";
@@ -433,7 +579,7 @@ function formatEventsMarkdown(events, title) {
433
579
  day = current;
434
580
  lines.push("", `## ${day}`, "");
435
581
  }
436
- lines.push(markdownEvent(event));
582
+ lines.push(markdownEvent(event, kinds));
437
583
  }
438
584
  return lines.join("\n");
439
585
  }
@@ -442,43 +588,9 @@ function sessionTitle(carnet, session) {
442
588
  }
443
589
  function logOnce(carnet, io, options) {
444
590
  const session = resolveSession(carnet, options.session);
445
- const events = carnet.events.read(session.id, options.count, options.agents);
446
- io.stdout(`${options.md ? formatEventsMarkdown(events, sessionTitle(carnet, session)) : formatEvents(events, io)}\n`);
447
- }
448
- // src/workspace-option.ts
449
- const workspaceArgument = { ws: {
450
- type: "string",
451
- description: "Workspace name (default: from RUCHER_WS, the run directory or the repo you are in)"
452
- } };
453
- function forwardWorkspace({ args }) {
454
- if (args.ws) process.env.RUCHER_WS = args.ws;
455
- }
456
- function announceWorkspace(io, resolution) {
457
- if (!resolution.workspace) return;
458
- if (resolution.origin === "run-directory") io.stderr(`workspace ${resolution.workspace.name} (from its run directory)\n`);
459
- else if (resolution.origin === "repo" && resolution.repo) io.stderr(`workspace ${resolution.workspace.name} (from ${resolution.repo.name})\n`);
460
- }
461
- function warnNoWorkspace(carnet, io) {
462
- if (!carnet.workspace) io.stderr("no workspace here: pass --ws\n");
463
- }
464
- function openCliCarnet(io, workspace) {
465
- const { carnet, resolution } = openResolvedCarnet({
466
- cwd: io.cwd,
467
- env: io.env,
468
- workspace
469
- });
470
- announceWorkspace(io, resolution);
471
- return carnet;
472
- }
473
- function currentWorkspace(io, workspace) {
474
- const resolution = resolveWorkspace({
475
- cwd: io.cwd,
476
- env: io.env,
477
- workspace
478
- });
479
- const found = requireWorkspace(resolution.workspace);
480
- announceWorkspace(io, resolution);
481
- return found;
591
+ const events = carnet.events.read(session.id, options.count, options.agents, options.kind);
592
+ const kinds = new Map(carnet.agents.list(session.id, { includeClosed: true }).map((agent) => [agent.name, agent.kind]));
593
+ io.stdout(`${options.md ? formatEventsMarkdown(events, sessionTitle(carnet, session), kinds) : formatEvents(events, io, kinds)}\n`);
482
594
  }
483
595
  // src/commands/notes.ts
484
596
  const KIND_TITLES = {
@@ -543,9 +655,8 @@ function notesList(carnet, io, options = {}) {
543
655
  return;
544
656
  }
545
657
  const colors = paint(io);
546
- warnNoWorkspace(carnet, io);
547
658
  if (notes.length === 0) {
548
- if (carnet.workspace) io.stdout(`${colors.dim(options.stale ? "no note to review" : "no notes")}\n`);
659
+ io.stdout(`${colors.dim(options.stale ? "no note to review" : "no notes")}\n`);
549
660
  return;
550
661
  }
551
662
  const blocks = grouped(notes).map(([kind, kindNotes]) => `${colors.bold(KIND_TITLES[kind])}\n${kindNotes.map((note) => noteLine(io, note)).join("\n")}`);
@@ -626,29 +737,30 @@ function launchEnv(workspace, session, promptVersion, kind) {
626
737
  };
627
738
  }
628
739
  function planNew(carnet, io, options) {
629
- if (options.kind === "active" && !options.name) throw new CliError("An active session needs a name", "rucher new <name>");
740
+ if (options.kind === "active" && !options.name) throw new CliError("An active session needs a name", withWorkspace("rucher new <name>", carnet.workspace?.name));
741
+ const workspace = carnet.requireWorkspace();
630
742
  const session = carnet.sessions.create({
631
743
  id: randomUUID(),
632
744
  kind: options.kind,
633
745
  name: options.name,
634
- cwd: carnet.workspace?.runDirectory ?? io.cwd,
635
- repo: repoNameFor(carnet.workspace, io.cwd)
746
+ cwd: workspace.runDirectory,
747
+ repo: repoNameFor(workspace, io.cwd)
636
748
  });
637
749
  const host = hostById(session.host);
638
- if (carnet.workspace) renderRunDirectory(carnet.workspace, {
750
+ renderRunDirectory(workspace, {
639
751
  env: io.env,
640
752
  host: session.host
641
753
  });
642
- const prompt = appendPromptFile(carnet.workspace, session, io.env);
754
+ const prompt = appendPromptFile(workspace, session, io.env);
643
755
  return {
644
756
  ...host.launchCommand(session.id, {
645
757
  name: session.name,
646
758
  appendPromptFile: prompt.path,
647
- directories: repoDirectories(carnet.workspace),
759
+ directories: repoDirectories(workspace),
648
760
  passthrough: options.passthrough
649
761
  }),
650
- cwd: carnet.workspace?.runDirectory ?? io.cwd,
651
- env: launchEnv(carnet.workspace, session, prompt.version),
762
+ cwd: workspace.runDirectory,
763
+ env: launchEnv(workspace, session, prompt.version),
652
764
  sessionId: session.id
653
765
  };
654
766
  }
@@ -656,7 +768,7 @@ function repoDirectories(workspace) {
656
768
  return (workspace?.repos ?? []).map((repo) => repo.path).filter((path) => existsSync(path));
657
769
  }
658
770
  function sessionWorkspace(carnet, session, env) {
659
- if (!session.workspace || !isWorkspaceName(session.workspace)) return null;
771
+ if (!isWorkspaceName(session.workspace)) return null;
660
772
  return carnet.workspace?.name === session.workspace ? carnet.workspace : loadWorkspace(session.workspace, env);
661
773
  }
662
774
  function prepareSession(carnet, session, env) {
@@ -699,12 +811,12 @@ function planResume(carnet, io, reference, passthrough = []) {
699
811
  };
700
812
  }
701
813
  function planFork(carnet, io, reference, options = {}) {
702
- if (options.active && !options.name) throw new CliError("An active fork needs a name", "rucher fork <session> <name> --active");
814
+ if (options.active && !options.name) throw new CliError("An active fork needs a name", withWorkspace("rucher fork <session> <name> --active", carnet.workspace?.name));
703
815
  if (options.name && carnet.sessions.byName(options.name)) throw new CliError(`A session named "${options.name}" already exists`);
704
816
  const parent = findSession(carnet, reference);
705
817
  if (!hostById(parent.host).hasConversation(parent, io.env)) {
706
818
  const label = sessionLabel$1(parent);
707
- throw new CliError(`Session ${label} has no conversation yet, nothing to fork`, `rucher resume ${label}`);
819
+ throw new CliError(`Session ${label} has no conversation yet, nothing to fork`, withWorkspace(`rucher resume ${label}`, parent.workspace));
708
820
  }
709
821
  const workspace = prepareSession(carnet, parent, io.env);
710
822
  const cwd = sessionDirectory(parent);
@@ -765,25 +877,27 @@ function lastUse(at, now) {
765
877
  return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
766
878
  }
767
879
  function pickerLines(sessions, now = /* @__PURE__ */ new Date()) {
768
- const rows = sessions.map((session, index) => [
880
+ return table(sessions.map((session, index) => [
769
881
  String(index + 1),
770
882
  session.name ?? shortId(session.id),
771
883
  session.kind,
772
884
  session.status,
773
885
  lastUse(session.lastActiveAt, now),
774
886
  shortId(session.id)
775
- ]);
887
+ ]));
888
+ }
889
+ function table(rows) {
776
890
  const widths = (rows[0] ?? []).map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
777
891
  return rows.map((row) => row.map((cell, column) => column < row.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell).join(" "));
778
892
  }
779
893
  function hasFzf() {
780
894
  return spawnSync("fzf", ["--version"], { stdio: "ignore" }).status === 0;
781
895
  }
782
- function pickWithFzf(sessions, lines) {
896
+ function pickWithFzf(items, lines, label) {
783
897
  const result = spawnSync("fzf", [
784
898
  "--with-nth=2..",
785
899
  "--no-sort",
786
- "--prompt=session> "
900
+ `--prompt=${label}> `
787
901
  ], {
788
902
  input: lines.join("\n"),
789
903
  stdio: [
@@ -793,36 +907,92 @@ function pickWithFzf(sessions, lines) {
793
907
  ],
794
908
  encoding: "utf8"
795
909
  });
796
- return sessions[Number(result.stdout?.trim().split(/\s+/)[0]) - 1];
910
+ return items[Number(result.stdout?.trim().split(/\s+/)[0]) - 1];
797
911
  }
798
- async function pickFromList(sessions, lines) {
912
+ async function pickFromList(items, lines, label) {
799
913
  process.stderr.write(`${lines.join("\n")}\n`);
800
914
  const prompt = createInterface({
801
915
  input: process.stdin,
802
916
  output: process.stderr
803
917
  });
804
918
  try {
805
- const answer = await prompt.question("session number> ");
806
- return sessions[Number(answer.trim()) - 1];
919
+ const answer = await prompt.question(`${label} number> `);
920
+ return items[Number(answer.trim()) - 1];
807
921
  } finally {
808
922
  prompt.close();
809
923
  }
810
924
  }
925
+ function pick(items, lines, label) {
926
+ return hasFzf() ? Promise.resolve(pickWithFzf(items, lines, label)) : pickFromList(items, lines, label);
927
+ }
811
928
  async function pickSession(carnet) {
812
929
  const sessions = pickerSessions(carnet);
813
- if (sessions.length === 0) throw new CliError("No session to resume in this workspace", "rucher new <name>");
814
- if (!process.stdin.isTTY) throw new CliError("No session given", "rucher resume <name, id or id prefix>");
815
- const lines = pickerLines(sessions);
816
- const picked = hasFzf() ? pickWithFzf(sessions, lines) : await pickFromList(sessions, lines);
930
+ const workspace = carnet.workspace?.name;
931
+ if (sessions.length === 0) throw new CliError("No session to resume in this workspace", withWorkspace("rucher new <name>", workspace));
932
+ if (!process.stdin.isTTY) throw new CliError("No session given", withWorkspace("rucher resume <name, id or id prefix>", workspace));
933
+ const picked = await pick(sessions, pickerLines(sessions), "session");
817
934
  if (!picked) throw new CliError("No session picked");
818
935
  return picked;
819
936
  }
937
+ function workspaceChoices(env) {
938
+ const carnet = openWorkspaceCarnet(null, { env });
939
+ try {
940
+ const lastActive = workspaceLastActive(carnet.db);
941
+ return listWorkspaces(env).map((workspace) => ({
942
+ name: workspace.name,
943
+ lastActiveAt: lastActive.get(workspace.name)
944
+ })).sort((a, b) => (b.lastActiveAt ?? "").localeCompare(a.lastActiveAt ?? "") || a.name.localeCompare(b.name));
945
+ } finally {
946
+ carnet.close();
947
+ }
948
+ }
949
+ function workspaceLines(choices, now = /* @__PURE__ */ new Date()) {
950
+ return table(choices.map((choice, index) => [
951
+ String(index + 1),
952
+ choice.name,
953
+ choice.lastActiveAt ? lastUse(choice.lastActiveAt, now) : "never"
954
+ ]));
955
+ }
956
+ async function pickWorkspace(choices) {
957
+ return (await pick(choices, workspaceLines(choices), "workspace"))?.name;
958
+ }
959
+ // src/commands/report.ts
960
+ function runEditor(editor, file) {
961
+ return spawnSync(`${editor} "$RUCHER_EDIT_FILE"`, {
962
+ shell: true,
963
+ stdio: "inherit",
964
+ env: {
965
+ ...process.env,
966
+ RUCHER_EDIT_FILE: file
967
+ }
968
+ }).status ?? 1;
969
+ }
970
+ function colorHeadings(text, io) {
971
+ const colors = paint(io);
972
+ return text.split("\n").map((line) => /^#{1,3}\s/.test(line) ? colors.bold(line) : line).join("\n");
973
+ }
974
+ function reportOnce(carnet, io, name, options) {
975
+ const session = options.session || carnet.sessions.list({ includeTemp: true }).length === 0 ? resolveSession(carnet, options.session) : locateAgent(carnet, name).session;
976
+ const document = reportDocument(carnet, session.id, name);
977
+ if (options.path) {
978
+ io.stdout(`${document.path}\n`);
979
+ return 0;
980
+ }
981
+ if (options.edit) {
982
+ const editor = io.env.EDITOR || io.env.VISUAL;
983
+ if (!editor) throw new CliError("No editor set", "set $EDITOR or $VISUAL, or print it without --edit");
984
+ return (options.openEditor ?? runEditor)(editor, document.path);
985
+ }
986
+ io.stdout(`${colorHeadings(document.text, io)}\n`);
987
+ return 0;
988
+ }
820
989
  // src/commands/serve.ts
821
990
  function serve(io) {
822
991
  serveCarnet({
823
992
  cwd: io.cwd,
824
993
  env: io.env,
825
- sessionId: claudeCode.sessionIdFromEnvironment(io.env)
994
+ sessionId: claudeCode.sessionIdFromEnvironment(io.env),
995
+ afterTool: (carnet, sessionId) => refreshStatusLine(carnet, sessionId, io.env)
826
996
  });
827
997
  }
828
998
  // src/commands/sessions.ts
@@ -848,10 +1018,9 @@ function sessionsOnce(carnet, io, options = {}) {
848
1018
  includeTemp: options.all,
849
1019
  includeArchived: options.all
850
1020
  });
851
- warnNoWorkspace(carnet, io);
852
1021
  if (sessions.length === 0) {
853
1022
  const hint = options.all ? "" : " (temp and archived ones are hidden, use --all)";
854
- if (carnet.workspace) io.stdout(`${colors.dim(`no active session yet${hint}`)}\n`);
1023
+ io.stdout(`${colors.dim(`no active session yet${hint}`)}\n`);
855
1024
  return;
856
1025
  }
857
1026
  const now = options.now ?? /* @__PURE__ */ new Date();
@@ -875,13 +1044,14 @@ function sessionsMerge(carnet, fromReference, intoReference, io) {
875
1044
  const from = findSession(carnet, fromReference);
876
1045
  const into = findSession(carnet, intoReference);
877
1046
  const result = carnet.sessions.merge(from.id, into.id);
1047
+ for (const session of [from, into]) refreshStatusLine(carnet, session.id, io.env);
878
1048
  const label = (session) => session.name ?? session.id.slice(0, 8);
879
1049
  const lines = [
880
1050
  `merged ${label(from)} into ${label(result.session)}`,
881
1051
  ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
882
1052
  ...result.closedAgents.length ? [` agents closed (name already used): ${result.closedAgents.join(", ")}`] : [],
883
1053
  ` events moved: ${result.movedEvents}`,
884
- ` table line moved: ${result.movedTable ? "yes" : "no"}`
1054
+ ` Main line moved: ${result.movedTable ? "yes" : "no"}`
885
1055
  ];
886
1056
  io.stdout(`${lines.join("\n")}\n`);
887
1057
  }
@@ -902,7 +1072,7 @@ function sessionsMove(carnet, reference, workspaceReference, io, options = {}) {
902
1072
  ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
903
1073
  ...result.skippedAgents.length ? [` agents left out (name already used): ${result.skippedAgents.join(", ")}`] : [],
904
1074
  ` events moved: ${result.movedEvents}`,
905
- ` table line moved: ${result.movedTable ? "yes" : "no"}`,
1075
+ ` Main line moved: ${result.movedTable ? "yes" : "no"}`,
906
1076
  ...result.keptNotes ? [` notes kept in ${workspaceLabel(carnet.workspace)}: ${result.keptNotes}`] : []
907
1077
  ];
908
1078
  io.stdout(`${lines.join("\n")}\n`);
@@ -973,6 +1143,62 @@ function sessionsClean(carnet, io, options = {}) {
973
1143
  if (options.purge) purgeTranscripts(session, io);
974
1144
  }
975
1145
  }
1146
+ // src/commands/fit.ts
1147
+ function charWidth(char) {
1148
+ const code = char.codePointAt(0) ?? 0;
1149
+ if (code === 65039 || code === 8205) return 0;
1150
+ return code >= 126976 || code >= 8960 && code <= 10175 || code >= 11008 && code <= 11263 ? 2 : 1;
1151
+ }
1152
+ function displayWidth(text) {
1153
+ return Array.from(stripVTControlCharacters(text)).reduce((width, char) => width + charWidth(char), 0);
1154
+ }
1155
+ function wrapLegend(legend, columns) {
1156
+ const lines = [];
1157
+ let line = "";
1158
+ for (const item of legend.split(" · ")) {
1159
+ const next = line ? `${line} · ${item}` : item;
1160
+ if (line && displayWidth(next) > columns) {
1161
+ lines.push(line);
1162
+ line = item;
1163
+ } else line = next;
1164
+ }
1165
+ if (line) lines.push(line);
1166
+ return lines;
1167
+ }
1168
+ function sectionName(header) {
1169
+ return stripVTControlCharacters(header).replace(/ {2}.*$/, "");
1170
+ }
1171
+ function splitSections(body) {
1172
+ const sections = [[]];
1173
+ for (const line of body) if (line === "") sections.push([]);
1174
+ else sections.at(-1)?.push(line);
1175
+ return sections.filter((section) => section.length > 0);
1176
+ }
1177
+ function fitToRows({ head, body, bottom, rows, cutOrder, more }) {
1178
+ const room = rows - bottom.length - 1;
1179
+ if (room < 1) return bottom.slice(-rows);
1180
+ const sections = splitSections(body);
1181
+ const content = () => [...head, ...sections.flatMap((section, index) => index ? ["", ...section] : section)];
1182
+ for (const name of cutOrder) {
1183
+ const overflow = content().length - room;
1184
+ if (overflow <= 0) break;
1185
+ const section = sections.find((candidate) => sectionName(candidate[0] ?? "") === name);
1186
+ if (!section || section.length <= 2) continue;
1187
+ const items = section.length - 1;
1188
+ const keep = Math.max(items - overflow - 1, 0);
1189
+ section.splice(1 + keep, items - keep, more(items - keep));
1190
+ }
1191
+ let lines = content();
1192
+ if (lines.length > room) {
1193
+ const kept = lines.slice(0, room - 1);
1194
+ lines = [...kept, more(lines.length - kept.length)];
1195
+ }
1196
+ return [
1197
+ ...lines,
1198
+ ...Array(rows - bottom.length - lines.length).fill(""),
1199
+ ...bottom
1200
+ ];
1201
+ }
976
1202
  // src/commands/watch-keys.ts
977
1203
  const INITIAL_WATCH_STATE = {
978
1204
  notesOpen: false,
@@ -1081,11 +1307,13 @@ function pressKey(state, key, noteCount) {
1081
1307
  }
1082
1308
  // src/commands/status.ts
1083
1309
  const SECTION_HEADERS = /* @__PURE__ */ new Set([
1084
- "On the table",
1310
+ MAIN_HEADER,
1085
1311
  "Waiting on you",
1312
+ BLOCKED_HEADER,
1086
1313
  "Running",
1087
1314
  NOTES_HEADER
1088
1315
  ]);
1316
+ const AGENT_LINE = new RegExp(`^ {2}(?:\\d+\\. )?\\S+ ${KIND_TAG_PATTERN.source} `);
1089
1317
  function truncate(line, columns) {
1090
1318
  const chars = Array.from(line);
1091
1319
  return chars.length > columns ? `${chars.slice(0, Math.max(columns - 1, 1)).join("")}…` : line;
@@ -1095,8 +1323,9 @@ function colorizeLine(line, io) {
1095
1323
  if (line === LEGEND) return colors.dim(line);
1096
1324
  const cut = truncate(line, io.columns);
1097
1325
  if (SECTION_HEADERS.has(line)) return colors.bold(cut);
1098
- if (line.startsWith(" ⚙️")) return colors.yellow(cut);
1099
- if (line === " nothing") return colors.dim(cut);
1326
+ if (line.startsWith(" ⚠")) return colors.red(cut);
1327
+ if (line.startsWith(" ⚙️") || line.startsWith(" ⏸")) return colors.yellow(cut);
1328
+ if (line === " nothing" || line === ` ${MAIN_IDLE}`) return colors.dim(cut);
1100
1329
  if (cut.startsWith(`${NOTES_HEADER} `)) return `${colors.bold(NOTES_HEADER)}${cut.slice(NOTES_HEADER.length)}`;
1101
1330
  const marker = /^ {2}\+ #\d+ +\S+ {2}(similar to [^·]*·)/.exec(cut);
1102
1331
  if (marker?.[1]) {
@@ -1104,6 +1333,7 @@ function colorizeLine(line, io) {
1104
1333
  const end = start + marker[1].length;
1105
1334
  return `${cut.slice(0, start)}${colors.yellow(cut.slice(start, end))}${cut.slice(end)}`;
1106
1335
  }
1336
+ if (AGENT_LINE.test(cut)) return cut.replace(KIND_TAG_PATTERN, (tag) => colors.dim(tag));
1107
1337
  return cut;
1108
1338
  }
1109
1339
  function sessionName(session) {
@@ -1162,42 +1392,80 @@ function hasSomethingToShow(carnet, session) {
1162
1392
  function sessionBlock(session, view, io) {
1163
1393
  return [sessionHeader(session, io), ...sessionLines(session, view, io, "summary")].join("\n");
1164
1394
  }
1165
- function singleView(carnet, session, io, state) {
1395
+ const CUT_ORDER = [
1396
+ "Notes",
1397
+ "Running",
1398
+ "Waiting on agents",
1399
+ "Waiting on you"
1400
+ ];
1401
+ const NOTES_OPEN_CUT_ORDER = [
1402
+ "Running",
1403
+ "Waiting on agents",
1404
+ "Waiting on you",
1405
+ "Notes"
1406
+ ];
1407
+ function legendLines(io, fit) {
1408
+ const colors = paint(io);
1409
+ const legend = fit ? wrapLegend(LEGEND, io.columns) : [LEGEND];
1410
+ return [colors.dim(truncate(KIND_LEGEND, io.columns)), ...legend.map((line) => colors.dim(line))];
1411
+ }
1412
+ function layout(io, rows, parts) {
1413
+ if (rows === void 0) return [
1414
+ ...parts.head,
1415
+ ...parts.body,
1416
+ "",
1417
+ ...parts.footer,
1418
+ ...legendLines(io, false)
1419
+ ].join("\n");
1166
1420
  const colors = paint(io);
1167
- const view = carnet.status.view(session);
1421
+ return fitToRows({
1422
+ head: parts.head,
1423
+ body: parts.body,
1424
+ bottom: [...parts.footer, ...legendLines(io, true)],
1425
+ rows,
1426
+ cutOrder: parts.cutOrder,
1427
+ more: (count) => colors.dim(` … ${count} more`)
1428
+ }).join("\n");
1429
+ }
1430
+ function singleView(carnet, session, io, kind, state, rows) {
1431
+ const colors = paint(io);
1432
+ const view = carnet.status.view(session, { kind });
1168
1433
  const separator = " - ";
1169
1434
  const label = sessionLabel(carnet, session, io.columns - view.time.length - 3);
1170
1435
  const title = `${colors.dim(view.time)}${separator}${colors.cyan(label)}`;
1171
1436
  const body = state ? interactiveLines(carnet, session, view, io, state) : sessionLines(session, view, io);
1172
1437
  const footer = footerLine(view, io, state);
1173
- return [
1174
- title,
1175
- "",
1176
- ...body,
1177
- "",
1178
- ...footer ? [footer] : [],
1179
- colors.dim(LEGEND)
1180
- ].join("\n");
1438
+ const lag = pluginLagNotice(session.pluginVersion);
1439
+ return layout(io, rows, {
1440
+ head: [
1441
+ title,
1442
+ ...lag ? [colors.yellow(truncate(lag, io.columns))] : [],
1443
+ ""
1444
+ ],
1445
+ body,
1446
+ footer: footer ? [footer] : [],
1447
+ cutOrder: state?.notesOpen ? NOTES_OPEN_CUT_ORDER : CUT_ORDER
1448
+ });
1181
1449
  }
1182
1450
  function renderStatusView(carnet, io, options) {
1183
1451
  const sessions = options.all ? carnet.sessions.list({ includeTemp: true }).filter((session) => hasSomethingToShow(carnet, session)) : [];
1184
- if (sessions.length === 0) return singleView(carnet, resolveSession(carnet, options.session), io, options.interaction);
1452
+ if (sessions.length === 0) return singleView(carnet, resolveSession(carnet, options.session), io, options.kind, options.interaction, options.rows);
1185
1453
  let time = "";
1186
1454
  const blocks = sessions.map((session) => {
1187
- const view = carnet.status.view(session);
1455
+ const view = carnet.status.view(session, { kind: options.kind });
1188
1456
  time ||= view.time;
1189
1457
  return sessionBlock(session, view, io);
1190
1458
  });
1191
1459
  const colors = paint(io);
1192
1460
  const separator = " - ";
1193
1461
  const workspace = truncate(workspaceLabel(carnet.workspace), io.columns - time.length - 3);
1194
- return [
1195
- `${colors.dim(time)}${separator}${colors.cyan(workspace)}`,
1196
- "",
1197
- blocks.join("\n\n"),
1198
- "",
1199
- colors.dim(LEGEND)
1200
- ].join("\n");
1462
+ const title = `${colors.dim(time)}${separator}${colors.cyan(workspace)}`;
1463
+ return layout(io, options.rows, {
1464
+ head: [title, ""],
1465
+ body: blocks.join("\n\n").split("\n"),
1466
+ footer: [],
1467
+ cutOrder: []
1468
+ });
1201
1469
  }
1202
1470
  function statusOnce(carnet, io, options) {
1203
1471
  io.stdout(`${renderStatusView(carnet, io, options)}\n`);
@@ -1236,23 +1504,26 @@ function statusWatch(carnet, io, options) {
1236
1504
  try {
1237
1505
  text = renderStatusView(carnet, io, {
1238
1506
  ...options,
1239
- interaction: interactive ? state : void 0
1507
+ interaction: interactive ? state : void 0,
1508
+ rows: io.rows
1240
1509
  });
1241
1510
  } catch (error) {
1242
1511
  text = paint(io).dim(error instanceof Error ? error.message : String(error));
1243
1512
  }
1244
1513
  if (text === last) return;
1245
1514
  last = text;
1246
- io.stdout(`${CLEAR}${text}\n`);
1515
+ io.stdout(`${CLEAR}${text}${io.rows === void 0 ? "\n" : ""}`);
1247
1516
  };
1248
1517
  const timer = setInterval(() => {
1249
1518
  if (state.reason === null) repaint();
1250
1519
  }, options.intervalMilliseconds);
1520
+ const offResize = options.onResize?.(repaint);
1251
1521
  let stopped = false;
1252
1522
  const stop = () => {
1253
1523
  if (stopped) return;
1254
1524
  stopped = true;
1255
1525
  clearInterval(timer);
1526
+ offResize?.();
1256
1527
  options.keys?.close();
1257
1528
  io.stdout(SHOW_CURSOR);
1258
1529
  resolve();
@@ -1272,6 +1543,70 @@ function statusWatch(carnet, io, options) {
1272
1543
  repaint();
1273
1544
  });
1274
1545
  }
1546
+ // src/commands/statusline.ts
1547
+ function statusLineDirectory(io) {
1548
+ io.stdout(`${dirname(statusLinePath("session", io.env))}\n`);
1549
+ return 0;
1550
+ }
1551
+ function statusLine(stdinText, io) {
1552
+ let sessionId;
1553
+ try {
1554
+ sessionId = JSON.parse(stdinText).session_id;
1555
+ } catch {
1556
+ return 0;
1557
+ }
1558
+ if (typeof sessionId !== "string" || !/^[\w-]+$/.test(sessionId)) return 0;
1559
+ const line = labelStatusLine(readStatusLine(sessionId, io.env));
1560
+ if (line) io.stdout(`${line}\n`);
1561
+ return 0;
1562
+ }
1563
+ // src/workspace-option.ts
1564
+ const workspaceArgument = { ws: {
1565
+ type: "string",
1566
+ description: "Workspace name (default: from RUCHER_WS or the run directory, else asked)"
1567
+ } };
1568
+ function forwardWorkspace({ args }) {
1569
+ if (args.ws) process.env.RUCHER_WS = args.ws;
1570
+ }
1571
+ async function chooseWorkspace(io, workspace, { interactive = process.stdin.isTTY === true && process.stderr.isTTY === true, choose = pickWorkspace } = {}) {
1572
+ if (workspace || !interactive) return;
1573
+ if (resolveWorkspace({
1574
+ cwd: io.cwd,
1575
+ env: io.env
1576
+ }).workspace) return;
1577
+ const choices = workspaceChoices(io.env);
1578
+ if (choices.length === 0) return;
1579
+ const chosen = await choose(choices);
1580
+ if (chosen) io.env.RUCHER_WS = chosen;
1581
+ }
1582
+ function announceWorkspace(io, resolution) {
1583
+ if (resolution.workspace && resolution.origin === "run-directory") io.stderr(`workspace ${resolution.workspace.name} (from its run directory)\n`);
1584
+ }
1585
+ function openCliCarnet(io, workspace) {
1586
+ const { carnet, resolution } = openResolvedCarnet({
1587
+ cwd: io.cwd,
1588
+ env: io.env,
1589
+ workspace
1590
+ });
1591
+ try {
1592
+ requireWorkspace(resolution.workspace);
1593
+ } catch (error) {
1594
+ carnet.close();
1595
+ throw error;
1596
+ }
1597
+ announceWorkspace(io, resolution);
1598
+ return carnet;
1599
+ }
1600
+ function currentWorkspace(io, workspace) {
1601
+ const resolution = resolveWorkspace({
1602
+ cwd: io.cwd,
1603
+ env: io.env,
1604
+ workspace
1605
+ });
1606
+ const found = requireWorkspace(resolution.workspace);
1607
+ announceWorkspace(io, resolution);
1608
+ return found;
1609
+ }
1275
1610
  // src/commands/ws.ts
1276
1611
  function carnetErrors(io, run) {
1277
1612
  try {
@@ -1437,6 +1772,7 @@ function workspaceDrop(name, io, options = {}) {
1437
1772
  refuseLive(carnet, "drop", options.isAlive ?? processIsAlive);
1438
1773
  const at = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
1439
1774
  const archived = archiveWorkspaceSessions(carnet.db, name, at);
1775
+ carnet.releaseClosedSandboxes();
1440
1776
  const deletedNotes = options.purge ? deleteWorkspaceNotes(carnet.db, name) : 0;
1441
1777
  const workspace = dropWorkspace(name, {
1442
1778
  purge: options.purge,
@@ -1453,6 +1789,110 @@ function workspaceDrop(name, io, options = {}) {
1453
1789
  carnet.close();
1454
1790
  }
1455
1791
  }
1792
+ function moveLines(plan) {
1793
+ return plan.moves.map((move) => ` ${move.what}: ${move.from} → ${move.to}`);
1794
+ }
1795
+ function rowLine(plan) {
1796
+ const { sessions, notes, activeDays } = plan.rows;
1797
+ return ` Carnet: ${plural(sessions, "session")}, ${plural(notes, "note")}, ${plural(activeDays, "active day")}`;
1798
+ }
1799
+ function workspaceRename(from, to, io, options = {}) {
1800
+ const carnet = openWorkspaceCarnet(null, { env: io.env });
1801
+ try {
1802
+ const result = renameWorkspace(carnet.db, from, to, {
1803
+ env: io.env,
1804
+ dryRun: options.dryRun,
1805
+ isAlive: options.isAlive ?? processIsAlive,
1806
+ now: options.now
1807
+ });
1808
+ if (options.dryRun) {
1809
+ const lines = [
1810
+ `would rename ${from} to ${to}:`,
1811
+ ...moveLines(result),
1812
+ " Claude Code project folder and trust entry, when they exist",
1813
+ rowLine(result),
1814
+ ...result.running.length ? [`the real run would stop: ${plural(result.running.length, "session")} running (${result.running.map((row) => row.name ?? row.id.slice(0, 8)).join(", ")})`] : []
1815
+ ];
1816
+ io.stdout(`${lines.join("\n")}\n`);
1817
+ return 0;
1818
+ }
1819
+ const done = result;
1820
+ const lines = [
1821
+ `renamed ${from} to ${to}`,
1822
+ ...moveLines(done),
1823
+ rowLine(done),
1824
+ ` paths rewritten: ${done.paths}`,
1825
+ ` trust entry ${done.trustMoved ? "moved" : "not found, unchanged"}`,
1826
+ ` backup: ${done.backup}`,
1827
+ ...done.warnings.map((warning) => `warning: ${warning}`),
1828
+ `Next: \`rucher resume <session> --ws ${to}\``
1829
+ ];
1830
+ io.stdout(`${lines.join("\n")}\n`);
1831
+ return 0;
1832
+ } finally {
1833
+ carnet.close();
1834
+ }
1835
+ }
1836
+ function moveList(title, moves) {
1837
+ if (!moves.length) return [];
1838
+ return [` ${title}:`, ...moves.map((move) => ` ${move.from} → ${move.to}`)];
1839
+ }
1840
+ function mergePlanLines(plan) {
1841
+ const { sessions, notes, activeDays } = plan.rows;
1842
+ return [
1843
+ ` Carnet: ${plural(sessions, "session")}, ${plural(activeDays, "active day")}, ${plural(notes, "note")}${notes ? ` numbered #${plan.firstNumber} to #${plan.lastNumber} in ${plan.into}` : ""}`,
1844
+ ...plan.reposAdded.length ? [` repos added: ${plan.reposAdded.join(", ")}`] : [],
1845
+ ...plan.reposRenamed.map(([from, into]) => ` repo ${from} is ${into} in ${plan.into}`),
1846
+ ...plan.settingsConflicts.length ? [` settings kept from ${plan.into}: ${plan.settingsConflicts.join(", ")}`] : [],
1847
+ ` ${plan.instructions} of ${plan.from} appended to ${plan.into}'s under ## Ex-workspace ${plan.from}`,
1848
+ ` Claude Code project folder of ${plan.from} merged into ${plan.into}'s (conversations, memory), trust entry dropped`,
1849
+ ...moveList("reports", plan.reports),
1850
+ ...moveList("sandboxes", plan.sandboxes),
1851
+ ...moveList("other files", plan.files),
1852
+ ` then ${plan.from}'s definition and run directory go to the backup folder`
1853
+ ];
1854
+ }
1855
+ async function workspaceMerge(from, into, io, options = {}) {
1856
+ const carnet = openWorkspaceCarnet(null, { env: io.env });
1857
+ try {
1858
+ const isAlive = options.isAlive ?? processIsAlive;
1859
+ const plan = planWorkspaceMerge(carnet.db, from, into, {
1860
+ env: io.env,
1861
+ isAlive
1862
+ });
1863
+ const running = plan.running.length ? [`the real run would stop: ${plural(plan.running.length, "session")} running (${plan.running.map((row) => row.name ?? row.id.slice(0, 8)).join(", ")})`] : [];
1864
+ io.stdout(`${[
1865
+ `merge ${from} into ${into}:`,
1866
+ ...mergePlanLines(plan),
1867
+ ...running
1868
+ ].join("\n")}\n`);
1869
+ if (options.dryRun) return 0;
1870
+ if (!options.yes) {
1871
+ if (!options.confirm) throw new CliError(`merging deletes ${from}`, "pass --yes to merge without a question");
1872
+ if (!await options.confirm(`Merge ${from} into ${into}? [y/N] `)) {
1873
+ io.stdout("nothing merged\n");
1874
+ return 1;
1875
+ }
1876
+ }
1877
+ const result = mergeWorkspaces(carnet.db, from, into, {
1878
+ env: io.env,
1879
+ isAlive,
1880
+ now: options.now
1881
+ });
1882
+ const lines = [
1883
+ `merged ${from} into ${into}`,
1884
+ ` backup: ${result.backup}`,
1885
+ ...result.warnings.map((warning) => `warning: ${warning}`)
1886
+ ];
1887
+ io.stdout(`${lines.join("\n")}\n`);
1888
+ if (options.edit === false) return 0;
1889
+ if ((options.openEditor ?? openEditorFor(io))(result.instructionsPath) !== 0) io.stderr(`warning: ${editorCommand(io.env)} exited with an error; the appended instructions stay\n`);
1890
+ workspaceSync(io, { workspace: into });
1891
+ return 0;
1892
+ } finally {
1893
+ carnet.close();
1894
+ }
1895
+ }
1456
1896
  function workspaceErrors(io, run) {
1457
1897
  try {
1458
1898
  return run();
@@ -1468,6 +1908,15 @@ function workspaceErrors(io, run) {
1468
1908
  throw error;
1469
1909
  }
1470
1910
  }
1911
+ async function workspaceErrorsAsync(io, run) {
1912
+ try {
1913
+ return await run();
1914
+ } catch (error) {
1915
+ return workspaceErrors(io, () => {
1916
+ throw error;
1917
+ });
1918
+ }
1919
+ }
1471
1920
  // src/io.ts
1472
1921
  function processIo(options = {}) {
1473
1922
  const tty = process.stdout.isTTY === true;
@@ -1478,7 +1927,12 @@ function processIo(options = {}) {
1478
1927
  cwd: process.cwd(),
1479
1928
  env: process.env,
1480
1929
  color: tty && colorWanted && !process.env.NO_COLOR,
1481
- columns: process.stdout.columns ?? 80
1930
+ get columns() {
1931
+ return process.stdout.columns ?? 80;
1932
+ },
1933
+ get rows() {
1934
+ return tty ? process.stdout.rows : void 0;
1935
+ }
1482
1936
  };
1483
1937
  }
1484
1938
  function readStdin() {
@@ -1523,6 +1977,22 @@ function fail(io, error) {
1523
1977
  else io.stderr(`error: ${error instanceof Error ? error.message : String(error)}\n`);
1524
1978
  process.exit(1);
1525
1979
  }
1980
+ async function askWorkspace({ args }) {
1981
+ const io = processIo();
1982
+ try {
1983
+ await chooseWorkspace(io, args.ws);
1984
+ } catch (error) {
1985
+ fail(io, error);
1986
+ }
1987
+ }
1988
+ const kindArgument = { kind: {
1989
+ type: "string",
1990
+ description: AGENT_KINDS.join(", ")
1991
+ } };
1992
+ function agentKind(value) {
1993
+ if (value === void 0 || isAgentKind(value)) return value;
1994
+ throw new CliError(`Unknown agent kind ${value}`, `use one of ${AGENT_KINDS.join(", ")}`);
1995
+ }
1526
1996
  const colorArgument = { color: {
1527
1997
  type: "boolean",
1528
1998
  default: true,
@@ -1556,16 +2026,19 @@ const statusCommand = defineCommand({
1556
2026
  default: "1",
1557
2027
  description: "Refresh interval in seconds with --watch"
1558
2028
  },
2029
+ ...kindArgument,
1559
2030
  ...workspaceArgument,
1560
2031
  ...colorArgument
1561
2032
  },
2033
+ setup: askWorkspace,
1562
2034
  async run({ args }) {
1563
2035
  const io = processIo({ color: args.color });
1564
2036
  try {
1565
2037
  const carnet = openCliCarnet(io, args.ws);
1566
2038
  const options = {
1567
2039
  session: args.session,
1568
- all: args.all
2040
+ all: args.all,
2041
+ kind: agentKind(args.kind)
1569
2042
  };
1570
2043
  if (!args.watch) {
1571
2044
  statusOnce(carnet, io, options);
@@ -1579,7 +2052,11 @@ const statusCommand = defineCommand({
1579
2052
  ...options,
1580
2053
  intervalMilliseconds,
1581
2054
  signal: controller.signal,
1582
- keys: terminalKeys(process.stdin, process.stdout)
2055
+ keys: terminalKeys(process.stdin, process.stdout),
2056
+ onResize: (listener) => {
2057
+ process.stdout.on("resize", listener);
2058
+ return () => process.stdout.off("resize", listener);
2059
+ }
1583
2060
  });
1584
2061
  } catch (error) {
1585
2062
  fail(io, error);
@@ -1609,9 +2086,11 @@ const logCommand = defineCommand({
1609
2086
  default: false,
1610
2087
  description: "Agent events only, without session starts and ends"
1611
2088
  },
2089
+ ...kindArgument,
1612
2090
  ...workspaceArgument,
1613
2091
  ...colorArgument
1614
2092
  },
2093
+ setup: askWorkspace,
1615
2094
  run({ args }) {
1616
2095
  const io = processIo({ color: args.color });
1617
2096
  try {
@@ -1619,13 +2098,53 @@ const logCommand = defineCommand({
1619
2098
  session: args.session,
1620
2099
  count: Number(args.count) || 20,
1621
2100
  md: args.md,
1622
- agents: args.agents
2101
+ agents: args.agents,
2102
+ kind: agentKind(args.kind)
1623
2103
  });
1624
2104
  } catch (error) {
1625
2105
  fail(io, error);
1626
2106
  }
1627
2107
  }
1628
2108
  });
2109
+ const reportCommand = defineCommand({
2110
+ meta: {
2111
+ name: "report",
2112
+ description: "Print an agent's report, a plan agent's plan with each answer beside its question"
2113
+ },
2114
+ args: {
2115
+ name: {
2116
+ type: "positional",
2117
+ description: "Agent name",
2118
+ required: true
2119
+ },
2120
+ ...sessionArgument,
2121
+ edit: {
2122
+ type: "boolean",
2123
+ default: false,
2124
+ description: "Open the report in $EDITOR"
2125
+ },
2126
+ path: {
2127
+ type: "boolean",
2128
+ default: false,
2129
+ description: "Print the report path alone"
2130
+ },
2131
+ ...workspaceArgument,
2132
+ ...colorArgument
2133
+ },
2134
+ setup: askWorkspace,
2135
+ run({ args }) {
2136
+ const io = processIo({ color: args.color });
2137
+ let code = 0;
2138
+ withCarnet(io, args.ws, (carnet) => {
2139
+ code = reportOnce(carnet, io, args.name, {
2140
+ session: args.session,
2141
+ edit: args.edit,
2142
+ path: args.path
2143
+ });
2144
+ });
2145
+ if (code !== 0) process.exit(code);
2146
+ }
2147
+ });
1629
2148
  const sessionsListCommand = defineCommand({
1630
2149
  meta: {
1631
2150
  name: "list",
@@ -1640,6 +2159,7 @@ const sessionsListCommand = defineCommand({
1640
2159
  ...workspaceArgument,
1641
2160
  ...colorArgument
1642
2161
  },
2162
+ setup: askWorkspace,
1643
2163
  run({ args }) {
1644
2164
  const io = processIo({ color: args.color });
1645
2165
  try {
@@ -1652,7 +2172,7 @@ const sessionsListCommand = defineCommand({
1652
2172
  const sessionsMergeCommand = defineCommand({
1653
2173
  meta: {
1654
2174
  name: "merge",
1655
- description: "Move the agents, table line and journal of one session into another, then drop it"
2175
+ description: "Move the agents, Main line and journal of one session into another, then drop it"
1656
2176
  },
1657
2177
  args: {
1658
2178
  from: {
@@ -1667,6 +2187,7 @@ const sessionsMergeCommand = defineCommand({
1667
2187
  },
1668
2188
  ...workspaceArgument
1669
2189
  },
2190
+ setup: askWorkspace,
1670
2191
  run({ args }) {
1671
2192
  const io = processIo();
1672
2193
  try {
@@ -1697,6 +2218,7 @@ const sessionsRenameCommand = defineCommand({
1697
2218
  },
1698
2219
  ...workspaceArgument
1699
2220
  },
2221
+ setup: askWorkspace,
1700
2222
  run({ args }) {
1701
2223
  const io = processIo();
1702
2224
  withCarnet(io, args.ws, (carnet) => sessionsRename(carnet, args.session, args.name, io));
@@ -1716,6 +2238,7 @@ const sessionsPromoteCommand = defineCommand({
1716
2238
  },
1717
2239
  ...workspaceArgument
1718
2240
  },
2241
+ setup: askWorkspace,
1719
2242
  run({ args }) {
1720
2243
  const io = processIo();
1721
2244
  withCarnet(io, args.ws, (carnet) => sessionsPromote(carnet, args.session, args.name, io));
@@ -1730,6 +2253,7 @@ const sessionsDemoteCommand = defineCommand({
1730
2253
  session: sessionReference,
1731
2254
  ...workspaceArgument
1732
2255
  },
2256
+ setup: askWorkspace,
1733
2257
  run({ args }) {
1734
2258
  const io = processIo();
1735
2259
  withCarnet(io, args.ws, (carnet) => sessionsDemote(carnet, args.session, io));
@@ -1750,6 +2274,7 @@ const sessionsDropCommand = defineCommand({
1750
2274
  ...purgeArgument,
1751
2275
  ...workspaceArgument
1752
2276
  },
2277
+ setup: askWorkspace,
1753
2278
  run({ args }) {
1754
2279
  const io = processIo();
1755
2280
  withCarnet(io, args.ws, (carnet) => sessionsDrop(carnet, args.session, io, { purge: args.purge }));
@@ -1758,7 +2283,7 @@ const sessionsDropCommand = defineCommand({
1758
2283
  const sessionsMoveCommand = defineCommand({
1759
2284
  meta: {
1760
2285
  name: "move",
1761
- description: "Move a session, its agents, table line and journal to another workspace"
2286
+ description: "Move a session, its agents, Main line and journal to another workspace"
1762
2287
  },
1763
2288
  args: {
1764
2289
  session: sessionReference,
@@ -1779,6 +2304,7 @@ const sessionsMoveCommand = defineCommand({
1779
2304
  },
1780
2305
  ...workspaceArgument
1781
2306
  },
2307
+ setup: askWorkspace,
1782
2308
  run({ args }) {
1783
2309
  const io = processIo();
1784
2310
  withCarnet(io, args.ws, (carnet) => sessionsMove(carnet, args.session, args.to, io, {
@@ -1806,6 +2332,7 @@ const sessionsCleanCommand = defineCommand({
1806
2332
  },
1807
2333
  ...workspaceArgument
1808
2334
  },
2335
+ setup: askWorkspace,
1809
2336
  run({ args }) {
1810
2337
  const io = processIo();
1811
2338
  withCarnet(io, args.ws, (carnet) => sessionsClean(carnet, io, {
@@ -1886,6 +2413,7 @@ const notesListCommand = defineCommand({
1886
2413
  ...workspaceArgument,
1887
2414
  ...colorArgument
1888
2415
  },
2416
+ setup: askWorkspace,
1889
2417
  run({ args }) {
1890
2418
  const io = processIo({ color: args.color });
1891
2419
  withCarnet(io, args.ws, (carnet) => notesList(carnet, io, {
@@ -1912,6 +2440,7 @@ const notesShowCommand = defineCommand({
1912
2440
  ...workspaceArgument,
1913
2441
  ...colorArgument
1914
2442
  },
2443
+ setup: askWorkspace,
1915
2444
  run({ args }) {
1916
2445
  const io = processIo({ color: args.color });
1917
2446
  withCarnet(io, args.ws, (carnet) => notesShow(carnet, io, parseNoteId(args.id)));
@@ -1940,6 +2469,7 @@ const notesAddCommand = defineCommand({
1940
2469
  ...workspaceArgument,
1941
2470
  ...colorArgument
1942
2471
  },
2472
+ setup: askWorkspace,
1943
2473
  run({ args, rawArgs }) {
1944
2474
  const io = processIo({ color: args.color });
1945
2475
  withCarnet(io, args.ws, (carnet) => notesAdd(carnet, io, {
@@ -1971,6 +2501,7 @@ const notesDropCommand = defineCommand({
1971
2501
  },
1972
2502
  ...workspaceArgument
1973
2503
  },
2504
+ setup: askWorkspace,
1974
2505
  run({ args }) {
1975
2506
  const io = processIo();
1976
2507
  const replacement = args["replaced-by"];
@@ -2036,6 +2567,7 @@ const newCommand = defineCommand({
2036
2567
  },
2037
2568
  ...workspaceArgument
2038
2569
  },
2570
+ setup: askWorkspace,
2039
2571
  async run({ args, rawArgs }) {
2040
2572
  const { own, passthrough } = splitPassthrough(rawArgs);
2041
2573
  await launch(processIo(), args.ws, (carnet) => planNew(carnet, processIo(), {
@@ -2058,6 +2590,7 @@ const tmpCommand = defineCommand({
2058
2590
  },
2059
2591
  ...workspaceArgument
2060
2592
  },
2593
+ setup: askWorkspace,
2061
2594
  async run({ args, rawArgs }) {
2062
2595
  const { own, passthrough } = splitPassthrough(rawArgs);
2063
2596
  await launch(processIo(), args.ws, (carnet) => planNew(carnet, processIo(), {
@@ -2080,6 +2613,7 @@ const resumeCommand = defineCommand({
2080
2613
  },
2081
2614
  ...workspaceArgument
2082
2615
  },
2616
+ setup: askWorkspace,
2083
2617
  async run({ args, rawArgs }) {
2084
2618
  const { own, passthrough } = splitPassthrough(rawArgs);
2085
2619
  const io = processIo();
@@ -2112,6 +2646,7 @@ const forkCommand = defineCommand({
2112
2646
  },
2113
2647
  ...workspaceArgument
2114
2648
  },
2649
+ setup: askWorkspace,
2115
2650
  async run({ args, rawArgs }) {
2116
2651
  const { own, passthrough } = splitPassthrough(rawArgs);
2117
2652
  const [reference, name] = positionals(withoutWorkspaceOption(own));
@@ -2135,13 +2670,25 @@ async function askYes(question) {
2135
2670
  prompt.close();
2136
2671
  }
2137
2672
  }
2673
+ async function askNo(question) {
2674
+ const { createInterface } = await import("node:readline/promises");
2675
+ const prompt = createInterface({
2676
+ input: process.stdin,
2677
+ output: process.stderr
2678
+ });
2679
+ try {
2680
+ return /^y/i.test((await prompt.question(question)).trim());
2681
+ } finally {
2682
+ prompt.close();
2683
+ }
2684
+ }
2138
2685
  function commaList(value) {
2139
2686
  return value?.split(",").map((item) => item.trim()).filter(Boolean);
2140
2687
  }
2141
2688
  const wsCommand = defineCommand({
2142
2689
  meta: {
2143
2690
  name: "ws",
2144
- description: "The workspaces: create, list, show, add or remove repos, render, edit instructions"
2691
+ description: "The workspaces: create, rename, merge, list, show, add or remove repos, render, edit instructions"
2145
2692
  },
2146
2693
  args: { ...workspaceArgument },
2147
2694
  setup: forwardWorkspace,
@@ -2179,6 +2726,75 @@ const wsCommand = defineCommand({
2179
2726
  process.exitCode = workspaceErrors(io, () => workspaceCreate(args.name, io, { repos: commaList(args.repos) }));
2180
2727
  }
2181
2728
  }),
2729
+ rename: defineCommand({
2730
+ meta: {
2731
+ name: "rename",
2732
+ description: "Rename a workspace: its definition, run directory, Claude Code project folder and rows"
2733
+ },
2734
+ args: {
2735
+ old: {
2736
+ type: "positional",
2737
+ description: "Current workspace name",
2738
+ required: true
2739
+ },
2740
+ new: {
2741
+ type: "positional",
2742
+ description: "New name: a-z, 0-9 and -",
2743
+ required: true
2744
+ },
2745
+ "dry-run": {
2746
+ type: "boolean",
2747
+ default: false,
2748
+ description: "Print what would move, change nothing"
2749
+ }
2750
+ },
2751
+ run({ args }) {
2752
+ const io = processIo();
2753
+ process.exitCode = workspaceErrors(io, () => workspaceRename(args.old, args.new, io, { dryRun: args["dry-run"] }));
2754
+ }
2755
+ }),
2756
+ merge: defineCommand({
2757
+ meta: {
2758
+ name: "merge",
2759
+ description: "Merge a workspace into another: sessions, notes, reports, Claude Code conversations, instructions"
2760
+ },
2761
+ args: {
2762
+ from: {
2763
+ type: "positional",
2764
+ description: "Workspace merged, then removed",
2765
+ required: true
2766
+ },
2767
+ into: {
2768
+ type: "positional",
2769
+ description: "Workspace kept",
2770
+ required: true
2771
+ },
2772
+ "dry-run": {
2773
+ type: "boolean",
2774
+ default: false,
2775
+ description: "Print what would move, change nothing"
2776
+ },
2777
+ edit: {
2778
+ type: "boolean",
2779
+ default: true,
2780
+ description: "Open the merged instructions in $EDITOR (--no-edit to skip)"
2781
+ },
2782
+ yes: {
2783
+ type: "boolean",
2784
+ default: false,
2785
+ description: "Merge without asking"
2786
+ }
2787
+ },
2788
+ async run({ args }) {
2789
+ const io = processIo();
2790
+ process.exitCode = await workspaceErrorsAsync(io, () => workspaceMerge(args.from, args.into, io, {
2791
+ dryRun: args["dry-run"],
2792
+ edit: args.edit,
2793
+ yes: args.yes,
2794
+ confirm: process.stdin.isTTY ? askNo : void 0
2795
+ }));
2796
+ }
2797
+ }),
2182
2798
  drop: defineCommand({
2183
2799
  meta: {
2184
2800
  name: "drop",
@@ -2210,6 +2826,7 @@ const wsCommand = defineCommand({
2210
2826
  ...workspaceArgument,
2211
2827
  ...colorArgument
2212
2828
  },
2829
+ setup: askWorkspace,
2213
2830
  run({ args }) {
2214
2831
  process.exitCode = workspaceShow(processIo({ color: args.color }), { workspace: args.ws });
2215
2832
  }
@@ -2228,6 +2845,7 @@ const wsCommand = defineCommand({
2228
2845
  ...workspaceArgument,
2229
2846
  ...colorArgument
2230
2847
  },
2848
+ setup: askWorkspace,
2231
2849
  run({ args }) {
2232
2850
  process.exitCode = workspaceAdd(args.path, processIo({ color: args.color }), { workspace: args.ws });
2233
2851
  }
@@ -2246,6 +2864,7 @@ const wsCommand = defineCommand({
2246
2864
  ...workspaceArgument,
2247
2865
  ...colorArgument
2248
2866
  },
2867
+ setup: askWorkspace,
2249
2868
  run({ args }) {
2250
2869
  process.exitCode = workspaceRemove(args.path, processIo({ color: args.color }), { workspace: args.ws });
2251
2870
  }
@@ -2259,6 +2878,7 @@ const wsCommand = defineCommand({
2259
2878
  ...workspaceArgument,
2260
2879
  ...colorArgument
2261
2880
  },
2881
+ setup: askWorkspace,
2262
2882
  run({ args }) {
2263
2883
  process.exitCode = workspaceSync(processIo({ color: args.color }), { workspace: args.ws });
2264
2884
  }
@@ -2276,6 +2896,7 @@ const wsCommand = defineCommand({
2276
2896
  },
2277
2897
  ...workspaceArgument
2278
2898
  },
2899
+ setup: askWorkspace,
2279
2900
  async run({ args }) {
2280
2901
  process.exitCode = await workspaceEdit(processIo(), {
2281
2902
  workspace: args.ws,
@@ -2302,6 +2923,7 @@ const wsCommand = defineCommand({
2302
2923
  },
2303
2924
  ...workspaceArgument
2304
2925
  },
2926
+ setup: askWorkspace,
2305
2927
  run({ args }) {
2306
2928
  process.exitCode = workspacePath(processIo(), {
2307
2929
  workspace: args.ws,
@@ -2335,10 +2957,28 @@ const hookCommand = defineCommand({
2335
2957
  process.exitCode = sessionEnd(await readStdin(), processIo());
2336
2958
  }
2337
2959
  }),
2960
+ "pre-tool-use": defineCommand({
2961
+ meta: {
2962
+ name: "pre-tool-use",
2963
+ description: "PreToolUse hook: marks the main turn as waiting on the human"
2964
+ },
2965
+ async run() {
2966
+ process.exitCode = preToolUse(await readStdin(), processIo());
2967
+ }
2968
+ }),
2969
+ stop: defineCommand({
2970
+ meta: {
2971
+ name: "stop",
2972
+ description: "Stop hook: ends the main agent's turn"
2973
+ },
2974
+ async run() {
2975
+ process.exitCode = stopHook(await readStdin(), processIo());
2976
+ }
2977
+ }),
2338
2978
  "post-tool-use": defineCommand({
2339
2979
  meta: {
2340
2980
  name: "post-tool-use",
2341
- description: "PostToolUse hook: adds a repo's notes the first time a tool touches it"
2981
+ description: "PostToolUse hook: marks the main turn working, adds a repo's notes the first time a tool touches it"
2342
2982
  },
2343
2983
  async run() {
2344
2984
  process.exitCode = postToolUse(await readStdin(), processIo());
@@ -2347,7 +2987,7 @@ const hookCommand = defineCommand({
2347
2987
  "user-prompt-submit": defineCommand({
2348
2988
  meta: {
2349
2989
  name: "user-prompt-submit",
2350
- description: "UserPromptSubmit hook: names the session after a /rename"
2990
+ description: "UserPromptSubmit hook: starts the main turn, names the session after a /rename"
2351
2991
  },
2352
2992
  async run() {
2353
2993
  process.exitCode = userPromptSubmit(await readStdin(), processIo());
@@ -2373,6 +3013,23 @@ const hookCommand = defineCommand({
2373
3013
  })
2374
3014
  }
2375
3015
  });
3016
+ const statusLineCommand = defineCommand({
3017
+ meta: {
3018
+ name: "statusline",
3019
+ description: "Print the session's one-line status for a Claude Code statusLine command (JSON on stdin)"
3020
+ },
3021
+ args: { dir: {
3022
+ type: "boolean",
3023
+ description: "Print the folder of the status line files instead (for the plugin mod)"
3024
+ } },
3025
+ async run({ args }) {
3026
+ if (args.dir) {
3027
+ process.exitCode = statusLineDirectory(processIo());
3028
+ return;
3029
+ }
3030
+ process.exitCode = statusLine(await readStdin(), processIo());
3031
+ }
3032
+ });
2376
3033
  const serveCommand = defineCommand({
2377
3034
  meta: {
2378
3035
  name: "serve",
@@ -2382,21 +3039,16 @@ const serveCommand = defineCommand({
2382
3039
  serve(processIo());
2383
3040
  }
2384
3041
  });
2385
- function refuseRemovedOption(rawArgs) {
2386
- const removed = /^(-g|--group)(=|$)/;
2387
- const option = splitPassthrough([...rawArgs]).own.find((argument) => removed.test(argument));
2388
- if (option) fail(processIo(), new CliError(`Unknown option ${option}`, "use --ws <name>"));
2389
- }
2390
3042
  const main = defineCommand({
2391
3043
  meta: {
2392
3044
  name: "rucher",
2393
3045
  version,
2394
3046
  description: "Status, journal and sessions of your coding agents (Claude Code today)"
2395
3047
  },
2396
- setup: ({ rawArgs }) => refuseRemovedOption(rawArgs),
2397
3048
  subCommands: {
2398
3049
  status: statusCommand,
2399
3050
  log: logCommand,
3051
+ report: reportCommand,
2400
3052
  new: newCommand,
2401
3053
  tmp: tmpCommand,
2402
3054
  resume: resumeCommand,
@@ -2405,6 +3057,7 @@ const main = defineCommand({
2405
3057
  notes: notesCommand,
2406
3058
  ws: wsCommand,
2407
3059
  hook: hookCommand,
3060
+ statusline: statusLineCommand,
2408
3061
  serve: serveCommand
2409
3062
  }
2410
3063
  });