@rucher/carnet 0.2.0-beta.3 → 0.2.0-beta.5

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, 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,19 +531,151 @@ 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");
536
+ }
537
+ function reportPath(workspace, agentName) {
538
+ return join(reportsDirectory(workspace), `${agentName}.md`);
539
+ }
540
+ // src/workspace/workspace.ts
541
+ const WORKSPACE_FILE = "workspace.json";
542
+ const INSTRUCTIONS_FILE = "CLAUDE.md";
543
+ const AGENTS_FILE = "AGENTS.md";
544
+ const WORKSPACE_NAME = /^[a-z0-9-]+$/;
545
+ function isWorkspaceName(name) {
546
+ return WORKSPACE_NAME.test(name);
547
+ }
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`);
550
+ }
551
+ function expandHome(path, env = process.env) {
552
+ if (path !== "~" && !path.startsWith("~/")) return path;
553
+ return join(env.HOME || homedir(), path.slice(1));
554
+ }
555
+ function workspaceFilePath(name, env) {
556
+ return join(workspaceDefinition(name, env), WORKSPACE_FILE);
557
+ }
558
+ function workspaceExists(name, env) {
559
+ return isWorkspaceName(name) && existsSync(workspaceFilePath(name, env));
560
+ }
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"));
524
564
  }
525
- function reportPath(group, agentName) {
526
- return join(reportsDirectory(group), `${agentName}.md`);
565
+ function writeWorkspaceFile(name, file, env) {
566
+ writeFileSync(workspaceFilePath(name, env), `${JSON.stringify(file, null, 2)}\n`);
567
+ }
568
+ function loadWorkspace(name, env = process.env) {
569
+ const file = readWorkspaceFile(name, env);
570
+ return {
571
+ name,
572
+ definition: workspaceDefinition(name, env),
573
+ runDirectory: defaultRunDirectory(name, env),
574
+ repos: (file.repos ?? []).map((repo) => {
575
+ const path = resolve(expandHome(repo.path, env));
576
+ return {
577
+ path,
578
+ name: repo.name ?? basename(path)
579
+ };
580
+ }),
581
+ backends: file.backends ?? {}
582
+ };
583
+ }
584
+ function listWorkspaces(env = process.env) {
585
+ const directory = workspacesDirectory(env);
586
+ if (!existsSync(directory)) return [];
587
+ return readdirSync(directory).filter((name) => workspaceExists(name, env)).sort().map((name) => loadWorkspace(name, env));
588
+ }
589
+ function workspaceHosts(workspace) {
590
+ const hosts = Object.keys(workspace.backends);
591
+ return hosts.length ? hosts : [DEFAULT_HOST];
592
+ }
593
+ function checkedRepo(path, env) {
594
+ const absolute = resolve(expandHome(path, env));
595
+ if (!existsSync(absolute)) throw new CarnetError("REPO_NOT_FOUND", `Repo path does not exist: ${absolute}`);
596
+ return absolute;
597
+ }
598
+ function requireDistinctNames(workspace, repos) {
599
+ const names = repos.map((repo) => repo.name);
600
+ const shared = names.find((name, index) => names.indexOf(name) !== index);
601
+ if (shared) throw new CarnetError("REPO_NAME_TAKEN", `${workspace} would have two repos named ${shared}: give them distinct names`);
602
+ }
603
+ function createWorkspace(name, options = {}) {
604
+ const { env } = options;
605
+ requireWorkspaceName(name);
606
+ if (workspaceExists(name, env)) throw new CarnetError("WORKSPACE_EXISTS", `Workspace ${name} already exists`);
607
+ const repos = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))].map((path) => ({
608
+ path,
609
+ name: basename(path)
610
+ }));
611
+ requireDistinctNames(name, repos);
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, {
617
+ name,
618
+ repos,
619
+ backends: {}
620
+ }, env);
621
+ const instructions = join(definition, INSTRUCTIONS_FILE);
622
+ if (!existsSync(instructions)) writeFileSync(instructions, "");
623
+ return loadWorkspace(name, env);
624
+ }
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}`);
628
+ return agents ? AGENTS_FILE : INSTRUCTIONS_FILE;
629
+ }
630
+ function addWorkspaceRepo(name, repo, env) {
631
+ const file = readWorkspaceFile(name, env);
632
+ const workspace = loadWorkspace(name, env);
633
+ const path = checkedRepo(repo, env);
634
+ if (workspace.repos.some((existing) => existing.path === path)) return workspace;
635
+ requireDistinctNames(name, [...workspace.repos, {
636
+ path,
637
+ name: basename(path)
638
+ }]);
639
+ writeWorkspaceFile(name, {
640
+ ...file,
641
+ repos: [...file.repos ?? [], {
642
+ path,
643
+ name: basename(path)
644
+ }]
645
+ }, env);
646
+ return loadWorkspace(name, env);
647
+ }
648
+ function removeWorkspaceRepo(name, repo, env) {
649
+ const file = readWorkspaceFile(name, env);
650
+ const workspace = loadWorkspace(name, env);
651
+ const path = resolve(expandHome(repo, env));
652
+ const index = workspace.repos.findIndex((existing) => existing.path === path || existing.name === repo);
653
+ if (index === -1) throw new CarnetError("REPO_NOT_FOUND", `${repo} is not a repo of ${name}`);
654
+ writeWorkspaceFile(name, {
655
+ ...file,
656
+ repos: (file.repos ?? []).filter((_, position) => position !== index)
657
+ }, env);
658
+ return loadWorkspace(name, env);
659
+ }
660
+ function dropWorkspace(name, options = {}) {
661
+ const workspace = loadWorkspace(name, options.env);
662
+ rmSync(workspace.definition, {
663
+ recursive: true,
664
+ force: true
665
+ });
666
+ if (options.purge) rmSync(workspace.runDirectory, {
667
+ recursive: true,
668
+ force: true
669
+ });
670
+ return workspace;
527
671
  }
528
672
  // src/sessions.ts
