@rucher/carnet 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.
@@ -1,4 +1,4 @@
1
- import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
1
+ import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { DatabaseSync } from "node:sqlite";
4
4
  import { homedir } from "node:os";
@@ -437,6 +437,18 @@ CREATE TABLE active_days_new (
437
437
  INSERT INTO active_days_new (group_name, day) SELECT '', day FROM active_days;
438
438
  DROP TABLE active_days;
439
439
  ALTER TABLE active_days_new RENAME TO active_days;
440
+ `,
441
+ `
442
+ ALTER TABLE sessions RENAME COLUMN group_name TO workspace;
443
+ ALTER TABLE notes RENAME COLUMN group_name TO workspace;
444
+ ALTER TABLE active_days RENAME COLUMN group_name TO workspace;
445
+ DROP INDEX sessions_group_status;
446
+ DROP INDEX sessions_group_name;
447
+ DROP INDEX notes_group_number;
448
+ CREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_active_at);
449
+ CREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name)
450
+ WHERE workspace IS NOT NULL AND name IS NOT NULL;
451
+ CREATE UNIQUE INDEX notes_workspace_number ON notes(workspace, number);
440
452
  `
441
453
  ];
442
454
  function schemaVersion(db) {
@@ -504,13 +516,13 @@ function rucherPaths(env = process.env) {
504
516
  function databasePath(env) {
505
517
  return join(rucherPaths(env).data, "carnet.db");
506
518
  }
507
- function groupsDirectory(env) {
508
- return join(rucherPaths(env).config, "groups");
519
+ function workspacesDirectory(env) {
520
+ return join(rucherPaths(env).config, "workspaces");
509
521
  }
510
- function groupSource(name, env) {
511
- return join(groupsDirectory(env), name);
522
+ function workspaceDefinition(name, env) {
523
+ return join(workspacesDirectory(env), name);
512
524
  }
513
- function defaultWorkspace(name, env) {
525
+ function defaultRunDirectory(name, env) {
514
526
  return join(rucherPaths(env).data, "workspaces", name);
515
527
  }
516
528
  function promptsDirectory(env) {
@@ -519,46 +531,46 @@ function promptsDirectory(env) {
519
531
  function corePromptPath(env) {
520
532
  return join(rucherPaths(env).config, "prompt.md");
521
533
  }
522
- function reportsDirectory(group) {
523
- return join(group.workspace, "reports");
534
+ function reportsDirectory(workspace) {
535
+ return join(workspace.runDirectory, "reports");
524
536
  }
525
- function reportPath(group, agentName) {
526
- return join(reportsDirectory(group), `${agentName}.md`);
537
+ function reportPath(workspace, agentName) {
538
+ return join(reportsDirectory(workspace), `${agentName}.md`);
527
539
  }
528
- // src/group/group.ts
529
- const GROUP_FILE = "group.json";
540
+ // src/workspace/workspace.ts
541
+ const WORKSPACE_FILE = "workspace.json";
530
542
  const INSTRUCTIONS_FILE = "CLAUDE.md";
531
543
  const AGENTS_FILE = "AGENTS.md";
532
- const GROUP_NAME = /^[a-z0-9-]+$/;
533
- function isGroupName(name) {
534
- return GROUP_NAME.test(name);
544
+ const WORKSPACE_NAME = /^[a-z0-9-]+$/;
545
+ function isWorkspaceName(name) {
546
+ return WORKSPACE_NAME.test(name);
535
547
  }
536
- function requireGroupName(name) {
537
- if (!isGroupName(name)) throw new CarnetError("GROUP_NAME_INVALID", `Invalid group name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`);
548
+ function requireWorkspaceName(name) {
549
+ if (!isWorkspaceName(name)) throw new CarnetError("WORKSPACE_NAME_INVALID", `Invalid workspace name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`);
538
550
  }
539
551
  function expandHome(path, env = process.env) {
540
552
  if (path !== "~" && !path.startsWith("~/")) return path;
541
553
  return join(env.HOME || homedir(), path.slice(1));
542
554
  }
543
- function groupFilePath(name, env) {
544
- return join(groupSource(name, env), GROUP_FILE);
555
+ function workspaceFilePath(name, env) {
556
+ return join(workspaceDefinition(name, env), WORKSPACE_FILE);
545
557
  }
546
- function groupExists(name, env) {
547
- return isGroupName(name) && existsSync(groupFilePath(name, env));
558
+ function workspaceExists(name, env) {
559
+ return isWorkspaceName(name) && existsSync(workspaceFilePath(name, env));
548
560
  }
549
- function readGroupFile(name, env) {
550
- if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
551
- return JSON.parse(readFileSync(groupFilePath(name, env), "utf8"));
561
+ function readWorkspaceFile(name, env) {
562
+ if (!workspaceExists(name, env)) throw new CarnetError("WORKSPACE_NOT_FOUND", `No workspace named ${name}: see "rucher ws list"`);
563
+ return JSON.parse(readFileSync(workspaceFilePath(name, env), "utf8"));
552
564
  }
553
- function writeGroupFile(name, file, env) {
554
- writeFileSync(groupFilePath(name, env), `${JSON.stringify(file, null, 2)}\n`);
565
+ function writeWorkspaceFile(name, file, env) {
566
+ writeFileSync(workspaceFilePath(name, env), `${JSON.stringify(file, null, 2)}\n`);
555
567
  }
556
- function loadGroup(name, env = process.env) {
557
- const file = readGroupFile(name, env);
568
+ function loadWorkspace(name, env = process.env) {
569
+ const file = readWorkspaceFile(name, env);
558
570
  return {
559
571
  name,
560
- source: groupSource(name, env),
561
- workspace: resolve(expandHome(file.workspace ?? defaultWorkspace(name, env), env)),
572
+ definition: workspaceDefinition(name, env),
573
+ runDirectory: defaultRunDirectory(name, env),
562
574
  repos: (file.repos ?? []).map((repo) => {
563
575
  const path = resolve(expandHome(repo.path, env));
564
576
  return {
@@ -569,13 +581,13 @@ function loadGroup(name, env = process.env) {
569
581
  backends: file.backends ?? {}
570
582
  };
571
583
  }
572
- function listGroups(env = process.env) {
573
- const directory = groupsDirectory(env);
584
+ function listWorkspaces(env = process.env) {
585
+ const directory = workspacesDirectory(env);
574
586
  if (!existsSync(directory)) return [];
575
- return readdirSync(directory).filter((name) => groupExists(name, env)).sort().map((name) => loadGroup(name, env));
587
+ return readdirSync(directory).filter((name) => workspaceExists(name, env)).sort().map((name) => loadWorkspace(name, env));
576
588
  }
577
- function groupHosts(group) {
578
- const hosts = Object.keys(group.backends);
589
+ function workspaceHosts(workspace) {
590
+ const hosts = Object.keys(workspace.backends);
579
591
  return hosts.length ? hosts : [DEFAULT_HOST];
580
592
  }
581
593
  function checkedRepo(path, env) {
@@ -583,101 +595,87 @@ function checkedRepo(path, env) {
583
595
  if (!existsSync(absolute)) throw new CarnetError("REPO_NOT_FOUND", `Repo path does not exist: ${absolute}`);
584
596
  return absolute;
585
597
  }
586
- function requireDistinctNames(group, repos) {
598
+ function requireDistinctNames(workspace, repos) {
587
599
  const names = repos.map((repo) => repo.name);
588
600
  const shared = names.find((name, index) => names.indexOf(name) !== index);
589
- if (shared) throw new CarnetError("REPO_NAME_TAKEN", `${group} would have two repos named ${shared}: give them distinct names`);
601
+ if (shared) throw new CarnetError("REPO_NAME_TAKEN", `${workspace} would have two repos named ${shared}: give them distinct names`);
590
602
  }
591
- function createGroup(name, options = {}) {
603
+ function createWorkspace(name, options = {}) {
592
604
  const { env } = options;
593
- requireGroupName(name);
594
- if (groupExists(name, env)) throw new CarnetError("GROUP_EXISTS", `Group ${name} already exists`);
605
+ requireWorkspaceName(name);
606
+ if (workspaceExists(name, env)) throw new CarnetError("WORKSPACE_EXISTS", `Workspace ${name} already exists`);
595
607
  const repos = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))].map((path) => ({
596
608
  path,
597
609
  name: basename(path)
598
610
  }));
599
611
  requireDistinctNames(name, repos);
600
- const source = groupSource(name, env);
601
- const workspace = defaultWorkspace(name, env);
602
- mkdirSync(source, { recursive: true });
603
- mkdirSync(workspace, { recursive: true });
604
- writeGroupFile(name, {
612
+ const definition = workspaceDefinition(name, env);
613
+ const runDirectory = defaultRunDirectory(name, env);
614
+ mkdirSync(definition, { recursive: true });
615
+ mkdirSync(runDirectory, { recursive: true });
616
+ writeWorkspaceFile(name, {
605
617
  name,
606
- workspace,
607
618
  repos,
608
619
  backends: {}
609
620
  }, env);
610
- const instructions = join(source, INSTRUCTIONS_FILE);
621
+ const instructions = join(definition, INSTRUCTIONS_FILE);
611
622
  if (!existsSync(instructions)) writeFileSync(instructions, "");
612
- return loadGroup(name, env);
623
+ return loadWorkspace(name, env);
613
624
  }
614
- function sourceInstructions(group) {
615
- const agents = existsSync(join(group.source, AGENTS_FILE));
616
- if (agents && existsSync(join(group.source, "CLAUDE.md"))) throw new CarnetError("GROUP_INSTRUCTIONS_CONFLICT", `Group ${group.name} has both ${AGENTS_FILE} and ${INSTRUCTIONS_FILE} in ${group.source}: remove ${INSTRUCTIONS_FILE}`);
625
+ function definitionInstructions(workspace) {
626
+ const agents = existsSync(join(workspace.definition, AGENTS_FILE));
627
+ if (agents && existsSync(join(workspace.definition, "CLAUDE.md"))) throw new CarnetError("WORKSPACE_INSTRUCTIONS_CONFLICT", `Workspace ${workspace.name} has both ${AGENTS_FILE} and ${INSTRUCTIONS_FILE} in ${workspace.definition}: remove ${INSTRUCTIONS_FILE}`);
617
628
  return agents ? AGENTS_FILE : INSTRUCTIONS_FILE;
618
629
  }
619
- function addGroupRepo(name, repo, env) {
620
- const file = readGroupFile(name, env);
621
- const group = loadGroup(name, env);
630
+ function addWorkspaceRepo(name, repo, env) {
631
+ const file = readWorkspaceFile(name, env);
632
+ const workspace = loadWorkspace(name, env);
622
633
  const path = checkedRepo(repo, env);
623
- if (group.repos.some((existing) => existing.path === path)) return group;
624
- requireDistinctNames(name, [...group.repos, {
634
+ if (workspace.repos.some((existing) => existing.path === path)) return workspace;
635
+ requireDistinctNames(name, [...workspace.repos, {
625
636
  path,
626
637
  name: basename(path)
627
638
  }]);
628
- writeGroupFile(name, {
639
+ writeWorkspaceFile(name, {
629
640
  ...file,
630
641
  repos: [...file.repos ?? [], {
631
642
  path,
632
643
  name: basename(path)
633
644
  }]
634
645
  }, env);
635
- return loadGroup(name, env);
646
+ return loadWorkspace(name, env);
636
647
  }
637
- function removeGroupRepo(name, repo, env) {
638
- const file = readGroupFile(name, env);
639
- const group = loadGroup(name, env);
648
+ function removeWorkspaceRepo(name, repo, env) {
649
+ const file = readWorkspaceFile(name, env);
650
+ const workspace = loadWorkspace(name, env);
640
651
  const path = resolve(expandHome(repo, env));
641
- const index = group.repos.findIndex((existing) => existing.path === path || existing.name === repo);
652
+ const index = workspace.repos.findIndex((existing) => existing.path === path || existing.name === repo);
642
653
  if (index === -1) throw new CarnetError("REPO_NOT_FOUND", `${repo} is not a repo of ${name}`);
643
- writeGroupFile(name, {
654
+ writeWorkspaceFile(name, {
644
655
  ...file,
645
656
  repos: (file.repos ?? []).filter((_, position) => position !== index)
646
657
  }, env);
647
- return loadGroup(name, env);
648
- }
649
- function renameGroup(from, to, env) {
650
- const file = readGroupFile(from, env);
651
- requireGroupName(to);
652
- if (existsSync(groupSource(to, env))) throw new CarnetError("GROUP_EXISTS", `Group ${to} already exists`);
653
- const workspace = loadGroup(from, env).workspace;
654
- renameSync(groupSource(from, env), groupSource(to, env));
655
- writeGroupFile(to, {
656
- ...file,
657
- name: to,
658
- workspace
659
- }, env);
660
- return loadGroup(to, env);
658
+ return loadWorkspace(name, env);
661
659
  }
662
- function dropGroup(name, options = {}) {
663
- const group = loadGroup(name, options.env);
664
- rmSync(group.source, {
660
+ function dropWorkspace(name, options = {}) {
661
+ const workspace = loadWorkspace(name, options.env);
662
+ rmSync(workspace.definition, {
665
663
  recursive: true,
666
664
  force: true
667
665
  });
668
- if (options.purge) rmSync(group.workspace, {
666
+ if (options.purge) rmSync(workspace.runDirectory, {
669
667
  recursive: true,
670
668
  force: true
671
669
  });
672
- return group;
670
+ return workspace;
673
671
  }
674
672
  // src/sessions.ts
675
- const COLUMNS = `id, group_name, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
673
+ const COLUMNS = `id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
676
674
  parent_id, prompt_version, created_at, last_active_at, ended_at`;
