@rucher/carnet 0.2.0-beta.9 → 0.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
1
+ import { appendFileSync, closeSync, copyFileSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, 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";
@@ -182,11 +182,22 @@ function statusChangeArgs(next, at) {
182
182
  next
183
183
  ];
184
184
  }
185
+ const CLOSE_SET = `status = 'closed', pending_status = NULL, queue_order = NULL, blocked_on = NULL,
186
+ status_since = ?, updated_at = ?`;
187
+ function closeAgentsWhere(db, where, params, at) {
188
+ return Number(db.prepare(`UPDATE agents SET ${CLOSE_SET} WHERE status != 'closed' AND (${where})`).run(at, at, ...params).changes);
189
+ }
190
+ function moveAgentStatus(ctx, session, name, status, note) {
191
+ const at = nowIso(ctx);
192
+ ctx.db.prepare(`UPDATE agents SET status = ?, note = ?, ${statusChangeSql("?")}, updated_at = ?
193
+ WHERE session = ? AND name = ?`).run(status, note, ...statusChangeArgs(status, at), at, session, name);
194
+ }
185
195
  function publishPending(ctx, session, name) {
186
196
  const row = ctx.db.prepare("SELECT pending_status, report_path FROM agents WHERE session = ? AND name = ?").get(session, name);
187
197
  if (!row?.pending_status) return;
188
198
  ctx.db.prepare(`UPDATE agents SET status = pending_status, pending_status = NULL, note = NULL,
189
- ${statusChangeSql("pending_status")}, updated_at = ? WHERE session = ? AND name = ?`).run(nowIso(ctx), nowIso(ctx), session, name);
199
+ ${statusChangeSql("pending_status")}, updated_at = ?
200
+ WHERE session = ? AND name = ? AND status != 'closed'`).run(nowIso(ctx), nowIso(ctx), session, name);
190
201
  logEvent(ctx, session, {
191
202
  type: "finished",
192
203
  agent: name,
@@ -195,7 +206,7 @@ function publishPending(ctx, session, name) {
195
206
  }
196
207
  function publishOverdue(ctx, session) {
197
208
  const before = (/* @__PURE__ */ new Date(ctx.now().getTime() - PUBLISH_FALLBACK_MILLISECONDS)).toISOString();
198
- const rows = ctx.db.prepare("SELECT name FROM agents WHERE session = ? AND pending_status IS NOT NULL AND done_at <= ?").all(session, before);
209
+ const rows = ctx.db.prepare("SELECT name FROM agents WHERE session = ? AND pending_status IS NOT NULL AND done_at <= ? AND status != 'closed'").all(session, before);
199
210
  for (const row of rows) publishPending(ctx, session, row.name);
200
211
  }
201
212
  function getAgent(ctx, session, name) {
@@ -203,7 +214,7 @@ function getAgent(ctx, session, name) {
203
214
  const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND name = ?").get(session, name);
204
215
  return row && toAgent(row);
205
216
  }
206
- function requireAgent(ctx, session, name) {
217
+ function requireAgent$1(ctx, session, name) {
207
218
  const agent = getAgent(ctx, session, name);
208
219
  if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
209
220
  return agent;
@@ -237,7 +248,7 @@ function startAgent(ctx, session, input) {
237
248
  agent: name,
238
249
  note: input.task
239
250
  });
240
- return requireAgent(ctx, session, name);
251
+ return requireAgent$1(ctx, session, name);
241
252
  }
242
253
  function checkSandbox(ctx, session, name, kind, sandbox) {
243
254
  if (!SANDBOX_KINDS.includes(kind)) throw new CarnetError("INVALID_KIND", `Only a research or plan agent gets a sandbox; ${name} is ${kind}`);
@@ -266,7 +277,7 @@ function checkBlocker(ctx, session, name, blocker) {
266
277
  }
267
278
  }
268
279
  function updateAgent(ctx, session, name, input) {
269
- const current = requireAgent(ctx, session, name);
280
+ const current = requireAgent$1(ctx, session, name);
270
281
  if (!isAgentStatus(input.status) || input.status === "closed") throw new CarnetError("INVALID_STATUS", `Invalid agent status "${input.status}"; use agent_drop to close`);
271
282
  let note;
272
283
  if (input.note !== void 0) note = input.note === null ? null : sanitizeNote(input.note);
@@ -279,31 +290,31 @@ function updateAgent(ctx, session, name, input) {
279
290
  if (current.pendingStatus) publishPending(ctx, session, name);
280
291
  ctx.db.prepare(`UPDATE agents SET note = ?, ${statusChangeSql("?")}, status = ?,
281
292
  report_path = COALESCE(?, report_path), blocked_on = ?, updated_at = ? WHERE session = ? AND name = ?`).run(note, ...statusChangeArgs(input.status, nowIso(ctx)), input.status, input.reportPath ?? null, blockedOn, nowIso(ctx), session, name);
282
- return requireAgent(ctx, session, name);
293
+ return requireAgent$1(ctx, session, name);
283
294
  }
284
295
  function statusWhenDone(kind, hasQuestions) {
285
296
  if (hasQuestions) return "answer";
286
297
  return kind === "implement" ? "apply" : "review";
287
298
  }
288
299
  function finishAgent(ctx, session, name, input) {
289
- const agent = requireAgent(ctx, session, name);
300
+ const agent = requireAgent$1(ctx, session, name);
290
301
  const status = statusWhenDone(agent.kind, input.hasQuestions);
291
302
  const at = nowIso(ctx);
292
303
  ctx.db.prepare("UPDATE agents SET pending_status = ?, note = ?, report_path = ?, done_at = ?, updated_at = ? WHERE session = ? AND name = ?").run(status, REPORTING_NOTE, input.reportPath, at, at, session, name);
293
304
  if (!agent.hostAgentId) publishPending(ctx, session, name);
294
- return requireAgent(ctx, session, name);
305
+ return requireAgent$1(ctx, session, name);
295
306
  }
296
307
  function statusAfterAnswers(kind) {
297
308
  return kind === "implement" ? "apply" : "review";
298
309
  }
299
310
  function closeAgent(ctx, session, name, event) {
300
- requireAgent(ctx, session, name);
301
- ctx.db.prepare("UPDATE agents SET status = 'closed', pending_status = NULL, queue_order = NULL, blocked_on = NULL, status_since = ?, updated_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), nowIso(ctx), session, name);
311
+ requireAgent$1(ctx, session, name);
312
+ ctx.db.prepare(`UPDATE agents SET ${CLOSE_SET} WHERE session = ? AND name = ?`).run(nowIso(ctx), nowIso(ctx), session, name);
302
313
  logEvent(ctx, session, {
303
314
  ...event,
304
315
  agent: name
305
316
  });
306
- return requireAgent(ctx, session, name);
317
+ return requireAgent$1(ctx, session, name);
307
318
  }
308
319
  function dropAgent(ctx, session, name, reason) {
309
320
  return closeAgent(ctx, session, name, {
@@ -317,7 +328,7 @@ const PROMOTIONS = {
317
328
  };
318
329
  const PROMOTE_KIND_REQUIRED = "kind is required: plan or implement for a research agent, implement for a plan one";
319
330
  function promoteAgent(ctx, session, name, input) {
320
- const agent = requireAgent(ctx, session, name);
331
+ const agent = requireAgent$1(ctx, session, name);
321
332
  const target = input.kind;
322
333
  if (!isAgentKind(target)) throw new CarnetError("INVALID_KIND", PROMOTE_KIND_REQUIRED);
323
334
  const allowed = PROMOTIONS[agent.kind] ?? [];
@@ -332,7 +343,7 @@ function promoteAgent(ctx, session, name, input) {
332
343
  agent: name,
333
344
  note: `${agent.kind} to ${target}`
334
345
  });
335
- return requireAgent(ctx, session, name);
346
+ return requireAgent$1(ctx, session, name);
336
347
  }
337
348
  function listAgents(ctx, session, options = {}) {
338
349
  publishOverdue(ctx, session);
@@ -792,16 +803,25 @@ function schemaVersion(db) {
792
803
  function foreignKeyViolations(db) {
793
804
  return db.prepare("PRAGMA foreign_key_check").all().length;
794
805
  }
806
+ function knownVersion(db) {
807
+ const version = schemaVersion(db);
808
+ if (version > migrations.length) throw new CarnetError("SCHEMA_TOO_NEW", `The Carnet database is at schema v${version}, newer than this rucher (v${migrations.length}). Update rucher and its plugin; sessions started before the update run the old version until they are restarted.`);
809
+ return version;
810
+ }
795
811
  function migrate(db) {
796
- const current = schemaVersion(db);
797
- if (current >= migrations.length) return;
812
+ if (knownVersion(db) >= migrations.length) return;
798
813
  const foreignKeys = db.prepare("PRAGMA foreign_keys").get();
799
814
  db.exec("PRAGMA foreign_keys = OFF");
800
815
  try {
801
- for (const [version, migration] of migrations.entries()) {
802
- if (version < current) continue;
803
- db.exec("BEGIN");
816
+ for (;;) {
817
+ db.exec("BEGIN IMMEDIATE");
804
818
  try {
819
+ const version = knownVersion(db);
820
+ const migration = migrations[version];
821
+ if (migration === void 0) {
822
+ db.exec("COMMIT");
823
+ return;
824
+ }
805
825
  preconditions[version + 1]?.(db);
806
826
  db.exec(migration);
807
827
  if (foreignKeyViolations(db) > 0) throw new Error(`Migration ${version + 1} broke foreign keys`);
@@ -818,11 +838,21 @@ function migrate(db) {
818
838
  }
819
839
  // src/db/open.ts
820
840
  const MEMORY_DB = ":memory:";
841
+ function useWal(db) {
842
+ if (db.prepare("PRAGMA journal_mode").get().journal_mode === "wal") return;
843
+ for (let attempt = 1;; attempt += 1) try {
844
+ db.exec("PRAGMA journal_mode = WAL");
845
+ return;
846
+ } catch (error) {
847
+ if (attempt >= 50 || !String(error).includes("database is locked")) throw error;
848
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
849
+ }
850
+ }
821
851
  function openDatabase(path) {
822
852
  const db = new DatabaseSync(path);
823
- if (path !== ":memory:") db.exec("PRAGMA journal_mode = WAL");
824
- db.exec("PRAGMA foreign_keys = ON");
825
853
  db.exec("PRAGMA busy_timeout = 5000");
854
+ if (path !== ":memory:") useWal(db);
855
+ db.exec("PRAGMA foreign_keys = ON");
826
856
  migrate(db);
827
857
  return db;
828
858
  }
@@ -1231,18 +1261,18 @@ function listSessions(ctx, options = {}) {
1231
1261
  const conditions = ["workspace = ?"];
1232
1262
  if (!options.includeTemp) conditions.push("kind != 'temp'");
1233
1263
  if (!options.includeArchived) conditions.push("status != 'archived'");
1234
- return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC`).all(ctx.workspace).map(toSession);
1264
+ return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC, rowid DESC`).all(ctx.workspace).map(toSession);
1235
1265
  }
1236
1266
  function dropSession(ctx, id) {
1237
1267
  requireSession(ctx, id);
1238
1268
  const at = nowIso(ctx);
1239
- ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, id);
1269
+ closeAgentsWhere(ctx.db, "session = ?", [id], at);
1240
1270
  ctx.db.prepare("UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?").run(at, id);
1241
1271
  return requireSession(ctx, id);
1242
1272
  }
1243
1273
  function defaultSession(ctx) {
1244
1274
  const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND status != 'archived'
1245
- ORDER BY last_active_at DESC LIMIT 1`).get(ctx.workspace);
1275
+ ORDER BY last_active_at DESC, rowid DESC LIMIT 1`).get(ctx.workspace);
1246
1276
  return row && toSession(row);
1247
1277
  }
1248
1278
  function sessionByName(ctx, name) {
@@ -1261,7 +1291,7 @@ function findSession(ctx, reference) {
1261
1291
  const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
1262
1292
  if (isIdPrefix && reference.length >= 4) {
1263
1293
  const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND id LIKE ?
1264
- ORDER BY last_active_at DESC`).all(ctx.workspace, `${reference.toLowerCase()}%`);
1294
+ ORDER BY last_active_at DESC, rowid DESC`).all(ctx.workspace, `${reference.toLowerCase()}%`);
1265
1295
  const [only, ...others] = rows;
1266
1296
  if (only && others.length === 0) return toSession(only);
1267
1297
  if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
@@ -1271,7 +1301,7 @@ function findSession(ctx, reference) {
1271
1301
  function sessionByHostProcess(ctx, host, processId) {
1272
1302
  const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
1273
1303
  WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL
1274
- ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
1304
+ ORDER BY hooked_at DESC, rowid DESC LIMIT 1`).get(host, processId);
1275
1305
  return row && toSession(row);