529
- 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,
530
674
  parent_id, prompt_version, created_at, last_active_at, ended_at`;
531
675
  function toSession(row) {
532
676
  return {
533
677
  id: row.id,
534
- groupName: row.group_name,
678
+ workspace: row.workspace,
535
679
  name: row.name,
536
680
  purpose: row.purpose,
537
681
  kind: row.kind,
@@ -558,11 +702,11 @@ function requireSession(ctx, id) {
558
702
  if (!session) throw new CarnetError("SESSION_NOT_FOUND", `Unknown session ${id}`);
559
703
  return session;
560
704
  }
561
- function ensureSession(ctx, id, cwd, group) {
705
+ function ensureSession(ctx, id, cwd, workspace) {
562
706
  const existing = getSession(ctx, id);
563
707
  if (existing) return existing;
564
708
  const at = nowIso(ctx);
565
- 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);
566
710
  return requireSession(ctx, id);
567
711
  }
568
712
  function nameTaken(error, name) {
@@ -573,9 +717,9 @@ function createSession(ctx, input) {
573
717
  if (input.kind === "active" && !input.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
574
718
  const at = nowIso(ctx);
575
719
  try {
576
- 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,
577
721
  created_at, last_active_at)
578
- 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);
579
723
  } catch (error) {
580
724
  nameTaken(error, input.name);
581
725
  }
@@ -614,15 +758,15 @@ function adoptTitle(ctx, id, rawTitle) {
614
758
  WHERE id = ?`).run(title, id);
615
759
  return requireSession(ctx, id);
616
760
  }
617
- function upsertFromHook(ctx, group, payload, env = {}) {
761
+ function upsertFromHook(ctx, workspace, payload, env = {}) {
618
762
  const at = nowIso(ctx);
619
763
  const host = env.host ?? "claude-code";
620
764
  const hostPid = env.processId ?? null;
621
- const repo = group ? repoNameFor(group, payload.cwd) : null;
765
+ const repo = workspace ? repoNameFor(workspace, payload.cwd) : null;
622
766
  const existing = getSession(ctx, payload.session_id);
623
- 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,
624
768
  last_active_at)
625
- 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);
626
770
  else ctx.db.prepare(`UPDATE sessions
627
771
  SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
628
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);
@@ -645,10 +789,10 @@ function nameSession(ctx, id, name, purpose) {
645
789
  return requireSession(ctx, id);
646
790
  }
647
791
  function listSessions(ctx, options = {}) {
648
- const conditions = ["group_name IS ?"];
792
+ const conditions = ["workspace IS ?"];
649
793
  if (!options.includeTemp) conditions.push("kind != 'temp'");
650
794
  if (!options.includeArchived) conditions.push("status != 'archived'");
651
- 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);
652
796
  }
653
797
  function dropSession(ctx, id) {
654
798
  requireSession(ctx, id);
@@ -658,12 +802,12 @@ function dropSession(ctx, id) {
658
802
  return requireSession(ctx, id);
659
803
  }
660
804
  function defaultSession(ctx) {
661
- const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND status != 'archived'
662
- 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);
663
807
  return row && toSession(row);
664
808
  }
665
809
  function sessionByName(ctx, name) {
666
- 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);
667
811
  return row && toSession(row);
668
812
  }
669
813
  const MINIMUM_ID_PREFIX = 4;
@@ -677,8 +821,8 @@ function findSession(ctx, reference) {
677
821
  if (byId) return byId;
678
822
  const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
679
823
  if (isIdPrefix && reference.length >= 4) {
680
- const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND id LIKE ?
681
- 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()}%`);
682
826
  const [only, ...others] = rows;
683
827
  if (only && others.length === 0) return toSession(only);
684
828
  if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
@@ -745,8 +889,8 @@ function demoteSession(ctx, id) {
745
889
  function staleTempSessions(ctx, olderThanMilliseconds) {
746
890
  const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
747
891
  return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
748
- WHERE group_name IS ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
749
- 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);
750
894
  }
751
895
  function resetDeadSessions(ctx, isAlive) {
752
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));
@@ -767,27 +911,27 @@ function readIfPresent(path) {
767
911
  function baseRules(env = process.env) {
768
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.";
769
913
  }
770
- function groupRules(group) {
771
- 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;
772
916
  }
773
- function rulesText(group, env = process.env) {
774
- const extra = groupRules(group);
917
+ function rulesText(workspace, env = process.env) {
918
+ const extra = workspaceRules(workspace);
775
919
  const base = `Rucher rules, always follow them:\n${baseRules(env)}`;
776
- 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;
777
921
  }
778
- function rulesVersion(group, env = process.env) {
779
- 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);
780
924
  }
781
- function assemblePrompt(group, session, env = process.env) {
925
+ function assemblePrompt(workspace, session, env = process.env) {
782
926
  const label = session.name ?? shortId(session.id);
783
- 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.`;
784
928
  return {
785
- text: `${rulesText(group, env)}\n\n${identity}\n`,
786
- version: rulesVersion(group, env)
929
+ text: `${rulesText(workspace, env)}\n\n${identity}\n`,
930
+ version: rulesVersion(workspace, env)
787
931
  };
788
932
  }
789
- function appendPromptFile(group, session, env = process.env) {
790
- const { text, version } = assemblePrompt(group, session, env);
933
+ function appendPromptFile(workspace, session, env = process.env) {
934
+ const { text, version } = assemblePrompt(workspace, session, env);
791
935
  const directory = promptsDirectory(env);
792
936
  mkdirSync(directory, { recursive: true });
793
937
  const path = join(directory, `${session.id}.md`);
@@ -797,19 +941,19 @@ function appendPromptFile(group, session, env = process.env) {
797
941
  version
798
942
  };
799
943
  }
800
- function compactReminder(group, env = process.env) {
801
- 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)}`;
802
946
  }
803
- function outsideRucherContext(group, env = process.env) {
804
- 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)}`;
805
949
  }
806
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)";
807
951
  const RULES_UPDATED_NOTICE = "rucher: rules updated, will apply after the next compaction or in a new session";
808
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.";
809
- // src/workspace-files.ts
953
+ // src/run-directory-files.ts
810
954
  const GENERATED_MARKER = "generated by rucher, do not edit";
811
955
  function refuse(path) {
812
- 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`);
813
957
  }
