@rucher/cli 0.2.0-beta.4 → 0.2.0-beta.6

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 +4 -4
  2. package/dist/cli.mjs +900 -923
  3. package/package.json +2 -2
package/dist/cli.mjs CHANGED
@@ -3,9 +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, GROUP_FILE, LEGEND, NOTES_HEADER, NOTE_KINDS, SIMILAR_PREFIX, SUBAGENT_RULES, addGroupRepo, ambiguousGroupContext, appendPromptFile, archiveGroupSessions, claudeCode, createGroup, deleteGroupNotes, dropGroup, formatClock, groupExists, groupLabel, groupRepoNames, groupSessionCounts, handleSessionEnd, handleSessionStart, handleToolUse, handleUserPromptSubmit, hostById, isGroupName, listGroups, loadGroup, memoryHalfLife, moveSession, openCarnet, openGroupCarnet, openResolvedCarnet, removeGroupRepo, renameGroup, renameGroupRows, renderSections, renderWorkspace, repoNameFor, repoPathFor, requireGroup, resolveGroup, shortId, sourceInstructions } from "@rucher/carnet";
7
- import { spawnSync } from "node:child_process";
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";
8
7
  import { styleText } from "node:util";
8
+ import { spawnSync } from "node:child_process";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { createInterface } from "node:readline/promises";
11
11
  import { serveCarnet } from "@rucher/carnet/mcp";
@@ -27,22 +27,22 @@ function readTypedWords({ typedWords }) {
27
27
  const typed = typedWords.slice(0, -1);
28
28
  const passthrough = typed.indexOf("--");
29
29
  const own = passthrough === -1 ? typed : typed.slice(0, passthrough);
30
- const flag = own.findLastIndex((word) => word === "-g" || word === "--group");
30
+ const flag = own.lastIndexOf("--ws");
31
31
  return {
32
- group: flag === -1 ? void 0 : own[flag + 1],
33
- words: own.filter((_, index) => !(index > 0 && (own[index - 1] === "-g" || own[index - 1] === "--group")))
32
+ workspace: flag === -1 ? void 0 : own[flag + 1],
33
+ words: own.filter((_, index) => !(index > 0 && own[index - 1] === "--ws"))
34
34
  };
35
35
  }