1276
1306
  }
1277
1307
  function recordPluginVersion(ctx, id, version) {
@@ -1332,7 +1362,7 @@ function staleTempSessions(ctx, olderThanMilliseconds) {
1332
1362
  const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
1333
1363
  return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
1334
1364
  WHERE workspace = ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
1335
- ORDER BY last_active_at ASC`).all(ctx.workspace, before).map(toSession);
1365
+ ORDER BY last_active_at ASC, rowid ASC`).all(ctx.workspace, before).map(toSession);
1336
1366
  }
1337
1367
  function resetDeadSessions(ctx, isAlive) {
1338
1368
  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));
@@ -1341,7 +1371,7 @@ function resetDeadSessions(ctx, isAlive) {
1341
1371
  const CORE_RULES = `- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.
1342
1372
  - The human keeps the hand: only the human launches agents, asks for their report and its next action (inject, validate, apply, triage), applies, tests and commits. Agents propose, they never push.
1343
1373
  - Status lives in Carnet: agent statuses, the Main line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.
1344
- - When an agent finishes, say only "<name> finished, report ready". Never summarise, quote or act on its report or final message until the human asks for that report (/rucher:report), even when answering about something else.
1374
+ - When an agent finishes, say only "<name> finished, report ready". Never summarise, quote or act on its report or final message until the human asks for that report or its next action (/rucher:next), even when answering about something else.
1345
1375
  - Agents never commit, push, stash or record notes. An agent follows its kind's contract, 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.
1346
1376
  - To launch agents or handle their results, load the rucher skill: it holds the full workflow.`;
1347
1377
  // src/prompt/prompt.ts
@@ -1351,7 +1381,7 @@ function readIfPresent(path) {
1351
1381
  return readFileSync(path, "utf8").trim() || void 0;
1352
1382
  }
1353
1383
  function baseRules(env = process.env) {
1354
- 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 agents, asks for their report and its next action (inject, validate, apply, triage), applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the Main 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 an agent finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that report (/rucher:report), even when answering about something else.\n- Agents never commit, push, stash or record notes. An agent follows its kind's contract, 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 launch agents or handle their results, load the rucher skill: it holds the full workflow.";
1384
+ 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 agents, asks for their report and its next action (inject, validate, apply, triage), applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the Main 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 an agent finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that report or its next action (/rucher:next), even when answering about something else.\n- Agents never commit, push, stash or record notes. An agent follows its kind's contract, 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 launch agents or handle their results, load the rucher skill: it holds the full workflow.";
1355
1385
  }
1356
1386
  function workspaceRules(workspace) {
1357
1387
  return workspace ? readIfPresent(join(workspace.definition, PROMPT_FILE)) : void 0;
@@ -1451,6 +1481,52 @@ function mergeSettings(base, extra) {
1451
1481
  }
1452
1482
  return merged;
1453
1483
  }
1484
+ // src/workspace/undo.ts
1485
+ var UndoList = class {
1486
+ steps = [];
1487
+ push(step) {
1488
+ this.steps.push(step);
1489
+ }
1490
+ undo() {
1491
+ const outcome = {
1492
+ undone: [],
1493
+ left: []
1494
+ };
1495
+ for (const step of [...this.steps].reverse()) {
1496
+ if (outcome.left.length) {
1497
+ outcome.left.push(step.command);
1498
+ continue;
1499
+ }
1500
+ try {
1501
+ step.run();
1502
+ outcome.undone.push(step.command);
1503
+ } catch {
1504
+ outcome.left.push(step.command);
1505
+ }
1506
+ }
1507
+ this.steps.length = 0;
1508
+ return outcome;
1509
+ }
1510
+ };
1511
+ function shellQuote(path) {
1512
+ return `'${path.replaceAll("'", "'\\''")}'`;
1513
+ }
1514
+ function moveTracked(undo, move) {
1515
+ renameSync(move.from, move.to);
1516
+ undo.push({
1517
+ command: `mv ${shellQuote(move.to)} ${shellQuote(move.from)}`,
1518
+ run: () => renameSync(move.to, move.from)
1519
+ });
1520
+ }
1521
+ function relocateFailed(error, undo, backup) {
1522
+ const outcome = undo.undo();
1523
+ const cause = error instanceof Error ? error.message : String(error);
1524
+ if (outcome.left.length === 0) {
1525
+ if (error instanceof CarnetError) throw error;
1526
+ throw new CarnetError("WORKSPACE_RELOCATE_FAILED", `${cause}; nothing was changed`);
1527
+ }
1528
+ throw new CarnetError("WORKSPACE_RELOCATE_FAILED", `${cause}; undo stopped, run by hand:\n${outcome.left.join("\n")}\nDatabase backup: ${join(backup, "carnet.db")}`);
1529
+ }
1454
1530
  // src/hosts/claude-code.ts
1455
1531
  const TRANSCRIPT_TAIL_BYTES = 262144;
1456
1532
  const TRANSCRIPT_HEAD_BYTES = 65536;
@@ -1601,6 +1677,108 @@ const RENDERING_SOURCES = /* @__PURE__ */ new Set([
1601
1677
  function projectsDirectory(env) {
1602
1678
  return join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
1603
1679
  }
1680
+ function claudeProjectFolder(cwd, env = process.env) {
1681
+ return join(projectsDirectory(env), cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1682
+ }
1683
+ function claudeConfigFile(env = process.env) {
1684
+ return env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, ".claude.json") : join(env.HOME || homedir(), ".claude.json");
1685
+ }
1686
+ function renameStep(from, to) {
1687
+ return {
1688
+ command: `mv ${shellQuote(to)} ${shellQuote(from)}`,
1689
+ run: () => renameSync(to, from)
1690
+ };
1691
+ }
1692
+ function moveProject(source, target) {
1693
+ if (existsSync(target)) throw new CarnetError("WORKSPACE_EXISTS", `Claude Code already has a project folder: ${target}`);
1694
+ renameSync(source, target);
1695
+ return {
1696
+ moves: [{
1697
+ from: source,
1698
+ to: target
1699
+ }],
1700
+ undo: [renameStep(source, target)]
1701
+ };
1702
+ }
1703
+ const MEMORY_INDEX = "MEMORY.md";
1704
+ function mergeProject(source, target, prefix) {
1705
+ const relocation = {
1706
+ moves: [],
1707
+ undo: []
1708
+ };
1709
+ const move = (from, to) => {
1710
+ if (existsSync(to)) throw new CarnetError("WORKSPACE_EXISTS", `Claude Code project file already exists: ${to}`);
1711
+ mkdirSync(dirname(to), { recursive: true });
1712
+ renameSync(from, to);
1713
+ relocation.moves.push({
1714
+ from,
1715
+ to
1716
+ });
1717
+ relocation.undo.push(renameStep(from, to));
1718
+ };
1719
+ for (const entry of readdirSync(source)) if (entry !== "memory") move(join(source, entry), join(target, entry));
1720
+ const memory = join(source, "memory");
1721
+ if (!existsSync(memory)) return removeEmpty(relocation, [source]);
1722
+ const renamed = /* @__PURE__ */ new Map();
1723
+ for (const entry of readdirSync(memory)) {
1724
+ if (entry === MEMORY_INDEX) continue;
1725
+ const name = existsSync(join(target, "memory", entry)) ? `${prefix}-${entry}` : entry;
1726
+ if (name !== entry) renamed.set(entry, name);
1727
+ move(join(memory, entry), join(target, "memory", name));
1728
+ }
1729
+ const fromIndex = join(memory, MEMORY_INDEX);
1730
+ if (existsSync(fromIndex)) {
1731
+ const intoIndex = join(target, "memory", MEMORY_INDEX);
1732
+ if (!existsSync(intoIndex)) move(fromIndex, intoIndex);
1733
+ else {
1734
+ const original = readFileSync(intoIndex, "utf8");
1735
+ const added = [...renamed].reduce((text, [from, to]) => text.replaceAll(`(${from})`, `(${to})`), readFileSync(fromIndex, "utf8"));
1736
+ const separator = original.endsWith("\n") || original === "" ? "" : "\n";
1737
+ writeFileSync(intoIndex, `${original}${separator}\n## Ex-workspace ${prefix}\n\n${added}`);
1738
+ const fromText = readFileSync(fromIndex, "utf8");
1739
+ unlinkSync(fromIndex);
1740
+ relocation.undo.push({
1741
+ command: `# restore ${shellQuote(intoIndex)} and ${shellQuote(fromIndex)} by hand`,
1742
+ run: () => {
1743
+ writeFileSync(fromIndex, fromText);
1744
+ writeFileSync(intoIndex, original);
1745
+ }
1746
+ });
1747
+ }
1748
+ }
1749
+ return removeEmpty(relocation, [memory, source]);
1750
+ }
1751
+ function removeEmpty(relocation, folders) {
1752
+ for (const folder of folders) {
1753
+ if (readdirSync(folder).length > 0) continue;
1754
+ rmdirSync(folder);
1755
+ relocation.undo.push({
1756
+ command: `mkdir -p ${shellQuote(folder)}`,
1757
+ run: () => mkdirSync(folder, { recursive: true })
1758
+ });
1759
+ }
1760
+ return relocation;
1761
+ }
1762
+ function relocateProject(from, to, env, mode = "move") {
1763
+ const source = claudeProjectFolder(from, env);
1764
+ const target = claudeProjectFolder(to, env);
1765
+ if (!existsSync(source)) return null;
1766
+ if (mode === "move") return moveProject(source, target);
1767
+ if (!existsSync(target)) return moveProject(source, target);
1768
+ return mergeProject(source, target, basename(from));
1769
+ }
1770
+ function moveTrust(from, to, env) {
1771
+ const file = claudeConfigFile(env);
1772
+ if (!existsSync(file)) return false;
1773
+ const config = JSON.parse(readFileSync(file, "utf8"));
1774
+ const projects = config.projects;
1775
+ if (!projects || !(from in projects) || to !== null && to in projects) return false;
1776
+ config.projects = Object.fromEntries(Object.entries(projects).flatMap(([key, value]) => key !== from ? [[key, value]] : to === null ? [] : [[to, value]]));
1777
+ const temporary = `${file}.rucher-${process.pid}`;
1778
+ writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: statSync(file).mode });
1779
+ renameSync(temporary, file);
1780
+ return true;
1781
+ }
1604
1782
  const claudeCode = {
1605
1783
  id: "claude-code",
1606
1784
  displayName: "Claude Code",
@@ -1733,7 +1911,7 @@ const claudeCode = {
1733
1911
  },
1734
1912
  transcriptFiles(session, env = process.env) {
1735
1913
  if (!session.cwd) return [];
1736
- const project = join(projectsDirectory(env), session.cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1914
+ const project = claudeProjectFolder(session.cwd, env);
1737
1915
  return [join(project, `${session.id}.jsonl`), join(project, session.id)].filter((path) => existsSync(path));
1738
1916
  },
1739
1917
  hasConversation(session, env = process.env) {
@@ -1743,13 +1921,15 @@ const claudeCode = {
1743
1921
  },
1744
1922
  continues(parent, childId, env = process.env) {
1745
1923
  if (!parent.cwd) return false;
1746
- const project = join(projectsDirectory(env), parent.cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1924
+ const project = claudeProjectFolder(parent.cwd, env);
1747
1925
  return continuesConversation(join(project, `${parent.id}.jsonl`), join(project, `${childId}.jsonl`), parent.id, childId);
1748
1926
  },
1749
1927
  renameInstruction(name) {
1750
1928
  return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
1751
1929
  },
1752
- renderRunDirectory: renderClaudeRunDirectory
1930
+ renderRunDirectory: renderClaudeRunDirectory,
1931
+ relocateProject,
1932
+ moveTrust
1753
1933
  };
1754
1934
  // src/hosts/host.ts
1755
1935
  const DEFAULT_HOST = "claude-code";
@@ -1764,7 +1944,7 @@ function hostById(id) {
1764
1944
  }
1765
1945
  // src/workspace-rows.ts
1766
1946
  function inTransaction(db, run) {
1767
- db.exec("BEGIN");
1947
+ db.exec("BEGIN IMMEDIATE");
1768
1948
  try {
1769
1949
  const result = run();
1770
1950
  db.exec("COMMIT");
@@ -1779,8 +1959,7 @@ function sessionWorkspaceName(db, sessionId) {
1779
1959
  }
1780
1960
  function archiveWorkspaceSessions(db, name, at) {
1781
1961
  return inTransaction(db, () => {
1782
- db.prepare(`UPDATE agents SET status = 'closed', updated_at = ?
1783
- WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE workspace = ?)`).run(at, name);
1962
+ closeAgentsWhere(db, "session IN (SELECT id FROM sessions WHERE workspace = ?)", [name], at);
1784
1963
  return Number(db.prepare(`UPDATE sessions SET status = 'archived', last_active_at = ?
1785
1964
  WHERE workspace = ? AND status != 'archived'`).run(at, name).changes);
1786
1965
  });
@@ -1797,6 +1976,80 @@ function workspaceLastActive(db) {
1797
1976
  const rows = db.prepare("SELECT workspace, MAX(last_active_at) AS at FROM sessions GROUP BY workspace").all();
1798
1977
  return new Map(rows.map((row) => [row.workspace, row.at]));
1799
1978
  }
1979
+ function rewritePrefix(db, table, column, from, to) {
1980
+ return Number(db.prepare(`UPDATE ${table} SET ${column} = ? || substr(${column}, length(?) + 1)
1981
+ WHERE ${column} = ? OR substr(${column}, 1, length(?) + 1) = ? || '/'`).run(to, from, from, from, from).changes);
1982
+ }
1983
+ function rewriteRunDirectory(db, from, to) {
1984
+ return [
1985
+ ["sessions", "cwd"],
1986
+ ["agents", "report_path"],
1987
+ ["agents", "sandbox"],
1988
+ ["events", "link"]
1989
+ ].reduce((total, [table, column]) => total + rewritePrefix(db, table, column, from, to), 0);
1990
+ }
1991
+ function workspaceRowCounts(db, name) {
1992
+ const count = (table) => Number(db.prepare(`SELECT COUNT(*) AS total FROM ${table} WHERE workspace = ?`).get(name).total);
1993
+ return {
1994
+ sessions: count("sessions"),
1995
+ notes: count("notes"),
1996
+ activeDays: count("active_days")
1997
+ };
1998
+ }
1999
+ function runningWorkspaceSessions(db, name) {
2000
+ return db.prepare(`SELECT id, name, host_pid FROM sessions
2001
+ WHERE workspace = ? AND status = 'running' AND host_pid IS NOT NULL`).all(name).map((row) => ({
2002
+ id: row.id,
2003
+ name: row.name,
2004
+ hostPid: Number(row.host_pid)
2005
+ }));
2006
+ }
2007
+ function renameWorkspaceRows(db, names, runDirectories) {
2008
+ return inTransaction(db, () => {
2009
+ const counts = workspaceRowCounts(db, names.from);
2010
+ for (const table of [
2011
+ "sessions",
2012
+ "notes",
2013
+ "active_days"
2014
+ ]) db.prepare(`UPDATE ${table} SET workspace = ? WHERE workspace = ?`).run(names.to, names.from);
2015
+ return {
2016
+ ...counts,
2017
+ paths: rewriteRunDirectory(db, runDirectories.from, runDirectories.to)
2018
+ };
2019
+ });
2020
+ }
2021
+ function nextNoteNumber(db, name) {
2022
+ const row = db.prepare("SELECT COALESCE(MAX(number), 0) AS top FROM notes WHERE workspace = ?").get(name);
2023
+ return Number(row.top) + 1;
2024
+ }
2025
+ function mergeWorkspaceRows(db, input) {
2026
+ const { from, into } = input.names;
2027
+ return inTransaction(db, () => {
2028
+ const counts = workspaceRowCounts(db, from);
2029
+ for (const [fromName, intoName] of input.repos) {
2030
+ db.prepare(`UPDATE note_repos SET repo = ?
2031
+ WHERE repo = ? AND note IN (SELECT id FROM notes WHERE workspace = ?)`).run(intoName, fromName, from);
2032
+ db.prepare(`UPDATE session_repos SET repo = ?
2033
+ WHERE repo = ? AND session IN (SELECT id FROM sessions WHERE workspace = ?)`).run(intoName, fromName, from);
2034
+ db.prepare("UPDATE sessions SET repo = ? WHERE repo = ? AND workspace = ?").run(intoName, fromName, from);
2035
+ }
2036
+ const firstNumber = nextNoteNumber(db, into);
2037
+ db.prepare("UPDATE notes SET workspace = ?, number = number + ? WHERE workspace = ?").run(into, firstNumber - 1, from);
2038
+ db.prepare("UPDATE sessions SET workspace = ? WHERE workspace = ?").run(into, from);
2039
+ db.prepare("INSERT OR IGNORE INTO active_days (workspace, day) SELECT ?, day FROM active_days WHERE workspace = ?").run(into, from);
2040
+ db.prepare("DELETE FROM active_days WHERE workspace = ?").run(from);
2041
+ for (const [oldPath, newPath] of input.paths) for (const [table, column] of [
2042
+ ["agents", "report_path"],
2043
+ ["agents", "sandbox"],
2044
+ ["events", "link"]
2045
+ ]) db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ?`).run(newPath, oldPath);
2046
+ rewriteRunDirectory(db, input.runDirectories.from, input.runDirectories.into);
2047
+ return {
2048
+ ...counts,
2049
+ firstNumber
2050
+ };
2051
+ });
2052
+ }
1800
2053
  // src/workspace/locate.ts
1801
2054
  function isInside(directory, path) {
1802
2055
  const relativePath = relative(directory, path);
@@ -1973,7 +2226,7 @@ const CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citation
1973
2226
  note_citations.agent, note_citations.why, note_citations.at`;
1974
2227
  function citationsOf(ctx, number) {
1975
2228
  return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
1976
- WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.workspace, number);
2229
+ WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at, note_citations.rowid`).all(ctx.workspace, number);
1977
2230
  }
1978
2231
  function weightOf(citations, days, halfLifeDays) {
1979
2232
  const latest = /* @__PURE__ */ new Map();
@@ -2253,7 +2506,7 @@ function mergeSessions(ctx, fromId, intoId) {
2253
2506
  try {
2254
2507
  const moveAgent = ctx.db.prepare("UPDATE agents SET session = ?, updated_at = ? WHERE session = ? AND name = ?");
2255
2508
  for (const name of movedAgents) moveAgent.run(intoId, at, fromId, name);
2256
- ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, fromId);
2509
+ closeAgentsWhere(ctx.db, "session = ?", [fromId], at);
2257
2510
  const movedEvents = Number(ctx.db.prepare("UPDATE events SET session = ? WHERE session = ?").run(intoId, fromId).changes);
2258
2511
  const movedTable = !(ctx.db.prepare("SELECT 1 FROM table_items WHERE session = ?").get(intoId) !== void 0) && Number(ctx.db.prepare("UPDATE table_items SET session = ? WHERE session = ?").run(intoId, fromId).changes) > 0;
2259
2512
  ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(fromId);
@@ -2631,20 +2884,34 @@ function pendingPlanAgent(ctx, session) {
2631
2884
  function requestLaunch(ctx, session, name) {
2632
2885
  ctx.db.prepare("UPDATE agents SET launch_requested_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
2633
2886
  }
2634
- function pairSubagent(ctx, session, hostAgentId, names = []) {
2887
+ function pairsByFallback(agentType) {
2888
+ return agentType === void 0 || agentType === "fork" || /^rucher[\w-]*:/.test(agentType);
2889
+ }
2890
+ function openByName(ctx, session, names) {
2891
+ for (const name of names) {
2892
+ const row = ctx.db.prepare(`SELECT * FROM agents WHERE session = ? AND name = ? AND status != 'closed'`).get(session, name);
2893
+ if (row) return row;
2894
+ }
2895
+ }
2896
+ function pairWith(ctx, session, name, hostAgentId) {
2897
+ ctx.db.prepare("UPDATE agents SET host_agent_id = ?, launch_requested_at = NULL WHERE session = ? AND name = ?").run(hostAgentId, session, name);
2898
+ return byHostAgentId(ctx, session, hostAgentId);
2899
+ }
2900
+ function pairSubagent(ctx, session, hostAgentId, names = [], agentType) {
2635
2901
  const paired = byHostAgentId(ctx, session, hostAgentId);
2636
2902
  if (paired) return paired;
2903
+ const named = openByName(ctx, session, names);
2904
+ if (named) return pairWith(ctx, session, named.name, hostAgentId);
2905
+ if (!pairsByFallback(agentType)) return void 0;
2637
2906
  const since = (/* @__PURE__ */ new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS)).toISOString();
2638
- const row = unpairedByName(ctx, session, names) ?? ctx.db.prepare(`SELECT * FROM agents
2907
+ const row = ctx.db.prepare(`SELECT * FROM agents
2639
2908
  WHERE session = ? AND status != 'closed' AND host_agent_id IS NULL
2640
2909
  AND launch_requested_at >= ?
2641
2910
  ORDER BY launch_requested_at ASC, rowid ASC LIMIT 1`).get(session, since) ?? ctx.db.prepare(`SELECT * FROM agents
2642
2911
  WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND blocked_on IS NULL
2643
2912
  AND started_at >= ?
2644
2913
  ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session, since);
2645
- if (!row) return void 0;
2646
- ctx.db.prepare("UPDATE agents SET host_agent_id = ?, launch_requested_at = NULL WHERE session = ? AND name = ?").run(hostAgentId, session, row.name);
2647
- return byHostAgentId(ctx, session, hostAgentId);
2914
+ return row && pairWith(ctx, session, row.name, hostAgentId);
2648
2915
  }
2649
2916
  function byName(ctx, session, name) {
2650
2917
  const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND name = ?").get(session, name);
@@ -2668,7 +2935,7 @@ function stopSubagent(ctx, session, hostAgentId, names = []) {
2668
2935
  publishPending(ctx, session, agent.name);
2669
2936
  return byHostAgentId(ctx, session, hostAgentId);
2670
2937
  }
2671
- ctx.db.prepare("UPDATE agents SET status = 'review', note = ?, updated_at = ? WHERE session = ? AND name = ?").run(STOPPED_NOTE, nowIso(ctx), session, agent.name);
2938
+ moveAgentStatus(ctx, session, agent.name, "review", STOPPED_NOTE);
2672
2939
  logEvent(ctx, session, {
2673
2940
  type: "finished",
2674
2941
  agent: agent.name,
@@ -2780,7 +3047,7 @@ var Carnet = class {
2780
3047
  list: (session, options) => listAgents(this.ctx, session, options),
2781
3048
  reorderQueue: (session, names) => reorderQueue(this.ctx, session, names),
2782
3049
  byHostAgentId: (session, hostAgentId) => byHostAgentId(this.ctx, session, hostAgentId),
2783
- pairSubagent: (session, hostAgentId, names) => pairSubagent(this.ctx, session, hostAgentId, names),
3050
+ pairSubagent: (session, hostAgentId, names, agentType) => pairSubagent(this.ctx, session, hostAgentId, names, agentType),
2784
3051
  unpaired: (session, names) => unpairedAgent(this.ctx, session, names),
2785
3052
  pendingPlan: (session) => pendingPlanAgent(this.ctx, session),
2786
3053
  requestLaunch: (session, name) => requestLaunch(this.ctx, session, name),
@@ -2870,6 +3137,317 @@ function openResolvedCarnet(options = {}) {
2870
3137
  function openWorkspaceCarnet(workspace, options = {}) {
2871
3138
  return new Carnet(openStore(options), workspace, options);
2872
3139
  }
3140
+ // src/report.ts
3141
+ const HEADING = /^##\s+(.+?)\s*$/;
3142
+ const FENCE = /^\s*(```|~~~)/;
3143
+ function normalize(text) {
3144
+ return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "");
3145
+ }
3146
+ function hasSection(markdown, names) {
3147
+ return extractSection(markdown, names) !== void 0;
3148
+ }
3149
+ function headings(lines) {
3150
+ let fenced = false;
3151
+ return lines.map((line) => {
3152
+ if (FENCE.test(line)) fenced = !fenced;
3153
+ return fenced ? void 0 : HEADING.exec(line)?.[1];
3154
+ });
3155
+ }
3156
+ function headingTitle(heading) {
3157
+ const [title = ""] = normalize(heading).replace(/^\d+[.)]\s*/, "").replace(/[*_`]/g, "").split(/[:(]/);
3158
+ return title.trim();
3159
+ }
3160
+ function escape(text) {
3161
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3162
+ }
3163
+ function matchRank(heading, names) {
3164
+ const title = headingTitle(heading);
3165
+ if (names.some((name) => title === name || title === `${name}s`)) return 1;
3166
+ return names.some((name) => new RegExp(`(^|[^a-z0-9])${escape(name)}s?($|[^a-z0-9])`).test(title)) ? 2 : 0;
3167
+ }
3168
+ function extractSection(markdown, names) {
3169
+ const wanted = names.map(normalize);
3170
+ const lines = markdown.split("\n");
3171
+ const titles = headings(lines);
3172
+ const ranks = titles.map((heading) => heading === void 0 ? 0 : matchRank(heading, wanted));
3173
+ const exact = ranks.indexOf(1);
3174
+ const start = exact !== -1 ? exact : ranks.indexOf(2);
3175
+ if (start === -1) return void 0;
3176
+ const end = titles.findIndex((heading, index) => index > start && heading !== void 0);
3177
+ return lines.slice(start + 1, end === -1 ? void 0 : end).join("\n").trim();
3178
+ }
3179
+ function readReport(path) {
3180
+ return path && existsSync(path) ? readFileSync(path, "utf8") : void 0;
3181
+ }
3182
+ function appendToReport(path, markdown) {
3183
+ const current = readReport(path);
3184
+ if (current === void 0 || !path) return;
3185
+ const separator = current.endsWith("\n\n") ? "" : current.endsWith("\n") ? "\n" : "\n\n";
3186
+ appendFileSync(path, `${separator}${markdown.trimEnd()}\n`);
3187
+ }
3188
+ function keptReportPath(report, kind) {
3189
+ return report.replace(/(\.md)?$/, kind === "plan" ? ".plan.md" : ".research.md");
3190
+ }
3191
+ // src/kinds.ts
3192
+ function kindAction(agent) {
3193
+ return KIND_ACTIONS[agent.kind];
3194
+ }
3195
+ function finishWithItems(carnet, session, name, input) {
3196
+ const agent = requireAgent(carnet, session, name);
3197
+ if (input.findings?.length && agent.kind !== "review") throw new CarnetError("INVALID_KIND", `Only a review agent reports findings; ${name} is ${agent.kind}`);
3198
+ const report = readReport(input.reportPath);
3199
+ if (input.questions?.length) {
3200
+ const open = carnet.questions.add(session, name, input.questions).filter((question) => question.answer === null);
3201
+ if (report !== void 0 && !hasSection(report, ["questions"])) appendToReport(input.reportPath, renderQuestions(open));
3202
+ }
3203
+ if (input.findings?.length) {
3204
+ const findings = carnet.findings.replace(session, name, input.findings);
3205
+ if (report !== void 0 && !hasSection(report, ["findings"])) appendToReport(input.reportPath, renderFindings(findings));
3206
+ }
3207
+ const openQuestions = carnet.questions.list(session, name, true).length;
3208
+ return carnet.agents.finish(session, name, {
3209
+ reportPath: input.reportPath,
3210
+ hasQuestions: openQuestions > 0 || input.hasQuestions === true
3211
+ });
3212
+ }
3213
+ function requireAgent(carnet, session, name) {
3214
+ const agent = carnet.agents.get(session, name);
3215
+ if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
3216
+ return agent;
3217
+ }
3218
+ function locateAgent(carnet, name) {
3219
+ const found = carnet.sessions.list({ includeTemp: true }).flatMap((session) => {
3220
+ const agent = carnet.agents.get(session.id, name);
3221
+ return agent ? [{
3222
+ session,
3223
+ agent
3224
+ }] : [];
3225
+ });
3226
+ const open = found.filter((entry) => entry.agent.status !== "closed");
3227
+ const only = found.length === 1 ? found[0] : open.length === 1 ? open[0] : void 0;
3228
+ if (only) return only;
3229
+ if (found.length === 0) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in the open sessions of this workspace`);
3230
+ throw new CarnetError("AGENT_AMBIGUOUS", `"${name}" is in several sessions: ${found.map((entry) => entry.session.name ?? shortId(entry.session.id)).join(", ")}; pass --session`);
3231
+ }
3232
+ function nextAgent(carnet, session, prefix) {
3233
+ if (!prefix) return carnet.status.view(carnet.sessions.require(session)).waiting[0]?.name;
3234
+ if (carnet.agents.get(session, prefix)) return prefix;
3235
+ const matches = carnet.agents.list(session, { includeClosed: true }).filter((agent) => agent.name.startsWith(prefix)).map((agent) => agent.name);
3236
+ if (matches.length === 1) return matches[0];
3237
+ if (matches.length === 0) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${prefix}" in this session`);
3238
+ throw new CarnetError("AGENT_AMBIGUOUS", `"${prefix}" matches ${matches.join(", ")}: which one?`);
3239
+ }
3240
+ function formatQuestion(question) {
3241
+ const lines = [`${question.n}/${question.total} ${question.text}`];
3242
+ if (question.context) lines.push(` context: ${question.context}`);
3243
+ lines.push(` recommended: ${question.recommendation}`);
3244
+ if (question.alternatives.length) lines.push(` alternatives: ${question.alternatives.join(" | ")}`);
3245
+ return lines.join("\n");
3246
+ }
3247
+ function openQuestionsText(carnet, session, name) {
3248
+ requireAgent(carnet, session, name);
3249
+ const open = carnet.questions.list(session, name, true);
3250
+ if (!open.length) return `${name}: no open questions`;
3251
+ const total = open[0]?.total ?? open.length;
3252
+ return [`${name}: ${open.length} of ${total} open`, ...open.map(formatQuestion)].join("\n");
3253
+ }
3254
+ function today(carnet) {
3255
+ return carnet.now().toISOString().slice(0, 10);
3256
+ }
3257
+ function answerQuestionsText(carnet, session, name, answers) {
3258
+ const agent = requireAgent(carnet, session, name);
3259
+ const questions = carnet.questions.answer(session, name, answers);
3260
+ const lines = [...answers].sort((a, b) => a.n - b.n).map((answer) => `${answer.n}. ${answer.answer.trim()}`);
3261
+ appendToReport(agent.reportPath, `## Answers (${today(carnet)})\n\n${lines.join("\n")}`);
3262
+ const open = questions.filter((question) => question.answer === null).length;
3263
+ if (open) return `answered ${answers.length} · ${open} of ${questions.length} open`;
3264
+ const next = statusAfterAnswers(agent.kind);
3265
+ carnet.events.log(session, {
3266
+ type: "answered",
3267
+ agent: name
3268
+ });
3269
+ carnet.agents.update(session, name, {
3270
+ status: next,
3271
+ note: null
3272
+ });
3273
+ return `all ${questions.length} answered · ${EMOJI[next]} ${name} ${next}`;
3274
+ }
3275
+ const FOR_MAIN = ["for the main", "pour le main"];
3276
+ const PLAN = ["plan"];
3277
+ function injectReport(carnet, session, name, input) {
3278
+ const agent = requireAgent(carnet, session, name);
3279
+ const report = readReport(agent.reportPath);
3280
+ if (report === void 0) throw new CarnetError("REPORT_MISSING", `${name} has no report to inject yet`);
3281
+ const names = input.section ? [input.section] : agent.kind === "plan" || agent.promotedFrom === "plan" ? PLAN : FOR_MAIN;
3282
+ const text = input.full ? report.trim() : extractSection(report, names);
3283
+ if (text === void 0) throw new CarnetError("SECTION_NOT_FOUND", `No "## ${names[0]}" section in ${name}'s report; pass section or full`);
3284
+ const lineCount = text.split("\n").length;
3285
+ const note = `${input.full ? "full report" : names[0]}, ${lineCount} lines`;
3286
+ let removed = false;
3287
+ if (agent.kind === "research" && agent.status !== "closed") removed = carnet.agents.close(session, name, {
3288
+ type: "injected",
3289
+ note,
3290
+ link: agent.reportPath ?? void 0
3291
+ }).sandboxRemoved;
3292
+ else carnet.events.log(session, {
3293
+ type: "injected",
3294
+ agent: name,
3295
+ note
3296
+ });
3297
+ const confirmation = `${name} injected (${lineCount} lines)${sandboxRemovedSuffix(removed)}`;
3298
+ return input.echo === false ? confirmation : `${confirmation}\n${text}`;
3299
+ }
3300
+ function firstLines(text, max) {
3301
+ if (!text) return [];
3302
+ const lines = text.split("\n").filter((line) => line.trim() !== "");
3303
+ return lines.length > max ? [...lines.slice(0, max), "…"] : lines;
3304
+ }
3305
+ function firstParagraph(text, max) {
3306
+ return firstLines(text?.split(/\n\s*\n/)[0], max);
3307
+ }
3308
+ const TOP_LEVEL_ITEM = /^(-|\*|\d+\.)\s|^\*\*/;
3309
+ function topLevelItems(text, max) {
3310
+ return firstLines(text?.split("\n").filter((line) => TOP_LEVEL_ITEM.test(line)).join("\n"), max);
3311
+ }
3312
+ function planSteps(plan) {
3313
+ if (!plan) return [];
3314
+ const headings = plan.split("\n").filter((line) => /^###\s/.test(line));
3315
+ return (headings.length > 0 ? headings : plan.split("\n").filter((line) => /^\d+\.\s/.test(line))).map((line) => line.replace(/^###\s+/, "").trim());
3316
+ }
3317
+ function block(title, lines) {
3318
+ return lines.length > 0 ? [`${title}:`, ...lines] : [];
3319
+ }
3320
+ function reportSummary(carnet, session, name) {
3321
+ const agent = requireAgent(carnet, session, name);
3322
+ const report = readReport(agent.reportPath);
3323
+ if (report === void 0) throw new CarnetError("REPORT_MISSING", `${name} has no report yet`);
3324
+ const section = (...names) => extractSection(report, names);
3325
+ const emoji = agent.status === "closed" ? "" : `${EMOJI[agent.status]} `;
3326
+ const lines = [`${name} ${kindTag(agent.kind)} ${emoji}→ ${kindAction(agent)}`];
3327
+ if (agent.kind === "research") lines.push(...block("For the main", firstLines(section(...FOR_MAIN), 15)), ...block("Gaps", firstLines(section("gaps"), 3)));
3328
+ else if (agent.kind === "plan") {
3329
+ const plan = section(...PLAN);
3330
+ const steps = planSteps(plan);
3331
+ const open = carnet.questions.list(session, name, true).length;
3332
+ const understanding = section("understanding");
3333
+ lines.push(...block("Understanding", steps.length > 0 ? firstParagraph(understanding, 5) : firstLines(understanding, 15)), ...steps.length > 0 ? block(`Plan, ${steps.length} steps`, steps) : [`Plan: ${firstLines(plan, 1)[0] ?? "none"}`], `Questions: ${open} open`);
3334
+ } else if (agent.kind === "implement") lines.push(...block("Done", topLevelItems(section("done"), 8)), ...block("Deviations", firstLines(section("deviations"), 6)), ...block("Risks", firstLines(section("risks"), 6)), ...block("Commit message", firstLines(section("commit message")?.replace(/```\w*/g, ""), 1)));
3335
+ else {
3336
+ const pending = carnet.findings.list(session, name, true);
3337
+ const bySeverity = [
3338
+ "blocking",
3339
+ "to_fix",
3340
+ "suggestion"
3341
+ ].map((severity) => [severity, pending.filter((f) => f.severity === severity).length]).filter(([, count]) => count > 0).map(([severity, count]) => `${count} ${severity.replace("_", " ")}`);
3342
+ lines.push(...block("Verdict", firstLines(section("verdict"), 1)), `Findings: ${bySeverity.length > 0 ? bySeverity.join(", ") : "none pending"}`, ...block("Not verified", firstLines(section("not verified"), 3)));
3343
+ }
3344
+ if (!hasSection(report, [
3345
+ ...FOR_MAIN,
3346
+ ...PLAN,
3347
+ "understanding",
3348
+ "done",
3349
+ "verdict"
3350
+ ])) lines.push(...block("Report", firstLines(report.replace(/^#[^\n]*\n/, ""), 10)));
3351
+ lines.push(`report: ${agent.reportPath}`);
3352
+ return lines.join("\n");
3353
+ }
3354
+ function decisions(questions) {
3355
+ return questions.flatMap((question) => [
3356
+ `${question.n}. ${question.text}`,
3357
+ ` Recommended: ${question.recommendation}`,
3358
+ ` Answered: ${question.answer ?? "open"}`
3359
+ ]);
3360
+ }
3361
+ function reportDocument(carnet, session, name) {
3362
+ const agent = requireAgent(carnet, session, name);
3363
+ const report = readReport(agent.reportPath);
3364
+ if (report === void 0 || !agent.reportPath) throw new CarnetError("REPORT_MISSING", `${name} has no report yet`);
3365
+ const understanding = extractSection(report, ["understanding"]);
3366
+ const plan = extractSection(report, PLAN);
3367
+ if (agent.kind !== "plan" || plan === void 0) return {
3368
+ text: report.trimEnd(),
3369
+ path: agent.reportPath
3370
+ };
3371
+ const questions = carnet.questions.list(session, name);
3372
+ const lines = [`# ${name} ${kindTag(agent.kind)}: the plan as answered`];
3373
+ if (understanding !== void 0) lines.push("", "## Understanding", "", understanding);
3374
+ lines.push("", "## Plan", "", plan);
3375
+ if (questions.length > 0) lines.push("", "## Decisions", "", ...decisions(questions));
3376
+ return {
3377
+ text: lines.join("\n"),
3378
+ path: agent.reportPath
3379
+ };
3380
+ }
3381
+ function promoteText(carnet, session, name, input) {
3382
+ const current = requireAgent(carnet, session, name);
3383
+ const agent = carnet.agents.promote(session, name, input);
3384
+ const lines = [`${EMOJI.running} ${name} promoted to ${agent.kind}`];
3385
+ const from = current.kind;
3386
+ if ((from === "research" || from === "plan") && current.reportPath) {
3387
+ if (existsSync(current.reportPath)) {
3388
+ const kept = keptReportPath(current.reportPath, from);
3389
+ copyFileSync(current.reportPath, kept);
3390
+ lines.push(`${from === "plan" ? "plan" : "research"} kept: ${kept}`);
3391
+ }
3392
+ }
3393
+ if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);
3394
+ if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);
3395
+ if (agent.sandbox) lines.push(`sandbox kept: ${agent.sandbox}`);
3396
+ if (agent.sandboxRemoved) lines.push("sandbox removed");
3397
+ return lines.join("\n");
3398
+ }
3399
+ function reviewContext(carnet, session, target) {
3400
+ const range = mainTargetRange(target);
3401
+ if (range !== void 0) return range ? `target main, commits ${range}` : "target main, the uncommitted changes of the main repo";
3402
+ const agent = requireAgent(carnet, session, target);
3403
+ if (agent.kind !== "implement") throw new CarnetError("INVALID_TARGET", `${target} is ${agent.kind}, not implement`);
3404
+ const lines = [`target ${target} (implement${agent.promotedFrom ? `, promoted from ${agent.promotedFrom}` : ""}, ${agent.status})`];
3405
+ if (agent.task) lines.push(`task: ${agent.task}`);
3406
+ if (agent.reportPath) lines.push(`report: ${agent.reportPath}`);
3407
+ if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);
3408
+ if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);
3409
+ for (const kind of ["research", "plan"]) {
3410
+ const kept = agent.reportPath ? keptReportPath(agent.reportPath, kind) : null;
3411
+ if (kept && existsSync(kept)) lines.push(`${kind === "plan" ? "plan" : "research"}: ${kept}`);
3412
+ }
3413
+ const answered = carnet.questions.list(session, target).filter((question) => question.answer);
3414
+ if (answered.length) {
3415
+ lines.push("answers:");
3416
+ for (const question of answered) lines.push(` ${question.n}. ${question.text} → ${question.answer}`);
3417
+ }
3418
+ return lines.join("\n");
3419
+ }
3420
+ function findingsText(carnet, session, name, pendingOnly) {
3421
+ const agent = requireAgent(carnet, session, name);
3422
+ const findings = carnet.findings.list(session, name, pendingOnly);
3423
+ const all = carnet.findings.list(session, name);
3424
+ if (!findings.length) return `${name}: ${all.length ? "no pending findings" : "no findings"}`;
3425
+ const pending = all.filter((finding) => finding.decision === null).length;
3426
+ const target = agent.target ? ` · target ${agent.target}` : "";
3427
+ return [`${name}: ${pending} of ${all.length} pending${target}`, ...findings.map((finding) => {
3428
+ const decided = finding.decision ? ` → ${finding.decision}` : "";
3429
+ return `${formatFinding(finding)}${decided}`;
3430
+ })].join("\n");
3431
+ }
3432
+ function decideText(carnet, session, name, decisions) {
3433
+ const agent = requireAgent(carnet, session, name);
3434
+ if (agent.kind !== "review") throw new CarnetError("INVALID_KIND", `${name} is ${agent.kind}, not review`);
3435
+ if (decisions.some((item) => item.decision === "sent") && agent.target && mainTargetRange(agent.target) !== void 0) throw new CarnetError("INVALID_TARGET", `${name} reviews main: there is no agent to send findings to; fix or ignore them`);
3436
+ const findings = carnet.findings.decide(session, name, decisions);
3437
+ const pending = findings.filter((finding) => finding.decision === null).length;
3438
+ if (pending) return `decided ${decisions.length} · ${pending} of ${findings.length} pending`;
3439
+ const count = (decision) => findings.filter((finding) => finding.decision === decision).length;
3440
+ const note = `${count("sent")} sent, ${count("fixed")} fixed, ${count("ignored")} ignored`;
3441
+ carnet.agents.close(session, name, {
3442
+ type: "triaged",
3443
+ note,
3444
+ link: agent.reportPath ?? void 0
3445
+ });
3446
+ const lines = [`${name} triaged: ${note}, closed`];
3447
+ const sent = findings.filter((finding) => finding.decision === "sent");
3448
+ if (sent.length && agent.target) lines.push(`send to ${agent.target}:`, ...sent.map(formatFinding));
3449
+ return lines.join("\n");
3450
+ }
2873
3451
  // src/resume.ts
2874
3452
  const RESUME_EVENTS = 20;
2875
3453
  const RESUME_MAX_CHARACTERS = 2e3;
@@ -2963,6 +3541,6 @@ function stepAgent(carnet, session, input) {
2963
3541
  }
2964
3542
  }
2965
3543
  }
2966
- export { repoPathFor as $, renderFindings as $t, renderNotesSummary as A, KIND_ABBREVIATIONS as An, rulesVersion as At, DEFAULT_HALF_LIFE_DAYS as B, isUserActionStatus as Bn, definitionInstructions as Bt, NOTES_FOLD_LINES as C, mainTargetRange as Cn, SUBAGENT_RULES as Ct, renderMainLine as D, sanitizeNote as Dn, compactReminder as Dt, renderAgentLine as E, NOTE_MAX as En, baseRules as Et, purgeDays as F, MAIN_WAITING_EMOJI as Fn, AGENTS_FILE as Ft, isNoteKind as G, CarnetError as Gn, loadWorkspace as Gt, NOTE_KINDS as H, EVENT_TYPES as Hn, expandHome as Ht, sandboxRemovedSuffix as I, MAIN_WORKING_EMOJI as In, INSTRUCTIONS_FILE as It, sessionNoteActivity as J, workspaceHosts as Jt, localDay as K, removeWorkspaceRepo as Kt, MEMORY_MAX_CHARACTERS as L, OPEN_AGENT_STATUSES as Ln, WORKSPACE_FILE as Lt, renderStatus as M, KIND_TAG_PATTERN as Mn, CORE_RULES as Mt, renderTableLine as N, LEGEND as Nn, MINIMUM_ID_PREFIX as Nt, renderNoteLine as O, AGENT_STATUSES as On, outsideRucherContext as Ot, DEFAULT_PURGE_DAYS as P, MAIN_FAILED_EMOJI as Pn, shortId as Pt, repoNameFor as Q, formatFinding as Qt, memoryMaxCharacters as R, USER_ACTION_STATUSES as Rn, addWorkspaceRepo as Rt, MAIN_WORKING_SUFFIX as S, isAgentKind as Sn, RULES_UPDATED_NOTICE as St, SIMILAR_PREFIX as T, statusWhenDone as Tn, assemblePrompt as Tt, NOTE_TEXT_LIMIT as U, SESSION_EVENT_TYPES as Un, isWorkspaceName as Ut, DUPLICATE_SIMILARITY as V, kindTag as Vn, dropWorkspace as Vt, STALE_AFTER_ACTIVE_DAYS as W, isEventType as Wn, listWorkspaces as Wt, workspaceRepoNames as X, FINDING_DECISIONS as Xt, similarity as Y, renderQuestions as Yt, isInside as Z, FINDING_SEVERITIES as Zt, BLOCKED_HEADER as _, KIND_REQUIRED as _n, mergeSettings as _t, formatEventLine as a, reportsDirectory as an, sessionWorkspaceName as at, MAIN_IDLE as b, REPORTING_NOTE as bn, OUTSIDE_RUCHER_NOTICE as bt, Carnet as c, workspaceDefinition as cn, DEFAULT_HOST as ct, openWorkspaceCarnet as d, openDatabase as dn, claudeCode as dt, corePromptPath as en, requireWorkspace as et, PAIRING_WINDOW_MILLISECONDS as f, migrate as fn, transcriptTitle as ft, TURNS as g, KIND_ACTIONS as gn, markdownCopy as gt, formatClock as h, AGENT_KINDS as hn, MARKDOWN_MARKER as ht, RESUME_MAX_CHARACTERS as i, reportPath as in, deleteWorkspaceNotes as it, renderSections as j, KIND_LEGEND as jn, workspaceRules as jt, renderNotes as k, EMOJI as kn, rulesText as kt, openCarnet as l, workspacesDirectory as ln, allHosts as lt, buildStatusView as m, schemaVersion as mn, GENERATED_MARKER as mt, stepAgent as n, defaultRunDirectory as nn, workspaceLabel as nt, resumeContext as o, rucherPaths as on, workspaceLastActive as ot, STOPPED_NOTE as p, migrations as pn, workspaceSettings as pt, memoryHalfLife as q, workspaceExists as qt, RESUME_EVENTS as r, promptsDirectory as rn, archiveWorkspaceSessions as rt, sessionLabel as s, sandboxesDirectory as sn, workspaceSessionCounts as st, AGENT_STEPS as t, databasePath as tn, resolveWorkspace as tt, openResolvedCarnet as u, MEMORY_DB as un, hostById as ut, MAIN_FAILED_SUFFIX as v, PROMOTE_KIND_REQUIRED as vn, removeStaleCopies as vt, NOTES_HEADER as w, statusAfterAnswers as wn, appendPromptFile as wt, MAIN_WAITING_SUFFIX as x, SANDBOX_KINDS as xn, PROMPT_FILE as xt, MAIN_HEADER as y, PUBLISH_FALLBACK_MILLISECONDS as yn, writeGenerated as yt, renderMemory as z, isAgentStatus as zn, createWorkspace as zt };
3544
+ export { DEFAULT_HALF_LIFE_DAYS as $, MAIN_WORKING_EMOJI as $n, rulesVersion as $t, BLOCKED_HEADER as A, MEMORY_DB as An, claudeConfigFile as At, renderMainLine as B, SANDBOX_KINDS as Bn, mergeSettings as Bt, openResolvedCarnet as C, promptsDirectory as Cn, workspaceLastActive as Ct, buildStatusView as D, sandboxesDirectory as Dn, allHosts as Dt, STOPPED_NOTE as E, rucherPaths as En, DEFAULT_HOST as Et, MAIN_WORKING_SUFFIX as F, AGENT_KINDS as Fn, moveTracked as Ft, renderStatus as G, AGENT_STATUSES as Gn, RULES_UPDATED_NOTICE as Gt, renderNotes as H, statusWhenDone as Hn, writeGenerated as Ht, NOTES_FOLD_LINES as I, KIND_REQUIRED as In, relocateFailed as It, purgeDays as J, KIND_LEGEND as Jn, assemblePrompt as Jt, renderTableLine as K, EMOJI as Kn, SUBAGENT_RULES as Kt, NOTES_HEADER as L, PROMOTE_KIND_REQUIRED as Ln, GENERATED_MARKER as Lt, MAIN_HEADER as M, migrate as Mn, transcriptTitle as Mt, MAIN_IDLE as N, migrations as Nn, workspaceSettings as Nt, formatClock as O, workspaceDefinition as On, hostById as Ot, MAIN_WAITING_SUFFIX as P, schemaVersion as Pn, UndoList as Pt, renderMemory as Q, MAIN_WAITING_EMOJI as Qn, rulesText as Qt, SIMILAR_PREFIX as R, PUBLISH_FALLBACK_MILLISECONDS as Rn, MARKDOWN_MARKER as Rt, openCarnet as S, defaultRunDirectory as Sn, sessionWorkspaceName as St, PAIRING_WINDOW_MILLISECONDS as T, reportsDirectory as Tn, workspaceSessionCounts as Tt, renderNotesSummary as U, NOTE_MAX as Un, OUTSIDE_RUCHER_NOTICE as Ut, renderNoteLine as V, isAgentKind as Vn, removeStaleCopies as Vt, renderSections as W, sanitizeNote as Wn, PROMPT_FILE as Wt, MEMORY_MAX_CHARACTERS as X, LEGEND as Xn, compactReminder as Xt, sandboxRemovedSuffix as Y, KIND_TAG_PATTERN as Yn, baseRules as Yt, memoryMaxCharacters as Z, MAIN_FAILED_EMOJI as Zn, outsideRucherContext as Zt, promoteText as _, workspaceHosts as _n, deleteWorkspaceNotes as _t, formatEventLine as a, INSTRUCTIONS_FILE as an, EVENT_TYPES as ar, localDay as at, reviewContext as b, corePromptPath as bn, renameWorkspaceRows as bt, answerQuestionsText as c, createWorkspace as cn, CarnetError as cr, similarity as ct, finishWithItems as d, expandHome as dn, repoNameFor as dt, workspaceRules as en, OPEN_AGENT_STATUSES as er, DUPLICATE_SIMILARITY as et, injectReport as f, isWorkspaceName as fn, repoPathFor as ft, openQuestionsText as g, workspaceExists as gn, archiveWorkspaceSessions as gt, nextAgent as h, removeWorkspaceRepo as hn, workspaceLabel as ht, RESUME_MAX_CHARACTERS as i, AGENTS_FILE as in, kindTag as ir, isNoteKind as it, MAIN_FAILED_SUFFIX as j, openDatabase as jn, claudeProjectFolder as jt, TURNS as k, workspacesDirectory as kn, claudeCode as kt, decideText as l, definitionInstructions as ln, workspaceRepoNames as lt, locateAgent as m, loadWorkspace as mn, resolveWorkspace as mt, stepAgent as n, MINIMUM_ID_PREFIX as nn, isAgentStatus as nr, NOTE_TEXT_LIMIT as nt, resumeContext as o, WORKSPACE_FILE as on, SESSION_EVENT_TYPES as or, memoryHalfLife as ot, kindAction as p, listWorkspaces as pn, requireWorkspace as pt, DEFAULT_PURGE_DAYS as q, KIND_ABBREVIATIONS as qn, appendPromptFile as qt, RESUME_EVENTS as r, shortId as rn, isUserActionStatus as rr, STALE_AFTER_ACTIVE_DAYS as rt, sessionLabel as s, addWorkspaceRepo as sn, isEventType as sr, sessionNoteActivity as st, AGENT_STEPS as t, CORE_RULES as tn, USER_ACTION_STATUSES as tr, NOTE_KINDS as tt, findingsText as u, dropWorkspace as un, isInside as ut, reportDocument as v, FINDING_DECISIONS as vn, mergeWorkspaceRows as vt, openWorkspaceCarnet as w, reportPath as wn, workspaceRowCounts as wt, Carnet as x, databasePath as xn, runningWorkspaceSessions as xt, reportSummary as y, FINDING_SEVERITIES as yn, nextNoteNumber as yt, renderAgentLine as z, REPORTING_NOTE as zn, markdownCopy as zt };
2967
3545
 
2968
- //# sourceMappingURL=steps-wNm8GU_c.mjs.map
3546
+ //# sourceMappingURL=steps-j8vhVj8h.mjs.map