814
958
  function entry(path) {
815
959
  try {
@@ -828,6 +972,7 @@ function isMarkdownCopy(path) {
828
972
  }
829
973
  function removeStaleCopies(directory, keep) {
830
974
  const removed = [];
975
+ if (!entry(directory)) return removed;
831
976
  for (const name of readdirSync(directory)) {
832
977
  if (!name.endsWith(".md") || keep.has(name)) continue;
833
978
  const path = join(directory, name);
@@ -921,32 +1066,55 @@ function transcriptTitle(path) {
921
1066
  }
922
1067
  }
923
1068
  const SETTINGS_FILE = join(".claude", "settings.json");
924
- function instructionFiles(group) {
925
- if (!existsSync(group.source)) return [];
926
- return readdirSync(group.source, { withFileTypes: true }).filter((item) => item.isFile() && item.name.endsWith(".md") && item.name !== "prompt.md").map((item) => item.name).sort();
1069
+ const BACKEND_NOTES = "backends/claude.md";
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();
1073
+ }
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)}`);
1076
+ }
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))]));
1081
+ if (!agents) return copies;
1082
+ const imports = [`@${AGENTS_FILE}`];
1083
+ if (existsSync(join(workspace.definition, BACKEND_NOTES))) {
1084
+ copies.set(BACKEND_NOTES, markdownCopy(read(BACKEND_NOTES)));
1085
+ imports.push(`@${BACKEND_NOTES}`);
1086
+ }
1087
+ imports.push(...repoAgentsImports(workspace));
1088
+ copies.set(INSTRUCTIONS_FILE, markdownCopy(`${imports.join("\n")}\n`));
1089
+ return copies;
927
1090
  }
928
- function groupSettings(group) {
1091
+ function workspaceSettings(workspace) {
929
1092
  return mergeSettings({
930
1093
  "//": GENERATED_MARKER,
931
1094
  permissions: {
932
- additionalDirectories: group.repos.map((repo) => repo.path),
933
- deny: instructionFiles(group).map((name) => `Edit(/${name})`)
1095
+ additionalDirectories: workspace.repos.map((repo) => repo.path),
1096
+ deny: [...runDirectoryCopies(workspace).keys()].sort().map((name) => `Edit(/${name})`)
934
1097
  }
935
- }, group.backends["claude-code"]?.settings ?? {});
1098
+ }, workspace.backends["claude-code"]?.settings ?? {});
936
1099
  }
937
- function renderClaudeWorkspace(group) {
1100
+ function removeStaleBackendNotes(workspace, keep) {
1101
+ const directory = join(workspace.runDirectory, dirname(BACKEND_NOTES));
1102
+ const removed = removeStaleCopies(directory, new Set([...keep].filter((name) => dirname(name) === dirname(BACKEND_NOTES)).map((name) => basename(name))));
1103
+ if (existsSync(directory) && readdirSync(directory).length === 0) rmdirSync(directory);
1104
+ return removed.map((name) => join(dirname(BACKEND_NOTES), name));
1105
+ }
1106
+ function renderClaudeRunDirectory(workspace) {
938
1107
  const rendered = {
939
1108
  written: [],
940
1109
  removed: []
941
1110
  };
942
- const names = instructionFiles(group);
943
- for (const name of names) {
944
- const content = markdownCopy(readFileSync(join(group.source, name), "utf8"));
945
- if (writeGenerated(join(group.workspace, name), content)) rendered.written.push(name);
946
- }
947
- rendered.removed.push(...removeStaleCopies(group.workspace, new Set(names)));
948
- const settings = `${JSON.stringify(groupSettings(group), null, 2)}\n`;
949
- if (writeGenerated(join(group.workspace, SETTINGS_FILE), settings)) rendered.written.push(SETTINGS_FILE);
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);
1113
+ const names = new Set(copies.keys());
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);
950
1118
  return rendered;
951
1119
  }
952
1120
  function launchArguments(options = {}) {
@@ -1088,7 +1256,7 @@ const claudeCode = {
1088
1256
  renameInstruction(name) {
1089
1257
  return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
1090
1258
  },
1091
- renderWorkspace: renderClaudeWorkspace
1259
+ renderRunDirectory: renderClaudeRunDirectory
1092
1260
  };
1093
1261
  // src/hosts/host.ts
1094
1262
  const DEFAULT_HOST = "claude-code";
@@ -1101,7 +1269,7 @@ function hostById(id) {
1101
1269
  if (!host) throw new CarnetError("UNKNOWN_HOST", `Unknown host "${id}" (available: ${Object.keys(HOSTS).join(", ")})`);
1102
1270
  return host;
1103
1271
  }
1104
- // src/group-rows.ts
1272
+ // src/workspace-rows.ts
1105
1273
  function inTransaction(db, run) {
1106
1274
  db.exec("BEGIN");
1107
1275
  try {
@@ -1113,269 +1281,120 @@ function inTransaction(db, run) {
1113
1281
  throw error;
1114
1282
  }
1115
1283
  }
1116
- function sessionGroupName(db, sessionId) {
1117
- const row = db.prepare("SELECT group_name FROM sessions WHERE id = ?").get(sessionId);
1118
- return row ? row.group_name : void 0;
1284
+ function sessionWorkspaceName(db, sessionId) {
1285
+ const row = db.prepare("SELECT workspace FROM sessions WHERE id = ?").get(sessionId);
1286
+ return row ? row.workspace : void 0;
1119
1287
  }
1120
- function renameGroupRows(db, from, to) {
1121
- inTransaction(db, () => {
1122
- for (const table of [
1123
- "sessions",
1124
- "notes",
1125
- "active_days"
1126
- ]) db.prepare(`UPDATE ${table} SET group_name = ? WHERE group_name = ?`).run(to, from);
1127
- });
1128
- }
1129
- function archiveGroupSessions(db, name, at) {
1288
+ function archiveWorkspaceSessions(db, name, at) {
1130
1289
  return inTransaction(db, () => {
1131
1290
  db.prepare(`UPDATE agents SET status = 'closed', updated_at = ?
1132
- WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE group_name = ?)`).run(at, name);
1291
+ WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE workspace = ?)`).run(at, name);
1133
1292
  return Number(db.prepare(`UPDATE sessions SET status = 'archived', last_active_at = ?
1134
- WHERE group_name = ? AND status != 'archived'`).run(at, name).changes);
1293
+ WHERE workspace = ? AND status != 'archived'`).run(at, name).changes);
1135
1294
  });
1136
1295
  }
1137
- function deleteGroupNotes(db, name) {
1138
- return Number(db.prepare("DELETE FROM notes WHERE group_name = ?").run(name).changes);
1139
- }
1140
- function groupSessionCounts(db) {
1141
- const rows = db.prepare(`SELECT group_name, COUNT(*) AS count FROM sessions
1142
- WHERE group_name IS NOT NULL AND status != 'archived' GROUP BY group_name`).all();
1143
- return new Map(rows.map((row) => [row.group_name, Number(row.count)]));
1144
- }
1145
- // src/group/group.ts
1146
- const GROUP_FILE = "group.json";
1147
- const INSTRUCTIONS_FILE = "CLAUDE.md";
1148
- const GROUP_NAME = /^[a-z0-9-]+$/;
1149
- function isGroupName(name) {
1150
- return GROUP_NAME.test(name);
1151
- }
1152
- function requireGroupName(name) {
1153
- if (!isGroupName(name)) throw new CarnetError("GROUP_NAME_INVALID", `Invalid group name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`);
1154
- }
1155
- function expandHome(path, env = process.env) {
1156
- if (path !== "~" && !path.startsWith("~/")) return path;
1157
- return join(env.HOME || homedir(), path.slice(1));
1158
- }
1159
- function groupFilePath(name, env) {
1160
- return join(groupSource(name, env), GROUP_FILE);
1161
- }
1162
- function groupExists(name, env) {
1163
- return isGroupName(name) && existsSync(groupFilePath(name, env));
1164
- }
1165
- function readGroupFile(name, env) {
1166
- if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
1167
- return JSON.parse(readFileSync(groupFilePath(name, env), "utf8"));
1168
- }
1169
- function writeGroupFile(name, file, env) {
1170
- writeFileSync(groupFilePath(name, env), `${JSON.stringify(file, null, 2)}\n`);
1171
- }
1172
- function loadGroup(name, env = process.env) {
1173
- const file = readGroupFile(name, env);
1174
- return {
1175
- name,
1176
- source: groupSource(name, env),
1177
- workspace: resolve(expandHome(file.workspace ?? defaultWorkspace(name, env), env)),
1178
- repos: (file.repos ?? []).map((repo) => {
1179
- const path = resolve(expandHome(repo.path, env));
1180
- return {
1181
- path,
1182
- name: repo.name ?? basename(path)
1183
- };
1184
- }),
1185
- backends: file.backends ?? {}
1186
- };
1187
- }
1188
- function listGroups(env = process.env) {
1189
- const directory = groupsDirectory(env);
1190
- if (!existsSync(directory)) return [];
1191
- return readdirSync(directory).filter((name) => groupExists(name, env)).sort().map((name) => loadGroup(name, env));
1192
- }
1193
- function groupHosts(group) {
1194
- const hosts = Object.keys(group.backends);
1195
- return hosts.length ? hosts : [DEFAULT_HOST];
1196
- }
1197
- function checkedRepo(path, env) {
1198
- const absolute = resolve(expandHome(path, env));
1199
- if (!existsSync(absolute)) throw new CarnetError("REPO_NOT_FOUND", `Repo path does not exist: ${absolute}`);
1200
- return absolute;
1201
- }
1202
- function requireDistinctNames(group, repos) {
1203
- const names = repos.map((repo) => repo.name);
1204
- const shared = names.find((name, index) => names.indexOf(name) !== index);
1205
- if (shared) throw new CarnetError("REPO_NAME_TAKEN", `${group} would have two repos named ${shared}: give them distinct names`);
1206
- }
1207
- function createGroup(name, options = {}) {
1208
- const { env } = options;
1209
- requireGroupName(name);
1210
- if (groupExists(name, env)) throw new CarnetError("GROUP_EXISTS", `Group ${name} already exists`);
1211
- const repos = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))].map((path) => ({
1212
- path,
1213
- name: basename(path)
1214
- }));
1215
- requireDistinctNames(name, repos);
1216
- const source = groupSource(name, env);
1217
- const workspace = defaultWorkspace(name, env);
1218
- mkdirSync(source, { recursive: true });
1219
- mkdirSync(workspace, { recursive: true });
1220
- writeGroupFile(name, {
1221
- name,
1222
- workspace,
1223
- repos,
1224
- backends: {}
1225
- }, env);
1226
- const instructions = join(source, INSTRUCTIONS_FILE);
1227
- if (!existsSync(instructions)) writeFileSync(instructions, "");
1228
- return loadGroup(name, env);
1229
- }
1230
- function addGroupRepo(name, repo, env) {
1231
- const file = readGroupFile(name, env);
1232
- const group = loadGroup(name, env);
1233
- const path = checkedRepo(repo, env);
1234
- if (group.repos.some((existing) => existing.path === path)) return group;
1235
- requireDistinctNames(name, [...group.repos, {
1236
- path,
1237
- name: basename(path)
1238
- }]);
1239
- writeGroupFile(name, {
1240
- ...file,
1241
- repos: [...file.repos ?? [], {
1242
- path,
1243
- name: basename(path)
1244
- }]
1245
- }, env);
1246
- return loadGroup(name, env);
1247
- }
1248
- function removeGroupRepo(name, repo, env) {
1249
- const file = readGroupFile(name, env);
1250
- const group = loadGroup(name, env);
1251
- const path = resolve(expandHome(repo, env));
1252
- const index = group.repos.findIndex((existing) => existing.path === path || existing.name === repo);
1253
- if (index === -1) throw new CarnetError("REPO_NOT_FOUND", `${repo} is not a repo of ${name}`);
1254
- writeGroupFile(name, {
1255
- ...file,
1256
- repos: (file.repos ?? []).filter((_, position) => position !== index)
1257
- }, env);
1258
- return loadGroup(name, env);
1259
- }
1260
- function renameGroup(from, to, env) {
1261
- const file = readGroupFile(from, env);
1262
- requireGroupName(to);
1263
- if (existsSync(groupSource(to, env))) throw new CarnetError("GROUP_EXISTS", `Group ${to} already exists`);
1264
- const workspace = loadGroup(from, env).workspace;
1265
- renameSync(groupSource(from, env), groupSource(to, env));
1266
- writeGroupFile(to, {
1267
- ...file,
1268
- name: to,
1269
- workspace
1270
- }, env);
1271
- return loadGroup(to, env);
1296
+ function deleteWorkspaceNotes(db, name) {
1297
+ return Number(db.prepare("DELETE FROM notes WHERE workspace = ?").run(name).changes);
1272
1298
  }
1273
- function dropGroup(name, options = {}) {
1274
- const group = loadGroup(name, options.env);
1275
- rmSync(group.source, {
1276
- recursive: true,
1277
- force: true
1278
- });
1279
- if (options.purge) rmSync(group.workspace, {
1280
- recursive: true,
1281
- force: true
1282
- });
1283
- return group;
1299
+ function workspaceSessionCounts(db) {
1300
+ const rows = db.prepare(`SELECT workspace, COUNT(*) AS count FROM sessions
1301
+ WHERE workspace IS NOT NULL AND status != 'archived' GROUP BY workspace`).all();
1302
+ return new Map(rows.map((row) => [row.workspace, Number(row.count)]));
1284
1303
  }
1285
- // src/group/locate.ts
1304
+ // src/workspace/locate.ts
1286
1305
  function isInside(directory, path) {
1287
1306
  const relativePath = relative(directory, path);
1288
1307
  return relativePath === "" || !relativePath.startsWith("..") && !resolve(relativePath).startsWith(relativePath);
1289
1308
  }
1290
- function repoOf(group, path) {
1309
+ function repoOf(workspace, path) {
1291
1310
  const absolutePath = resolve(path);
1292
- return group?.repos.find((repo) => isInside(repo.path, absolutePath));
1311
+ return workspace?.repos.find((repo) => isInside(repo.path, absolutePath));
1293
1312
  }
1294
- function repoNameFor(group, path) {
1295
- return path ? repoOf(group, path)?.name ?? null : null;
1313
+ function repoNameFor(workspace, path) {
1314
+ return path ? repoOf(workspace, path)?.name ?? null : null;
1296
1315
  }
1297
- function repoPathFor(group, path) {
1316
+ function repoPathFor(workspace, path) {
1298
1317
  if (!path) return null;
1299
- const repo = repoOf(group, path);
1318
+ const repo = repoOf(workspace, path);
1300
1319
  if (!repo) return null;
1301
1320
  const relativePath = relative(repo.path, resolve(path));
1302
1321
  return relativePath ? join(repo.name, relativePath) : repo.name;
1303
1322
  }
1304
- function namedGroup(name, env) {
1305
- if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
1306
- return loadGroup(name, env);
1323
+ function namedWorkspace(name, env) {
1324
+ if (!workspaceExists(name, env)) throw new CarnetError("WORKSPACE_NOT_FOUND", `No workspace named ${name}: see "rucher ws list"`);
1325
+ return loadWorkspace(name, env);
1307
1326
  }
1308
- function byWorkspace(groups, directories) {
1309
- return groups.find((group) => directories.some((directory) => isInside(group.workspace, directory)));
1327
+ function byRunDirectory(workspaces, directories) {
1328
+ return workspaces.find((workspace) => directories.some((directory) => isInside(workspace.runDirectory, directory)));
1310
1329
  }
1311
- function byRepo(groups, directory) {
1330
+ function byRepo(workspaces, directory) {
1312
1331
  let best = [];
1313
- for (const group of groups) for (const repo of group.repos) {
1332
+ for (const workspace of workspaces) for (const repo of workspace.repos) {
1314
1333
  if (!isInside(repo.path, directory)) continue;
1315
1334
  const length = best[0]?.repo.path.length ?? -1;
1316
1335
  if (repo.path.length > length) best = [{
1317
- group,
1336
+ workspace,
1318
1337
  repo
1319
1338
  }];
1320
1339
  else if (repo.path.length === length) best.push({
1321
- group,
1340
+ workspace,
1322
1341
  repo
1323
1342
  });
1324
1343
  }
1325
- const names = [...new Set(best.map((match) => match.group.name))];
1326
- if (names.length > 1) throw new CarnetError("GROUP_AMBIGUOUS", `${directory} is in repos of several groups (${names.join(", ")}): pass --group`);
1344
+ const names = [...new Set(best.map((match) => match.workspace.name))];
1345
+ if (names.length > 1) throw new CarnetError("WORKSPACE_AMBIGUOUS", `${directory} is in repos of several workspaces (${names.join(", ")}): pass --ws`);
1327
1346
  return best[0];
1328
1347
  }
1329
- function resolveGroup({ db, sessionId, group, cwd = process.cwd(), env = process.env } = {}) {
1348
+ function resolveWorkspace({ db, sessionId, workspace, cwd = process.cwd(), env = process.env } = {}) {
1330
1349
  if (db && sessionId) {
1331
- const name = sessionGroupName(db, sessionId);
1350
+ const name = sessionWorkspaceName(db, sessionId);
1332
1351
  if (name === null) return {
1333
- group: null,
1352
+ workspace: null,
1334
1353
  origin: "session"
1335
1354
  };
1336
- if (name !== void 0 && groupExists(name, env)) return {
1337
- group: loadGroup(name, env),
1355
+ if (name !== void 0 && workspaceExists(name, env)) return {
1356
+ workspace: loadWorkspace(name, env),
1338
1357
  origin: "session"
1339
1358
  };
1340
1359
  }
1341
- if (group) return {
1342
- group: namedGroup(group, env),
1360
+ if (workspace) return {
1361
+ workspace: namedWorkspace(workspace, env),
1343
1362
  origin: "option"
1344
1363
  };
1345
- if (env.RUCHER_GROUP) return {
1346
- group: namedGroup(env.RUCHER_GROUP, env),
1364
+ if (env.RUCHER_WS) return {
1365
+ workspace: namedWorkspace(env.RUCHER_WS, env),
1347
1366
  origin: "env"
1348
1367
  };
1349
1368
  const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
1350
1369
  const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
1351
- const groups = listGroups(env);
1352
- const workspaceGroup = byWorkspace(groups, directories);
1353
- if (workspaceGroup) return {
1354
- group: workspaceGroup,
1355
- origin: "workspace"
1370
+ const workspaces = listWorkspaces(env);
1371
+ const runDirectoryWorkspace = byRunDirectory(workspaces, directories);
1372
+ if (runDirectoryWorkspace) return {
1373
+ workspace: runDirectoryWorkspace,
1374
+ origin: "run-directory"
1356
1375
  };
1357
1376
  for (const directory of directories) {
1358
- const match = byRepo(groups, directory);
1377
+ const match = byRepo(workspaces, directory);
1359
1378
  if (match) return {
1360
- group: match.group,
1379
+ workspace: match.workspace,
1361
1380
  origin: "repo",
1362
1381
  repo: match.repo
1363
1382
  };
1364
1383
  }
1365
1384
  return {
1366
- group: null,
1385
+ workspace: null,
1367
1386
  origin: "none"
1368
1387
  };
1369
1388
  }
1370
- function groupLabel(group) {
1371
- return group?.name ?? "no group";
1389
+ function workspaceLabel(workspace) {
1390
+ return workspace?.name ?? "no workspace";
1372
1391
  }
1373
- function requireGroup(group) {
1374
- if (group) return group;
1375
- throw new CarnetError("NO_GROUP", "No Rucher group here: pass --group, or run this from a repo or workspace of a group");
1392
+ function requireWorkspace(workspace) {
1393
+ if (workspace) return workspace;
1394
+ throw new CarnetError("NO_WORKSPACE", "No Rucher workspace here: pass --ws, or run this from a repo or run directory of a workspace");
1376
1395
  }
1377
- function ambiguousGroupContext(reason) {
1378
- return `Rucher could not tell which group this session belongs to, so Carnet records nothing for it: ${reason}.`;
1396
+ function ambiguousWorkspaceContext(reason) {
1397
+ return `Rucher could not tell which workspace this session belongs to, so Carnet records nothing for it: ${reason}.`;
1379
1398
  }
1380
1399
  // src/notes.ts
1381
1400
  const NOTE_KINDS = [
@@ -1410,14 +1429,14 @@ function cleanText(value, label) {
1410
1429
  if (MARKDOWN.test(text)) throw new CarnetError("INVALID_NOTE", `${label} must not use markdown`);
1411
1430
  return text;
1412
1431
  }
1413
- function groupRepoNames(group) {
1414
- return group.repos.map((repo) => repo.name);
1432
+ function workspaceRepoNames(workspace) {
1433
+ return workspace.repos.map((repo) => repo.name);
1415
1434
  }
1416
- function cleanRepos(group, repos) {
1417
- const known = groupRepoNames(group);
1435
+ function cleanRepos(workspace, repos) {
1436
+ const known = workspaceRepoNames(workspace);
1418
1437
  const unique = [...new Set((repos ?? []).map((repo) => repo.trim()).filter(Boolean))];
1419
1438
  const unknown = unique.filter((repo) => !known.includes(repo));
1420
- if (unknown.length) throw new CarnetError("INVALID_NOTE", `Unknown repo ${unknown.join(", ")} (group repos: ${known.join(", ") || "none"})`);
1439
+ if (unknown.length) throw new CarnetError("INVALID_NOTE", `Unknown repo ${unknown.join(", ")} (workspace repos: ${known.join(", ") || "none"})`);
1421
1440
  return unique;
1422
1441
  }
1423
1442
  function words(text) {
@@ -1437,11 +1456,11 @@ function localDay(date) {
1437
1456
  return `${date.getFullYear()}-${month}-${day}`;
1438
1457
  }
1439
1458
  function recordActiveDay(ctx) {
1440
- if (ctx.group === null) return;
1441
- ctx.db.prepare("INSERT OR IGNORE INTO active_days (group_name, day) VALUES (?, ?)").run(ctx.group, localDay(ctx.now()));
1459
+ if (ctx.workspace === null) return;
1460
+ ctx.db.prepare("INSERT OR IGNORE INTO active_days (workspace, day) VALUES (?, ?)").run(ctx.workspace, localDay(ctx.now()));
1442
1461
  }
1443
1462
  function activeDays(ctx) {
1444
- return ctx.db.prepare("SELECT day FROM active_days WHERE group_name IS ? ORDER BY day").all(ctx.group).map((row) => row.day);
1463
+ return ctx.db.prepare("SELECT day FROM active_days WHERE workspace IS ? ORDER BY day").all(ctx.workspace).map((row) => row.day);
1445
1464
  }
1446
1465
  function activeDaysSince(days, at) {
1447
1466
  const since = localDay(new Date(at));
@@ -1467,7 +1486,7 @@ function toNote(ctx, row) {
1467
1486
  };
1468
1487
  }
1469
1488
  function noteRow(ctx, number) {
1470
- return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND number = ?`).get(ctx.group, number);
1489
+ return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND number = ?`).get(ctx.workspace, number);
1471
1490
  }
1472
1491
  function noteId(ctx, number) {
1473
1492
  const row = noteRow(ctx, number);
@@ -1492,7 +1511,7 @@ const CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citation
1492
1511
  note_citations.agent, note_citations.why, note_citations.at`;