36
- function inGroup(context) {
36
+ function inWorkspace(context) {
37
37
  return {
38
38
  cwd: context.cwd,
39
39
  env: context.env,
40
- group: readTypedWords(context).group
40
+ workspace: readTypedWords(context).workspace
41
41
  };
42
42
  }
43
43
  function suggestSessions(context, complete) {
44
44
  quietly(() => {
45
- const carnet = openCarnet(inGroup(context));
45
+ const carnet = openCarnet(inWorkspace(context));
46
46
  try {
47
47
  const typed = readTypedWords(context).words;
48
48
  const sessions = carnet.sessions.list({ includeTemp: true });
@@ -59,20 +59,20 @@ function suggestSessions(context, complete) {
59
59
  }
60
60
  });
61
61
  }
62
- function suggestGroups(context, complete) {
62
+ function suggestWorkspaces(context, complete) {
63
63
  quietly(() => {
64
- for (const group of listGroups(context.env)) complete(group.name, group.workspace);
64
+ for (const workspace of listWorkspaces(context.env)) complete(workspace.name, workspace.runDirectory);
65
65
  });
66
66
  }
67
67
  function suggestRepos(context, complete) {
68
68
  quietly(() => {
69
- for (const repo of resolveGroup(inGroup(context)).group?.repos ?? []) complete(repo.path, repo.name);
69
+ for (const repo of resolveWorkspace(inWorkspace(context)).workspace?.repos ?? []) complete(repo.path, repo.name);
70
70
  });
71
71
  }
72
72
  function suggestRepoNames(context, complete) {
73
73
  quietly(() => {
74
- const { group } = resolveGroup(inGroup(context));
75
- for (const repo of group ? groupRepoNames(group) : []) complete(repo, "");
74
+ const { workspace } = resolveWorkspace(inWorkspace(context));
75
+ for (const repo of workspace ? workspaceRepoNames(workspace) : []) complete(repo, "");
76
76
  });
77
77
  }
78
78
  function suggestNoteKinds(complete) {
@@ -80,7 +80,7 @@ function suggestNoteKinds(complete) {
80
80
  }
81
81
  function suggestNotes(context, complete) {
82
82
  quietly(() => {
83
- const carnet = openCarnet(inGroup(context));
83
+ const carnet = openCarnet(inWorkspace(context));
84
84
  try {
85
85
  for (const note of carnet.notes.list()) complete(String(note.id), note.text.slice(0, 60));
86
86
  } finally {
@@ -105,119 +105,119 @@ function processContext() {
105
105
  };
106
106
  }
107
107
  const sessions = (complete) => suggestSessions(processContext(), complete);
108
- const groups = (complete) => suggestGroups(processContext(), complete);
108
+ const workspaces = (complete) => suggestWorkspaces(processContext(), complete);
109
109
  const repos = (complete) => suggestRepos(processContext(), complete);
110
110
  const directories = (complete) => suggestDirectories(processContext(), complete);
111
111
  const repoNames = (complete) => suggestRepoNames(processContext(), complete);
112
112
  const noteKinds = (complete) => suggestNoteKinds(complete);
113
113
  const notes = (complete) => suggestNotes(processContext(), complete);
114
- const group = { group: groups };
114
+ const workspace = { ws: workspaces };
115
115
  const completionConfig = { subCommands: {
116
116
  status: { options: {
117
117
  session: sessions,
118
- ...group
118
+ ...workspace
119
119
  } },
120
120
  log: { options: {
121
121
  session: sessions,
122
- ...group
122
+ ...workspace
123
123
  } },
124
- new: { options: group },
125
- tmp: { options: group },
124
+ new: { options: workspace },
125
+ tmp: { options: workspace },
126
126
  resume: {
127
127
  args: { session: sessions },
128
- options: group
128
+ options: workspace
129
129
  },
130
130
  fork: {
131
131
  args: { session: sessions },
132
- options: group
132
+ options: workspace
133
133
  },
134
134
  sessions: {
135
- options: group,
135
+ options: workspace,
136
136
  subCommands: {
137
- list: { options: group },
137
+ list: { options: workspace },
138
138
  merge: {
139
139
  args: {
140
140
  from: sessions,
141
141
  into: sessions
142
142
  },
143
- options: group
143
+ options: workspace
144
144
  },
145
145
  move: {
146
146
  args: { session: sessions },
147
147
  options: {
148
- to: groups,
149
- ...group
148
+ to: workspaces,
149
+ ...workspace
150
150
  }
151
151
  },
152
152
  rename: {
153
153
  args: { session: sessions },
154
- options: group
154
+ options: workspace
155
155
  },
156
156
  promote: {
157
157
  args: { session: sessions },
158
- options: group
158
+ options: workspace
159
159
  },
160
160
  demote: {
161
161
  args: { session: sessions },
162
- options: group
162
+ options: workspace
163
163
  },
164
164
  drop: {
165
165
  args: { session: sessions },
166
- options: group
166
+ options: workspace
167
167
  },
168
- clean: { options: group }
168
+ clean: { options: workspace }
169
169
  }
170
170
  },
171
171
  notes: {
172
172
  options: {
173
173
  kind: noteKinds,
174
174
  repo: repoNames,
175
- ...group
175
+ ...workspace
176
176
  },
177
177
  subCommands: {
178
178
  list: { options: {
179
179
  kind: noteKinds,
180
180
  repo: repoNames,
181
- ...group
181
+ ...workspace
182
182
  } },
183
183
  show: {
184
184
  args: { id: notes },
185
- options: group
185
+ options: workspace
186
186
  },
187
187
  add: {
188
188
  args: { kind: noteKinds },
189
189
  options: {
190
190
  repo: repoNames,
191
- ...group
191
+ ...workspace
192
192
  }
193
193
  },
194
194
  drop: {
195
195
  args: { id: notes },
196
196
  options: {
197
197
  "replaced-by": notes,
198
- ...group
198
+ ...workspace
199
199
  }
200
200
  }
201
201
  }
202
202
  },
203
- group: { subCommands: {
204
- show: { options: group },
205
- add: {
206
- args: { path: directories },
207
- options: group
208
- },
209
- remove: {
210
- args: { path: repos },
211
- options: group
212
- },
213
- sync: { options: group },
214
- edit: { options: group },
215
- path: { options: group }
216
- } },
217
- groups: { subCommands: {
218
- rename: { args: { from: groups } },
219
- drop: { args: { name: groups } }
220
- } }
203
+ ws: {
204
+ options: workspace,
205
+ subCommands: {
206
+ drop: { args: { name: workspaces } },
207
+ show: { options: workspace },
208
+ add: {
209
+ args: { path: directories },
210
+ options: workspace
211
+ },
212
+ remove: {
213
+ args: { path: repos },
214
+ options: workspace
215
+ },
216
+ sync: { options: workspace },
217
+ edit: { options: workspace },
218
+ path: { options: workspace }
219
+ }
220
+ }
221
221
  } };
222
222
  async function setupCompletion(main) {
223
223
  const subCommands = await (typeof main.subCommands === "function" ? main.subCommands() : main.subCommands);
@@ -239,165 +239,137 @@ async function setupCompletion(main) {
239
239
  };
240
240
  }
241
241
  // package.json
242
- var version = "0.2.0-beta.4";
243
- // src/color.ts
244
- function paint(io) {
245
- const style = (name) => (text) => io.color ? styleText(name, text, { validateStream: false }) : text;
246
- return {
247
- bold: style("bold"),
248
- dim: style("dim"),
249
- yellow: style("yellow"),
250
- red: style("red"),
251
- cyan: style("cyan")
252
- };
253
- }
254
- // src/group-option.ts
255
- const groupArgument = { group: {
256
- type: "string",
257
- alias: "g",
258
- description: "Group name (default: from RUCHER_GROUP, the workspace or the repo you are in)"
259
- } };
260
- function announceGroup(io, resolution) {
261
- if (!resolution.group) return;
262
- if (resolution.origin === "workspace") io.stderr(`group ${resolution.group.name} (from its workspace)\n`);
263
- else if (resolution.origin === "repo" && resolution.repo) io.stderr(`group ${resolution.group.name} (from ${resolution.repo.name})\n`);
264
- }
265
- function warnNoGroup(carnet, io) {
266
- if (!carnet.group) io.stderr("no group here: pass -g after the subcommand\n");
267
- }
268
- function openCliCarnet(io, group) {
269
- const { carnet, resolution } = openResolvedCarnet({
270
- cwd: io.cwd,
271
- env: io.env,
272
- group
273
- });
274
- announceGroup(io, resolution);
275
- return carnet;
276
- }
277
- function currentGroup(io, group) {
278
- const resolution = resolveGroup({
279
- cwd: io.cwd,
280
- env: io.env,
281
- group
282
- });
283
- const found = requireGroup(resolution.group);
284
- announceGroup(io, resolution);
285
- return found;
286
- }
287
- // src/commands/group.ts
288
- function carnetErrors(io, run) {
242
+ var version = "0.2.0-beta.6";
243
+ // src/commands/hook.ts
244
+ const host = claudeCode;
245
+ function runHook(io, run, hookEventName) {
289
246
  try {
290
- return run();
247
+ run();
291
248
  } catch (error) {
292
- if (error instanceof CarnetError) {
293
- io.stderr(`error: ${error.message}\n`);
294
- return 1;
249
+ 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;
295
260
  }
296
- throw error;
261
+ io.stderr(`rucher hook: ${error instanceof Error ? error.message : String(error)}\n`);
297
262
  }
263
+ return 0;
298
264
  }
299
- function rendered(group, io) {
300
- const result = renderWorkspace(group, { env: io.env });
301
- return [...result.written.map((path) => `written ${path}`), ...result.removed.map((path) => `removed ${path}`)];
265
+ function withCarnet$1(payload, io, use) {
266
+ const carnet = openCarnet({
267
+ cwd: payload.cwd ?? io.cwd,
268
+ env: io.env,
269
+ sessionId: payload.session_id
270
+ });
271
+ try {
272
+ const known = payload.session_id ? carnet.sessions.get(payload.session_id) : void 0;
273
+ if (!carnet.workspace && !io.env.RUCHER_SESSION_ID && !known) return;
274
+ use(carnet);
275
+ } finally {
276
+ carnet.close();
277
+ }
302
278
  }
303
- function withChanges(line, changes) {
304
- return `${line}${changes.length ? ` (${changes.join(", ")})` : ""}\n`;
279
+ function sessionStart(stdinText, io) {
280
+ return runHook(io, () => {
281
+ const payload = host.parseSessionPayload(stdinText);
282
+ withCarnet$1(payload, io, (carnet) => {
283
+ const { additionalContext, notices } = handleSessionStart(carnet, payload, {
284
+ host: host.id,
285
+ processId: host.processId(io.env),
286
+ RUCHER_PURGE_DAYS: io.env.RUCHER_PURGE_DAYS,
287
+ RUCHER_HOME: io.env.RUCHER_HOME,
288
+ RUCHER_SESSION_ID: io.env.RUCHER_SESSION_ID,
289
+ RUCHER_SESSION_KIND: io.env.RUCHER_SESSION_KIND,
290
+ RUCHER_SESSION_NAME: io.env.RUCHER_SESSION_NAME,
291
+ RUCHER_PROMPT_VERSION: io.env.RUCHER_PROMPT_VERSION,
292
+ RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
293
+ RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
294
+ });
295
+ for (const notice of notices) io.stderr(`${notice}\n`);
296
+ if (additionalContext) {
297
+ const hookSpecificOutput = {
298
+ hookEventName: "SessionStart",
299
+ additionalContext
300
+ };
301
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
302
+ }
303
+ });
304
+ }, "SessionStart");
305
305
  }
306
- function groupShow(io, options = {}) {
307
- return carnetErrors(io, () => {
308
- const colors = paint(io);
309
- const group = currentGroup(io, options.group);
310
- const repos = group.repos.length ? group.repos.map((repo) => ` ${repo.name} ${colors.dim(repo.path)}`).join("\n") : ` ${colors.dim("none")}`;
311
- io.stdout(`${colors.bold(group.name)}\nsource: ${group.source}\nworkspace: ${group.workspace}\nrepos:\n${repos}\n`);
312
- return 0;
306
+ function subagentStart(stdinText, io) {
307
+ return runHook(io, () => {
308
+ const payload = host.parseSubagentPayload(stdinText);
309
+ withCarnet$1(payload, io, (carnet) => {
310
+ carnet.agents.pairSubagent(payload.session_id, payload.agent_id);
311
+ });
312
+ if (host.subagentInheritsContext(payload)) return;
313
+ const hookSpecificOutput = {
314
+ hookEventName: "SubagentStart",
315
+ additionalContext: SUBAGENT_RULES
316
+ };
317
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
313
318
  });
314
319
  }
315
- function groupAdd(repo, io, options = {}) {
316
- return carnetErrors(io, () => {
317
- const found = currentGroup(io, options.group);
318
- const path = resolve(io.cwd, repo);
319
- const group = addGroupRepo(found.name, path, io.env);
320
- io.stdout(withChanges(`added ${basename(path)} to ${group.name}`, rendered(group, io)));
321
- return 0;
320
+ function subagentStop(stdinText, io) {
321
+ return runHook(io, () => {
322
+ const payload = host.parseSubagentPayload(stdinText);
323
+ withCarnet$1(payload, io, (carnet) => {
324
+ carnet.agents.stopSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload));
325
+ });
322
326
  });
323
327
  }
324
- function groupRemove(repo, io, options = {}) {
325
- return carnetErrors(io, () => {
326
- const found = currentGroup(io, options.group);
327
- const group = removeGroupRepo(found.name, resolve(io.cwd, repo), io.env);
328
- io.stdout(withChanges(`removed ${basename(repo)} from ${group.name}`, rendered(group, io)));
329
- return 0;
330
- });
328
+ function userPromptSubmit(stdinText, io) {
329
+ return runHook(io, () => {
330
+ const payload = host.parsePromptPayload(stdinText);
331
+ withCarnet$1(payload, io, (carnet) => {
332
+ handleUserPromptSubmit(carnet, host, payload);
333
+ });
334
+ }, "UserPromptSubmit");
331
335
  }
332
- function groupSync(io, options = {}) {
333
- return carnetErrors(io, () => {
334
- const group = currentGroup(io, options.group);
335
- const changes = rendered(group, io);
336
- io.stdout(changes.length ? `${[`synced ${group.name}`, ...changes.map((change) => ` ${change}`)].join("\n")}\n` : `${group.name} already in sync\n`);
337
- return 0;
336
+ function postToolUse(stdinText, io) {
337
+ return runHook(io, () => {
338
+ const payload = host.parseToolPayload(stdinText);
339
+ if (payload.agent_id || !payload.path) return;
340
+ withCarnet$1(payload, io, (carnet) => {
341
+ const additionalContext = handleToolUse(carnet, payload, {
342
+ RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
343
+ RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
344
+ });
345
+ if (!additionalContext) return;
346
+ const hookSpecificOutput = {
347
+ hookEventName: "PostToolUse",
348
+ additionalContext
349
+ };
350
+ io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
351
+ });
338
352
  });
339
353
  }
340
- function groupPath(io, options = {}) {
341
- return carnetErrors(io, () => {
342
- const group = currentGroup(io, options.group);
343
- io.stdout(`${options.source ? group.source : group.workspace}\n`);
344
- return 0;
354
+ function sessionEnd(stdinText, io) {
355
+ return runHook(io, () => {
356
+ const payload = host.parseSessionEndPayload(stdinText);
357
+ withCarnet$1(payload, io, (carnet) => {
358
+ handleSessionEnd(carnet, payload);
359
+ });
345
360
  });
346
361
  }
347
- function editorCommand(env) {
348
- return env.VISUAL || env.EDITOR || "vi";
349
- }
350
- function openEditorFor(io) {
351
- return (file) => {
352
- return spawnSync(`${editorCommand(io.env)} "$RUCHER_EDIT_FILE"`, {
353
- shell: true,
354
- stdio: "inherit",
355
- env: {
356
- ...io.env,
357
- RUCHER_EDIT_FILE: file
358
- }
359
- }).status ?? 1;
362
+ // src/color.ts
363
+ function paint(io) {
364
+ const style = (name) => (text) => io.color ? styleText(name, text, { validateStream: false }) : text;
365
+ return {
366
+ bold: style("bold"),
367
+ dim: style("dim"),
368
+ yellow: style("yellow"),
369
+ red: style("red"),
370
+ cyan: style("cyan")
360
371
  };
361
372
  }
362
- function invalidGroupFile(name, io) {
363
- try {
364
- loadGroup(name, io.env);
365
- return null;
366
- } catch (error) {
367
- return error instanceof Error ? error.message : String(error);
368
- }
369
- }
370
- async function groupEdit(io, options = {}) {
371
- let group;
372
- let file;
373
- try {
374
- group = currentGroup(io, options.group);
375
- file = join(group.source, options.json ? GROUP_FILE : sourceInstructions(group));
376
- } catch (error) {
377
- if (error instanceof CarnetError) {
378
- io.stderr(`error: ${error.message}\n`);
379
- return 1;
380
- }
381
- throw error;
382
- }
383
- const original = readFileSync(file, "utf8");
384
- const openEditor = options.openEditor ?? openEditorFor(io);
385
- for (;;) {
386
- if (openEditor(file) !== 0) {
387
- io.stderr(`error: ${editorCommand(io.env)} exited with an error, nothing synced\n`);
388
- return 1;
389
- }
390
- const problem = options.json ? invalidGroupFile(group.name, io) : null;
391
- if (!problem) break;
392
- io.stderr(`error: ${GROUP_FILE} is invalid: ${problem}\n`);
393
- if (!options.confirm || !await options.confirm("Edit it again? [Y/n] ")) {
394
- writeFileSync(file, original);
395
- io.stderr(`restored the previous ${GROUP_FILE}\n`);
396
- return 1;
397
- }
398
- }
399
- return groupSync(io, { group: group.name });
400
- }
401
373
  // src/session.ts
402
374
  var CliError = class extends Error {
403
375
  hint;
@@ -419,394 +391,27 @@ function findSession(carnet, reference) {
419
391
  function resolveSession(carnet, reference) {
420
392
  if (reference) return findSession(carnet, reference);
421
393
  const session = carnet.sessions.default();
422
- if (!session) throw new CliError("No session in this group yet", "start a Claude Code session inside the group");
394
+ if (!session) throw new CliError("No session in this workspace yet", "start a Claude Code session inside the workspace");
423
395
  return session;
424
396
  }
425
- // src/commands/sessions.ts
426
- function lastActive(at, now) {
427
- const date = new Date(at);
428
- return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
397
+ // src/commands/log.ts
398
+ function formatEvents(events, io) {
399
+ const colors = paint(io);
400
+ if (events.length === 0) return colors.dim("no events yet");
401
+ return events.map((event) => {
402
+ return [
403
+ colors.dim(formatClock(new Date(event.at))),
404
+ colors.bold(event.type.padEnd(9)),
405
+ event.agent ?? "",
406
+ event.link ?? event.note ?? "",
407
+ event.commit ? colors.cyan(event.commit.slice(0, 7)) : ""
408
+ ].filter(Boolean).join(" ");
409
+ }).join("\n");
429
410
  }
430
- function row(carnet, session, now) {
431
- const open = carnet.agents.list(session.id).length;
432
- return [
433
- session.name ?? session.id.slice(0, 8),
434
- session.kind,
435
- session.status,
436
- repoPathFor(carnet.group, session.cwd) ?? session.repo ?? "",
437
- lastActive(session.lastActiveAt, now),
438
- open ? `${open} agent${open > 1 ? "s" : ""}` : "",
439
- session.purpose ?? ""
440
- ];
441
- }
442
- function sessionsOnce(carnet, io, options = {}) {
443
- const colors = paint(io);
444
- const sessions = carnet.sessions.list({
445
- includeTemp: options.all,
446
- includeArchived: options.all
447
- });
448
- warnNoGroup(carnet, io);
449
- if (sessions.length === 0) {
450
- const hint = options.all ? "" : " (temp and archived ones are hidden, use --all)";
451
- if (carnet.group) io.stdout(`${colors.dim(`no active session yet${hint}`)}\n`);
452
- return;
453
- }
454
- const now = options.now ?? /* @__PURE__ */ new Date();
455
- const rows = sessions.map((session) => ({
456
- session,
457
- cells: row(carnet, session, now)
458
- }));
459
- const widths = rows.reduce((current, { cells }) => cells.map((cell, column) => Math.max(current[column] ?? 0, cell.length)), []);
460
- const lines = rows.map(({ session, cells }) => {
461
- return cells.map((cell, column) => {
462
- const padded = column < cells.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell;
463
- if (column === 0) return colors.bold(padded);
464
- if (column === 1 && session.kind === "temp") return colors.dim(padded);
465
- if (column === 2 && session.status === "archived") return colors.dim(padded);
466
- return padded;
467
- }).join(" ").trimEnd();
468
- });
469
- io.stdout(`${lines.join("\n")}\n`);
470
- }
471
- function sessionsMerge(carnet, fromReference, intoReference, io) {
472
- const from = findSession(carnet, fromReference);
473
- const into = findSession(carnet, intoReference);
474
- const result = carnet.sessions.merge(from.id, into.id);
475
- const label = (session) => session.name ?? session.id.slice(0, 8);
476
- const lines = [
477
- `merged ${label(from)} into ${label(result.session)}`,
478
- ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
479
- ...result.closedAgents.length ? [` agents closed (name already used): ${result.closedAgents.join(", ")}`] : [],
480
- ` events moved: ${result.movedEvents}`,
481
- ` table line moved: ${result.movedTable ? "yes" : "no"}`
482
- ];
483
- io.stdout(`${lines.join("\n")}\n`);
484
- }
485
- function label(session) {
486
- return session.name ?? shortId(session.id);
487
- }
488
- function groupNamed(name, io) {
489
- if (!groupExists(name, io.env)) throw new CliError(`No group named "${name}"`, "see rucher groups list");
490
- return loadGroup(name, io.env);
491
- }
492
- function sessionsMove(carnet, reference, groupReference, io, options = {}) {
493
- const session = findSession(carnet, reference);
494
- const target = groupNamed(groupReference, io).name;
495
- const result = moveSession(carnet, session.id, target, options);
496
- const into = result.into ? ` into ${label(result.into)}` : "";
497
- const lines = [
498
- `${options.dryRun ? "would move" : "moved"} ${label(session)} from ${groupLabel(carnet.group)} to ${target}${into}`,
499
- ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
500
- ...result.skippedAgents.length ? [` agents left out (name already used): ${result.skippedAgents.join(", ")}`] : [],
501
- ` events moved: ${result.movedEvents}`,
502
- ` table line moved: ${result.movedTable ? "yes" : "no"}`,
503
- ...result.keptNotes ? [` notes kept in ${groupLabel(carnet.group)}: ${result.keptNotes}`] : []
504
- ];
505
- io.stdout(`${lines.join("\n")}\n`);
506
- }
507
- function sessionsRename(carnet, reference, name, io) {
508
- const session = carnet.sessions.rename(findSession(carnet, reference).id, name);
509
- io.stdout(`renamed to ${session.name}; rucher resume ${session.name} gives Claude the same title\n`);
510
- }
511
- function sessionsPromote(carnet, reference, name, io) {
512
- const session = carnet.sessions.promote(findSession(carnet, reference).id, name);
513
- io.stdout(`${label(session)} is now active\n`);
514
- }
515
- function sessionsDemote(carnet, reference, io) {
516
- const session = carnet.sessions.demote(findSession(carnet, reference).id);
517
- io.stdout(`${label(session)} is now temp, cleaned by rucher sessions clean once idle\n`);
518
- }
519
- function purgeTranscripts(session, io) {
520
- const files = hostById(session.host).transcriptFiles(session, io.env);
521
- for (const file of files) {
522
- rmSync(file, {
523
- recursive: true,
524
- force: true
525
- });
526
- io.stdout(` deleted ${file}\n`);
527
- }
528
- if (files.length === 0) io.stdout(" no transcript found\n");
529
- }
530
- function sessionsDrop(carnet, reference, io, options = {}) {
531
- const session = findSession(carnet, reference);
532
- if (options.purge && session.status === "running") throw new CliError(`Session ${label(session)} is running`, "drop it with --purge once it has ended");
533
- carnet.sessions.drop(session.id);
534
- io.stdout(`archived ${label(session)}\n`);
535
- if (options.purge) purgeTranscripts(session, io);
536
- }
537
- const UNIT_MILLISECONDS = {
538
- m: 6e4,
539
- h: 36e5,
540
- d: 864e5
541
- };
542
- function parseDuration(value) {
543
- const match = /^(\d+(?:\.\d+)?)([mhd]?)$/.exec(value.trim());
544
- if (!match) throw new CliError(`Invalid duration "${value}"`, "use a number of days, or 30m, 12h, 7d");
545
- return Number(match[1]) * (UNIT_MILLISECONDS[match[2] || "d"] ?? 0);
546
- }
547
- function processIsAlive(processId) {
548
- try {
549
- process.kill(processId, 0);
550
- return true;
551
- } catch (error) {
552
- return error.code === "EPERM";
553
- }
554
- }
555
- function sessionsClean(carnet, io, options = {}) {
556
- const olderThan = parseDuration(options.olderThan ?? "7d");
557
- if (!options.dryRun) for (const session of carnet.sessions.resetDead(options.isAlive ?? processIsAlive)) io.stdout(`${label(session)} was marked running but its process is gone: now idle\n`);
558
- const stale = carnet.sessions.staleTemp(olderThan);
559
- if (stale.length === 0) {
560
- io.stdout(`no temp session idle for more than ${options.olderThan ?? "7d"}\n`);
561
- return;
562
- }
563
- for (const session of stale) {
564
- if (options.dryRun) {
565
- io.stdout(`would archive ${label(session)}${options.purge ? " and delete its transcript" : ""}\n`);
566
- continue;
567
- }
568
- carnet.sessions.drop(session.id);
569
- io.stdout(`archived ${label(session)}\n`);
570
- if (options.purge) purgeTranscripts(session, io);
571
- }
572
- }
573
- // src/commands/groups.ts
574
- function plural(count, word) {
575
- return `${count} ${word}${count === 1 ? "" : "s"}`;
576
- }
577
- function groupsList(io) {
578
- const colors = paint(io);
579
- const groups = listGroups(io.env);
580
- if (groups.length === 0) {
581
- io.stdout(`${colors.dim("no group yet, create one with `rucher groups create <name>`")}\n`);
582
- return 0;
583
- }
584
- const carnet = openGroupCarnet(null, { env: io.env });
585
- const sessions = groupSessionCounts(carnet.db);
586
- carnet.close();
587
- const width = Math.max(...groups.map((group) => group.name.length));
588
- const lines = groups.map((group) => `${colors.bold(group.name.padEnd(width))} ${plural(group.repos.length, "repo")} ${plural(sessions.get(group.name) ?? 0, "session")} ${colors.dim(group.workspace)}`);
589
- io.stdout(`${lines.join("\n")}\n`);
590
- return 0;
591
- }
592
- function groupsCreate(name, io, options = {}) {
593
- const colors = paint(io);
594
- const group = createGroup(name, {
595
- repos: options.repos?.map((repo) => resolve(io.cwd, repo)),
596
- env: io.env
597
- });
598
- const result = renderWorkspace(group, { env: io.env });
599
- const lines = [
600
- `${colors.bold(group.name)} created`,
601
- ` source: ${group.source}`,
602
- ` workspace: ${group.workspace}`,
603
- ` repos: ${group.repos.length ? group.repos.map((repo) => repo.path).join(", ") : "none yet, add them with `rucher group add <path> -g " + group.name + "`"}`,
604
- ...result.written.map((path) => ` written ${path}`),
605
- "",
606
- "Accept the Claude Code trust prompt in its first session: until then the workspace settings are ignored, and rucher passes the repos with --add-dir.",
607
- `Next: \`rucher group edit -g ${group.name}\` for its instructions, then \`rucher new <session> -g ${group.name}\`.`
608
- ];
609
- io.stdout(`${lines.join("\n")}\n`);
610
- return 0;
611
- }
612
- function liveSessions(carnet, isAlive) {
613
- return carnet.sessions.list({ includeTemp: true }).filter((session) => session.status === "running" && session.hostPid !== null && isAlive(session.hostPid));
614
- }
615
- function refuseLive(carnet, action, isAlive) {
616
- const live = liveSessions(carnet, isAlive);
617
- if (live.length) throw new CliError(`${plural(live.length, "session")} of ${carnet.group?.name} still running: ${live.map((session) => session.name ?? session.id.slice(0, 8)).join(", ")}`, `end them before you ${action} the group`);
618
- }
619
- function groupsRename(from, to, io, options = {}) {
620
- const carnet = openGroupCarnet(loadGroup(from, io.env), { env: io.env });
621
- try {
622
- refuseLive(carnet, "rename", options.isAlive ?? processIsAlive);
623
- const group = renameGroup(from, to, io.env);
624
- try {
625
- renameGroupRows(carnet.db, from, to);
626
- } catch (error) {
627
- renameGroup(to, from, io.env);
628
- throw error;
629
- }
630
- io.stdout(`renamed ${from} to ${to}; its workspace stays at ${group.workspace}\n`);
631
- return 0;
632
- } finally {
633
- carnet.close();
634
- }
635
- }
636
- function groupsDrop(name, io, options = {}) {
637
- const carnet = openGroupCarnet(loadGroup(name, io.env), { env: io.env });
638
- try {
639
- refuseLive(carnet, "drop", options.isAlive ?? processIsAlive);
640
- const at = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
641
- const archived = archiveGroupSessions(carnet.db, name, at);
642
- const deletedNotes = options.purge ? deleteGroupNotes(carnet.db, name) : 0;
643
- const group = dropGroup(name, {
644
- purge: options.purge,
645
- env: io.env
646
- });
647
- const lines = [
648
- `dropped ${name}: source ${group.source} removed`,
649
- ` sessions archived: ${archived}`,
650
- options.purge ? ` notes deleted: ${deletedNotes}; workspace ${group.workspace} removed` : ` notes and workspace kept; recreate the group under the same name to see them again`
651
- ];
652
- io.stdout(`${lines.join("\n")}\n`);
653
- return 0;
654
- } finally {
655
- carnet.close();
656
- }
657
- }
658
- function groupsErrors(io, run) {
659
- try {
660
- return run();
661
- } catch (error) {
662
- if (error instanceof CliError) {
663
- io.stderr(`error: ${error.message}${error.hint ? `\n ${error.hint}` : ""}\n`);
664
- return 1;
665
- }
666
- if (error instanceof CarnetError) {
667
- io.stderr(`error: ${error.message}\n`);
668
- return 1;
669
- }
670
- throw error;
671
- }
672
- }
673
- // src/commands/hook.ts
674
- const host = claudeCode;
675
- function runHook(io, run, hookEventName) {
676
- try {
677
- run();
678
- } catch (error) {
679
- if (error instanceof CarnetError && error.code === "NO_GROUP") return 0;
680
- if (error instanceof CarnetError && error.code === "GROUP_AMBIGUOUS") {
681
- if (hookEventName) {
682
- io.stderr(`rucher: ${error.message}\n`);
683
- const additionalContext = ambiguousGroupContext(error.message);
684
- io.stdout(`${JSON.stringify({ hookSpecificOutput: {
685
- hookEventName,
686
- additionalContext
687
- } })}\n`);
688
- }
689
- return 0;
690
- }
691
- io.stderr(`rucher hook: ${error instanceof Error ? error.message : String(error)}\n`);
692
- }
693
- return 0;
694
- }
695
- function withCarnet$1(payload, io, use) {
696
- const carnet = openCarnet({
697
- cwd: payload.cwd ?? io.cwd,
698
- env: io.env,
699
- sessionId: payload.session_id
700
- });
701
- try {
702
- const known = payload.session_id ? carnet.sessions.get(payload.session_id) : void 0;
703
- if (!carnet.group && !io.env.RUCHER_SESSION_ID && !known) return;
704
- use(carnet);
705
- } finally {
706
- carnet.close();
707
- }
708
- }
709
- function sessionStart(stdinText, io) {
710
- return runHook(io, () => {
711
- const payload = host.parseSessionPayload(stdinText);
712
- withCarnet$1(payload, io, (carnet) => {
713
- const { additionalContext, notices } = handleSessionStart(carnet, payload, {
714
- host: host.id,
715
- processId: host.processId(io.env),
716
- RUCHER_PURGE_DAYS: io.env.RUCHER_PURGE_DAYS,
717
- RUCHER_HOME: io.env.RUCHER_HOME,
718
- RUCHER_SESSION_ID: io.env.RUCHER_SESSION_ID,
719
- RUCHER_SESSION_KIND: io.env.RUCHER_SESSION_KIND,
720
- RUCHER_SESSION_NAME: io.env.RUCHER_SESSION_NAME,
721
- RUCHER_PROMPT_VERSION: io.env.RUCHER_PROMPT_VERSION,
722
- RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
723
- RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
724
- });
725
- for (const notice of notices) io.stderr(`${notice}\n`);
726
- if (additionalContext) {
727
- const hookSpecificOutput = {
728
- hookEventName: "SessionStart",
729
- additionalContext
730
- };
731
- io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
732
- }
733
- });
734
- }, "SessionStart");
735
- }
736
- function subagentStart(stdinText, io) {
737
- return runHook(io, () => {
738
- const payload = host.parseSubagentPayload(stdinText);
739
- withCarnet$1(payload, io, (carnet) => {
740
- carnet.agents.pairSubagent(payload.session_id, payload.agent_id);
741
- });
742
- if (host.subagentInheritsContext(payload)) return;
743
- const hookSpecificOutput = {
744
- hookEventName: "SubagentStart",
745
- additionalContext: SUBAGENT_RULES
746
- };
747
- io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
748
- });
749
- }
750
- function subagentStop(stdinText, io) {
751
- return runHook(io, () => {
752
- const payload = host.parseSubagentPayload(stdinText);
753
- withCarnet$1(payload, io, (carnet) => {
754
- carnet.agents.stopSubagent(payload.session_id, payload.agent_id, host.subagentNames(payload));
755
- });
756
- });
757
- }
758
- function userPromptSubmit(stdinText, io) {
759
- return runHook(io, () => {
760
- const payload = host.parsePromptPayload(stdinText);
761
- withCarnet$1(payload, io, (carnet) => {
762
- handleUserPromptSubmit(carnet, host, payload);
763
- });
764
- }, "UserPromptSubmit");
765
- }
766
- function postToolUse(stdinText, io) {
767
- return runHook(io, () => {
768
- const payload = host.parseToolPayload(stdinText);
769
- if (payload.agent_id || !payload.path) return;
770
- withCarnet$1(payload, io, (carnet) => {
771
- const additionalContext = handleToolUse(carnet, payload, {
772
- RUCHER_MEMORY_MAX_CHARACTERS: io.env.RUCHER_MEMORY_MAX_CHARACTERS,
773
- RUCHER_MEMORY_HALF_LIFE_DAYS: io.env.RUCHER_MEMORY_HALF_LIFE_DAYS
774
- });
775
- if (!additionalContext) return;
776
- const hookSpecificOutput = {
777
- hookEventName: "PostToolUse",
778
- additionalContext
779
- };
780
- io.stdout(`${JSON.stringify({ hookSpecificOutput })}\n`);
781
- });
782
- });
783
- }
784
- function sessionEnd(stdinText, io) {
785
- return runHook(io, () => {
786
- const payload = host.parseSessionEndPayload(stdinText);
787
- withCarnet$1(payload, io, (carnet) => {
788
- handleSessionEnd(carnet, payload);
789
- });
790
- });
791
- }
792
- // src/commands/log.ts
793
- function formatEvents(events, io) {
794
- const colors = paint(io);
795
- if (events.length === 0) return colors.dim("no events yet");
796
- return events.map((event) => {
797
- return [
798
- colors.dim(formatClock(new Date(event.at))),
799
- colors.bold(event.type.padEnd(9)),
800
- event.agent ?? "",
801
- event.link ?? event.note ?? "",
802
- event.commit ? colors.cyan(event.commit.slice(0, 7)) : ""
803
- ].filter(Boolean).join(" ");
804
- }).join("\n");
805
- }
806
- function formatDay(date) {
807
- const month = String(date.getMonth() + 1).padStart(2, "0");
808
- const day = String(date.getDate()).padStart(2, "0");
809
- return `${date.getFullYear()}-${month}-${day}`;
411
+ function formatDay(date) {
412
+ const month = String(date.getMonth() + 1).padStart(2, "0");
413
+ const day = String(date.getDate()).padStart(2, "0");
414
+ return `${date.getFullYear()}-${month}-${day}`;
810
415
  }
811
416
  function markdownEvent(event) {
812
417
  const parts = [`${formatClock(new Date(event.at))} **${event.type}**`];
@@ -833,13 +438,48 @@ function formatEventsMarkdown(events, title) {
833
438
  return lines.join("\n");
834
439
  }
835
440
  function sessionTitle(carnet, session) {
836
- return `${groupLabel(carnet.group)} · ${session.name ?? session.id.slice(0, 8)}`;
441
+ return `${workspaceLabel(carnet.workspace)} · ${session.name ?? session.id.slice(0, 8)}`;
837
442
  }
838
443
  function logOnce(carnet, io, options) {
839
444
  const session = resolveSession(carnet, options.session);
840
445
  const events = carnet.events.read(session.id, options.count, options.agents);
841
446
  io.stdout(`${options.md ? formatEventsMarkdown(events, sessionTitle(carnet, session)) : formatEvents(events, io)}\n`);
842
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;
482
+ }
843
483
  // src/commands/notes.ts
844
484
  const KIND_TITLES = {
845
485
  dead_end: "Dead ends",
@@ -888,7 +528,7 @@ function markdown(carnet, notes) {
888
528
  });
889
529
  return `## ${KIND_TITLES[kind]}\n\n${lines.join("\n")}`;
890
530
  });
891
- return `# Memory: ${groupLabel(carnet.group)}\n\n${sections.join("\n\n") || "No notes."}\n`;
531
+ return `# Memory: ${workspaceLabel(carnet.workspace)}\n\n${sections.join("\n\n") || "No notes."}\n`;
892
532
  }
893
533
  function notesList(carnet, io, options = {}) {
894
534
  const notes = options.stale ? carnet.notes.stale(halfLife(io)) : carnet.notes.list({
@@ -903,15 +543,15 @@ function notesList(carnet, io, options = {}) {
903
543
  return;
904
544
  }
905
545
  const colors = paint(io);
906
- warnNoGroup(carnet, io);
546
+ warnNoWorkspace(carnet, io);
907
547
  if (notes.length === 0) {
908
- if (carnet.group) io.stdout(`${colors.dim(options.stale ? "no note to review" : "no notes")}\n`);
548
+ if (carnet.workspace) io.stdout(`${colors.dim(options.stale ? "no note to review" : "no notes")}\n`);
909
549
  return;
910
550
  }
911
551
  const blocks = grouped(notes).map(([kind, kindNotes]) => `${colors.bold(KIND_TITLES[kind])}\n${kindNotes.map((note) => noteLine(io, note)).join("\n")}`);
912
552
  io.stdout(`${blocks.join("\n\n")}\n`);
913
553
  }
914
- function sessionLabel$1(carnet, id) {
554
+ function sessionLabel$2(carnet, id) {
915
555
  if (!id) return "-";
916
556
  return carnet.sessions.get(id)?.name ?? shortId(id);
917
557
  }
@@ -926,7 +566,7 @@ function notesShow(carnet, io, id) {
926
566
  `${colors.bold(`#${note.id}`)} ${note.kind}${note.droppedAt ? colors.dim(" (dropped)") : ""}`,
927
567
  note.text,
928
568
  `repos: ${note.repos.length ? note.repos.join(", ") : "general"}`,
929
- `added: ${when(note.createdAt)} in ${sessionLabel$1(carnet, note.session)}${note.agent ? `, from ${note.agent}` : ""}`,
569
+ `added: ${when(note.createdAt)} in ${sessionLabel$2(carnet, note.session)}${note.agent ? `, from ${note.agent}` : ""}`,
930
570
  `weight: ${note.weight.toFixed(2)} · ${note.citationCount} citation${note.citationCount === 1 ? "" : "s"}`
931
571
  ];
932
572
  if (note.similarNotes.length) lines.push(colors.yellow(`similar to: ${note.similarNotes.map((other) => `#${other}`).join(", ")}`));
@@ -938,7 +578,7 @@ function notesShow(carnet, io, id) {
938
578
  lines.push("citations:");
939
579
  for (const citation of note.citations) {
940
580
  const by = citation.agent ? ` ${citation.agent}` : "";
941
- lines.push(` ${when(citation.at)} ${sessionLabel$1(carnet, citation.session)}${by} ${citation.why}`);
581
+ lines.push(` ${when(citation.at)} ${sessionLabel$2(carnet, citation.session)}${by} ${citation.why}`);
942
582
  }
943
583
  }
944
584
  io.stdout(`${lines.join("\n")}\n`);
@@ -975,13 +615,13 @@ function splitPassthrough(rawArgs) {
975
615
  function positionals(own) {
976
616
  return own.filter((argument) => !argument.startsWith("-"));
977
617
  }
978
- function launchEnv(group, session, promptVersion, kind) {
618
+ function launchEnv(workspace, session, promptVersion, kind) {
979
619
  return {
980
620
  RUCHER_SESSION_ID: session.id,
981
621
  RUCHER_PROMPT_VERSION: promptVersion,
982
622
  RUCHER_SESSION_NAME: session.name ?? "",
983
623
  CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: "1",
984
- ...group ? { RUCHER_GROUP: group.name } : {},
624
+ ...workspace ? { RUCHER_WS: workspace.name } : {},
985
625
  ...kind ? { RUCHER_SESSION_KIND: kind } : {}
986
626
  };
987
627
  }
@@ -991,60 +631,70 @@ function planNew(carnet, io, options) {
991
631
  id: randomUUID(),
992
632
  kind: options.kind,
993
633
  name: options.name,
994
- cwd: carnet.group?.workspace ?? io.cwd,
995
- repo: repoNameFor(carnet.group, io.cwd)
634
+ cwd: carnet.workspace?.runDirectory ?? io.cwd,
635
+ repo: repoNameFor(carnet.workspace, io.cwd)
996
636
  });
997
637
  const host = hostById(session.host);
998
- if (carnet.group) renderWorkspace(carnet.group, {
638
+ if (carnet.workspace) renderRunDirectory(carnet.workspace, {
999
639
  env: io.env,
1000
640
  host: session.host
1001
641
  });
1002
- const prompt = appendPromptFile(carnet.group, session, io.env);
642
+ const prompt = appendPromptFile(carnet.workspace, session, io.env);
1003
643
  return {
1004
644
  ...host.launchCommand(session.id, {
1005
645
  name: session.name,
1006
646
  appendPromptFile: prompt.path,
1007
- directories: repoDirectories(carnet.group),
647
+ directories: repoDirectories(carnet.workspace),
1008
648
  passthrough: options.passthrough
1009
649
  }),
1010
- cwd: carnet.group?.workspace ?? io.cwd,
1011
- env: launchEnv(carnet.group, session, prompt.version),
650
+ cwd: carnet.workspace?.runDirectory ?? io.cwd,
651
+ env: launchEnv(carnet.workspace, session, prompt.version),
1012
652
  sessionId: session.id
1013
653
  };
1014
654
  }
1015
- function repoDirectories(group) {
1016
- return (group?.repos ?? []).map((repo) => repo.path).filter((path) => existsSync(path));
655
+ function repoDirectories(workspace) {
656
+ return (workspace?.repos ?? []).map((repo) => repo.path).filter((path) => existsSync(path));
1017
657
  }
1018
- function sessionGroup(carnet, session, env) {
1019
- if (!session.groupName || !isGroupName(session.groupName)) return null;
1020
- return carnet.group?.name === session.groupName ? carnet.group : loadGroup(session.groupName, env);
658
+ function sessionWorkspace(carnet, session, env) {
659
+ if (!session.workspace || !isWorkspaceName(session.workspace)) return null;
660
+ return carnet.workspace?.name === session.workspace ? carnet.workspace : loadWorkspace(session.workspace, env);
1021
661
  }
1022
662
  function prepareSession(carnet, session, env) {
1023
- const group = sessionGroup(carnet, session, env);
1024
- if (group) renderWorkspace(group, {
663
+ const workspace = sessionWorkspace(carnet, session, env);
664
+ if (workspace) renderRunDirectory(workspace, {
1025
665
  env,
1026
666
  host: session.host
1027
667
  });
1028
- return group;
668
+ return workspace;
669
+ }
670
+ function sessionLabel$1(session) {
671
+ return session.name ?? session.id.slice(0, 8);
1029
672
  }
1030
673
  function sessionDirectory(session) {
1031
674
  if (session.cwd && existsSync(session.cwd)) return session.cwd;
1032
- throw new CarnetError("SESSION_CWD_MISSING", `The directory of session ${session.name ?? session.id.slice(0, 8)} no longer exists: ${session.cwd ?? "none recorded"}`);
675
+ throw new CarnetError("SESSION_CWD_MISSING", `The directory of session ${sessionLabel$1(session)} no longer exists: ${session.cwd ?? "none recorded"}`);
1033
676
  }
1034
677
  function planResume(carnet, io, reference, passthrough = []) {
1035
678
  const session = findSession(carnet, reference);
1036
679
  if (session.status === "archived") io.stderr(`warning: session ${reference} is archived\n`);
1037
- const group = prepareSession(carnet, session, io.env);
680
+ const workspace = prepareSession(carnet, session, io.env);
1038
681
  const cwd = sessionDirectory(session);
1039
- const prompt = appendPromptFile(group, session, io.env);
682
+ const prompt = appendPromptFile(workspace, session, io.env);
683
+ const host = hostById(session.host);
684
+ const options = {
685
+ appendPromptFile: prompt.path,
686
+ directories: repoDirectories(workspace),
687
+ passthrough
688
+ };
689
+ const fresh = !host.hasConversation(session, io.env);
690
+ if (fresh) io.stderr(`no conversation yet for ${sessionLabel$1(session)}: starting it\n`);
1040
691
  return {
1041
- ...hostById(session.host).resumeCommand(session, {
1042
- appendPromptFile: prompt.path,
1043
- directories: repoDirectories(group),
1044
- passthrough
1045
- }),
692
+ ...fresh ? host.launchCommand(session.id, {
693
+ name: session.name,
694
+ ...options
695
+ }) : host.resumeCommand(session, options),
1046
696
  cwd,
1047
- env: launchEnv(group, session, prompt.version),
697
+ env: launchEnv(workspace, session, prompt.version),
1048
698
  sessionId: session.id
1049
699
  };
1050
700
  }
@@ -1052,19 +702,23 @@ function planFork(carnet, io, reference, options = {}) {
1052
702
  if (options.active && !options.name) throw new CliError("An active fork needs a name", "rucher fork <session> <name> --active");
1053
703
  if (options.name && carnet.sessions.byName(options.name)) throw new CliError(`A session named "${options.name}" already exists`);
1054
704
  const parent = findSession(carnet, reference);
1055
- const group = prepareSession(carnet, parent, io.env);
705
+ if (!hostById(parent.host).hasConversation(parent, io.env)) {
706
+ const label = sessionLabel$1(parent);
707
+ throw new CliError(`Session ${label} has no conversation yet, nothing to fork`, `rucher resume ${label}`);
708
+ }
709
+ const workspace = prepareSession(carnet, parent, io.env);
1056
710
  const cwd = sessionDirectory(parent);
1057
711
  const kind = options.active ? "active" : "temp";
1058
712
  return {
1059
713
  ...hostById(parent.host).forkCommand(parent, {
1060
714
  name: options.name,
1061
- appendPromptFile: appendPromptFile(group, parent, io.env).path,
1062
- directories: repoDirectories(group),
715
+ appendPromptFile: appendPromptFile(workspace, parent, io.env).path,
716
+ directories: repoDirectories(workspace),
1063
717
  passthrough: options.passthrough
1064
718
  }),
1065
719
  cwd,
1066
720
  env: {
1067
- ...launchEnv(group, parent, parent.promptVersion ?? "", kind),
721
+ ...launchEnv(workspace, parent, parent.promptVersion ?? "", kind),
1068
722
  RUCHER_SESSION_NAME: options.name ?? ""
1069
723
  },
1070
724
  parentId: parent.id,
@@ -1122,54 +776,202 @@ function pickerLines(sessions, now = /* @__PURE__ */ new Date()) {
1122
776
  const widths = (rows[0] ?? []).map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
1123
777
  return rows.map((row) => row.map((cell, column) => column < row.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell).join(" "));
1124
778
  }
1125
- function hasFzf() {
1126
- return spawnSync("fzf", ["--version"], { stdio: "ignore" }).status === 0;
779
+ function hasFzf() {
780
+ return spawnSync("fzf", ["--version"], { stdio: "ignore" }).status === 0;
781
+ }
782
+ function pickWithFzf(sessions, lines) {
783
+ const result = spawnSync("fzf", [
784
+ "--with-nth=2..",
785
+ "--no-sort",
786
+ "--prompt=session> "
787
+ ], {
788
+ input: lines.join("\n"),
789
+ stdio: [
790
+ "pipe",
791
+ "pipe",
792
+ "inherit"
793
+ ],
794
+ encoding: "utf8"
795
+ });
796
+ return sessions[Number(result.stdout?.trim().split(/\s+/)[0]) - 1];
797
+ }
798
+ async function pickFromList(sessions, lines) {
799
+ process.stderr.write(`${lines.join("\n")}\n`);
800
+ const prompt = createInterface({
801
+ input: process.stdin,
802
+ output: process.stderr
803
+ });
804
+ try {
805
+ const answer = await prompt.question("session number> ");
806
+ return sessions[Number(answer.trim()) - 1];
807
+ } finally {
808
+ prompt.close();
809
+ }
810
+ }
811
+ async function pickSession(carnet) {
812
+ 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);
817
+ if (!picked) throw new CliError("No session picked");
818
+ return picked;
819
+ }
820
+ // src/commands/serve.ts
821
+ function serve(io) {
822
+ serveCarnet({
823
+ cwd: io.cwd,
824
+ env: io.env,
825
+ sessionId: claudeCode.sessionIdFromEnvironment(io.env)
826
+ });
827
+ }
828
+ // src/commands/sessions.ts
829
+ function lastActive(at, now) {
830
+ const date = new Date(at);
831
+ return date.toDateString() === now.toDateString() ? formatClock(date) : date.toISOString().slice(0, 10);
832
+ }
833
+ function row(carnet, session, now) {
834
+ const open = carnet.agents.list(session.id).length;
835
+ return [
836
+ session.name ?? session.id.slice(0, 8),
837
+ session.kind,
838
+ session.status,
839
+ repoPathFor(carnet.workspace, session.cwd) ?? session.repo ?? "",
840
+ lastActive(session.lastActiveAt, now),
841
+ open ? `${open} agent${open > 1 ? "s" : ""}` : "",
842
+ session.purpose ?? ""
843
+ ];
844
+ }
845
+ function sessionsOnce(carnet, io, options = {}) {
846
+ const colors = paint(io);
847
+ const sessions = carnet.sessions.list({
848
+ includeTemp: options.all,
849
+ includeArchived: options.all
850
+ });
851
+ warnNoWorkspace(carnet, io);
852
+ if (sessions.length === 0) {
853
+ 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`);
855
+ return;
856
+ }
857
+ const now = options.now ?? /* @__PURE__ */ new Date();
858
+ const rows = sessions.map((session) => ({
859
+ session,
860
+ cells: row(carnet, session, now)
861
+ }));
862
+ const widths = rows.reduce((current, { cells }) => cells.map((cell, column) => Math.max(current[column] ?? 0, cell.length)), []);
863
+ const lines = rows.map(({ session, cells }) => {
864
+ return cells.map((cell, column) => {
865
+ const padded = column < cells.length - 1 ? cell.padEnd(widths[column] ?? 0) : cell;
866
+ if (column === 0) return colors.bold(padded);
867
+ if (column === 1 && session.kind === "temp") return colors.dim(padded);
868
+ if (column === 2 && session.status === "archived") return colors.dim(padded);
869
+ return padded;
870
+ }).join(" ").trimEnd();
871
+ });
872
+ io.stdout(`${lines.join("\n")}\n`);
873
+ }
874
+ function sessionsMerge(carnet, fromReference, intoReference, io) {
875
+ const from = findSession(carnet, fromReference);
876
+ const into = findSession(carnet, intoReference);
877
+ const result = carnet.sessions.merge(from.id, into.id);
878
+ const label = (session) => session.name ?? session.id.slice(0, 8);
879
+ const lines = [
880
+ `merged ${label(from)} into ${label(result.session)}`,
881
+ ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
882
+ ...result.closedAgents.length ? [` agents closed (name already used): ${result.closedAgents.join(", ")}`] : [],
883
+ ` events moved: ${result.movedEvents}`,
884
+ ` table line moved: ${result.movedTable ? "yes" : "no"}`
885
+ ];
886
+ io.stdout(`${lines.join("\n")}\n`);
887
+ }
888
+ function label(session) {
889
+ return session.name ?? shortId(session.id);
890
+ }
891
+ function workspaced(name, io) {
892
+ if (!workspaceExists(name, io.env)) throw new CliError(`No workspace named "${name}"`, "see rucher ws list");
893
+ return loadWorkspace(name, io.env);
894
+ }
895
+ function sessionsMove(carnet, reference, workspaceReference, io, options = {}) {
896
+ const session = findSession(carnet, reference);
897
+ const target = workspaced(workspaceReference, io).name;
898
+ const result = moveSession(carnet, session.id, target, options);
899
+ const into = result.into ? ` into ${label(result.into)}` : "";
900
+ const lines = [
901
+ `${options.dryRun ? "would move" : "moved"} ${label(session)} from ${workspaceLabel(carnet.workspace)} to ${target}${into}`,
902
+ ` agents moved: ${result.movedAgents.join(", ") || "none"}`,
903
+ ...result.skippedAgents.length ? [` agents left out (name already used): ${result.skippedAgents.join(", ")}`] : [],
904
+ ` events moved: ${result.movedEvents}`,
905
+ ` table line moved: ${result.movedTable ? "yes" : "no"}`,
906
+ ...result.keptNotes ? [` notes kept in ${workspaceLabel(carnet.workspace)}: ${result.keptNotes}`] : []
907
+ ];
908
+ io.stdout(`${lines.join("\n")}\n`);
909
+ }
910
+ function sessionsRename(carnet, reference, name, io) {
911
+ const session = carnet.sessions.rename(findSession(carnet, reference).id, name);
912
+ io.stdout(`renamed to ${session.name}; rucher resume ${session.name} gives Claude the same title\n`);
913
+ }
914
+ function sessionsPromote(carnet, reference, name, io) {
915
+ const session = carnet.sessions.promote(findSession(carnet, reference).id, name);
916
+ io.stdout(`${label(session)} is now active\n`);
917
+ }
918
+ function sessionsDemote(carnet, reference, io) {
919
+ const session = carnet.sessions.demote(findSession(carnet, reference).id);
920
+ io.stdout(`${label(session)} is now temp, cleaned by rucher sessions clean once idle\n`);
921
+ }
922
+ function purgeTranscripts(session, io) {
923
+ const files = hostById(session.host).transcriptFiles(session, io.env);
924
+ for (const file of files) {
925
+ rmSync(file, {
926
+ recursive: true,
927
+ force: true
928
+ });
929
+ io.stdout(` deleted ${file}\n`);
930
+ }
931
+ if (files.length === 0) io.stdout(" no transcript found\n");
1127
932
  }
1128
- function pickWithFzf(sessions, lines) {
1129
- const result = spawnSync("fzf", [
1130
- "--with-nth=2..",
1131
- "--no-sort",
1132
- "--prompt=session> "
1133
- ], {
1134
- input: lines.join("\n"),
1135
- stdio: [
1136
- "pipe",
1137
- "pipe",
1138
- "inherit"
1139
- ],
1140
- encoding: "utf8"
1141
- });
1142
- return sessions[Number(result.stdout?.trim().split(/\s+/)[0]) - 1];
933
+ function sessionsDrop(carnet, reference, io, options = {}) {
934
+ const session = findSession(carnet, reference);
935
+ if (options.purge && session.status === "running") throw new CliError(`Session ${label(session)} is running`, "drop it with --purge once it has ended");
936
+ carnet.sessions.drop(session.id);
937
+ io.stdout(`archived ${label(session)}\n`);
938
+ if (options.purge) purgeTranscripts(session, io);
1143
939
  }
1144
- async function pickFromList(sessions, lines) {
1145
- process.stderr.write(`${lines.join("\n")}\n`);
1146
- const prompt = createInterface({
1147
- input: process.stdin,
1148
- output: process.stderr
1149
- });
940
+ const UNIT_MILLISECONDS = {
941
+ m: 6e4,
942
+ h: 36e5,
943
+ d: 864e5
944
+ };
945
+ function parseDuration(value) {
946
+ const match = /^(\d+(?:\.\d+)?)([mhd]?)$/.exec(value.trim());
947
+ if (!match) throw new CliError(`Invalid duration "${value}"`, "use a number of days, or 30m, 12h, 7d");
948
+ return Number(match[1]) * (UNIT_MILLISECONDS[match[2] || "d"] ?? 0);
949
+ }
950
+ function processIsAlive(processId) {
1150
951
  try {
1151
- const answer = await prompt.question("session number> ");
1152
- return sessions[Number(answer.trim()) - 1];
1153
- } finally {
1154
- prompt.close();
952
+ process.kill(processId, 0);
953
+ return true;
954
+ } catch (error) {
955
+ return error.code === "EPERM";
1155
956
  }
1156
957
  }
1157
- async function pickSession(carnet) {
1158
- const sessions = pickerSessions(carnet);
1159
- if (sessions.length === 0) throw new CliError("No session to resume in this group", "rucher new <name>");
1160
- if (!process.stdin.isTTY) throw new CliError("No session given", "rucher resume <name, id or id prefix>");
1161
- const lines = pickerLines(sessions);
1162
- const picked = hasFzf() ? pickWithFzf(sessions, lines) : await pickFromList(sessions, lines);
1163
- if (!picked) throw new CliError("No session picked");
1164
- return picked;
1165
- }
1166
- // src/commands/serve.ts
1167
- function serve(io) {
1168
- serveCarnet({
1169
- cwd: io.cwd,
1170
- env: io.env,
1171
- sessionId: claudeCode.sessionIdFromEnvironment(io.env)
1172
- });
958
+ function sessionsClean(carnet, io, options = {}) {
959
+ const olderThan = parseDuration(options.olderThan ?? "7d");
960
+ if (!options.dryRun) for (const session of carnet.sessions.resetDead(options.isAlive ?? processIsAlive)) io.stdout(`${label(session)} was marked running but its process is gone: now idle\n`);
961
+ const stale = carnet.sessions.staleTemp(olderThan);
962
+ if (stale.length === 0) {
963
+ io.stdout(`no temp session idle for more than ${options.olderThan ?? "7d"}\n`);
964
+ return;
965
+ }
966
+ for (const session of stale) {
967
+ if (options.dryRun) {
968
+ io.stdout(`would archive ${label(session)}${options.purge ? " and delete its transcript" : ""}\n`);
969
+ continue;
970
+ }
971
+ carnet.sessions.drop(session.id);
972
+ io.stdout(`archived ${label(session)}\n`);
973
+ if (options.purge) purgeTranscripts(session, io);
974
+ }
1173
975
  }
1174
976
  // src/commands/watch-keys.ts
1175
977
  const INITIAL_WATCH_STATE = {
@@ -1310,7 +1112,7 @@ function sessionName(session) {
1310
1112
  function sessionLabel(carnet, session, columns) {
1311
1113
  const name = sessionName(session);
1312
1114
  const room = columns - Array.from(name).length - 3;
1313
- return room > 1 ? `${name} · ${truncate(groupLabel(carnet.group), room)}` : name;
1115
+ return room > 1 ? `${name} · ${truncate(workspaceLabel(carnet.workspace), room)}` : name;
1314
1116
  }
1315
1117
  function sessionHeader(session, io) {
1316
1118
  return paint(io).cyan(truncate(sessionName(session), io.columns));
@@ -1387,89 +1189,285 @@ function renderStatusView(carnet, io, options) {
1387
1189
  return sessionBlock(session, view, io);
1388
1190
  });
1389
1191
  const colors = paint(io);
1390
- const separator = " - ";
1391
- const group = truncate(groupLabel(carnet.group), io.columns - time.length - 3);
1392
- return [
1393
- `${colors.dim(time)}${separator}${colors.cyan(group)}`,
1394
- "",
1395
- blocks.join("\n\n"),
1192
+ const separator = " - ";
1193
+ 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");
1201
+ }
1202
+ function statusOnce(carnet, io, options) {
1203
+ io.stdout(`${renderStatusView(carnet, io, options)}\n`);
1204
+ }
1205
+ function dropSelected(carnet, options, index, reason) {
1206
+ const session = resolveSession(carnet, options.session);
1207
+ const item = carnet.notes.activity(session.id)[index];
1208
+ if (!item) return "no note selected";
1209
+ try {
1210
+ carnet.notes.drop(item.note, {
1211
+ reason,
1212
+ session: session.id
1213
+ });
1214
+ return null;
1215
+ } catch (error) {
1216
+ return error instanceof Error ? error.message : String(error);
1217
+ }
1218
+ }
1219
+ function noteCount(carnet, options) {
1220
+ try {
1221
+ return carnet.notes.activity(resolveSession(carnet, options.session).id).length;
1222
+ } catch {
1223
+ return 0;
1224
+ }
1225
+ }
1226
+ const CLEAR = "\x1B[H\x1B[2J";
1227
+ const HIDE_CURSOR = "\x1B[?25l";
1228
+ const SHOW_CURSOR = "\x1B[?25h";
1229
+ function statusWatch(carnet, io, options) {
1230
+ return new Promise((resolve) => {
1231
+ let last = "";
1232
+ const interactive = options.keys !== void 0 && !options.all;
1233
+ let state = INITIAL_WATCH_STATE;
1234
+ const repaint = () => {
1235
+ let text;
1236
+ try {
1237
+ text = renderStatusView(carnet, io, {
1238
+ ...options,
1239
+ interaction: interactive ? state : void 0
1240
+ });
1241
+ } catch (error) {
1242
+ text = paint(io).dim(error instanceof Error ? error.message : String(error));
1243
+ }
1244
+ if (text === last) return;
1245
+ last = text;
1246
+ io.stdout(`${CLEAR}${text}\n`);
1247
+ };
1248
+ const timer = setInterval(() => {
1249
+ if (state.reason === null) repaint();
1250
+ }, options.intervalMilliseconds);
1251
+ let stopped = false;
1252
+ const stop = () => {
1253
+ if (stopped) return;
1254
+ stopped = true;
1255
+ clearInterval(timer);
1256
+ options.keys?.close();
1257
+ io.stdout(SHOW_CURSOR);
1258
+ resolve();
1259
+ };
1260
+ options.keys?.onKey((key) => {
1261
+ const result = pressKey(state, key, interactive ? noteCount(carnet, options) : 0);
1262
+ state = result.state;
1263
+ if (result.action?.type === "quit") return stop();
1264
+ if (result.action?.type === "drop") state = {
1265
+ ...state,
1266
+ message: dropSelected(carnet, options, result.action.index, result.action.reason)
1267
+ };
1268
+ repaint();
1269
+ });
1270
+ options.signal?.addEventListener("abort", stop, { once: true });
1271
+ io.stdout(HIDE_CURSOR);
1272
+ repaint();
1273
+ });
1274
+ }
1275
+ // src/commands/ws.ts
1276
+ function carnetErrors(io, run) {
1277
+ try {
1278
+ return run();
1279
+ } catch (error) {
1280
+ if (error instanceof CarnetError) {
1281
+ io.stderr(`error: ${error.message}\n`);
1282
+ return 1;
1283
+ }
1284
+ throw error;
1285
+ }
1286
+ }
1287
+ function rendered(workspace, io) {
1288
+ const result = renderRunDirectory(workspace, { env: io.env });
1289
+ return [...result.written.map((path) => `written ${path}`), ...result.removed.map((path) => `removed ${path}`)];
1290
+ }
1291
+ function withChanges(line, changes) {
1292
+ return `${line}${changes.length ? ` (${changes.join(", ")})` : ""}\n`;
1293
+ }
1294
+ function workspaceShow(io, options = {}) {
1295
+ return carnetErrors(io, () => {
1296
+ const colors = paint(io);
1297
+ const workspace = currentWorkspace(io, options.workspace);
1298
+ const repos = workspace.repos.length ? workspace.repos.map((repo) => ` ${repo.name} ${colors.dim(repo.path)}`).join("\n") : ` ${colors.dim("none")}`;
1299
+ io.stdout(`${colors.bold(workspace.name)}\ndefinition: ${workspace.definition}\nrun directory: ${workspace.runDirectory}\nrepos:\n${repos}\n`);
1300
+ return 0;
1301
+ });
1302
+ }
1303
+ function workspaceAdd(repo, io, options = {}) {
1304
+ return carnetErrors(io, () => {
1305
+ const found = currentWorkspace(io, options.workspace);
1306
+ const path = resolve(io.cwd, repo);
1307
+ const workspace = addWorkspaceRepo(found.name, path, io.env);
1308
+ io.stdout(withChanges(`added ${basename(path)} to ${workspace.name}`, rendered(workspace, io)));
1309
+ return 0;
1310
+ });
1311
+ }
1312
+ function workspaceRemove(repo, io, options = {}) {
1313
+ return carnetErrors(io, () => {
1314
+ const found = currentWorkspace(io, options.workspace);
1315
+ const workspace = removeWorkspaceRepo(found.name, resolve(io.cwd, repo), io.env);
1316
+ io.stdout(withChanges(`removed ${basename(repo)} from ${workspace.name}`, rendered(workspace, io)));
1317
+ return 0;
1318
+ });
1319
+ }
1320
+ function workspaceSync(io, options = {}) {
1321
+ return carnetErrors(io, () => {
1322
+ const workspace = currentWorkspace(io, options.workspace);
1323
+ const changes = rendered(workspace, io);
1324
+ io.stdout(changes.length ? `${[`synced ${workspace.name}`, ...changes.map((change) => ` ${change}`)].join("\n")}\n` : `${workspace.name} already in sync\n`);
1325
+ return 0;
1326
+ });
1327
+ }
1328
+ function workspacePath(io, options = {}) {
1329
+ return carnetErrors(io, () => {
1330
+ const workspace = currentWorkspace(io, options.workspace);
1331
+ io.stdout(`${options.definition ? workspace.definition : workspace.runDirectory}\n`);
1332
+ return 0;
1333
+ });
1334
+ }
1335
+ function editorCommand(env) {
1336
+ return env.VISUAL || env.EDITOR || "vi";
1337
+ }
1338
+ function openEditorFor(io) {
1339
+ return (file) => {
1340
+ return spawnSync(`${editorCommand(io.env)} "$RUCHER_EDIT_FILE"`, {
1341
+ shell: true,
1342
+ stdio: "inherit",
1343
+ env: {
1344
+ ...io.env,
1345
+ RUCHER_EDIT_FILE: file
1346
+ }
1347
+ }).status ?? 1;
1348
+ };
1349
+ }
1350
+ function invalidWorkspaceFile(name, io) {
1351
+ try {
1352
+ loadWorkspace(name, io.env);
1353
+ return null;
1354
+ } catch (error) {
1355
+ return error instanceof Error ? error.message : String(error);
1356
+ }
1357
+ }
1358
+ async function workspaceEdit(io, options = {}) {
1359
+ let workspace;
1360
+ let file;
1361
+ try {
1362
+ workspace = currentWorkspace(io, options.workspace);
1363
+ file = join(workspace.definition, options.json ? WORKSPACE_FILE : definitionInstructions(workspace));
1364
+ } catch (error) {
1365
+ if (error instanceof CarnetError) {
1366
+ io.stderr(`error: ${error.message}\n`);
1367
+ return 1;
1368
+ }
1369
+ throw error;
1370
+ }
1371
+ const original = readFileSync(file, "utf8");
1372
+ const openEditor = options.openEditor ?? openEditorFor(io);
1373
+ for (;;) {
1374
+ if (openEditor(file) !== 0) {
1375
+ io.stderr(`error: ${editorCommand(io.env)} exited with an error, nothing synced\n`);
1376
+ return 1;
1377
+ }
1378
+ const problem = options.json ? invalidWorkspaceFile(workspace.name, io) : null;
1379
+ if (!problem) break;
1380
+ io.stderr(`error: ${WORKSPACE_FILE} is invalid: ${problem}\n`);
1381
+ if (!options.confirm || !await options.confirm("Edit it again? [Y/n] ")) {
1382
+ writeFileSync(file, original);
1383
+ io.stderr(`restored the previous ${WORKSPACE_FILE}\n`);
1384
+ return 1;
1385
+ }
1386
+ }
1387
+ return workspaceSync(io, { workspace: workspace.name });
1388
+ }
1389
+ function plural(count, word) {
1390
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
1391
+ }
1392
+ function workspaceList(io) {
1393
+ const colors = paint(io);
1394
+ const workspaces = listWorkspaces(io.env);
1395
+ if (workspaces.length === 0) {
1396
+ io.stdout(`${colors.dim("no workspace yet, create one with `rucher ws create <name>`")}\n`);
1397
+ return 0;
1398
+ }
1399
+ const carnet = openWorkspaceCarnet(null, { env: io.env });
1400
+ const sessions = workspaceSessionCounts(carnet.db);
1401
+ carnet.close();
1402
+ const width = Math.max(...workspaces.map((workspace) => workspace.name.length));
1403
+ const lines = workspaces.map((workspace) => `${colors.bold(workspace.name.padEnd(width))} ${plural(workspace.repos.length, "repo")} ${plural(sessions.get(workspace.name) ?? 0, "session")} ${colors.dim(workspace.runDirectory)}`);
1404
+ io.stdout(`${lines.join("\n")}\n`);
1405
+ return 0;
1406
+ }
1407
+ function workspaceCreate(name, io, options = {}) {
1408
+ const colors = paint(io);
1409
+ const workspace = createWorkspace(name, {
1410
+ repos: options.repos?.map((repo) => resolve(io.cwd, repo)),
1411
+ env: io.env
1412
+ });
1413
+ const result = renderRunDirectory(workspace, { env: io.env });
1414
+ const lines = [
1415
+ `${colors.bold(workspace.name)} created`,
1416
+ ` definition: ${workspace.definition}`,
1417
+ ` run directory: ${workspace.runDirectory}`,
1418
+ ` repos: ${workspace.repos.length ? workspace.repos.map((repo) => repo.path).join(", ") : "none yet, add them with `rucher ws add <path> --ws " + workspace.name + "`"}`,
1419
+ ...result.written.map((path) => ` written ${path}`),
1396
1420
  "",
1397
- colors.dim(LEGEND)
1398
- ].join("\n");
1421
+ "Accept the Claude Code trust prompt in its first session: until then the run directory settings are ignored, and rucher passes the repos with --add-dir.",
1422
+ `Next: \`rucher ws edit --ws ${workspace.name}\` for its instructions, then \`rucher new <session> --ws ${workspace.name}\`.`
1423
+ ];
1424
+ io.stdout(`${lines.join("\n")}\n`);
1425
+ return 0;
1399
1426
  }
1400
- function statusOnce(carnet, io, options) {
1401
- io.stdout(`${renderStatusView(carnet, io, options)}\n`);
1427
+ function liveSessions(carnet, isAlive) {
1428
+ return carnet.sessions.list({ includeTemp: true }).filter((session) => session.status === "running" && session.hostPid !== null && isAlive(session.hostPid));
1402
1429
  }
1403
- function dropSelected(carnet, options, index, reason) {
1404
- const session = resolveSession(carnet, options.session);
1405
- const item = carnet.notes.activity(session.id)[index];
1406
- if (!item) return "no note selected";
1430
+ function refuseLive(carnet, action, isAlive) {
1431
+ const live = liveSessions(carnet, isAlive);
1432
+ if (live.length) throw new CliError(`${plural(live.length, "session")} of ${carnet.workspace?.name} still running: ${live.map((session) => session.name ?? session.id.slice(0, 8)).join(", ")}`, `end them before you ${action} the workspace`);
1433
+ }
1434
+ function workspaceDrop(name, io, options = {}) {
1435
+ const carnet = openWorkspaceCarnet(loadWorkspace(name, io.env), { env: io.env });
1407
1436
  try {
1408
- carnet.notes.drop(item.note, {
1409
- reason,
1410
- session: session.id
1437
+ refuseLive(carnet, "drop", options.isAlive ?? processIsAlive);
1438
+ const at = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
1439
+ const archived = archiveWorkspaceSessions(carnet.db, name, at);
1440
+ const deletedNotes = options.purge ? deleteWorkspaceNotes(carnet.db, name) : 0;
1441
+ const workspace = dropWorkspace(name, {
1442
+ purge: options.purge,
1443
+ env: io.env
1411
1444
  });
1412
- return null;
1413
- } catch (error) {
1414
- return error instanceof Error ? error.message : String(error);
1445
+ const lines = [
1446
+ `dropped ${name}: definition ${workspace.definition} removed`,
1447
+ ` sessions archived: ${archived}`,
1448
+ options.purge ? ` notes deleted: ${deletedNotes}; run directory ${workspace.runDirectory} removed` : ` notes and run directory kept; recreate the workspace under the same name to see them again`
1449
+ ];
1450
+ io.stdout(`${lines.join("\n")}\n`);
1451
+ return 0;
1452
+ } finally {
1453
+ carnet.close();
1415
1454
  }
1416
1455
  }
1417
- function noteCount(carnet, options) {
1456
+ function workspaceErrors(io, run) {
1418
1457
  try {
1419
- return carnet.notes.activity(resolveSession(carnet, options.session).id).length;
1420
- } catch {
1421
- return 0;
1458
+ return run();
1459
+ } catch (error) {
1460
+ if (error instanceof CliError) {
1461
+ io.stderr(`error: ${error.message}${error.hint ? `\n ${error.hint}` : ""}\n`);
1462
+ return 1;
1463
+ }
1464
+ if (error instanceof CarnetError) {
1465
+ io.stderr(`error: ${error.message}\n`);
1466
+ return 1;
1467
+ }
1468
+ throw error;
1422
1469
  }
1423
1470
  }
1424
- const CLEAR = "\x1B[H\x1B[2J";
1425
- const HIDE_CURSOR = "\x1B[?25l";
1426
- const SHOW_CURSOR = "\x1B[?25h";
1427
- function statusWatch(carnet, io, options) {
1428
- return new Promise((resolve) => {
1429
- let last = "";
1430
- const interactive = options.keys !== void 0 && !options.all;
1431
- let state = INITIAL_WATCH_STATE;
1432
- const repaint = () => {
1433
- let text;
1434
- try {
1435
- text = renderStatusView(carnet, io, {
1436
- ...options,
1437
- interaction: interactive ? state : void 0
1438
- });
1439
- } catch (error) {
1440
- text = paint(io).dim(error instanceof Error ? error.message : String(error));
1441
- }
1442
- if (text === last) return;
1443
- last = text;
1444
- io.stdout(`${CLEAR}${text}\n`);
1445
- };
1446
- const timer = setInterval(() => {
1447
- if (state.reason === null) repaint();
1448
- }, options.intervalMilliseconds);
1449
- let stopped = false;
1450
- const stop = () => {
1451
- if (stopped) return;
1452
- stopped = true;
1453
- clearInterval(timer);
1454
- options.keys?.close();
1455
- io.stdout(SHOW_CURSOR);
1456
- resolve();
1457
- };
1458
- options.keys?.onKey((key) => {
1459
- const result = pressKey(state, key, interactive ? noteCount(carnet, options) : 0);
1460
- state = result.state;
1461
- if (result.action?.type === "quit") return stop();
1462
- if (result.action?.type === "drop") state = {
1463
- ...state,
1464
- message: dropSelected(carnet, options, result.action.index, result.action.reason)
1465
- };
1466
- repaint();
1467
- });
1468
- options.signal?.addEventListener("abort", stop, { once: true });
1469
- io.stdout(HIDE_CURSOR);
1470
- repaint();
1471
- });
1472
- }
1473
1471
  // src/io.ts
1474
1472
  function processIo(options = {}) {
1475
1473
  const tty = process.stdout.isTTY === true;
@@ -1558,13 +1556,13 @@ const statusCommand = defineCommand({
1558
1556
  default: "1",
1559
1557
  description: "Refresh interval in seconds with --watch"
1560
1558
  },
1561
- ...groupArgument,
1559
+ ...workspaceArgument,
1562
1560
  ...colorArgument
1563
1561
  },
1564
1562
  async run({ args }) {
1565
1563
  const io = processIo({ color: args.color });
1566
1564
  try {
1567
- const carnet = openCliCarnet(io, args.group);
1565
+ const carnet = openCliCarnet(io, args.ws);
1568
1566
  const options = {
1569
1567
  session: args.session,
1570
1568
  all: args.all
@@ -1611,13 +1609,13 @@ const logCommand = defineCommand({
1611
1609
  default: false,
1612
1610
  description: "Agent events only, without session starts and ends"
1613
1611
  },
1614
- ...groupArgument,
1612
+ ...workspaceArgument,
1615
1613
  ...colorArgument
1616
1614
  },
1617
1615
  run({ args }) {
1618
1616
  const io = processIo({ color: args.color });
1619
1617
  try {
1620
- logOnce(openCliCarnet(io, args.group), io, {
1618
+ logOnce(openCliCarnet(io, args.ws), io, {
1621
1619
  session: args.session,
1622
1620
  count: Number(args.count) || 20,
1623
1621
  md: args.md,
@@ -1631,7 +1629,7 @@ const logCommand = defineCommand({
1631
1629
  const sessionsListCommand = defineCommand({
1632
1630
  meta: {
1633
1631
  name: "list",
1634
- description: "List the named sessions of the group"
1632
+ description: "List the named sessions of the workspace"
1635
1633
  },
1636
1634
  args: {
1637
1635
  all: {
@@ -1639,13 +1637,13 @@ const sessionsListCommand = defineCommand({
1639
1637
  default: false,
1640
1638
  description: "Include temp and archived sessions"
1641
1639
  },
1642
- ...groupArgument,
1640
+ ...workspaceArgument,
1643
1641
  ...colorArgument
1644
1642
  },
1645
1643
  run({ args }) {
1646
1644
  const io = processIo({ color: args.color });
1647
1645
  try {
1648
- sessionsOnce(openCliCarnet(io, args.group), io, { all: args.all });
1646
+ sessionsOnce(openCliCarnet(io, args.ws), io, { all: args.all });
1649
1647
  } catch (error) {
1650
1648
  fail(io, error);
1651
1649
  }
@@ -1667,12 +1665,12 @@ const sessionsMergeCommand = defineCommand({
1667
1665
  description: "Session that keeps everything (name, id or id prefix)",
1668
1666
  required: true
1669
1667
  },
1670
- ...groupArgument
1668
+ ...workspaceArgument
1671
1669
  },
1672
1670
  run({ args }) {
1673
1671
  const io = processIo();
1674
1672
  try {
1675
- const carnet = openCliCarnet(io, args.group);
1673
+ const carnet = openCliCarnet(io, args.ws);
1676
1674
  sessionsMerge(carnet, args.from, args.into, io);
1677
1675
  carnet.close();
1678
1676
  } catch (error) {
@@ -1697,11 +1695,11 @@ const sessionsRenameCommand = defineCommand({
1697
1695
  description: "New name",
1698
1696
  required: true
1699
1697
  },
1700
- ...groupArgument
1698
+ ...workspaceArgument
1701
1699
  },
1702
1700
  run({ args }) {
1703
1701
  const io = processIo();
1704
- withCarnet(io, args.group, (carnet) => sessionsRename(carnet, args.session, args.name, io));
1702
+ withCarnet(io, args.ws, (carnet) => sessionsRename(carnet, args.session, args.name, io));
1705
1703
  }
1706
1704
  });
1707
1705
  const sessionsPromoteCommand = defineCommand({
@@ -1716,11 +1714,11 @@ const sessionsPromoteCommand = defineCommand({
1716
1714
  description: "Name, when the session has none",
1717
1715
  required: false
1718
1716
  },
1719
- ...groupArgument
1717
+ ...workspaceArgument
1720
1718
  },
1721
1719
  run({ args }) {
1722
1720
  const io = processIo();
1723
- withCarnet(io, args.group, (carnet) => sessionsPromote(carnet, args.session, args.name, io));
1721
+ withCarnet(io, args.ws, (carnet) => sessionsPromote(carnet, args.session, args.name, io));
1724
1722
  }
1725
1723
  });
1726
1724
  const sessionsDemoteCommand = defineCommand({
@@ -1730,11 +1728,11 @@ const sessionsDemoteCommand = defineCommand({
1730
1728
  },
1731
1729
  args: {
1732
1730
  session: sessionReference,
1733
- ...groupArgument
1731
+ ...workspaceArgument
1734
1732
  },
1735
1733
  run({ args }) {
1736
1734
  const io = processIo();
1737
- withCarnet(io, args.group, (carnet) => sessionsDemote(carnet, args.session, io));
1735
+ withCarnet(io, args.ws, (carnet) => sessionsDemote(carnet, args.session, io));
1738
1736
  }
1739
1737
  });
1740
1738
  const purgeArgument = { purge: {
@@ -1750,40 +1748,40 @@ const sessionsDropCommand = defineCommand({
1750
1748
  args: {
1751
1749
  session: sessionReference,
1752
1750
  ...purgeArgument,
1753
- ...groupArgument
1751
+ ...workspaceArgument
1754
1752
  },
1755
1753
  run({ args }) {
1756
1754
  const io = processIo();
1757
- withCarnet(io, args.group, (carnet) => sessionsDrop(carnet, args.session, io, { purge: args.purge }));
1755
+ withCarnet(io, args.ws, (carnet) => sessionsDrop(carnet, args.session, io, { purge: args.purge }));
1758
1756
  }
1759
1757
  });
1760
1758
  const sessionsMoveCommand = defineCommand({
1761
1759
  meta: {
1762
1760
  name: "move",
1763
- description: "Move a session, its agents, table line and journal to another group"
1761
+ description: "Move a session, its agents, table line and journal to another workspace"
1764
1762
  },
1765
1763
  args: {
1766
1764
  session: sessionReference,
1767
1765
  to: {
1768
1766
  type: "string",
1769
1767
  required: true,
1770
- description: "Target group name"
1768
+ description: "Target workspace name"
1771
1769
  },
1772
1770
  merge: {
1773
1771
  type: "boolean",
1774
1772
  default: false,
1775
- description: "Merge into the session the target group already has under this id or name"
1773
+ description: "Merge into the session the target workspace already has under this id or name"
1776
1774
  },
1777
1775
  "dry-run": {
1778
1776
  type: "boolean",
1779
1777
  default: false,
1780
1778
  description: "Show what would move"
1781
1779
  },
1782
- ...groupArgument
1780
+ ...workspaceArgument
1783
1781
  },
1784
1782
  run({ args }) {
1785
1783
  const io = processIo();
1786
- withCarnet(io, args.group, (carnet) => sessionsMove(carnet, args.session, args.to, io, {
1784
+ withCarnet(io, args.ws, (carnet) => sessionsMove(carnet, args.session, args.to, io, {
1787
1785
  merge: args.merge,
1788
1786
  dryRun: args["dry-run"]
1789
1787
  }));
@@ -1806,11 +1804,11 @@ const sessionsCleanCommand = defineCommand({
1806
1804
  default: false,
1807
1805
  description: "Show what would be archived"
1808
1806
  },
1809
- ...groupArgument
1807
+ ...workspaceArgument
1810
1808
  },
1811
1809
  run({ args }) {
1812
1810
  const io = processIo();
1813
- withCarnet(io, args.group, (carnet) => sessionsClean(carnet, io, {
1811
+ withCarnet(io, args.ws, (carnet) => sessionsClean(carnet, io, {
1814
1812
  olderThan: args["older-than"],
1815
1813
  purge: args.purge,
1816
1814
  dryRun: args["dry-run"]
@@ -1820,9 +1818,10 @@ const sessionsCleanCommand = defineCommand({
1820
1818
  const sessionsCommand = defineCommand({
1821
1819
  meta: {
1822
1820
  name: "sessions",
1823
- description: "List and manage the sessions of the group"
1821
+ description: "List and manage the sessions of the workspace"
1824
1822
  },
1825
- args: { ...groupArgument },
1823
+ args: { ...workspaceArgument },
1824
+ setup: forwardWorkspace,
1826
1825
  default: "list",
1827
1826
  subCommands: {
1828
1827
  list: sessionsListCommand,
@@ -1835,9 +1834,9 @@ const sessionsCommand = defineCommand({
1835
1834
  clean: sessionsCleanCommand
1836
1835
  }
1837
1836
  });
1838
- function withCarnet(io, group, run) {
1837
+ function withCarnet(io, workspace, run) {
1839
1838
  try {
1840
- const carnet = openCliCarnet(io, group);
1839
+ const carnet = openCliCarnet(io, workspace);
1841
1840
  try {
1842
1841
  run(carnet);
1843
1842
  } finally {
@@ -1860,7 +1859,7 @@ const noteFilterArguments = {
1860
1859
  const notesListCommand = defineCommand({
1861
1860
  meta: {
1862
1861
  name: "list",
1863
- description: "Active notes of the group, by kind"
1862
+ description: "Active notes of the workspace, by kind"
1864
1863
  },
1865
1864
  args: {
1866
1865
  all: {
@@ -1884,12 +1883,12 @@ const notesListCommand = defineCommand({
1884
1883
  default: false,
1885
1884
  description: "Markdown output, a view only"
1886
1885
  },
1887
- ...groupArgument,
1886
+ ...workspaceArgument,
1888
1887
  ...colorArgument
1889
1888
  },
1890
1889
  run({ args }) {
1891
1890
  const io = processIo({ color: args.color });
1892
- withCarnet(io, args.group, (carnet) => notesList(carnet, io, {
1891
+ withCarnet(io, args.ws, (carnet) => notesList(carnet, io, {
1893
1892
  all: args.all,
1894
1893
  kind: args.kind,
1895
1894
  repo: args.repo,
@@ -1910,12 +1909,12 @@ const notesShowCommand = defineCommand({
1910
1909
  description: "Note number",
1911
1910
  required: true
1912
1911
  },
1913
- ...groupArgument,
1912
+ ...workspaceArgument,
1914
1913
  ...colorArgument
1915
1914
  },
1916
1915
  run({ args }) {
1917
1916
  const io = processIo({ color: args.color });
1918
- withCarnet(io, args.group, (carnet) => notesShow(carnet, io, parseNoteId(args.id)));
1917
+ withCarnet(io, args.ws, (carnet) => notesShow(carnet, io, parseNoteId(args.id)));
1919
1918
  }
1920
1919
  });
1921
1920
  const notesAddCommand = defineCommand({
@@ -1938,12 +1937,12 @@ const notesAddCommand = defineCommand({
1938
1937
  type: "string",
1939
1938
  description: "Repo the note applies to (repeat for several)"
1940
1939
  },
1941
- ...groupArgument,
1940
+ ...workspaceArgument,
1942
1941
  ...colorArgument
1943
1942
  },
1944
1943
  run({ args, rawArgs }) {
1945
1944
  const io = processIo({ color: args.color });
1946
- withCarnet(io, args.group, (carnet) => notesAdd(carnet, io, {
1945
+ withCarnet(io, args.ws, (carnet) => notesAdd(carnet, io, {
1947
1946
  kind: args.kind,
1948
1947
  text: args.text,
1949
1948
  repos: repoList(rawArgs)
@@ -1970,12 +1969,12 @@ const notesDropCommand = defineCommand({
1970
1969
  type: "string",
1971
1970
  description: "Number of the note that replaces it"
1972
1971
  },
1973
- ...groupArgument
1972
+ ...workspaceArgument
1974
1973
  },
1975
1974
  run({ args }) {
1976
1975
  const io = processIo();
1977
1976
  const replacement = args["replaced-by"];
1978
- withCarnet(io, args.group, (carnet) => notesDrop(carnet, io, parseNoteId(args.id), {
1977
+ withCarnet(io, args.ws, (carnet) => notesDrop(carnet, io, parseNoteId(args.id), {
1979
1978
  reason: args.reason,
1980
1979
  replacedBy: replacement === void 0 ? void 0 : parseNoteId(replacement)
1981
1980
  }));
@@ -1984,12 +1983,13 @@ const notesDropCommand = defineCommand({
1984
1983
  const notesCommand = defineCommand({
1985
1984
  meta: {
1986
1985
  name: "notes",
1987
- description: "The group's memory: learnings, decisions and dead ends"
1986
+ description: "The workspace's memory: learnings, decisions and dead ends"
1988
1987
  },
1989
1988
  args: {
1990
1989
  ...noteFilterArguments,
1991
- ...groupArgument
1990
+ ...workspaceArgument
1992
1991
  },
1992
+ setup: forwardWorkspace,
1993
1993
  default: "list",
1994
1994
  subCommands: {
1995
1995
  list: notesListCommand,
@@ -1998,14 +1998,14 @@ const notesCommand = defineCommand({
1998
1998
  drop: notesDropCommand
1999
1999
  }
2000
2000
  });
2001
- async function launch(io, group, plan) {
2001
+ async function launch(io, workspace, plan) {
2002
2002
  try {
2003
- const carnet = openCliCarnet(io, group);
2003
+ const carnet = openCliCarnet(io, workspace);
2004
2004
  const launchPlan = await plan(carnet);
2005
2005
  startLaunch(carnet, launchPlan);
2006
2006
  carnet.close();
2007
2007
  const exitCode = spawnLaunch(launchPlan, io.env);
2008
- const after = openGroupCarnet(carnet.group, { env: io.env });
2008
+ const after = openWorkspaceCarnet(carnet.workspace, { env: io.env });
2009
2009
  finishLaunch(after, launchPlan);
2010
2010
  after.close();
2011
2011
  process.exitCode = exitCode;
@@ -2014,12 +2014,12 @@ async function launch(io, group, plan) {
2014
2014
  }
2015
2015
  }
2016
2016
  const passthroughHelp = "Arguments after -- are passed to Claude Code";
2017
- function withoutGroupOption(own) {
2017
+ function withoutWorkspaceOption(own) {
2018
2018
  const kept = [];
2019
2019
  for (let index = 0; index < own.length; index += 1) {
2020
2020
  const argument = own[index] ?? "";
2021
- if (argument === "-g" || argument === "--group") index += 1;
2022
- else if (!argument.startsWith("--group=") && !argument.startsWith("-g=")) kept.push(argument);
2021
+ if (argument === "--ws") index += 1;
2022
+ else if (!argument.startsWith("--ws=")) kept.push(argument);
2023
2023
  }
2024
2024
  return kept;
2025
2025
  }
@@ -2034,13 +2034,13 @@ const newCommand = defineCommand({
2034
2034
  description: "Session name",
2035
2035
  required: true
2036
2036
  },
2037
- ...groupArgument
2037
+ ...workspaceArgument
2038
2038
  },
2039
2039
  async run({ args, rawArgs }) {
2040
2040
  const { own, passthrough } = splitPassthrough(rawArgs);
2041
- await launch(processIo(), args.group, (carnet) => planNew(carnet, processIo(), {
2041
+ await launch(processIo(), args.ws, (carnet) => planNew(carnet, processIo(), {
2042
2042
  kind: "active",
2043
- name: positionals(withoutGroupOption(own))[0],
2043
+ name: positionals(withoutWorkspaceOption(own))[0],
2044
2044
  passthrough
2045
2045
  }));
2046
2046
  }
@@ -2056,13 +2056,13 @@ const tmpCommand = defineCommand({
2056
2056
  description: "Optional session name",
2057
2057
  required: false
2058
2058
  },
2059
- ...groupArgument
2059
+ ...workspaceArgument
2060
2060
  },
2061
2061
  async run({ args, rawArgs }) {
2062
2062
  const { own, passthrough } = splitPassthrough(rawArgs);
2063
- await launch(processIo(), args.group, (carnet) => planNew(carnet, processIo(), {
2063
+ await launch(processIo(), args.ws, (carnet) => planNew(carnet, processIo(), {
2064
2064
  kind: "temp",
2065
- name: positionals(withoutGroupOption(own))[0],
2065
+ name: positionals(withoutWorkspaceOption(own))[0],
2066
2066
  passthrough
2067
2067
  }));
2068
2068
  }
@@ -2078,13 +2078,13 @@ const resumeCommand = defineCommand({
2078
2078
  description: "Session name, id or id prefix",
2079
2079
  required: false
2080
2080
  },
2081
- ...groupArgument
2081
+ ...workspaceArgument
2082
2082
  },
2083
2083
  async run({ args, rawArgs }) {
2084
2084
  const { own, passthrough } = splitPassthrough(rawArgs);
2085
2085
  const io = processIo();
2086
- await launch(io, args.group, async (carnet) => {
2087
- const reference = positionals(withoutGroupOption(own))[0] ?? (await pickSession(carnet)).id;
2086
+ await launch(io, args.ws, async (carnet) => {
2087
+ const reference = positionals(withoutWorkspaceOption(own))[0] ?? (await pickSession(carnet)).id;
2088
2088
  return planResume(carnet, io, reference, passthrough);
2089
2089
  });
2090
2090
  }
@@ -2110,42 +2110,114 @@ const forkCommand = defineCommand({
2110
2110
  default: false,
2111
2111
  description: "Make the new session durable (needs a name)"
2112
2112
  },
2113
- ...groupArgument
2113
+ ...workspaceArgument
2114
2114
  },
2115
2115
  async run({ args, rawArgs }) {
2116
2116
  const { own, passthrough } = splitPassthrough(rawArgs);
2117
- const [reference, name] = positionals(withoutGroupOption(own));
2117
+ const [reference, name] = positionals(withoutWorkspaceOption(own));
2118
2118
  const io = processIo();
2119
- await launch(io, args.group, (carnet) => planFork(carnet, io, reference ?? "", {
2119
+ await launch(io, args.ws, (carnet) => planFork(carnet, io, reference ?? "", {
2120
2120
  name,
2121
2121
  active: own.includes("--active"),
2122
2122
  passthrough
2123
2123
  }));
2124
2124
  }
2125
2125
  });
2126
- const groupCommand = defineCommand({
2126
+ async function askYes(question) {
2127
+ const { createInterface } = await import("node:readline/promises");
2128
+ const prompt = createInterface({
2129
+ input: process.stdin,
2130
+ output: process.stderr
2131
+ });
2132
+ try {
2133
+ return !/^n/i.test((await prompt.question(question)).trim());
2134
+ } finally {
2135
+ prompt.close();
2136
+ }
2137
+ }
2138
+ function commaList(value) {
2139
+ return value?.split(",").map((item) => item.trim()).filter(Boolean);
2140
+ }
2141
+ const wsCommand = defineCommand({
2127
2142
  meta: {
2128
- name: "group",
2129
- description: "The current group: show it, add or remove repos, render, edit its instructions"
2143
+ name: "ws",
2144
+ description: "The workspaces: create, list, show, add or remove repos, render, edit instructions"
2130
2145
  },
2146
+ args: { ...workspaceArgument },
2147
+ setup: forwardWorkspace,
2148
+ default: "list",
2131
2149
  subCommands: {
2150
+ list: defineCommand({
2151
+ meta: {
2152
+ name: "list",
2153
+ description: "Workspaces with their repo and session counts"
2154
+ },
2155
+ args: { ...colorArgument },
2156
+ run({ args }) {
2157
+ process.exitCode = workspaceList(processIo({ color: args.color }));
2158
+ }
2159
+ }),
2160
+ create: defineCommand({
2161
+ meta: {
2162
+ name: "create",
2163
+ description: "Create a workspace and render its run directory"
2164
+ },
2165
+ args: {
2166
+ name: {
2167
+ type: "positional",
2168
+ description: "Workspace name: a-z, 0-9 and -",
2169
+ required: true
2170
+ },
2171
+ repos: {
2172
+ type: "string",
2173
+ description: "Comma-separated repo paths"
2174
+ },
2175
+ ...colorArgument
2176
+ },
2177
+ run({ args }) {
2178
+ const io = processIo({ color: args.color });
2179
+ process.exitCode = workspaceErrors(io, () => workspaceCreate(args.name, io, { repos: commaList(args.repos) }));
2180
+ }
2181
+ }),
2182
+ drop: defineCommand({
2183
+ meta: {
2184
+ name: "drop",
2185
+ description: "Archive the sessions of a workspace and remove its definition, keeping its notes"
2186
+ },
2187
+ args: {
2188
+ name: {
2189
+ type: "positional",
2190
+ description: "Workspace name",
2191
+ required: true
2192
+ },
2193
+ purge: {
2194
+ type: "boolean",
2195
+ default: false,
2196
+ description: "Also delete its notes and its run directory"
2197
+ }
2198
+ },
2199
+ run({ args }) {
2200
+ const io = processIo();
2201
+ process.exitCode = workspaceErrors(io, () => workspaceDrop(args.name, io, { purge: args.purge }));
2202
+ }
2203
+ }),
2132
2204
  show: defineCommand({
2133
2205
  meta: {
2134
2206
  name: "show",
2135
- description: "Name, source, workspace and repos of the group"
2207
+ description: "Name, definition, run directory and repos of the workspace"
2136
2208
  },
2137
2209
  args: {
2138
- ...groupArgument,
2210
+ ...workspaceArgument,
2139
2211
  ...colorArgument
2140
2212
  },
2141
2213
  run({ args }) {
2142
- process.exitCode = groupShow(processIo({ color: args.color }), { group: args.group });
2214
+ process.exitCode = workspaceShow(processIo({ color: args.color }), { workspace: args.ws });
2143
2215
  }
2144
2216
  }),
2145
2217
  add: defineCommand({
2146
2218
  meta: {
2147
2219
  name: "add",
2148
- description: "Add a repo path to the group, then render its workspace"
2220
+ description: "Add a repo path to the workspace, then render its run directory"
2149
2221
  },
2150
2222
  args: {
2151
2223
  path: {
@@ -2153,17 +2225,17 @@ const groupCommand = defineCommand({
2153
2225
  description: "Repo path",
2154
2226
  required: true
2155
2227
  },
2156
- ...groupArgument,
2228
+ ...workspaceArgument,
2157
2229
  ...colorArgument
2158
2230
  },
2159
2231
  run({ args }) {
2160
- process.exitCode = groupAdd(args.path, processIo({ color: args.color }), { group: args.group });
2232
+ process.exitCode = workspaceAdd(args.path, processIo({ color: args.color }), { workspace: args.ws });
2161
2233
  }
2162
2234
  }),
2163
2235
  remove: defineCommand({
2164
2236
  meta: {
2165
2237
  name: "remove",
2166
- description: "Remove a repo from the group, then render its workspace"
2238
+ description: "Remove a repo from the workspace, then render its run directory"
2167
2239
  },
2168
2240
  args: {
2169
2241
  path: {
@@ -2171,42 +2243,42 @@ const groupCommand = defineCommand({
2171
2243
  description: "Repo path or name",
2172
2244
  required: true
2173
2245
  },
2174
- ...groupArgument,
2246
+ ...workspaceArgument,
2175
2247
  ...colorArgument
2176
2248
  },
2177
2249
  run({ args }) {
2178
- process.exitCode = groupRemove(args.path, processIo({ color: args.color }), { group: args.group });
2250
+ process.exitCode = workspaceRemove(args.path, processIo({ color: args.color }), { workspace: args.ws });
2179
2251
  }
2180
2252
  }),
2181
2253
  sync: defineCommand({
2182
2254
  meta: {
2183
2255
  name: "sync",
2184
- description: "Render the group's workspace (instruction copies, generated settings)"
2256
+ description: "Render the workspace's run directory (instruction copies, generated settings)"
2185
2257
  },
2186
2258
  args: {
2187
- ...groupArgument,
2259
+ ...workspaceArgument,
2188
2260
  ...colorArgument
2189
2261
  },
2190
2262
  run({ args }) {
2191
- process.exitCode = groupSync(processIo({ color: args.color }), { group: args.group });
2263
+ process.exitCode = workspaceSync(processIo({ color: args.color }), { workspace: args.ws });
2192
2264
  }
2193
2265
  }),
2194
2266
  edit: defineCommand({
2195
2267
  meta: {
2196
2268
  name: "edit",
2197
- description: "Open the instructions (or group.json with --json) in $EDITOR, then sync"
2269
+ description: "Open the instructions (or workspace.json with --json) in $EDITOR, then sync"
2198
2270
  },
2199
2271
  args: {
2200
2272
  json: {
2201
2273
  type: "boolean",
2202
2274
  default: false,
2203
- description: "Edit group.json instead"
2275
+ description: "Edit workspace.json instead"
2204
2276
  },
2205
- ...groupArgument
2277
+ ...workspaceArgument
2206
2278
  },
2207
2279
  async run({ args }) {
2208
- process.exitCode = await groupEdit(processIo(), {
2209
- group: args.group,
2280
+ process.exitCode = await workspaceEdit(processIo(), {
2281
+ workspace: args.ws,
2210
2282
  json: args.json,
2211
2283
  confirm: askYes
2212
2284
  });
@@ -2215,130 +2287,30 @@ const groupCommand = defineCommand({
2215
2287
  path: defineCommand({
2216
2288
  meta: {
2217
2289
  name: "path",
2218
- description: "Print the workspace path (or the source with --source), for cd \"$(...)\""
2290
+ description: "Print the run directory path (or the definition with --def), for cd \"$(...)\""
2219
2291
  },
2220
2292
  args: {
2221
- source: {
2293
+ def: {
2222
2294
  type: "boolean",
2223
2295
  default: false,
2224
- description: "The source folder instead"
2296
+ description: "The definition folder instead"
2225
2297
  },
2226
- workspace: {
2298
+ run: {
2227
2299
  type: "boolean",
2228
2300
  default: false,
2229
- description: "The workspace (default)"
2301
+ description: "The run directory (default)"
2230
2302
  },
2231
- ...groupArgument
2303
+ ...workspaceArgument
2232
2304
  },
2233
2305
  run({ args }) {
2234
- process.exitCode = groupPath(processIo(), {
2235
- group: args.group,
2236
- source: args.source
2306
+ process.exitCode = workspacePath(processIo(), {
2307
+ workspace: args.ws,
2308
+ definition: args.def
2237
2309
  });
2238
2310
  }
2239
2311
  })
2240
2312
  }
2241
2313
  });
2242
- async function askYes(question) {
2243
- const { createInterface } = await import("node:readline/promises");
2244
- const prompt = createInterface({
2245
- input: process.stdin,
2246
- output: process.stderr
2247
- });
2248
- try {
2249
- return !/^n/i.test((await prompt.question(question)).trim());
2250
- } finally {
2251
- prompt.close();
2252
- }
2253
- }
2254
- function commaList(value) {
2255
- return value?.split(",").map((item) => item.trim()).filter(Boolean);
2256
- }
2257
- const groupsCommand = defineCommand({
2258
- meta: {
2259
- name: "groups",
2260
- description: "The groups of this machine"
2261
- },
2262
- default: "list",
2263
- subCommands: {
2264
- list: defineCommand({
2265
- meta: {
2266
- name: "list",
2267
- description: "Groups with their repo and session counts"
2268
- },
2269
- args: { ...colorArgument },
2270
- run({ args }) {
2271
- process.exitCode = groupsList(processIo({ color: args.color }));
2272
- }
2273
- }),
2274
- create: defineCommand({
2275
- meta: {
2276
- name: "create",
2277
- description: "Create a group and render its workspace"
2278
- },
2279
- args: {
2280
- name: {
2281
- type: "positional",
2282
- description: "Group name: a-z, 0-9 and -",
2283
- required: true
2284
- },
2285
- repos: {
2286
- type: "string",
2287
- description: "Comma-separated repo paths"
2288
- },
2289
- ...colorArgument
2290
- },
2291
- run({ args }) {
2292
- const io = processIo({ color: args.color });
2293
- process.exitCode = groupsErrors(io, () => groupsCreate(args.name, io, { repos: commaList(args.repos) }));
2294
- }
2295
- }),
2296
- rename: defineCommand({
2297
- meta: {
2298
- name: "rename",
2299
- description: "Rename a group with no running session; its workspace stays"
2300
- },
2301
- args: {
2302
- from: {
2303
- type: "positional",
2304
- description: "Current name",
2305
- required: true
2306
- },
2307
- to: {
2308
- type: "positional",
2309
- description: "New name",
2310
- required: true
2311
- }
2312
- },
2313
- run({ args }) {
2314
- const io = processIo();
2315
- process.exitCode = groupsErrors(io, () => groupsRename(args.from, args.to, io));
2316
- }
2317
- }),
2318
- drop: defineCommand({
2319
- meta: {
2320
- name: "drop",
2321
- description: "Archive the sessions of a group and remove its source, keeping its notes"
2322
- },
2323
- args: {
2324
- name: {
2325
- type: "positional",
2326
- description: "Group name",
2327
- required: true
2328
- },
2329
- purge: {
2330
- type: "boolean",
2331
- default: false,
2332
- description: "Also delete its notes and its workspace"
2333
- }
2334
- },
2335
- run({ args }) {
2336
- const io = processIo();
2337
- process.exitCode = groupsErrors(io, () => groupsDrop(args.name, io, { purge: args.purge }));
2338
- }
2339
- })
2340
- }
2341
- });
2342
2314
  const hookCommand = defineCommand({
2343
2315
  meta: {
2344
2316
  name: "hook",
@@ -2410,12 +2382,18 @@ const serveCommand = defineCommand({
2410
2382
  serve(processIo());
2411
2383
  }
2412
2384
  });
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
+ }
2413
2390
  const main = defineCommand({
2414
2391
  meta: {
2415
2392
  name: "rucher",
2416
2393
  version,
2417
2394
  description: "Status, journal and sessions of your coding agents (Claude Code today)"
2418
2395
  },
2396
+ setup: ({ rawArgs }) => refuseRemovedOption(rawArgs),
2419
2397
  subCommands: {
2420
2398
  status: statusCommand,
2421
2399
  log: logCommand,
@@ -2425,8 +2403,7 @@ const main = defineCommand({
2425
2403
  fork: forkCommand,
2426
2404
  sessions: sessionsCommand,
2427
2405
  notes: notesCommand,
2428
- group: groupCommand,
2429
- groups: groupsCommand,
2406
+ ws: wsCommand,
2430
2407
  hook: hookCommand,
2431
2408
  serve: serveCommand
2432
2409
  }