677
675
  function toSession(row) {
678
676
  return {
679
677
  id: row.id,
680
- groupName: row.group_name,
678
+ workspace: row.workspace,
681
679
  name: row.name,
682
680
  purpose: row.purpose,
683
681
  kind: row.kind,
@@ -704,11 +702,11 @@ function requireSession(ctx, id) {
704
702
  if (!session) throw new CarnetError("SESSION_NOT_FOUND", `Unknown session ${id}`);
705
703
  return session;
706
704
  }
707
- function ensureSession(ctx, id, cwd, group) {
705
+ function ensureSession(ctx, id, cwd, workspace) {
708
706
  const existing = getSession(ctx, id);
709
707
  if (existing) return existing;
710
708
  const at = nowIso(ctx);
711
- ctx.db.prepare("INSERT INTO sessions (id, group_name, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?, ?)").run(id, ctx.group, cwd ?? null, group ? repoNameFor(group, cwd) : null, at, at);
709
+ ctx.db.prepare("INSERT INTO sessions (id, workspace, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?, ?)").run(id, ctx.workspace, cwd ?? null, workspace ? repoNameFor(workspace, cwd) : null, at, at);
712
710
  return requireSession(ctx, id);
713
711
  }
714
712
  function nameTaken(error, name) {
@@ -719,9 +717,9 @@ function createSession(ctx, input) {
719
717
  if (input.kind === "active" && !input.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
720
718
  const at = nowIso(ctx);
721
719
  try {
722
- ctx.db.prepare(`INSERT INTO sessions (id, group_name, name, kind, status, cwd, repo, host, last_title,
720
+ ctx.db.prepare(`INSERT INTO sessions (id, workspace, name, kind, status, cwd, repo, host, last_title,
723
721
  created_at, last_active_at)
724
- VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(input.id, ctx.group, input.name ?? null, input.kind, input.cwd, input.repo ?? null, input.host ?? "claude-code", input.name ?? null, at, at);
722
+ VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(input.id, ctx.workspace, input.name ?? null, input.kind, input.cwd, input.repo ?? null, input.host ?? "claude-code", input.name ?? null, at, at);
725
723
  } catch (error) {
726
724
  nameTaken(error, input.name);
727
725
  }
@@ -760,15 +758,15 @@ function adoptTitle(ctx, id, rawTitle) {
760
758
  WHERE id = ?`).run(title, id);
761
759
  return requireSession(ctx, id);
762
760
  }
763
- function upsertFromHook(ctx, group, payload, env = {}) {
761
+ function upsertFromHook(ctx, workspace, payload, env = {}) {
764
762
  const at = nowIso(ctx);
765
763
  const host = env.host ?? "claude-code";
766
764
  const hostPid = env.processId ?? null;
767
- const repo = group ? repoNameFor(group, payload.cwd) : null;
765
+ const repo = workspace ? repoNameFor(workspace, payload.cwd) : null;
768
766
  const existing = getSession(ctx, payload.session_id);
769
- if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, group_name, cwd, repo, host, host_pid, hooked_at, created_at,
767
+ if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, workspace, cwd, repo, host, host_pid, hooked_at, created_at,
770
768
  last_active_at)
771
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, ctx.group, payload.cwd ?? null, repo, host, hostPid, at, at, at);
769
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, ctx.workspace, payload.cwd ?? null, repo, host, hostPid, at, at, at);
772
770
  else ctx.db.prepare(`UPDATE sessions
773
771
  SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
774
772
  WHERE id = ?`).run(at, at, existing.cwd ?? payload.cwd ?? null, existing.cwd ? existing.repo : repo ?? existing.repo, host, hostPid ?? existing.hostPid, payload.session_id);
@@ -791,10 +789,10 @@ function nameSession(ctx, id, name, purpose) {
791
789
  return requireSession(ctx, id);
792
790
  }
793
791
  function listSessions(ctx, options = {}) {
794
- const conditions = ["group_name IS ?"];
792
+ const conditions = ["workspace IS ?"];
795
793
  if (!options.includeTemp) conditions.push("kind != 'temp'");
796
794
  if (!options.includeArchived) conditions.push("status != 'archived'");
797
- return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC`).all(ctx.group).map(toSession);
795
+ return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC`).all(ctx.workspace).map(toSession);
798
796
  }
799
797
  function dropSession(ctx, id) {
800
798
  requireSession(ctx, id);
@@ -804,12 +802,12 @@ function dropSession(ctx, id) {
804
802
  return requireSession(ctx, id);
805
803
  }
806
804
  function defaultSession(ctx) {
807
- const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND status != 'archived'
808
- ORDER BY last_active_at DESC LIMIT 1`).get(ctx.group);
805
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace IS ? AND status != 'archived'
806
+ ORDER BY last_active_at DESC LIMIT 1`).get(ctx.workspace);
809
807
  return row && toSession(row);
810
808
  }
811
809
  function sessionByName(ctx, name) {
812
- const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND name = ?`).get(ctx.group, name);
810
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace IS ? AND name = ?`).get(ctx.workspace, name);
813
811
  return row && toSession(row);
814
812
  }
815
813
  const MINIMUM_ID_PREFIX = 4;
@@ -823,8 +821,8 @@ function findSession(ctx, reference) {
823
821
  if (byId) return byId;
824
822
  const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
825
823
  if (isIdPrefix && reference.length >= 4) {
826
- const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND id LIKE ?
827
- ORDER BY last_active_at DESC`).all(ctx.group, `${reference.toLowerCase()}%`);
824
+ const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace IS ? AND id LIKE ?
825
+ ORDER BY last_active_at DESC`).all(ctx.workspace, `${reference.toLowerCase()}%`);
828
826
  const [only, ...others] = rows;
829
827
  if (only && others.length === 0) return toSession(only);
830
828
  if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
@@ -891,8 +889,8 @@ function demoteSession(ctx, id) {
891
889
  function staleTempSessions(ctx, olderThanMilliseconds) {
892
890
  const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
893
891
  return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
894
- WHERE group_name IS ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
895
- ORDER BY last_active_at ASC`).all(ctx.group, before).map(toSession);
892
+ WHERE workspace IS ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
893
+ ORDER BY last_active_at ASC`).all(ctx.workspace, before).map(toSession);
896
894
  }
897
895
  function resetDeadSessions(ctx, isAlive) {
898
896
  return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE status = 'running'`).all().map(toSession).filter((session) => session.hostPid === null || !isAlive(session.hostPid)).map((session) => endSession(ctx, session.id));
@@ -913,27 +911,27 @@ function readIfPresent(path) {
913
911
  function baseRules(env = process.env) {
914
912
  return readIfPresent(corePromptPath(env)) ?? "- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the \"On the table\" line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When a fork finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that fork's report, even when answering about something else.\n- Forks never commit, push, stash or record notes. A fork writes its report to a file, ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.";
915
913
  }
916
- function groupRules(group) {
917
- return group ? readIfPresent(join(group.source, PROMPT_FILE)) : void 0;
914
+ function workspaceRules(workspace) {
915
+ return workspace ? readIfPresent(join(workspace.definition, PROMPT_FILE)) : void 0;
918
916
  }
919
- function rulesText(group, env = process.env) {
920
- const extra = groupRules(group);
917
+ function rulesText(workspace, env = process.env) {
918
+ const extra = workspaceRules(workspace);
921
919
  const base = `Rucher rules, always follow them:\n${baseRules(env)}`;
922
- return extra && group ? `${base}\n\nRules of the ${group.name} group:\n${extra}` : base;
920
+ return extra && workspace ? `${base}\n\nRules of the ${workspace.name} workspace:\n${extra}` : base;
923
921
  }
924
- function rulesVersion(group, env = process.env) {
925
- return createHash("sha256").update(rulesText(group, env)).digest("hex").slice(0, 12);
922
+ function rulesVersion(workspace, env = process.env) {
923
+ return createHash("sha256").update(rulesText(workspace, env)).digest("hex").slice(0, 12);
926
924
  }
927
- function assemblePrompt(group, session, env = process.env) {
925
+ function assemblePrompt(workspace, session, env = process.env) {
928
926
  const label = session.name ?? shortId(session.id);
929
- const identity = group ? `This is the Rucher session ${label} (${session.kind}) of the ${group.name} group.` : `This is the Rucher session ${label} (${session.kind}), outside any group.`;
927
+ const identity = workspace ? `This is the Rucher session ${label} (${session.kind}) of the ${workspace.name} workspace.` : `This is the Rucher session ${label} (${session.kind}), outside any workspace.`;
930
928
  return {
931
- text: `${rulesText(group, env)}\n\n${identity}\n`,
932
- version: rulesVersion(group, env)
929
+ text: `${rulesText(workspace, env)}\n\n${identity}\n`,
930
+ version: rulesVersion(workspace, env)
933
931
  };
934
932
  }
935
- function appendPromptFile(group, session, env = process.env) {
936
- const { text, version } = assemblePrompt(group, session, env);
933
+ function appendPromptFile(workspace, session, env = process.env) {
934
+ const { text, version } = assemblePrompt(workspace, session, env);
937
935
  const directory = promptsDirectory(env);
938
936
  mkdirSync(directory, { recursive: true });
939
937
  const path = join(directory, `${session.id}.md`);
@@ -943,19 +941,19 @@ function appendPromptFile(group, session, env = process.env) {
943
941
  version
944
942
  };
945
943
  }
946
- function compactReminder(group, env = process.env) {
947
- return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${rulesText(group, env)}`;
944
+ function compactReminder(workspace, env = process.env) {
945
+ return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${rulesText(workspace, env)}`;
948
946
  }
949
- function outsideRucherContext(group, env = process.env) {
950
- return `This session was started without rucher, so its system prompt does not hold the Rucher rules. ${rulesText(group, env)}`;
947
+ function outsideRucherContext(workspace, env = process.env) {
948
+ return `This session was started without rucher, so its system prompt does not hold the Rucher rules. ${rulesText(workspace, env)}`;
951
949
  }
952
950
  const OUTSIDE_RUCHER_NOTICE = "rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)";
953
951
  const RULES_UPDATED_NOTICE = "rucher: rules updated, will apply after the next compaction or in a new session";
954
952
  const SUBAGENT_RULES = "Rucher rules for sub-agents: never commit, push or stash. When your task asks for a report, write it to the file it names. If your prompt names you as a Carnet agent, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.";
955
- // src/workspace-files.ts
953
+ // src/run-directory-files.ts
956
954
  const GENERATED_MARKER = "generated by rucher, do not edit";
957
955
  function refuse(path) {
958
- throw new CarnetError("WORKSPACE_FILE_CONFLICT", `${path} was not written by rucher: move its content to the group source, then remove it`);
956
+ throw new CarnetError("RUN_DIRECTORY_FILE_CONFLICT", `${path} was not written by rucher: move its content to the workspace definition, then remove it`);
959
957
  }
960
958
  function entry(path) {
961
959
  try {
@@ -1069,54 +1067,54 @@ function transcriptTitle(path) {
1069
1067
  }
1070
1068
  const SETTINGS_FILE = join(".claude", "settings.json");
1071
1069
  const BACKEND_NOTES = "backends/claude.md";
1072
- function instructionFiles(group) {
1073
- if (!existsSync(group.source)) return [];
1074
- return readdirSync(group.source, { withFileTypes: true }).filter((item) => item.isFile() && item.name.endsWith(".md") && item.name !== "prompt.md").map((item) => item.name).sort();
1070
+ function instructionFiles(workspace) {
1071
+ if (!existsSync(workspace.definition)) return [];
1072
+ return readdirSync(workspace.definition, { withFileTypes: true }).filter((item) => item.isFile() && item.name.endsWith(".md") && item.name !== "prompt.md").map((item) => item.name).sort();
1075
1073
  }
1076
- function repoAgentsImports(group) {
1077
- return group.repos.filter((repo) => existsSync(join(repo.path, "AGENTS.md")) && !existsSync(join(repo.path, "CLAUDE.md")) && !existsSync(join(repo.path, ".claude", "CLAUDE.md"))).map((repo) => `@${join(repo.path, AGENTS_FILE)}`);
1074
+ function repoAgentsImports(workspace) {
1075
+ return workspace.repos.filter((repo) => existsSync(join(repo.path, "AGENTS.md")) && !existsSync(join(repo.path, "CLAUDE.md")) && !existsSync(join(repo.path, ".claude", "CLAUDE.md"))).map((repo) => `@${join(repo.path, AGENTS_FILE)}`);
1078
1076
  }
1079
- function workspaceCopies(group) {
1080
- const agents = sourceInstructions(group) === AGENTS_FILE;
1081
- const read = (name) => readFileSync(join(group.source, name), "utf8");
1082
- const copies = new Map(instructionFiles(group).map((name) => [name, markdownCopy(read(name))]));
1077
+ function runDirectoryCopies(workspace) {
1078
+ const agents = definitionInstructions(workspace) === AGENTS_FILE;
1079
+ const read = (name) => readFileSync(join(workspace.definition, name), "utf8");
1080
+ const copies = new Map(instructionFiles(workspace).map((name) => [name, markdownCopy(read(name))]));
1083
1081
  if (!agents) return copies;
1084
1082
  const imports = [`@${AGENTS_FILE}`];
1085
- if (existsSync(join(group.source, BACKEND_NOTES))) {
1083
+ if (existsSync(join(workspace.definition, BACKEND_NOTES))) {
1086
1084
  copies.set(BACKEND_NOTES, markdownCopy(read(BACKEND_NOTES)));
1087
1085
  imports.push(`@${BACKEND_NOTES}`);
1088
1086
  }
1089
- imports.push(...repoAgentsImports(group));
1087
+ imports.push(...repoAgentsImports(workspace));
1090
1088
  copies.set(INSTRUCTIONS_FILE, markdownCopy(`${imports.join("\n")}\n`));
1091
1089
  return copies;
1092
1090
  }
1093
- function groupSettings(group) {
1091
+ function workspaceSettings(workspace) {
1094
1092
  return mergeSettings({
1095
1093
  "//": GENERATED_MARKER,
1096
1094
  permissions: {
1097
- additionalDirectories: group.repos.map((repo) => repo.path),
1098
- deny: [...workspaceCopies(group).keys()].sort().map((name) => `Edit(/${name})`)
1095
+ additionalDirectories: workspace.repos.map((repo) => repo.path),
1096
+ deny: [...runDirectoryCopies(workspace).keys()].sort().map((name) => `Edit(/${name})`)
1099
1097
  }
1100
- }, group.backends["claude-code"]?.settings ?? {});
1098
+ }, workspace.backends["claude-code"]?.settings ?? {});
1101
1099
  }
1102
- function removeStaleBackendNotes(group, keep) {
1103
- const directory = join(group.workspace, dirname(BACKEND_NOTES));
1100
+ function removeStaleBackendNotes(workspace, keep) {
1101
+ const directory = join(workspace.runDirectory, dirname(BACKEND_NOTES));
1104
1102
  const removed = removeStaleCopies(directory, new Set([...keep].filter((name) => dirname(name) === dirname(BACKEND_NOTES)).map((name) => basename(name))));
1105
1103
  if (existsSync(directory) && readdirSync(directory).length === 0) rmdirSync(directory);
1106
1104
  return removed.map((name) => join(dirname(BACKEND_NOTES), name));
1107
1105
  }
1108
- function renderClaudeWorkspace(group) {
1106
+ function renderClaudeRunDirectory(workspace) {
1109
1107
  const rendered = {
1110
1108
  written: [],
1111
1109
  removed: []
1112
1110
  };
1113
- const copies = workspaceCopies(group);
1114
- for (const [name, content] of [...copies].sort(([a], [b]) => a.localeCompare(b))) if (writeGenerated(join(group.workspace, name), content)) rendered.written.push(name);
1111
+ const copies = runDirectoryCopies(workspace);
1112
+ for (const [name, content] of [...copies].sort(([a], [b]) => a.localeCompare(b))) if (writeGenerated(join(workspace.runDirectory, name), content)) rendered.written.push(name);
1115
1113
  const names = new Set(copies.keys());
1116
- rendered.removed.push(...removeStaleCopies(group.workspace, names));
1117
- rendered.removed.push(...removeStaleBackendNotes(group, names));
1118
- const settings = `${JSON.stringify(groupSettings(group), null, 2)}\n`;
1119
- if (writeGenerated(join(group.workspace, SETTINGS_FILE), settings)) rendered.written.push(SETTINGS_FILE);
1114
+ rendered.removed.push(...removeStaleCopies(workspace.runDirectory, names));
1115
+ rendered.removed.push(...removeStaleBackendNotes(workspace, names));
1116
+ const settings = `${JSON.stringify(workspaceSettings(workspace), null, 2)}\n`;
1117
+ if (writeGenerated(join(workspace.runDirectory, SETTINGS_FILE), settings)) rendered.written.push(SETTINGS_FILE);
1120
1118
  return rendered;
1121
1119
  }
1122
1120
  function launchArguments(options = {}) {
@@ -1133,6 +1131,9 @@ const RENDERING_SOURCES = /* @__PURE__ */ new Set([
1133
1131
  "compact",
1134
1132
  "fork"
1135
1133
  ]);
1134
+ function projectsDirectory(env) {
1135
+ return join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
1136
+ }
1136
1137
  const claudeCode = {
1137
1138
  id: "claude-code",
1138
1139
  displayName: "Claude Code",
@@ -1251,14 +1252,18 @@ const claudeCode = {
1251
1252
  },
1252
1253
  transcriptFiles(session, env = process.env) {
1253
1254
  if (!session.cwd) return [];
1254
- const root = env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
1255
- const project = join(root, "projects", session.cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1255
+ const project = join(projectsDirectory(env), session.cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1256
1256
  return [join(project, `${session.id}.jsonl`), join(project, session.id)].filter((path) => existsSync(path));
1257
1257
  },
1258
+ hasConversation(session, env = process.env) {
1259
+ const projects = projectsDirectory(env);
1260
+ if (!existsSync(projects)) return false;
1261
+ return readdirSync(projects).some((project) => existsSync(join(projects, project, `${session.id}.jsonl`)));
1262
+ },
1258
1263
  renameInstruction(name) {
1259
1264
  return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
1260
1265
  },
1261
- renderWorkspace: renderClaudeWorkspace
1266
+ renderRunDirectory: renderClaudeRunDirectory
1262
1267
  };
1263
1268
  // src/hosts/host.ts
1264
1269
  const DEFAULT_HOST = "claude-code";
@@ -1271,7 +1276,7 @@ function hostById(id) {
1271
1276
  if (!host) throw new CarnetError("UNKNOWN_HOST", `Unknown host "${id}" (available: ${Object.keys(HOSTS).join(", ")})`);
1272
1277
  return host;
1273
1278
  }
1274
- // src/group-rows.ts
1279
+ // src/workspace-rows.ts
1275
1280
  function inTransaction(db, run) {
1276
1281
  db.exec("BEGIN");
1277
1282
  try {
@@ -1283,129 +1288,120 @@ function inTransaction(db, run) {
1283
1288
  throw error;
1284
1289
  }
1285
1290
  }
1286
- function sessionGroupName(db, sessionId) {
1287
- const row = db.prepare("SELECT group_name FROM sessions WHERE id = ?").get(sessionId);
1288
- return row ? row.group_name : void 0;
1289
- }
1290
- function renameGroupRows(db, from, to) {
1291
- inTransaction(db, () => {
1292
- for (const table of [
1293
- "sessions",
1294
- "notes",
1295
- "active_days"
1296
- ]) db.prepare(`UPDATE ${table} SET group_name = ? WHERE group_name = ?`).run(to, from);
1297
- });
1291
+ function sessionWorkspaceName(db, sessionId) {
1292
+ const row = db.prepare("SELECT workspace FROM sessions WHERE id = ?").get(sessionId);
1293
+ return row ? row.workspace : void 0;
1298
1294
  }
1299
- function archiveGroupSessions(db, name, at) {
1295
+ function archiveWorkspaceSessions(db, name, at) {
1300
1296
  return inTransaction(db, () => {
1301
1297
  db.prepare(`UPDATE agents SET status = 'closed', updated_at = ?
1302
- WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE group_name = ?)`).run(at, name);
1298
+ WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE workspace = ?)`).run(at, name);
1303
1299
  return Number(db.prepare(`UPDATE sessions SET status = 'archived', last_active_at = ?
1304
- WHERE group_name = ? AND status != 'archived'`).run(at, name).changes);
1300
+ WHERE workspace = ? AND status != 'archived'`).run(at, name).changes);
1305
1301
  });
1306
1302
  }
1307
- function deleteGroupNotes(db, name) {
1308
- return Number(db.prepare("DELETE FROM notes WHERE group_name = ?").run(name).changes);
1303
+ function deleteWorkspaceNotes(db, name) {
1304
+ return Number(db.prepare("DELETE FROM notes WHERE workspace = ?").run(name).changes);
1309
1305
  }
1310
- function groupSessionCounts(db) {
1311
- const rows = db.prepare(`SELECT group_name, COUNT(*) AS count FROM sessions
1312
- WHERE group_name IS NOT NULL AND status != 'archived' GROUP BY group_name`).all();
1313
- return new Map(rows.map((row) => [row.group_name, Number(row.count)]));
1306
+ function workspaceSessionCounts(db) {
1307
+ const rows = db.prepare(`SELECT workspace, COUNT(*) AS count FROM sessions
1308
+ WHERE workspace IS NOT NULL AND status != 'archived' GROUP BY workspace`).all();
1309
+ return new Map(rows.map((row) => [row.workspace, Number(row.count)]));
1314
1310
  }
1315
- // src/group/locate.ts
1311
+ // src/workspace/locate.ts
1316
1312
  function isInside(directory, path) {
1317
1313
  const relativePath = relative(directory, path);
1318
1314
  return relativePath === "" || !relativePath.startsWith("..") && !resolve(relativePath).startsWith(relativePath);
1319
1315
  }
1320
- function repoOf(group, path) {
1316
+ function repoOf(workspace, path) {
1321
1317
  const absolutePath = resolve(path);
1322
- return group?.repos.find((repo) => isInside(repo.path, absolutePath));
1318
+ return workspace?.repos.find((repo) => isInside(repo.path, absolutePath));
1323
1319
  }
1324
- function repoNameFor(group, path) {
1325
- return path ? repoOf(group, path)?.name ?? null : null;
1320
+ function repoNameFor(workspace, path) {
1321
+ return path ? repoOf(workspace, path)?.name ?? null : null;
1326
1322
  }
1327
- function repoPathFor(group, path) {
1323
+ function repoPathFor(workspace, path) {
1328
1324
  if (!path) return null;
1329
- const repo = repoOf(group, path);
1325
+ const repo = repoOf(workspace, path);
1330
1326
  if (!repo) return null;
1331
1327
  const relativePath = relative(repo.path, resolve(path));
1332
1328
  return relativePath ? join(repo.name, relativePath) : repo.name;
1333
1329
  }
1334
- function namedGroup(name, env) {
1335
- if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
1336
- return loadGroup(name, env);
1330
+ function namedWorkspace(name, env) {
1331
+ if (!workspaceExists(name, env)) throw new CarnetError("WORKSPACE_NOT_FOUND", `No workspace named ${name}: see "rucher ws list"`);
1332
+ return loadWorkspace(name, env);
1337
1333
  }
1338
- function byWorkspace(groups, directories) {
1339
- return groups.find((group) => directories.some((directory) => isInside(group.workspace, directory)));
1334
+ function byRunDirectory(workspaces, directories) {
1335
+ return workspaces.find((workspace) => directories.some((directory) => isInside(workspace.runDirectory, directory)));
1340
1336
  }
1341
- function byRepo(groups, directory) {
1337
+ function byRepo(workspaces, directory) {
1342
1338
  let best = [];
1343
- for (const group of groups) for (const repo of group.repos) {
1339
+ for (const workspace of workspaces) for (const repo of workspace.repos) {
1344
1340
  if (!isInside(repo.path, directory)) continue;
1345
1341
  const length = best[0]?.repo.path.length ?? -1;
1346
1342
  if (repo.path.length > length) best = [{
1347
- group,
1343
+ workspace,
1348
1344
  repo
1349
1345
  }];
1350
1346
  else if (repo.path.length === length) best.push({
1351
- group,
1347
+ workspace,
1352
1348
  repo
1353
1349
  });
1354
1350
  }
1355
- const names = [...new Set(best.map((match) => match.group.name))];
1356
- if (names.length > 1) throw new CarnetError("GROUP_AMBIGUOUS", `${directory} is in repos of several groups (${names.join(", ")}): pass --group`);
1351
+ const names = [...new Set(best.map((match) => match.workspace.name))];
1352
+ if (names.length > 1) throw new CarnetError("WORKSPACE_AMBIGUOUS", `${directory} is in repos of several workspaces (${names.join(", ")}): pass --ws`);
1357
1353
  return best[0];
1358
1354
  }
1359
- function resolveGroup({ db, sessionId, group, cwd = process.cwd(), env = process.env } = {}) {
1355
+ function resolveWorkspace({ db, sessionId, workspace, cwd = process.cwd(), env = process.env } = {}) {
1360
1356
  if (db && sessionId) {
1361
- const name = sessionGroupName(db, sessionId);
1357
+ const name = sessionWorkspaceName(db, sessionId);
1362
1358
  if (name === null) return {
1363
- group: null,
1359
+ workspace: null,
1364
1360
  origin: "session"
1365
1361
  };
1366
- if (name !== void 0 && groupExists(name, env)) return {
1367
- group: loadGroup(name, env),
1362
+ if (name !== void 0 && workspaceExists(name, env)) return {
1363
+ workspace: loadWorkspace(name, env),
1368
1364
  origin: "session"
1369
1365
  };
1370
1366
  }
1371
- if (group) return {
1372
- group: namedGroup(group, env),
1367
+ if (workspace) return {
1368
+ workspace: namedWorkspace(workspace, env),
1373
1369
  origin: "option"
1374
1370
  };
1375
- if (env.RUCHER_GROUP) return {
1376
- group: namedGroup(env.RUCHER_GROUP, env),
1371
+ if (env.RUCHER_WS) return {
1372
+ workspace: namedWorkspace(env.RUCHER_WS, env),
1377
1373
  origin: "env"
1378
1374
  };
1379
1375
  const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
1380
1376
  const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
1381
- const groups = listGroups(env);
1382
- const workspaceGroup = byWorkspace(groups, directories);
1383
- if (workspaceGroup) return {
1384
- group: workspaceGroup,
1385
- origin: "workspace"
1377
+ const workspaces = listWorkspaces(env);
1378
+ const runDirectoryWorkspace = byRunDirectory(workspaces, directories);
1379
+ if (runDirectoryWorkspace) return {
1380
+ workspace: runDirectoryWorkspace,
1381
+ origin: "run-directory"
1386
1382
  };
1387
1383
  for (const directory of directories) {
1388
- const match = byRepo(groups, directory);
1384
+ const match = byRepo(workspaces, directory);
1389
1385
  if (match) return {
1390
- group: match.group,
1386
+ workspace: match.workspace,
1391
1387
  origin: "repo",
1392
1388
  repo: match.repo
1393
1389
  };
1394
1390
  }
1395
1391
  return {
1396
- group: null,
1392
+ workspace: null,
1397
1393
  origin: "none"
1398
1394
  };
1399
1395
  }
1400
- function groupLabel(group) {
1401
- return group?.name ?? "no group";
1396
+ function workspaceLabel(workspace) {
1397
+ return workspace?.name ?? "no workspace";
1402
1398
  }
1403
- function requireGroup(group) {
1404
- if (group) return group;
1405
- throw new CarnetError("NO_GROUP", "No Rucher group here: pass --group, or run this from a repo or workspace of a group");
1399
+ function requireWorkspace(workspace) {
1400
+ if (workspace) return workspace;
1401
+ throw new CarnetError("NO_WORKSPACE", "No Rucher workspace here: pass --ws, or run this from a repo or run directory of a workspace");
1406
1402
  }
1407
- function ambiguousGroupContext(reason) {
1408
- return `Rucher could not tell which group this session belongs to, so Carnet records nothing for it: ${reason}.`;
1403
+ function ambiguousWorkspaceContext(reason) {
1404
+ return `Rucher could not tell which workspace this session belongs to, so Carnet records nothing for it: ${reason}.`;
1409
1405
  }
1410
1406
  // src/notes.ts
1411
1407
  const NOTE_KINDS = [
@@ -1440,14 +1436,14 @@ function cleanText(value, label) {
1440
1436
  if (MARKDOWN.test(text)) throw new CarnetError("INVALID_NOTE", `${label} must not use markdown`);
1441
1437
  return text;
1442
1438
  }
1443
- function groupRepoNames(group) {
1444
- return group.repos.map((repo) => repo.name);
1439
+ function workspaceRepoNames(workspace) {
1440
+ return workspace.repos.map((repo) => repo.name);
1445
1441
  }
1446
- function cleanRepos(group, repos) {
1447
- const known = groupRepoNames(group);
1442
+ function cleanRepos(workspace, repos) {
1443
+ const known = workspaceRepoNames(workspace);
1448
1444
  const unique = [...new Set((repos ?? []).map((repo) => repo.trim()).filter(Boolean))];
1449
1445
  const unknown = unique.filter((repo) => !known.includes(repo));
1450
- if (unknown.length) throw new CarnetError("INVALID_NOTE", `Unknown repo ${unknown.join(", ")} (group repos: ${known.join(", ") || "none"})`);
1446
+ if (unknown.length) throw new CarnetError("INVALID_NOTE", `Unknown repo ${unknown.join(", ")} (workspace repos: ${known.join(", ") || "none"})`);
1451
1447
  return unique;
1452
1448
  }
1453
1449
  function words(text) {
@@ -1467,11 +1463,11 @@ function localDay(date) {
1467
1463
  return `${date.getFullYear()}-${month}-${day}`;
1468
1464
  }
1469
1465
  function recordActiveDay(ctx) {
1470
- if (ctx.group === null) return;
1471
- ctx.db.prepare("INSERT OR IGNORE INTO active_days (group_name, day) VALUES (?, ?)").run(ctx.group, localDay(ctx.now()));
1466
+ if (ctx.workspace === null) return;
1467
+ ctx.db.prepare("INSERT OR IGNORE INTO active_days (workspace, day) VALUES (?, ?)").run(ctx.workspace, localDay(ctx.now()));
1472
1468
  }
1473
1469
  function activeDays(ctx) {
1474
- return ctx.db.prepare("SELECT day FROM active_days WHERE group_name IS ? ORDER BY day").all(ctx.group).map((row) => row.day);
1470
+ return ctx.db.prepare("SELECT day FROM active_days WHERE workspace IS ? ORDER BY day").all(ctx.workspace).map((row) => row.day);
1475
1471
  }
1476
1472
  function activeDaysSince(days, at) {
1477
1473
  const since = localDay(new Date(at));
@@ -1497,7 +1493,7 @@ function toNote(ctx, row) {
1497
1493
  };
1498
1494
  }
1499
1495
  function noteRow(ctx, number) {
1500
- return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND number = ?`).get(ctx.group, number);
1496
+ return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND number = ?`).get(ctx.workspace, number);
1501
1497
  }
1502
1498
  function noteId(ctx, number) {
1503
1499
  const row = noteRow(ctx, number);
@@ -1522,7 +1518,7 @@ const CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citation
1522
1518
  note_citations.agent, note_citations.why, note_citations.at`;
1523
1519
  function citationsOf(ctx, number) {
1524
1520
  return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
1525
- WHERE notes.group_name IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.group, number);
1521
+ WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.workspace, number);
1526
1522
  }
1527
1523
  function weightOf(citations, days, halfLifeDays) {
1528
1524
  const latest = /* @__PURE__ */ new Map();
@@ -1550,23 +1546,23 @@ function compareNotes(first, second) {
1550
1546
  return second.id - first.id;
1551
1547
  }
1552
1548
  function activeNotesOfKind(ctx, kind) {
1553
- return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND kind = ? AND dropped_at IS NULL`).all(ctx.group, kind).map((row) => toNote(ctx, row));
1549
+ return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND kind = ? AND dropped_at IS NULL`).all(ctx.workspace, kind).map((row) => toNote(ctx, row));
1554
1550
  }
1555
- function addNote(ctx, group, input) {
1556
- if (group === null || ctx.group === null) throw new CarnetError("NO_GROUP", "Notes belong to a group: this session has none");
1551
+ function addNote(ctx, workspace, input) {
1552
+ if (workspace === null || ctx.workspace === null) throw new CarnetError("NO_WORKSPACE", "Notes belong to a workspace: this session has none");
1557
1553
  if (!isNoteKind(input.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${input.kind}" (use ${NOTE_KINDS.join(", ")})`);
1558
1554
  const kind = input.kind;
1559
1555
  const text = cleanText(input.text, "Note text");
1560
- const repos = cleanRepos(group, input.repos);
1556
+ const repos = cleanRepos(workspace, input.repos);
1561
1557
  const similar = activeNotesOfKind(ctx, kind).map((note) => ({
1562
1558
  note,
1563
1559
  score: similarity(text, note.text)
1564
1560
  })).filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY).sort((first, second) => second.score - first.score).slice(0, SIMILAR_SHOWN).map((candidate) => candidate.note);
1565
1561
  ctx.db.exec("BEGIN");
1566
1562
  try {
1567
- const next = ctx.db.prepare("SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE group_name = ?").get(ctx.group);
1568
- const result = ctx.db.prepare(`INSERT INTO notes (group_name, number, kind, text, session, agent, similar_notes, created_at)
1569
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(ctx.group, next.number, kind, text, input.session ?? null, input.agent ?? null, similar.length ? JSON.stringify(similar.map((note) => note.id)) : null, nowIso(ctx));
1563
+ const next = ctx.db.prepare("SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE workspace = ?").get(ctx.workspace);
1564
+ const result = ctx.db.prepare(`INSERT INTO notes (workspace, number, kind, text, session, agent, similar_notes, created_at)
1565
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(ctx.workspace, next.number, kind, text, input.session ?? null, input.agent ?? null, similar.length ? JSON.stringify(similar.map((note) => note.id)) : null, nowIso(ctx));
1570
1566
  const id = Number(result.lastInsertRowid);
1571
1567
  const addRepo = ctx.db.prepare("INSERT INTO note_repos (note, repo) VALUES (?, ?)");
1572
1568
  for (const repo of repos) addRepo.run(id, repo);
@@ -1582,8 +1578,8 @@ function addNote(ctx, group, input) {
1582
1578
  }
1583
1579
  function listNotes(ctx, options = {}) {
1584
1580
  if (options.kind !== void 0 && !isNoteKind(options.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${options.kind}"`);
1585
- const conditions = ["group_name IS ?"];
1586
- const parameters = [ctx.group];
1581
+ const conditions = ["workspace IS ?"];
1582
+ const parameters = [ctx.workspace];
1587
1583
  if (!options.includeDropped) conditions.push("dropped_at IS NULL");
1588
1584
  if (options.kind) {
1589
1585
  conditions.push("kind = ?");
@@ -1642,16 +1638,16 @@ const ACTIVITY_ORDER = {
1642
1638
  };
1643
1639
  function activeIds(ctx, json) {
1644
1640
  if (!json) return [];
1645
- const active = ctx.db.prepare("SELECT 1 FROM notes WHERE group_name IS ? AND number = ? AND dropped_at IS NULL");
1646
- return JSON.parse(json).filter((number) => active.get(ctx.group, number) !== void 0);
1641
+ const active = ctx.db.prepare("SELECT 1 FROM notes WHERE workspace IS ? AND number = ? AND dropped_at IS NULL");
1642
+ return JSON.parse(json).filter((number) => active.get(ctx.workspace, number) !== void 0);
1647
1643
  }
1648
1644
  function sessionNoteActivity(ctx, session) {
1649
1645
  const added = ctx.db.prepare(`SELECT number, kind, text, similar_notes, created_at FROM notes
1650
- WHERE group_name IS ? AND session = ?`).all(ctx.group, session);
1646
+ WHERE workspace IS ? AND session = ?`).all(ctx.workspace, session);
1651
1647
  const cited = ctx.db.prepare(`SELECT notes.number AS note, notes.kind, note_citations.why, note_citations.at
1652
1648
  FROM note_citations JOIN notes ON notes.id = note_citations.note
1653
- WHERE notes.group_name IS ? AND note_citations.session = ?`).all(ctx.group, session);
1654
- const dropped = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND dropped_session = ?`).all(ctx.group, session);
1649
+ WHERE notes.workspace IS ? AND note_citations.session = ?`).all(ctx.workspace, session);
1650
+ const dropped = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND dropped_session = ?`).all(ctx.workspace, session);
1655
1651
  return [
1656
1652
  ...added.map((row) => ({
1657
1653
  activity: "added",
@@ -1745,26 +1741,26 @@ function notesFor(ctx, repos, general, halfLifeDays) {
1745
1741
  }));
1746
1742
  return [...byId.values()].sort(compareNotes);
1747
1743
  }
1748
- function groupTitle(group) {
1749
- return group ? `Rucher memory of the ${group.name} group` : "Rucher memory";
1744
+ function workspaceTitle(workspace) {
1745
+ return workspace ? `Rucher memory of the ${workspace.name} workspace` : "Rucher memory";
1750
1746
  }
1751
- function sessionStartMemory(ctx, group, session, options = {}) {
1747
+ function sessionStartMemory(ctx, workspace, session, options = {}) {
1752
1748
  const halfLifeDays = options.halfLifeDays ?? 20;
1753
1749
  const repos = session.repo ? [session.repo] : [];
1754
1750
  const notes = notesFor(ctx, repos, true, halfLifeDays);
1755
1751
  if (!notes.length) return void 0;
1756
1752
  for (const repo of repos) if (notes.some((note) => note.repos.includes(repo))) recordRepo(ctx, session.id, repo);
1757
1753
  return renderMemory({
1758
- title: groupTitle(group),
1754
+ title: workspaceTitle(workspace),
1759
1755
  notes
1760
1756
  }, options.maxCharacters);
1761
1757
  }
1762
- function sessionMemory(ctx, group, session, options = {}) {
1758
+ function sessionMemory(ctx, workspace, session, options = {}) {
1763
1759
  const halfLifeDays = options.halfLifeDays ?? 20;
1764
1760
  const notes = notesFor(ctx, injectedRepos(ctx, session.id), true, halfLifeDays);
1765
1761
  if (!notes.length) return void 0;
1766
1762
  return renderMemory({
1767
- title: groupTitle(group),
1763
+ title: workspaceTitle(workspace),
1768
1764
  notes
1769
1765
  }, options.maxCharacters);
1770
1766
  }
@@ -1833,7 +1829,7 @@ function purgeDays(value) {
1833
1829
  return Number.isFinite(days) && days > 0 ? days : 3;
1834
1830
  }
1835
1831
  const PURGEABLE = `
1836
- group_name IS ? AND id != ? AND last_active_at < ?
1832
+ workspace IS ? AND id != ? AND last_active_at < ?
1837
1833
  AND NOT EXISTS (
1838
1834
  SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
1839
1835
  )
@@ -1845,7 +1841,7 @@ function purgeSessions(ctx, keepId, days) {
1845
1841
  const cutoff = (/* @__PURE__ */ new Date(ctx.now().getTime() - days * DAY_MILLISECONDS)).toISOString();
1846
1842
  ctx.db.exec("BEGIN");
1847
1843
  try {
1848
- const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(ctx.group, keepId, cutoff).map((row) => row.id);
1844
+ const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(ctx.workspace, keepId, cutoff).map((row) => row.id);
1849
1845
  for (const table of [
1850
1846
  "table_items",
1851
1847
  "agents",
@@ -2049,27 +2045,27 @@ function stopSubagent(ctx, session, hostAgentId, names = []) {
2049
2045
  }
2050
2046
  // src/carnet.ts
2051
2047
  var Carnet = class {
2052
- group;
2048
+ workspace;
2053
2049
  db;
2054
2050
  ctx;
2055
- constructor(db, group, options = {}) {
2056
- this.group = group;
2051
+ constructor(db, workspace, options = {}) {
2052
+ this.workspace = workspace;
2057
2053
  this.db = db;
2058
2054
  this.ctx = {
2059
2055
  db,
2060
2056
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
2061
- group: group?.name ?? null
2057
+ workspace: workspace?.name ?? null
2062
2058
  };
2063
2059
  }
2064
- requireGroup() {
2065
- return requireGroup(this.group);
2060
+ requireWorkspace() {
2061
+ return requireWorkspace(this.workspace);
2066
2062
  }
2067
2063
  sessions = {
2068
2064
  get: (id) => getSession(this.ctx, id),
2069
2065
  find: (reference) => findSession(this.ctx, reference),
2070
2066
  require: (id) => requireSession(this.ctx, id),
2071
- ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group ?? void 0),
2072
- upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.group, payload, env),
2067
+ ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.workspace ?? void 0),
2068
+ upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.workspace, payload, env),
2073
2069
  touch: (id) => touchSession(this.ctx, id),
2074
2070
  merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
2075
2071
  purge: (keepId, days) => purgeSessions(this.ctx, keepId, days),
@@ -2117,7 +2113,7 @@ var Carnet = class {
2117
2113
  })
2118
2114
  };
2119
2115
  notes = {
2120
- add: (input) => addNote(this.ctx, this.group, input),
2116
+ add: (input) => addNote(this.ctx, this.workspace, input),
2121
2117
  get: (id) => getNote(this.ctx, id),
2122
2118
  show: (id, halfLifeDays) => noteDetail(this.ctx, id, halfLifeDays),
2123
2119
  list: (options) => listNotes(this.ctx, options),
@@ -2128,8 +2124,8 @@ var Carnet = class {
2128
2124
  activity: (session) => sessionNoteActivity(this.ctx, session)
2129
2125
  };
2130
2126
  memory = {
2131
- atStart: (session, options) => sessionStartMemory(this.ctx, this.group, session, options),
2132
- ofSession: (session, options) => sessionMemory(this.ctx, this.group, session, options),
2127
+ atStart: (session, options) => sessionStartMemory(this.ctx, this.workspace, session, options),
2128
+ ofSession: (session, options) => sessionMemory(this.ctx, this.workspace, session, options),
2133
2129
  forRepo: (session, repo, options) => repoMemory(this.ctx, session, repo, options),
2134
2130
  copyRepos: (from, into) => copyInjectedRepos(this.ctx, from, into)
2135
2131
  };
@@ -2153,12 +2149,12 @@ function openCarnet(options = {}) {
2153
2149
  function openResolvedCarnet(options = {}) {
2154
2150
  const db = openStore(options);
2155
2151
  try {
2156
- const resolution = resolveGroup({
2152
+ const resolution = resolveWorkspace({
2157
2153
  ...options,
2158
2154
  db
2159
2155
  });
2160
2156
  return {
2161
- carnet: new Carnet(db, resolution.group, options),
2157
+ carnet: new Carnet(db, resolution.workspace, options),
2162
2158
  resolution
2163
2159
  };
2164
2160
  } catch (error) {
@@ -2166,8 +2162,8 @@ function openResolvedCarnet(options = {}) {
2166
2162
  throw error;
2167
2163
  }
2168
2164
  }
2169
- function openGroupCarnet(group, options = {}) {
2170
- return new Carnet(openStore(options), group, options);
2165
+ function openWorkspaceCarnet(workspace, options = {}) {
2166
+ return new Carnet(openStore(options), workspace, options);
2171
2167
  }
2172
2168
  // src/resume.ts
2173
2169
  const RESUME_EVENTS = 20;
@@ -2259,6 +2255,6 @@ function stepAgent(carnet, session, input) {
2259
2255
  }
2260
2256
  }
2261
2257
  }
2262
- export { renameGroupRows as $, openDatabase as $t, memoryMaxCharacters as A, INSTRUCTIONS_FILE as At, memoryHalfLife as B, removeGroupRepo as Bt, renderNotesSummary as C, rulesText as Ct, DEFAULT_PURGE_DAYS as D, shortId as Dt, renderTableLine as E, MINIMUM_ID_PREFIX as Et, NOTE_TEXT_LIMIT as F, groupExists as Ft, isInside as G, defaultWorkspace as Gt, similarity as H, sourceInstructions as Ht, STALE_AFTER_ACTIVE_DAYS as I, groupHosts as It, requireGroup as J, promptsDirectory as Jt, repoNameFor as K, groupSource as Kt, groupRepoNames as L, isGroupName as Lt, DEFAULT_HALF_LIFE_DAYS as M, createGroup as Mt, DUPLICATE_SIMILARITY as N, dropGroup as Nt, purgeDays as O, AGENTS_FILE as Ot, NOTE_KINDS as P, expandHome as Pt, groupSessionCounts as Q, MEMORY_DB as Qt, isNoteKind as R, listGroups as Rt, renderNotes as S, outsideRucherContext as St, renderStatus as T, CORE_RULES as Tt, ambiguousGroupContext as U, corePromptPath as Ut, sessionNoteActivity as V, renameGroup as Vt, groupLabel as W, databasePath as Wt, archiveGroupSessions as X, reportsDirectory as Xt, resolveGroup as Y, reportPath as Yt, deleteGroupNotes as Z, rucherPaths as Zt, NOTES_FOLD_LINES as _, isEventType as _n, appendPromptFile as _t, formatEventLine as a, NOTE_MAX as an, groupSettings as at, renderAgentLine as b, compactReminder as bt, Carnet as c, EMOJI as cn, MARKDOWN_MARKER as ct, openResolvedCarnet as d, OPEN_AGENT_STATUSES as dn, removeStaleCopies as dt, migrate as en, sessionGroupName as et, PAIRING_WINDOW_MILLISECONDS as f, USER_ACTION_STATUSES as fn, writeGenerated as ft, MAIN_WORKING_SUFFIX as g, SESSION_EVENT_TYPES as gn, SUBAGENT_RULES as gt, formatClock as h, EVENT_TYPES as hn, RULES_UPDATED_NOTICE as ht, RESUME_MAX_CHARACTERS as i, REPORTING_NOTE as in, claudeCode as it, renderMemory as j, addGroupRepo as jt, MEMORY_MAX_CHARACTERS as k, GROUP_FILE as kt, openCarnet as l, LEGEND as ln, markdownCopy as lt, buildStatusView as m, isUserActionStatus as mn, PROMPT_FILE as mt, stepAgent as n, schemaVersion as nn, allHosts as nt, resumeContext as o, sanitizeNote as on, transcriptTitle as ot, STOPPED_NOTE as p, isAgentStatus as pn, OUTSIDE_RUCHER_NOTICE as pt, repoPathFor as q, groupsDirectory as qt, RESUME_EVENTS as r, PUBLISH_FALLBACK_MILLISECONDS as rn, hostById as rt, sessionLabel as s, AGENT_STATUSES as sn, GENERATED_MARKER as st, AGENT_STEPS as t, migrations as tn, DEFAULT_HOST as tt, openGroupCarnet as u, MAIN_WORKING_EMOJI as un, mergeSettings as ut, NOTES_HEADER as v, CarnetError as vn, assemblePrompt as vt, renderSections as w, rulesVersion as wt, renderNoteLine as x, groupRules as xt, SIMILAR_PREFIX as y, baseRules as yt, localDay as z, loadGroup as zt };
2258
+ export { workspaceSessionCounts as $, migrations as $t, memoryMaxCharacters as A, addWorkspaceRepo as At, sessionNoteActivity as B, workspaceHosts as Bt, renderNotesSummary as C, workspaceRules as Ct, DEFAULT_PURGE_DAYS as D, AGENTS_FILE as Dt, renderTableLine as E, shortId as Et, NOTE_TEXT_LIMIT as F, isWorkspaceName as Ft, repoNameFor as G, reportPath as Gt, workspaceRepoNames as H, databasePath as Ht, STALE_AFTER_ACTIVE_DAYS as I, listWorkspaces as It, resolveWorkspace as J, workspaceDefinition as Jt, repoPathFor as K, reportsDirectory as Kt, isNoteKind as L, loadWorkspace as Lt, DEFAULT_HALF_LIFE_DAYS as M, definitionInstructions as Mt, DUPLICATE_SIMILARITY as N, dropWorkspace as Nt, purgeDays as O, INSTRUCTIONS_FILE as Ot, NOTE_KINDS as P, expandHome as Pt, sessionWorkspaceName as Q, migrate as Qt, localDay as R, removeWorkspaceRepo as Rt, renderNotes as S, rulesVersion as St, renderStatus as T, MINIMUM_ID_PREFIX as Tt, ambiguousWorkspaceContext as U, defaultRunDirectory as Ut, similarity as V, corePromptPath as Vt, isInside as W, promptsDirectory as Wt, archiveWorkspaceSessions as X, MEMORY_DB as Xt, workspaceLabel as Y, workspacesDirectory as Yt, deleteWorkspaceNotes as Z, openDatabase as Zt, NOTES_FOLD_LINES as _, assemblePrompt as _t, formatEventLine as a, AGENT_STATUSES as an, workspaceSettings as at, renderAgentLine as b, outsideRucherContext as bt, Carnet as c, MAIN_WORKING_EMOJI as cn, markdownCopy as ct, openWorkspaceCarnet as d, isAgentStatus as dn, writeGenerated as dt, schemaVersion as en, DEFAULT_HOST as et, PAIRING_WINDOW_MILLISECONDS as f, isUserActionStatus as fn, OUTSIDE_RUCHER_NOTICE as ft, MAIN_WORKING_SUFFIX as g, CarnetError as gn, appendPromptFile as gt, formatClock as h, isEventType as hn, SUBAGENT_RULES as ht, RESUME_MAX_CHARACTERS as i, sanitizeNote as in, transcriptTitle as it, renderMemory as j, createWorkspace as jt, MEMORY_MAX_CHARACTERS as k, WORKSPACE_FILE as kt, openCarnet as l, OPEN_AGENT_STATUSES as ln, mergeSettings as lt, buildStatusView as m, SESSION_EVENT_TYPES as mn, RULES_UPDATED_NOTICE as mt, stepAgent as n, REPORTING_NOTE as nn, hostById as nt, resumeContext as o, EMOJI as on, GENERATED_MARKER as ot, STOPPED_NOTE as p, EVENT_TYPES as pn, PROMPT_FILE as pt, requireWorkspace as q, rucherPaths as qt, RESUME_EVENTS as r, NOTE_MAX as rn, claudeCode as rt, sessionLabel as s, LEGEND as sn, MARKDOWN_MARKER as st, AGENT_STEPS as t, PUBLISH_FALLBACK_MILLISECONDS as tn, allHosts as tt, openResolvedCarnet as u, USER_ACTION_STATUSES as un, removeStaleCopies as ut, NOTES_HEADER as v, baseRules as vt, renderSections as w, CORE_RULES as wt, renderNoteLine as x, rulesText as xt, SIMILAR_PREFIX as y, compactReminder as yt, memoryHalfLife as z, workspaceExists as zt };
2263
2259
 
2264
- //# sourceMappingURL=steps-BeTGxQk4.mjs.map
2260
+ //# sourceMappingURL=steps-4ZTrBzcd.mjs.map