1493
1512
  function citationsOf(ctx, number) {
1494
1513
  return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
1495
- WHERE notes.group_name IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.group, number);
1514
+ WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.workspace, number);
1496
1515
  }
1497
1516
  function weightOf(citations, days, halfLifeDays) {
1498
1517
  const latest = /* @__PURE__ */ new Map();
@@ -1520,23 +1539,23 @@ function compareNotes(first, second) {
1520
1539
  return second.id - first.id;
1521
1540
  }
1522
1541
  function activeNotesOfKind(ctx, kind) {
1523
- 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));
1542
+ 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));
1524
1543
  }
1525
- function addNote(ctx, group, input) {
1526
- if (group === null || ctx.group === null) throw new CarnetError("NO_GROUP", "Notes belong to a group: this session has none");
1544
+ function addNote(ctx, workspace, input) {
1545
+ if (workspace === null || ctx.workspace === null) throw new CarnetError("NO_WORKSPACE", "Notes belong to a workspace: this session has none");
1527
1546
  if (!isNoteKind(input.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${input.kind}" (use ${NOTE_KINDS.join(", ")})`);
1528
1547
  const kind = input.kind;
1529
1548
  const text = cleanText(input.text, "Note text");
1530
- const repos = cleanRepos(group, input.repos);
1549
+ const repos = cleanRepos(workspace, input.repos);
1531
1550
  const similar = activeNotesOfKind(ctx, kind).map((note) => ({
1532
1551
  note,
1533
1552
  score: similarity(text, note.text)
1534
1553
  })).filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY).sort((first, second) => second.score - first.score).slice(0, SIMILAR_SHOWN).map((candidate) => candidate.note);
1535
1554
  ctx.db.exec("BEGIN");
1536
1555
  try {
1537
- const next = ctx.db.prepare("SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE group_name = ?").get(ctx.group);
1538
- const result = ctx.db.prepare(`INSERT INTO notes (group_name, number, kind, text, session, agent, similar_notes, created_at)
1539
- 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));
1556
+ const next = ctx.db.prepare("SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE workspace = ?").get(ctx.workspace);
1557
+ const result = ctx.db.prepare(`INSERT INTO notes (workspace, number, kind, text, session, agent, similar_notes, created_at)
1558
+ 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));
1540
1559
  const id = Number(result.lastInsertRowid);
1541
1560
  const addRepo = ctx.db.prepare("INSERT INTO note_repos (note, repo) VALUES (?, ?)");
1542
1561
  for (const repo of repos) addRepo.run(id, repo);
@@ -1552,8 +1571,8 @@ function addNote(ctx, group, input) {
1552
1571
  }
1553
1572
  function listNotes(ctx, options = {}) {
1554
1573
  if (options.kind !== void 0 && !isNoteKind(options.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${options.kind}"`);
1555
- const conditions = ["group_name IS ?"];
1556
- const parameters = [ctx.group];
1574
+ const conditions = ["workspace IS ?"];
1575
+ const parameters = [ctx.workspace];
1557
1576
  if (!options.includeDropped) conditions.push("dropped_at IS NULL");
1558
1577
  if (options.kind) {
1559
1578
  conditions.push("kind = ?");
@@ -1612,16 +1631,16 @@ const ACTIVITY_ORDER = {
1612
1631
  };
1613
1632
  function activeIds(ctx, json) {
1614
1633
  if (!json) return [];
1615
- const active = ctx.db.prepare("SELECT 1 FROM notes WHERE group_name IS ? AND number = ? AND dropped_at IS NULL");
1616
- return JSON.parse(json).filter((number) => active.get(ctx.group, number) !== void 0);
1634
+ const active = ctx.db.prepare("SELECT 1 FROM notes WHERE workspace IS ? AND number = ? AND dropped_at IS NULL");
1635
+ return JSON.parse(json).filter((number) => active.get(ctx.workspace, number) !== void 0);
1617
1636
  }
1618
1637
  function sessionNoteActivity(ctx, session) {
1619
1638
  const added = ctx.db.prepare(`SELECT number, kind, text, similar_notes, created_at FROM notes
1620
- WHERE group_name IS ? AND session = ?`).all(ctx.group, session);
1639
+ WHERE workspace IS ? AND session = ?`).all(ctx.workspace, session);
1621
1640
  const cited = ctx.db.prepare(`SELECT notes.number AS note, notes.kind, note_citations.why, note_citations.at
1622
1641
  FROM note_citations JOIN notes ON notes.id = note_citations.note
1623
- WHERE notes.group_name IS ? AND note_citations.session = ?`).all(ctx.group, session);
1624
- const dropped = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND dropped_session = ?`).all(ctx.group, session);
1642
+ WHERE notes.workspace IS ? AND note_citations.session = ?`).all(ctx.workspace, session);
1643
+ const dropped = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE workspace IS ? AND dropped_session = ?`).all(ctx.workspace, session);
1625
1644
  return [
1626
1645
  ...added.map((row) => ({
1627
1646
  activity: "added",
@@ -1715,26 +1734,26 @@ function notesFor(ctx, repos, general, halfLifeDays) {
1715
1734
  }));
1716
1735
  return [...byId.values()].sort(compareNotes);
1717
1736
  }
1718
- function groupTitle(group) {
1719
- return group ? `Rucher memory of the ${group.name} group` : "Rucher memory";
1737
+ function workspaceTitle(workspace) {
1738
+ return workspace ? `Rucher memory of the ${workspace.name} workspace` : "Rucher memory";
1720
1739
  }
1721
- function sessionStartMemory(ctx, group, session, options = {}) {
1740
+ function sessionStartMemory(ctx, workspace, session, options = {}) {
1722
1741
  const halfLifeDays = options.halfLifeDays ?? 20;
1723
1742
  const repos = session.repo ? [session.repo] : [];
1724
1743
  const notes = notesFor(ctx, repos, true, halfLifeDays);
1725
1744
  if (!notes.length) return void 0;
1726
1745
  for (const repo of repos) if (notes.some((note) => note.repos.includes(repo))) recordRepo(ctx, session.id, repo);
1727
1746
  return renderMemory({
1728
- title: groupTitle(group),
1747
+ title: workspaceTitle(workspace),
1729
1748
  notes
1730
1749
  }, options.maxCharacters);
1731
1750
  }
1732
- function sessionMemory(ctx, group, session, options = {}) {
1751
+ function sessionMemory(ctx, workspace, session, options = {}) {
1733
1752
  const halfLifeDays = options.halfLifeDays ?? 20;
1734
1753
  const notes = notesFor(ctx, injectedRepos(ctx, session.id), true, halfLifeDays);
1735
1754
  if (!notes.length) return void 0;
1736
1755
  return renderMemory({
1737
- title: groupTitle(group),
1756
+ title: workspaceTitle(workspace),
1738
1757
  notes
1739
1758
  }, options.maxCharacters);
1740
1759
  }
@@ -1803,7 +1822,7 @@ function purgeDays(value) {
1803
1822
  return Number.isFinite(days) && days > 0 ? days : 3;
1804
1823
  }
1805
1824
  const PURGEABLE = `
1806
- group_name IS ? AND id != ? AND last_active_at < ?
1825
+ workspace IS ? AND id != ? AND last_active_at < ?
1807
1826
  AND NOT EXISTS (
1808
1827
  SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
1809
1828
  )
@@ -1815,7 +1834,7 @@ function purgeSessions(ctx, keepId, days) {
1815
1834
  const cutoff = (/* @__PURE__ */ new Date(ctx.now().getTime() - days * DAY_MILLISECONDS)).toISOString();
1816
1835
  ctx.db.exec("BEGIN");
1817
1836
  try {
1818
- const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(ctx.group, keepId, cutoff).map((row) => row.id);
1837
+ const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(ctx.workspace, keepId, cutoff).map((row) => row.id);
1819
1838
  for (const table of [
1820
1839
  "table_items",
1821
1840
  "agents",
@@ -2019,27 +2038,27 @@ function stopSubagent(ctx, session, hostAgentId, names = []) {
2019
2038
  }
2020
2039
  // src/carnet.ts
2021
2040
  var Carnet = class {
2022
- group;
2041
+ workspace;
2023
2042
  db;
2024
2043
  ctx;
2025
- constructor(db, group, options = {}) {
2026
- this.group = group;
2044
+ constructor(db, workspace, options = {}) {
2045
+ this.workspace = workspace;
2027
2046
  this.db = db;
2028
2047
  this.ctx = {
2029
2048
  db,
2030
2049
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
2031
- group: group?.name ?? null
2050
+ workspace: workspace?.name ?? null
2032
2051
  };
2033
2052
  }
2034
- requireGroup() {
2035
- return requireGroup(this.group);
2053
+ requireWorkspace() {
2054
+ return requireWorkspace(this.workspace);
2036
2055
  }
2037
2056
  sessions = {
2038
2057
  get: (id) => getSession(this.ctx, id),
2039
2058
  find: (reference) => findSession(this.ctx, reference),
2040
2059
  require: (id) => requireSession(this.ctx, id),
2041
- ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group ?? void 0),
2042
- upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.group, payload, env),
2060
+ ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.workspace ?? void 0),
2061
+ upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.workspace, payload, env),
2043
2062
  touch: (id) => touchSession(this.ctx, id),
2044
2063
  merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
2045
2064
  purge: (keepId, days) => purgeSessions(this.ctx, keepId, days),
@@ -2087,7 +2106,7 @@ var Carnet = class {
2087
2106
  })
2088
2107
  };
2089
2108
  notes = {
2090
- add: (input) => addNote(this.ctx, this.group, input),
2109
+ add: (input) => addNote(this.ctx, this.workspace, input),
2091
2110
  get: (id) => getNote(this.ctx, id),
2092
2111
  show: (id, halfLifeDays) => noteDetail(this.ctx, id, halfLifeDays),
2093
2112
  list: (options) => listNotes(this.ctx, options),
@@ -2098,8 +2117,8 @@ var Carnet = class {
2098
2117
  activity: (session) => sessionNoteActivity(this.ctx, session)
2099
2118
  };
2100
2119
  memory = {
2101
- atStart: (session, options) => sessionStartMemory(this.ctx, this.group, session, options),
2102
- ofSession: (session, options) => sessionMemory(this.ctx, this.group, session, options),
2120
+ atStart: (session, options) => sessionStartMemory(this.ctx, this.workspace, session, options),
2121
+ ofSession: (session, options) => sessionMemory(this.ctx, this.workspace, session, options),
2103
2122
  forRepo: (session, repo, options) => repoMemory(this.ctx, session, repo, options),
2104
2123
  copyRepos: (from, into) => copyInjectedRepos(this.ctx, from, into)
2105
2124
  };
@@ -2123,12 +2142,12 @@ function openCarnet(options = {}) {
2123
2142
  function openResolvedCarnet(options = {}) {
2124
2143
  const db = openStore(options);
2125
2144
  try {
2126
- const resolution = resolveGroup({
2145
+ const resolution = resolveWorkspace({
2127
2146
  ...options,
2128
2147
  db
2129
2148
  });
2130
2149
  return {
2131
- carnet: new Carnet(db, resolution.group, options),
2150
+ carnet: new Carnet(db, resolution.workspace, options),
2132
2151
  resolution
2133
2152
  };
2134
2153
  } catch (error) {
@@ -2136,8 +2155,8 @@ function openResolvedCarnet(options = {}) {
2136
2155
  throw error;
2137
2156
  }
2138
2157
  }
2139
- function openGroupCarnet(group, options = {}) {
2140
- return new Carnet(openStore(options), group, options);
2158
+ function openWorkspaceCarnet(workspace, options = {}) {
2159
+ return new Carnet(openStore(options), workspace, options);
2141
2160
  }
2142
2161
  // src/resume.ts
2143
2162
  const RESUME_EVENTS = 20;
@@ -2229,6 +2248,6 @@ function stepAgent(carnet, session, input) {
2229
2248
  }
2230
2249
  }
2231
2250
  }
2232
- export { createGroup as $, migrations as $t, memoryMaxCharacters as A, appendPromptFile as At, memoryHalfLife as B, shortId as Bt, renderNotesSummary as C, mergeSettings as Ct, DEFAULT_PURGE_DAYS as D, PROMPT_FILE as Dt, renderTableLine as E, OUTSIDE_RUCHER_NOTICE as Et, NOTE_TEXT_LIMIT as F, outsideRucherContext as Ft, isInside as G, groupsDirectory as Gt, similarity as H, databasePath as Ht, STALE_AFTER_ACTIVE_DAYS as I, rulesText as It, requireGroup as J, reportsDirectory as Jt, repoNameFor as K, promptsDirectory as Kt, groupRepoNames as L, rulesVersion as Lt, DEFAULT_HALF_LIFE_DAYS as M, baseRules as Mt, DUPLICATE_SIMILARITY as N, compactReminder as Nt, purgeDays as O, RULES_UPDATED_NOTICE as Ot, NOTE_KINDS as P, groupRules as Pt, addGroupRepo as Q, migrate as Qt, isNoteKind as R, CORE_RULES as Rt, renderNotes as S, markdownCopy as St, renderStatus as T, writeGenerated as Tt, ambiguousGroupContext as U, defaultWorkspace as Ut, sessionNoteActivity as V, corePromptPath as Vt, groupLabel as W, groupSource as Wt, GROUP_FILE as X, MEMORY_DB as Xt, resolveGroup as Y, rucherPaths as Yt, INSTRUCTIONS_FILE as Z, openDatabase as Zt, NOTES_FOLD_LINES as _, claudeCode as _t, formatEventLine as a, AGENT_STATUSES as an, listGroups as at, renderAgentLine as b, GENERATED_MARKER as bt, Carnet as c, MAIN_WORKING_EMOJI as cn, renameGroup as ct, openResolvedCarnet as d, isAgentStatus as dn, groupSessionCounts as dt, schemaVersion as en, dropGroup as et, PAIRING_WINDOW_MILLISECONDS as f, isUserActionStatus as fn, renameGroupRows as ft, MAIN_WORKING_SUFFIX as g, CarnetError as gn, hostById as gt, formatClock as h, isEventType as hn, allHosts as ht, RESUME_MAX_CHARACTERS as i, sanitizeNote as in, isGroupName as it, renderMemory as j, assemblePrompt as jt, MEMORY_MAX_CHARACTERS as k, SUBAGENT_RULES as kt, openCarnet as l, OPEN_AGENT_STATUSES as ln, archiveGroupSessions as lt, buildStatusView as m, SESSION_EVENT_TYPES as mn, DEFAULT_HOST as mt, stepAgent as n, REPORTING_NOTE as nn, groupExists as nt, resumeContext as o, EMOJI as on, loadGroup as ot, STOPPED_NOTE as p, EVENT_TYPES as pn, sessionGroupName as pt, repoPathFor as q, reportPath as qt, RESUME_EVENTS as r, NOTE_MAX as rn, groupHosts as rt, sessionLabel as s, LEGEND as sn, removeGroupRepo as st, AGENT_STEPS as t, PUBLISH_FALLBACK_MILLISECONDS as tn, expandHome as tt, openGroupCarnet as u, USER_ACTION_STATUSES as un, deleteGroupNotes as ut, NOTES_HEADER as v, groupSettings as vt, renderSections as w, removeStaleCopies as wt, renderNoteLine as x, MARKDOWN_MARKER as xt, SIMILAR_PREFIX as y, transcriptTitle as yt, localDay as z, MINIMUM_ID_PREFIX as zt };
2251
+ 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 };
2233
2252
 
2234
- //# sourceMappingURL=steps-U_Ge5YFh.mjs.map
2253
+ //# sourceMappingURL=steps-CzJOqsBI.mjs.map