@rucher/carnet 0.2.0 → 0.3.0-beta.1

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";
@@ -24,7 +24,10 @@ const EVENT_TYPES = [
24
24
  "applied",
25
25
  "tested",
26
26
  "committed",
27
- "dropped"
27
+ "dropped",
28
+ "injected",
29
+ "promoted",
30
+ "triaged"
28
31
  ];
29
32
  const SESSION_EVENT_TYPES = [
30
33
  "session.started",
@@ -53,9 +56,10 @@ function logEvent(ctx, session, input) {
53
56
  const result = ctx.db.prepare("INSERT INTO events (session, at, type, agent, commit_sha, link, note) VALUES (?, ?, ?, ?, ?, ?, ?)").run(session, nowIso(ctx), input.type, input.agent ?? null, input.commit ?? null, input.link ?? null, input.note ?? null);
54
57
  return toEvent(ctx.db.prepare("SELECT * FROM events WHERE id = ?").get(result.lastInsertRowid));
55
58
  }
56
- function readEvents(ctx, { session, limit = 20, agentOnly = false }) {
57
- const filter = agentOnly ? "AND type NOT LIKE 'session.%'" : "";
58
- return ctx.db.prepare(`SELECT * FROM (SELECT * FROM events WHERE session = ? ${filter} ORDER BY at DESC, id DESC LIMIT ?) ORDER BY at, id`).all(session, limit).map(toEvent);
59
+ function readEvents(ctx, { session, limit = 20, agentOnly = false, kind }) {
60
+ const filters = [agentOnly ? "AND type NOT LIKE 'session.%'" : "", kind ? "AND agent IN (SELECT name FROM agents WHERE session = events.session AND kind = ?)" : ""].join(" ");
61
+ const parameters = kind ? [session, kind] : [session];
62
+ return ctx.db.prepare(`SELECT * FROM (SELECT * FROM events WHERE session = ? ${filters} ORDER BY at DESC, id DESC LIMIT ?) ORDER BY at, id`).all(...parameters, limit).map(toEvent);
59
63
  }
60
64
  // src/status/model.ts
61
65
  const AGENT_STATUSES = [
@@ -65,8 +69,6 @@ const AGENT_STATUSES = [
65
69
  "review",
66
70
  "apply",
67
71
  "test",
68
- "commit",
69
- "branch",
70
72
  "closed"
71
73
  ];
72
74
  const USER_ACTION_STATUSES = [
@@ -74,9 +76,7 @@ const USER_ACTION_STATUSES = [
74
76
  "answer",
75
77
  "review",
76
78
  "apply",
77
- "test",
78
- "commit",
79
- "branch"
79
+ "test"
80
80
  ];
81
81
  const EMOJI = {
82
82
  running: "⏳",
@@ -84,12 +84,23 @@ const EMOJI = {
84
84
  answer: "❓",
85
85
  review: "👀",
86
86
  apply: "📥",
87
- test: "🧪",
88
- commit: "✅",
89
- branch: "🌿"
87
+ test: "🧪"
90
88
  };
91
89
  const MAIN_WORKING_EMOJI = "⚙️";
92
- const LEGEND = "⚙️ main working · 💬 discussing · ❓ answer · 👀 review · 📥 apply · 🧪 test · ✅ commit · 🌿 branch · ⏳ running";
90
+ const MAIN_WAITING_EMOJI = "⏸";
91
+ const MAIN_FAILED_EMOJI = "⚠";
92
+ const LEGEND = "⚙️ main working · ⏸ waiting on you · ⚠ turn failed · 💬 discussing · ❓ answer · 👀 review · 📥 apply · 🧪 test · ⏳ running";
93
+ const KIND_ABBREVIATIONS = {
94
+ research: "rs",
95
+ plan: "pl",
96
+ implement: "im",
97
+ review: "rv"
98
+ };
99
+ function kindTag(kind) {
100
+ return `[${KIND_ABBREVIATIONS[kind]}]`;
101
+ }
102
+ const KIND_TAG_PATTERN = /\[(?:rs|pl|im|rv)\]/;
103
+ const KIND_LEGEND = "[rs] research · [pl] plan · [im] implement · [rv] review";
93
104
  function isAgentStatus(value) {
94
105
  return typeof value === "string" && AGENT_STATUSES.includes(value);
95
106
  }
@@ -112,30 +123,81 @@ function sanitizeNote(text) {
112
123
  return `${cleaned.slice(0, 59).trimEnd()}…`;
113
124
  }
114
125
  // src/agents.ts
126
+ const AGENT_KINDS = [
127
+ "research",
128
+ "plan",
129
+ "implement",
130
+ "review"
131
+ ];
132
+ const KIND_REQUIRED = "kind is required: research, plan, implement or review";
133
+ const KIND_ACTIONS = {
134
+ research: "inject",
135
+ plan: "validate",
136
+ implement: "apply",
137
+ review: "triage"
138
+ };
139
+ function isAgentKind(value) {
140
+ return typeof value === "string" && AGENT_KINDS.includes(value);
141
+ }
142
+ const MAIN_TARGET = /^main(?::(.+))?$/;
143
+ function mainTargetRange(target) {
144
+ const match = MAIN_TARGET.exec(target);
145
+ return match ? match[1]?.trim() ?? null : void 0;
146
+ }
147
+ const SANDBOX_KINDS = ["research", "plan"];
115
148
  function toAgent(row) {
116
149
  return {
117
150
  session: row.session,
118
151
  name: row.name,
152
+ kind: row.kind,
153
+ promotedFrom: row.promoted_from,
154
+ target: row.target,
155
+ blockedOn: row.blocked_on,
119
156
  task: row.task,
120
157
  status: row.status,
121
158
  note: row.note,
122
159
  reportPath: row.report_path,
123
160
  baseCommit: row.base_commit,
124
161
  worktree: row.worktree,
162
+ sandbox: row.sandbox,
125
163
  queueOrder: row.queue_order,
126
164
  hostAgentId: row.host_agent_id,
127
165
  pendingStatus: row.pending_status,
128
166
  doneAt: row.done_at,
129
167
  startedAt: row.started_at,
130
- updatedAt: row.updated_at
168
+ updatedAt: row.updated_at,
169
+ statusSince: row.status_since ?? row.updated_at
131
170
  };
132
171
  }
133
172
  const REPORTING_NOTE = "reporting";
134
173
  const PUBLISH_FALLBACK_MILLISECONDS = 12e4;
174
+ function statusChangeSql(next) {
175
+ return `status_since = CASE WHEN status = ${next} THEN status_since ELSE ? END,
176
+ queue_order = CASE WHEN status = ${next} THEN queue_order ELSE NULL END`;
177
+ }
178
+ function statusChangeArgs(next, at) {
179
+ return [
180
+ next,
181
+ at,
182
+ next
183
+ ];
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
+ }
135
195
  function publishPending(ctx, session, name) {
136
196
  const row = ctx.db.prepare("SELECT pending_status, report_path FROM agents WHERE session = ? AND name = ?").get(session, name);
137
197
  if (!row?.pending_status) return;
138
- ctx.db.prepare("UPDATE agents SET status = pending_status, pending_status = NULL, note = NULL, updated_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
198
+ ctx.db.prepare(`UPDATE agents SET status = pending_status, pending_status = NULL, note = NULL,
199
+ ${statusChangeSql("pending_status")}, updated_at = ?
200
+ WHERE session = ? AND name = ? AND status != 'closed'`).run(nowIso(ctx), nowIso(ctx), session, name);
139
201
  logEvent(ctx, session, {
140
202
  type: "finished",
141
203
  agent: name,
@@ -144,7 +206,7 @@ function publishPending(ctx, session, name) {
144
206
  }
145
207
  function publishOverdue(ctx, session) {
146
208
  const before = (/* @__PURE__ */ new Date(ctx.now().getTime() - PUBLISH_FALLBACK_MILLISECONDS)).toISOString();
147
- 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);
148
210
  for (const row of rows) publishPending(ctx, session, row.name);
149
211
  }
150
212
  function getAgent(ctx, session, name) {
@@ -152,51 +214,136 @@ function getAgent(ctx, session, name) {
152
214
  const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND name = ?").get(session, name);
153
215
  return row && toAgent(row);
154
216
  }
155
- function requireAgent(ctx, session, name) {
217
+ function requireAgent$1(ctx, session, name) {
156
218
  const agent = getAgent(ctx, session, name);
157
219
  if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
158
220
  return agent;
159
221
  }
222
+ function checkReviewTarget(ctx, session, target) {
223
+ if (mainTargetRange(target) !== void 0) return;
224
+ const agent = getAgent(ctx, session, target);
225
+ if (!agent || agent.kind !== "implement") throw new CarnetError("INVALID_TARGET", `Target "${target}" is not an implement agent of this session; use its name, or main[:<range>]`);
226
+ if (agent.status === "running") throw new CarnetError("INVALID_TARGET", `Target "${target}" is still running`);
227
+ if (agent.status === "closed") throw new CarnetError("INVALID_TARGET", `Target "${target}" is closed; review main[:<range>] instead`);
228
+ }
160
229
  function startAgent(ctx, session, input) {
161
230
  const name = sanitizeNote(input.name);
231
+ const kind = input.kind;
232
+ if (!isAgentKind(kind)) throw new CarnetError("INVALID_KIND", KIND_REQUIRED);
233
+ if (input.worktree && kind !== "implement") throw new CarnetError("INVALID_KIND", `A worktree means an implement agent: start ${name} with kind implement, or promote a research or plan agent with agent_promote`);
234
+ const target = input.target?.trim() || null;
235
+ if (kind === "review" && !target) throw new CarnetError("INVALID_TARGET", "A review needs a target: an implement agent name, or main[:<range>]");
236
+ if (kind !== "review" && target) throw new CarnetError("INVALID_TARGET", "Only a review agent takes a target");
237
+ if (target) checkReviewTarget(ctx, session, target);
238
+ if (input.sandbox) checkSandbox(ctx, session, name, kind, input.sandbox);
162
239
  const existing = getAgent(ctx, session, name);
163
240
  if (existing && existing.status !== "closed") throw new CarnetError("AGENT_EXISTS", `Agent "${name}" is already open in this session`);
164
241
  if (existing) ctx.db.prepare("DELETE FROM agents WHERE session = ? AND name = ?").run(session, name);
165
242
  const at = nowIso(ctx);
166
- ctx.db.prepare(`INSERT INTO agents (session, name, task, status, base_commit, worktree, started_at, updated_at)
167
- VALUES (?, ?, ?, 'running', ?, ?, ?, ?)`).run(session, name, input.task, input.baseCommit ?? null, input.worktree ?? null, at, at);
243
+ ctx.db.prepare(`INSERT INTO agents (session, name, kind, target, task, status, base_commit, worktree,
244
+ sandbox, started_at, updated_at, status_since)
245
+ VALUES (?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(session, name, kind, target, input.task, input.baseCommit ?? null, input.worktree ?? null, input.sandbox ?? null, at, at, at);
168
246
  logEvent(ctx, session, {
169
247
  type: "started",
170
248
  agent: name,
171
249
  note: input.task
172
250
  });
173
- return requireAgent(ctx, session, name);
251
+ return requireAgent$1(ctx, session, name);
252
+ }
253
+ function checkSandbox(ctx, session, name, kind, sandbox) {
254
+ if (!SANDBOX_KINDS.includes(kind)) throw new CarnetError("INVALID_KIND", `Only a research or plan agent gets a sandbox; ${name} is ${kind}`);
255
+ const holder = ctx.db.prepare(`SELECT agents.name FROM agents JOIN sessions ON sessions.id = agents.session
256
+ WHERE agents.sandbox = ? AND sessions.workspace = (SELECT workspace FROM sessions WHERE id = ?)
257
+ AND NOT (agents.session = ? AND agents.name = ?)`).get(sandbox, session, session, name);
258
+ if (holder) throw new CarnetError("INVALID_SANDBOX", `${sandbox} is already the sandbox of ${holder.name}`);
259
+ }
260
+ function clearSandbox(ctx, session, name) {
261
+ ctx.db.prepare("UPDATE agents SET sandbox = NULL WHERE session = ? AND name = ?").run(session, name);
262
+ }
263
+ function closedSandboxes(ctx, session) {
264
+ const where = session ? "agents.session = ?" : "agents.session IN (SELECT id FROM sessions WHERE workspace = ?)";
265
+ return ctx.db.prepare(`SELECT session, name, sandbox FROM agents
266
+ WHERE ${where} AND status = 'closed' AND sandbox IS NOT NULL`).all(session ?? ctx.workspace);
267
+ }
268
+ function checkBlocker(ctx, session, name, blocker) {
269
+ if (blocker === name) throw new CarnetError("INVALID_BLOCKER", `Agent "${name}" can't wait on itself`);
270
+ const seen = /* @__PURE__ */ new Set([name]);
271
+ let current = getAgent(ctx, session, blocker);
272
+ if (!current || current.status === "closed") throw new CarnetError("INVALID_BLOCKER", `"${blocker}" is not an open agent of this session`);
273
+ while (current?.blockedOn && current.status !== "closed") {
274
+ if (seen.has(current.blockedOn)) throw new CarnetError("INVALID_BLOCKER", `"${blocker}" already waits on "${name}", directly or through another agent`);
275
+ seen.add(current.name);
276
+ current = getAgent(ctx, session, current.blockedOn);
277
+ }
174
278
  }
175
279
  function updateAgent(ctx, session, name, input) {
176
- const current = requireAgent(ctx, session, name);
280
+ const current = requireAgent$1(ctx, session, name);
177
281
  if (!isAgentStatus(input.status) || input.status === "closed") throw new CarnetError("INVALID_STATUS", `Invalid agent status "${input.status}"; use agent_drop to close`);
178
- const note = input.note === void 0 ? null : sanitizeNote(input.note);
282
+ let note;
283
+ if (input.note !== void 0) note = input.note === null ? null : sanitizeNote(input.note);
284
+ else note = current.status === "running" && input.status !== "running" ? null : current.note;
285
+ let blockedOn = current.blockedOn;
286
+ if (input.blockedOn !== void 0) {
287
+ blockedOn = input.blockedOn === null ? null : sanitizeNote(input.blockedOn);
288
+ if (blockedOn) checkBlocker(ctx, session, name, blockedOn);
289
+ }
179
290
  if (current.pendingStatus) publishPending(ctx, session, name);
180
- ctx.db.prepare("UPDATE agents SET note = COALESCE(?, CASE WHEN status = 'running' AND ? <> 'running' THEN NULL ELSE note END), status = ?, report_path = COALESCE(?, report_path), updated_at = ? WHERE session = ? AND name = ?").run(note, input.status, input.status, input.reportPath ?? null, nowIso(ctx), session, name);
181
- return requireAgent(ctx, session, name);
291
+ ctx.db.prepare(`UPDATE agents SET note = ?, ${statusChangeSql("?")}, status = ?,
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);
293
+ return requireAgent$1(ctx, session, name);
294
+ }
295
+ function statusWhenDone(kind, hasQuestions) {
296
+ if (hasQuestions) return "answer";
297
+ return kind === "implement" ? "apply" : "review";
182
298
  }
183
299
  function finishAgent(ctx, session, name, input) {
184
- const agent = requireAgent(ctx, session, name);
185
- const status = input.hasQuestions ? "answer" : "review";
300
+ const agent = requireAgent$1(ctx, session, name);
301
+ const status = statusWhenDone(agent.kind, input.hasQuestions);
186
302
  const at = nowIso(ctx);
187
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);
188
304
  if (!agent.hostAgentId) publishPending(ctx, session, name);
189
- return requireAgent(ctx, session, name);
305
+ return requireAgent$1(ctx, session, name);
190
306
  }
191
- function dropAgent(ctx, session, name, reason) {
192
- requireAgent(ctx, session, name);
193
- ctx.db.prepare("UPDATE agents SET status = 'closed', queue_order = NULL, updated_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
307
+ function statusAfterAnswers(kind) {
308
+ return kind === "implement" ? "apply" : "review";
309
+ }
310
+ function closeAgent(ctx, session, name, event) {
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);
194
313
  logEvent(ctx, session, {
314
+ ...event,
315
+ agent: name
316
+ });
317
+ return requireAgent$1(ctx, session, name);
318
+ }
319
+ function dropAgent(ctx, session, name, reason) {
320
+ return closeAgent(ctx, session, name, {
195
321
  type: "dropped",
196
- agent: name,
197
322
  note: reason
198
323
  });
199
- return requireAgent(ctx, session, name);
324
+ }
325
+ const PROMOTIONS = {
326
+ research: ["plan", "implement"],
327
+ plan: ["implement"]
328
+ };
329
+ const PROMOTE_KIND_REQUIRED = "kind is required: plan or implement for a research agent, implement for a plan one";
330
+ function promoteAgent(ctx, session, name, input) {
331
+ const agent = requireAgent$1(ctx, session, name);
332
+ const target = input.kind;
333
+ if (!isAgentKind(target)) throw new CarnetError("INVALID_KIND", PROMOTE_KIND_REQUIRED);
334
+ const allowed = PROMOTIONS[agent.kind] ?? [];
335
+ if (!allowed.includes(target)) throw new CarnetError("INVALID_KIND", allowed.length === 0 ? `A ${agent.kind} agent is never promoted; only research and plan are` : `${name} is ${agent.kind}: it is promoted to ${allowed.join(" or ")}, not ${target}`);
336
+ if (input.worktree && target !== "implement") throw new CarnetError("INVALID_KIND", `A worktree means an implement agent: promote ${name} with kind implement`);
337
+ ctx.db.prepare(`UPDATE agents SET kind = ?, promoted_from = ?, status = 'running',
338
+ pending_status = NULL, note = NULL, blocked_on = NULL, worktree = COALESCE(?, worktree),
339
+ base_commit = COALESCE(?, base_commit), queue_order = NULL, status_since = ?, updated_at = ?
340
+ WHERE session = ? AND name = ?`).run(target, agent.kind, input.worktree ?? null, input.baseCommit ?? null, nowIso(ctx), nowIso(ctx), session, name);
341
+ logEvent(ctx, session, {
342
+ type: "promoted",
343
+ agent: name,
344
+ note: `${agent.kind} to ${target}`
345
+ });
346
+ return requireAgent$1(ctx, session, name);
200
347
  }
201
348
  function listAgents(ctx, session, options = {}) {
202
349
  publishOverdue(ctx, session);
@@ -213,6 +360,14 @@ function reorderQueue(ctx, session, names) {
213
360
  return listAgents(ctx, session);
214
361
  }
215
362
  // src/db/schema.ts
363
+ const DISPOSABLE_SESSION = `workspace IS NULL
364
+ AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id)
365
+ AND NOT EXISTS (
366
+ SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
367
+ )
368
+ AND NOT EXISTS (SELECT 1 FROM notes WHERE notes.session = sessions.id OR notes.dropped_session = sessions.id)
369
+ AND NOT EXISTS (SELECT 1 FROM note_citations WHERE note_citations.session = sessions.id)
370
+ AND NOT EXISTS (SELECT 1 FROM sessions AS child WHERE child.parent_id = sessions.id)`;
216
371
  const migrations = [
217
372
  `
218
373
  CREATE TABLE sessions (
@@ -449,24 +604,225 @@ CREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_activ
449
604
  CREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name)
450
605
  WHERE workspace IS NOT NULL AND name IS NOT NULL;
451
606
  CREATE UNIQUE INDEX notes_workspace_number ON notes(workspace, number);
607
+ `,
608
+ `
609
+ DELETE FROM events WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});
610
+ DELETE FROM table_items WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});
611
+ DELETE FROM session_repos WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});
612
+ DELETE FROM sessions WHERE ${DISPOSABLE_SESSION};
613
+
614
+ CREATE TABLE sessions_new (
615
+ id TEXT PRIMARY KEY,
616
+ workspace TEXT NOT NULL,
617
+ name TEXT,
618
+ purpose TEXT,
619
+ kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),
620
+ status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),
621
+ cwd TEXT,
622
+ repo TEXT,
623
+ host TEXT NOT NULL DEFAULT 'claude-code',
624
+ host_pid INTEGER,
625
+ hooked_at TEXT,
626
+ last_title TEXT,
627
+ parent_id TEXT REFERENCES sessions(id),
628
+ prompt_version TEXT,
629
+ created_at TEXT NOT NULL,
630
+ last_active_at TEXT NOT NULL,
631
+ ended_at TEXT,
632
+ turn TEXT CHECK (turn IN ('working', 'waiting', 'failed')),
633
+ turn_started_at TEXT,
634
+ CHECK (kind = 'temp' OR name IS NOT NULL)
635
+ );
636
+ INSERT INTO sessions_new (id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,
637
+ hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)
638
+ SELECT id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,
639
+ hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at
640
+ FROM sessions;
641
+ DROP TABLE sessions;
642
+ ALTER TABLE sessions_new RENAME TO sessions;
643
+ CREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);
644
+ CREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_active_at);
645
+ CREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name) WHERE name IS NOT NULL;
646
+
647
+ ALTER TABLE table_items DROP COLUMN main_working;
648
+
649
+ ALTER TABLE agents ADD COLUMN kind TEXT NOT NULL DEFAULT 'analyze'
650
+ CHECK (kind IN ('research', 'analyze', 'implement', 'review'));
651
+ ALTER TABLE agents ADD COLUMN promoted_from TEXT
652
+ CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review'));
653
+ ALTER TABLE agents ADD COLUMN target TEXT;
654
+ -- Older agents waiting on code steps, or given a worktree, wrote code.
655
+ UPDATE agents SET kind = 'implement'
656
+ WHERE (status IN ('apply', 'test', 'commit')) OR worktree IS NOT NULL;
657
+
658
+ CREATE TABLE agent_questions (
659
+ session TEXT NOT NULL,
660
+ agent TEXT NOT NULL,
661
+ n INTEGER NOT NULL CHECK (n >= 1),
662
+ text TEXT NOT NULL,
663
+ context TEXT,
664
+ recommendation TEXT NOT NULL,
665
+ alternatives TEXT NOT NULL DEFAULT '[]',
666
+ answer TEXT,
667
+ answered_at TEXT,
668
+ PRIMARY KEY (session, agent, n),
669
+ FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE
670
+ );
671
+
672
+ CREATE TABLE review_findings (
673
+ session TEXT NOT NULL,
674
+ agent TEXT NOT NULL,
675
+ n INTEGER NOT NULL CHECK (n >= 1),
676
+ severity TEXT NOT NULL CHECK (severity IN ('blocking', 'to_fix', 'suggestion')),
677
+ location TEXT,
678
+ text TEXT NOT NULL,
679
+ fix TEXT,
680
+ decision TEXT CHECK (decision IN ('sent', 'fixed', 'ignored')),
681
+ reason TEXT,
682
+ decided_at TEXT,
683
+ PRIMARY KEY (session, agent, n),
684
+ FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE
685
+ );
686
+
687
+ CREATE TABLE events_new (
688
+ id INTEGER PRIMARY KEY,
689
+ session TEXT NOT NULL REFERENCES sessions(id),
690
+ at TEXT NOT NULL,
691
+ type TEXT NOT NULL
692
+ CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped',
693
+ 'injected', 'promoted', 'triaged',
694
+ 'session.started', 'session.resumed', 'session.ended', 'session.forked')),
695
+ agent TEXT,
696
+ commit_sha TEXT,
697
+ link TEXT,
698
+ note TEXT
699
+ );
700
+ INSERT INTO events_new SELECT id, session, at, type, agent, commit_sha, link, note FROM events;
701
+ DROP TABLE events;
702
+ ALTER TABLE events_new RENAME TO events;
703
+ CREATE INDEX events_session_at ON events(session, at);
704
+ `,
705
+ `
706
+ -- Testing and committing are one human step, and no step ever led to branch.
707
+ UPDATE agents SET status = 'test' WHERE status IN ('commit', 'branch');
708
+ UPDATE agents SET pending_status = 'test' WHERE pending_status IN ('commit', 'branch');
709
+ UPDATE table_items SET status = 'test' WHERE status IN ('commit', 'branch');
710
+ CREATE TABLE agents_new (
711
+ session TEXT NOT NULL REFERENCES sessions(id),
712
+ name TEXT NOT NULL,
713
+ task TEXT,
714
+ status TEXT NOT NULL
715
+ CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),
716
+ note TEXT,
717
+ report_path TEXT,
718
+ base_commit TEXT,
719
+ worktree TEXT,
720
+ queue_order INTEGER,
721
+ started_at TEXT NOT NULL,
722
+ updated_at TEXT NOT NULL,
723
+ host_agent_id TEXT,
724
+ pending_status TEXT,
725
+ done_at TEXT,
726
+ kind TEXT NOT NULL DEFAULT 'analyze'
727
+ CHECK (kind IN ('research', 'analyze', 'implement', 'review')),
728
+ promoted_from TEXT CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review')),
729
+ target TEXT,
730
+ blocked_on TEXT,
731
+ PRIMARY KEY (session, name)
732
+ );
733
+ INSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,
734
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target)
735
+ SELECT session, name, task, status, note, report_path, base_commit, worktree,
736
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target
737
+ FROM agents;
738
+ DROP TABLE agents;
739
+ ALTER TABLE agents_new RENAME TO agents;
740
+ CREATE INDEX agents_session_status ON agents(session, status);
741
+ -- The CLI and the plugin update separately; the pane warns when the hooks lag behind.
742
+ ALTER TABLE sessions ADD COLUMN plugin_version TEXT;
743
+ `,
744
+ `
745
+ -- A research or analyze agent's throwaway folder under the run directory, writable through the guard.
746
+ ALTER TABLE agents ADD COLUMN sandbox TEXT;
747
+ `,
748
+ `
749
+ -- The analyze kind is now plan. launch_requested_at marks the Agent call that launches an agent,
750
+ -- so the next subagent pairs with it rather than with an older registered one.
751
+ CREATE TABLE agents_new (
752
+ session TEXT NOT NULL REFERENCES sessions(id),
753
+ name TEXT NOT NULL,
754
+ task TEXT,
755
+ status TEXT NOT NULL
756
+ CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),
757
+ note TEXT,
758
+ report_path TEXT,
759
+ base_commit TEXT,
760
+ worktree TEXT,
761
+ queue_order INTEGER,
762
+ started_at TEXT NOT NULL,
763
+ updated_at TEXT NOT NULL,
764
+ host_agent_id TEXT,
765
+ pending_status TEXT,
766
+ done_at TEXT,
767
+ kind TEXT NOT NULL CHECK (kind IN ('research', 'plan', 'implement', 'review')),
768
+ promoted_from TEXT CHECK (promoted_from IN ('research', 'plan', 'implement', 'review')),
769
+ target TEXT,
770
+ blocked_on TEXT,
771
+ sandbox TEXT,
772
+ launch_requested_at TEXT,
773
+ PRIMARY KEY (session, name)
774
+ );
775
+ INSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,
776
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from,
777
+ target, blocked_on, sandbox)
778
+ SELECT session, name, task, status, note, report_path, base_commit, worktree,
779
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at,
780
+ CASE kind WHEN 'analyze' THEN 'plan' ELSE kind END,
781
+ CASE promoted_from WHEN 'analyze' THEN 'plan' ELSE promoted_from END,
782
+ target, blocked_on, sandbox
783
+ FROM agents;
784
+ DROP TABLE agents;
785
+ ALTER TABLE agents_new RENAME TO agents;
786
+ CREATE INDEX agents_session_status ON agents(session, status);
787
+ `,
788
+ `
789
+ -- When the status last changed; rows from before it start from their last update.
790
+ ALTER TABLE agents ADD COLUMN status_since TEXT;
791
+ UPDATE agents SET status_since = updated_at;
452
792
  `
453
793
  ];
794
+ const preconditions = { 11: (db) => {
795
+ const kept = db.prepare(`SELECT id, name FROM sessions WHERE workspace IS NULL AND NOT (${DISPOSABLE_SESSION})`).all();
796
+ if (kept.length === 0) return;
797
+ const list = kept.map((row) => row.name ?? row.id).join(", ");
798
+ throw new Error(`Every session now needs a workspace, and these sessions without one hold agents, notes or forks: ${list}. Give each one a workspace with the previous rucher (rucher sessions move), or in SQL: UPDATE sessions SET workspace = '<name>' WHERE id = '<id>'`);
799
+ } };
454
800
  function schemaVersion(db) {
455
801
  return db.prepare("PRAGMA user_version").get().user_version;
456
802
  }
457
803
  function foreignKeyViolations(db) {
458
804
  return db.prepare("PRAGMA foreign_key_check").all().length;
459
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
+ }
460
811
  function migrate(db) {
461
- const current = schemaVersion(db);
462
- if (current >= migrations.length) return;
812
+ if (knownVersion(db) >= migrations.length) return;
463
813
  const foreignKeys = db.prepare("PRAGMA foreign_keys").get();
464
814
  db.exec("PRAGMA foreign_keys = OFF");
465
815
  try {
466
- for (const [version, migration] of migrations.entries()) {
467
- if (version < current) continue;
468
- db.exec("BEGIN");
816
+ for (;;) {
817
+ db.exec("BEGIN IMMEDIATE");
469
818
  try {
819
+ const version = knownVersion(db);
820
+ const migration = migrations[version];
821
+ if (migration === void 0) {
822
+ db.exec("COMMIT");
823
+ return;
824
+ }
825
+ preconditions[version + 1]?.(db);
470
826
  db.exec(migration);
471
827
  if (foreignKeyViolations(db) > 0) throw new Error(`Migration ${version + 1} broke foreign keys`);
472
828
  db.exec(`PRAGMA user_version = ${version + 1}`);
@@ -482,11 +838,21 @@ function migrate(db) {
482
838
  }
483
839
  // src/db/open.ts
484
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
+ }
485
851
  function openDatabase(path) {
486
852
  const db = new DatabaseSync(path);
487
- if (path !== ":memory:") db.exec("PRAGMA journal_mode = WAL");
488
- db.exec("PRAGMA foreign_keys = ON");
489
853
  db.exec("PRAGMA busy_timeout = 5000");
854
+ if (path !== ":memory:") useWal(db);
855
+ db.exec("PRAGMA foreign_keys = ON");
490
856
  migrate(db);
491
857
  return db;
492
858
  }
@@ -534,9 +900,116 @@ function corePromptPath(env) {
534
900
  function reportsDirectory(workspace) {
535
901
  return join(workspace.runDirectory, "reports");
536
902
  }
903
+ function sandboxesDirectory(workspace) {
904
+ return join(workspace.runDirectory, "sandboxes");
905
+ }
537
906
  function reportPath(workspace, agentName) {
538
907
  return join(reportsDirectory(workspace), `${agentName}.md`);
539
908
  }
909
+ // src/findings.ts
910
+ const FINDING_SEVERITIES = [
911
+ "blocking",
912
+ "to_fix",
913
+ "suggestion"
914
+ ];
915
+ const FINDING_DECISIONS = [
916
+ "sent",
917
+ "fixed",
918
+ "ignored"
919
+ ];
920
+ const SPAWN_KINDS = [
921
+ "implement",
922
+ "plan",
923
+ "research"
924
+ ];
925
+ function recommendedRoute(severity, canSendBack) {
926
+ if (canSendBack) return "send back";
927
+ return severity === "suggestion" ? "in main" : "implement";
928
+ }
929
+ function listFindings(ctx, session, agent, pendingOnly = false) {
930
+ const rows = ctx.db.prepare("SELECT * FROM review_findings WHERE session = ? AND agent = ? ORDER BY n").all(session, agent);
931
+ const total = rows.length;
932
+ return rows.filter((row) => !pendingOnly || row.decision === null).map((row) => ({
933
+ ...row,
934
+ total
935
+ }));
936
+ }
937
+ function replaceFindings(ctx, session, agent, inputs) {
938
+ const sorted = [...inputs].sort((a, b) => FINDING_SEVERITIES.indexOf(a.severity) - FINDING_SEVERITIES.indexOf(b.severity));
939
+ ctx.db.prepare("DELETE FROM review_findings WHERE session = ? AND agent = ?").run(session, agent);
940
+ const insert = ctx.db.prepare(`INSERT INTO review_findings (session, agent, n, severity, location, text, fix)
941
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);
942
+ sorted.forEach((input, index) => {
943
+ insert.run(session, agent, index + 1, input.severity, input.location?.trim() || null, input.text.trim(), input.fix?.trim() || null);
944
+ });
945
+ return listFindings(ctx, session, agent);
946
+ }
947
+ function decideFindings(ctx, session, agent, decisions) {
948
+ const known = new Set(listFindings(ctx, session, agent).map((finding) => finding.n));
949
+ const missing = decisions.filter((item) => !known.has(item.n)).map((item) => item.n);
950
+ if (missing.length) throw new CarnetError("FINDING_NOT_FOUND", `No finding ${missing.join(", ")} for ${agent}; review_findings lists them`);
951
+ const unexplained = decisions.filter((item) => item.decision === "ignored" && !item.reason?.trim());
952
+ if (unexplained.length) throw new CarnetError("REASON_REQUIRED", `Ignoring finding ${unexplained.map((item) => item.n).join(", ")} needs a short reason`);
953
+ const at = nowIso(ctx);
954
+ const update = ctx.db.prepare("UPDATE review_findings SET decision = ?, reason = ?, decided_at = ? WHERE session = ? AND agent = ? AND n = ?");
955
+ for (const item of decisions) update.run(item.decision, item.reason?.trim() || null, at, session, agent, item.n);
956
+ return listFindings(ctx, session, agent);
957
+ }
958
+ function formatFinding(finding) {
959
+ const location = finding.location ? ` ${finding.location}` : "";
960
+ const fix = finding.fix ? ` (fix: ${finding.fix})` : "";
961
+ return `${finding.n}/${finding.total} [${finding.severity}]${location} — ${finding.text}${fix}`;
962
+ }
963
+ function renderFindings(findings) {
964
+ return `## Findings\n\n${findings.map((finding) => {
965
+ const location = finding.location ? ` \`${finding.location}\`` : "";
966
+ const fix = finding.fix ? `\n Fix: ${finding.fix}` : "";
967
+ return `${finding.n}. **${finding.severity}**${location}: ${finding.text}${fix}`;
968
+ }).join("\n")}`;
969
+ }
970
+ function listQuestions(ctx, session, agent, openOnly = false) {
971
+ const rows = ctx.db.prepare("SELECT * FROM agent_questions WHERE session = ? AND agent = ? ORDER BY n").all(session, agent);
972
+ const total = rows.length;
973
+ return rows.filter((row) => !openOnly || row.answer === null).map((row) => ({
974
+ n: row.n,
975
+ total,
976
+ text: row.text,
977
+ context: row.context,
978
+ recommendation: row.recommendation,
979
+ alternatives: JSON.parse(row.alternatives),
980
+ answer: row.answer,
981
+ answeredAt: row.answered_at
982
+ }));
983
+ }
984
+ function addQuestions(ctx, session, agent, inputs) {
985
+ for (const input of inputs) if ((input.alternatives?.length ?? 0) > 3) throw new CarnetError("INVALID_QUESTIONS", `A question takes at most 3 alternatives; list more in its text`);
986
+ ctx.db.prepare("DELETE FROM agent_questions WHERE session = ? AND agent = ? AND answer IS NULL").run(session, agent);
987
+ const last = ctx.db.prepare("SELECT COALESCE(MAX(n), 0) AS n FROM agent_questions WHERE session = ? AND agent = ?").get(session, agent);
988
+ const insert = ctx.db.prepare(`INSERT INTO agent_questions (session, agent, n, text, context, recommendation, alternatives)
989
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);
990
+ inputs.forEach((input, index) => {
991
+ insert.run(session, agent, last.n + index + 1, input.text.trim(), input.context?.trim() || null, input.recommendation.trim(), JSON.stringify(input.alternatives ?? []));
992
+ });
993
+ return listQuestions(ctx, session, agent);
994
+ }
995
+ function answerQuestions(ctx, session, agent, answers) {
996
+ const known = new Set(listQuestions(ctx, session, agent).map((question) => question.n));
997
+ const missing = answers.filter((answer) => !known.has(answer.n)).map((answer) => answer.n);
998
+ if (missing.length) throw new CarnetError("QUESTION_NOT_FOUND", `No question ${missing.join(", ")} for ${agent}; agent_questions lists them`);
999
+ const at = nowIso(ctx);
1000
+ const update = ctx.db.prepare("UPDATE agent_questions SET answer = ?, answered_at = ? WHERE session = ? AND agent = ? AND n = ?");
1001
+ for (const answer of answers) update.run(answer.answer.trim(), at, session, agent, answer.n);
1002
+ return listQuestions(ctx, session, agent);
1003
+ }
1004
+ function renderQuestions(questions) {
1005
+ return `## Questions\n\n${questions.map((question) => {
1006
+ const lines = [`${question.n}. ${question.text}`];
1007
+ if (question.context) lines.push(` Context: ${question.context}`);
1008
+ lines.push(` Recommendation: ${question.recommendation}`);
1009
+ if (question.alternatives.length) lines.push(` Alternatives: ${question.alternatives.join(" · ")}`);
1010
+ return lines.join("\n");
1011
+ }).join("\n")}`;
1012
+ }
540
1013
  // src/workspace/workspace.ts
541
1014
  const WORKSPACE_FILE = "workspace.json";
542
1015
  const INSTRUCTIONS_FILE = "CLAUDE.md";
@@ -671,7 +1144,7 @@ function dropWorkspace(name, options = {}) {
671
1144
  }
672
1145
  // src/sessions.ts
673
1146
  const COLUMNS = `id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
674
- parent_id, prompt_version, created_at, last_active_at, ended_at`;
1147
+ parent_id, prompt_version, plugin_version, created_at, last_active_at, ended_at`;
675
1148
  function toSession(row) {
676
1149
  return {
677
1150
  id: row.id,
@@ -688,11 +1161,16 @@ function toSession(row) {
688
1161
  lastTitle: row.last_title,
689
1162
  parentId: row.parent_id,
690
1163
  promptVersion: row.prompt_version,
1164
+ pluginVersion: row.plugin_version,
691
1165
  createdAt: row.created_at,
692
1166
  lastActiveAt: row.last_active_at,
693
1167
  endedAt: row.ended_at
694
1168
  };
695
1169
  }
1170
+ function workspaceOf(ctx) {
1171
+ if (ctx.workspace !== null) return ctx.workspace;
1172
+ throw new CarnetError("NO_WORKSPACE", "A session belongs to a workspace: there is none here");
1173
+ }
696
1174
  function getSession(ctx, id) {
697
1175
  const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id);
698
1176
  return row && toSession(row);
@@ -706,7 +1184,7 @@ function ensureSession(ctx, id, cwd, workspace) {
706
1184
  const existing = getSession(ctx, id);
707
1185
  if (existing) return existing;
708
1186
  const at = nowIso(ctx);
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);
1187
+ ctx.db.prepare("INSERT INTO sessions (id, workspace, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?, ?)").run(id, workspaceOf(ctx), cwd ?? null, workspace ? repoNameFor(workspace, cwd) : null, at, at);
710
1188
  return requireSession(ctx, id);
711
1189
  }
712
1190
  function nameTaken(error, name) {
@@ -719,7 +1197,7 @@ function createSession(ctx, input) {
719
1197
  try {
720
1198
  ctx.db.prepare(`INSERT INTO sessions (id, workspace, name, kind, status, cwd, repo, host, last_title,
721
1199
  created_at, last_active_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);
1200
+ VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(input.id, workspaceOf(ctx), input.name ?? null, input.kind, input.cwd, input.repo ?? null, input.host ?? "claude-code", input.name ?? null, at, at);
723
1201
  } catch (error) {
724
1202
  nameTaken(error, input.name);
725
1203
  }
@@ -766,7 +1244,7 @@ function upsertFromHook(ctx, workspace, payload, env = {}) {
766
1244
  const existing = getSession(ctx, payload.session_id);
767
1245
  if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, workspace, cwd, repo, host, host_pid, hooked_at, created_at,
768
1246
  last_active_at)
769
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, ctx.workspace, payload.cwd ?? null, repo, host, hostPid, at, at, at);
1247
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, workspaceOf(ctx), payload.cwd ?? null, repo, host, hostPid, at, at, at);
770
1248
  else ctx.db.prepare(`UPDATE sessions
771
1249
  SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
772
1250
  WHERE id = ?`).run(at, at, existing.cwd ?? payload.cwd ?? null, existing.cwd ? existing.repo : repo ?? existing.repo, host, hostPid ?? existing.hostPid, payload.session_id);
@@ -789,25 +1267,25 @@ function nameSession(ctx, id, name, purpose) {
789
1267
  return requireSession(ctx, id);
790
1268
  }
791
1269
  function listSessions(ctx, options = {}) {
792
- const conditions = ["workspace IS ?"];
1270
+ const conditions = ["workspace = ?"];
793
1271
  if (!options.includeTemp) conditions.push("kind != 'temp'");
794
1272
  if (!options.includeArchived) conditions.push("status != 'archived'");
795
- return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC`).all(ctx.workspace).map(toSession);
1273
+ 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);
796
1274
  }
797
1275
  function dropSession(ctx, id) {
798
1276
  requireSession(ctx, id);
799
1277
  const at = nowIso(ctx);
800
- ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, id);
1278
+ closeAgentsWhere(ctx.db, "session = ?", [id], at);
801
1279
  ctx.db.prepare("UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?").run(at, id);
802
1280
  return requireSession(ctx, id);
803
1281
  }
804
1282
  function defaultSession(ctx) {
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);
1283
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND status != 'archived'
1284
+ ORDER BY last_active_at DESC, rowid DESC LIMIT 1`).get(ctx.workspace);
807
1285
  return row && toSession(row);
808
1286
  }
809
1287
  function sessionByName(ctx, name) {
810
- const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace IS ? AND name = ?`).get(ctx.workspace, name);
1288
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND name = ?`).get(ctx.workspace, name);
811
1289
  return row && toSession(row);
812
1290
  }
813
1291
  const MINIMUM_ID_PREFIX = 4;
@@ -821,8 +1299,8 @@ function findSession(ctx, reference) {
821
1299
  if (byId) return byId;
822
1300
  const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
823
1301
  if (isIdPrefix && reference.length >= 4) {
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()}%`);
1302
+ const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND id LIKE ?
1303
+ ORDER BY last_active_at DESC, rowid DESC`).all(ctx.workspace, `${reference.toLowerCase()}%`);
826
1304
  const [only, ...others] = rows;
827
1305
  if (only && others.length === 0) return toSession(only);
828
1306
  if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
@@ -832,9 +1310,12 @@ function findSession(ctx, reference) {
832
1310
  function sessionByHostProcess(ctx, host, processId) {
833
1311
  const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
834
1312
  WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL
835
- ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
1313
+ ORDER BY hooked_at DESC, rowid DESC LIMIT 1`).get(host, processId);
836
1314
  return row && toSession(row);
837
1315
  }
1316
+ function recordPluginVersion(ctx, id, version) {
1317
+ ctx.db.prepare("UPDATE sessions SET plugin_version = ? WHERE id = ?").run(version, id);
1318
+ }
838
1319
  function recordPromptVersion(ctx, id, version) {
839
1320
  requireSession(ctx, id);
840
1321
  ctx.db.prepare("UPDATE sessions SET prompt_version = ? WHERE id = ?").run(version, id);
@@ -889,19 +1370,19 @@ function demoteSession(ctx, id) {
889
1370
  function staleTempSessions(ctx, olderThanMilliseconds) {
890
1371
  const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
891
1372
  return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
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);
1373
+ WHERE workspace = ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
1374
+ ORDER BY last_active_at ASC, rowid ASC`).all(ctx.workspace, before).map(toSession);
894
1375
  }
895
1376
  function resetDeadSessions(ctx, isAlive) {
896
1377
  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));
897
1378
  }
898
1379
  // src/prompt/core-rules.ts
899
1380
  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.
900
- - The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.
901
- - 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.
902
- - 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.
903
- - 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.
904
- - To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.`;
1381
+ - 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.
1382
+ - 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.
1383
+ - 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.
1384
+ - 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.
1385
+ - To launch agents or handle their results, load the rucher skill: it holds the full workflow.`;
905
1386
  // src/prompt/prompt.ts
906
1387
  const PROMPT_FILE = "prompt.md";
907
1388
  function readIfPresent(path) {
@@ -909,7 +1390,7 @@ function readIfPresent(path) {
909
1390
  return readFileSync(path, "utf8").trim() || void 0;
910
1391
  }
911
1392
  function baseRules(env = process.env) {
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.";
1393
+ 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.";
913
1394
  }
914
1395
  function workspaceRules(workspace) {
915
1396
  return workspace ? readIfPresent(join(workspace.definition, PROMPT_FILE)) : void 0;
@@ -949,7 +1430,7 @@ function outsideRucherContext(workspace, env = process.env) {
949
1430
  }
950
1431
  const OUTSIDE_RUCHER_NOTICE = "rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)";
951
1432
  const RULES_UPDATED_NOTICE = "rucher: rules updated, will apply after the next compaction or in a new session";
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.";
1433
+ 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, follow the contract of its kind, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.";
953
1434
  // src/run-directory-files.ts
954
1435
  const GENERATED_MARKER = "generated by rucher, do not edit";
955
1436
  function refuse(path) {
@@ -1009,10 +1490,57 @@ function mergeSettings(base, extra) {
1009
1490
  }
1010
1491
  return merged;
1011
1492
  }
1493
+ // src/workspace/undo.ts
1494
+ var UndoList = class {
1495
+ steps = [];
1496
+ push(step) {
1497
+ this.steps.push(step);
1498
+ }
1499
+ undo() {
1500
+ const outcome = {
1501
+ undone: [],
1502
+ left: []
1503
+ };
1504
+ for (const step of [...this.steps].reverse()) {
1505
+ if (outcome.left.length) {
1506
+ outcome.left.push(step.command);
1507
+ continue;
1508
+ }
1509
+ try {
1510
+ step.run();
1511
+ outcome.undone.push(step.command);
1512
+ } catch {
1513
+ outcome.left.push(step.command);
1514
+ }
1515
+ }
1516
+ this.steps.length = 0;
1517
+ return outcome;
1518
+ }
1519
+ };
1520
+ function shellQuote(path) {
1521
+ return `'${path.replaceAll("'", "'\\''")}'`;
1522
+ }
1523
+ function moveTracked(undo, move) {
1524
+ renameSync(move.from, move.to);
1525
+ undo.push({
1526
+ command: `mv ${shellQuote(move.to)} ${shellQuote(move.from)}`,
1527
+ run: () => renameSync(move.to, move.from)
1528
+ });
1529
+ }
1530
+ function relocateFailed(error, undo, backup) {
1531
+ const outcome = undo.undo();
1532
+ const cause = error instanceof Error ? error.message : String(error);
1533
+ if (outcome.left.length === 0) {
1534
+ if (error instanceof CarnetError) throw error;
1535
+ throw new CarnetError("WORKSPACE_RELOCATE_FAILED", `${cause}; nothing was changed`);
1536
+ }
1537
+ throw new CarnetError("WORKSPACE_RELOCATE_FAILED", `${cause}; undo stopped, run by hand:\n${outcome.left.join("\n")}\nDatabase backup: ${join(backup, "carnet.db")}`);
1538
+ }
1012
1539
  // src/hosts/claude-code.ts
1013
1540
  const TRANSCRIPT_TAIL_BYTES = 262144;
1541
+ const TRANSCRIPT_HEAD_BYTES = 65536;
1014
1542
  const TITLE_PATTERN = /"type":"custom-title","customTitle":("(?:[^"\\]|\\.)*")/g;
1015
- const FORK_NAME_PATTERN = /You are fork `([^`]+)`/;
1543
+ const FORK_NAME_PATTERN = /You are (?:agent|fork) `([^`]+)`/;
1016
1544
  function payloadObject(json) {
1017
1545
  const data = JSON.parse(json);
1018
1546
  if (typeof data.session_id !== "string" || !data.session_id) throw new TypeError("Hook payload has no session_id");
@@ -1041,6 +1569,11 @@ function subagentMetadataDescription(transcriptPath) {
1041
1569
  return;
1042
1570
  }
1043
1571
  }
1572
+ function launchedNames(toolInput) {
1573
+ const prompt = text(toolInput, "prompt");
1574
+ const found = [text(toolInput, "description"), prompt && FORK_NAME_PATTERN.exec(prompt)?.[1]].filter((name) => Boolean(name));
1575
+ return found.length > 0 ? [...new Set(found)] : void 0;
1576
+ }
1044
1577
  function subagentPromptName(transcriptPath) {
1045
1578
  try {
1046
1579
  const firstLine = readFileSync(transcriptPath, "utf8").split("\n", 1)[0] ?? "";
@@ -1049,22 +1582,41 @@ function subagentPromptName(transcriptPath) {
1049
1582
  return;
1050
1583
  }
1051
1584
  }
1052
- function transcriptTitle(path) {
1585
+ function readSlice(path, from, bytes) {
1053
1586
  let descriptor;
1054
1587
  try {
1055
1588
  descriptor = openSync(path, "r");
1056
1589
  const size = fstatSync(descriptor).size;
1057
- const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
1590
+ const length = Math.min(size, bytes);
1058
1591
  const buffer = Buffer.alloc(length);
1059
- readSync(descriptor, buffer, 0, length, size - length);
1060
- const last = [...buffer.toString("utf8").matchAll(TITLE_PATTERN)].at(-1)?.[1];
1061
- return last === void 0 ? void 0 : JSON.parse(last);
1592
+ readSync(descriptor, buffer, 0, length, from === "end" ? size - length : 0);
1593
+ return buffer.toString("utf8");
1062
1594
  } catch {
1063
1595
  return;
1064
1596
  } finally {
1065
1597
  if (descriptor !== void 0) closeSync(descriptor);
1066
1598
  }
1067
1599
  }
1600
+ function transcriptTitle(path) {
1601
+ const tail = readSlice(path, "end", TRANSCRIPT_TAIL_BYTES);
1602
+ if (tail === void 0) return void 0;
1603
+ const last = [...tail.matchAll(TITLE_PATTERN)].at(-1)?.[1];
1604
+ return last === void 0 ? void 0 : JSON.parse(last);
1605
+ }
1606
+ function records(text) {
1607
+ return (text ?? "").split("\n").flatMap((line) => {
1608
+ try {
1609
+ const value = JSON.parse(line);
1610
+ return value && typeof value === "object" ? [value] : [];
1611
+ } catch {
1612
+ return [];
1613
+ }
1614
+ });
1615
+ }
1616
+ function continuesConversation(parentFile, childFile, parentId, childId) {
1617
+ if (records(readSlice(parentFile, "end", TRANSCRIPT_TAIL_BYTES)).some((record) => record.type === "continued-in" && record.continuedInSessionId === childId)) return true;
1618
+ return records(readSlice(childFile, "start", TRANSCRIPT_HEAD_BYTES)).some((record) => record.type === "derived-from" && Array.isArray(record.sessions) && record.sessions.some((source) => !!source && typeof source === "object" && source.id === parentId && source.via === "resume"));
1619
+ }
1068
1620
  const SETTINGS_FILE = join(".claude", "settings.json");
1069
1621
  const BACKEND_NOTES = "backends/claude.md";
1070
1622
  function instructionFiles(workspace) {
@@ -1134,6 +1686,108 @@ const RENDERING_SOURCES = /* @__PURE__ */ new Set([
1134
1686
  function projectsDirectory(env) {
1135
1687
  return join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
1136
1688
  }
1689
+ function claudeProjectFolder(cwd, env = process.env) {
1690
+ return join(projectsDirectory(env), cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1691
+ }
1692
+ function claudeConfigFile(env = process.env) {
1693
+ return env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, ".claude.json") : join(env.HOME || homedir(), ".claude.json");
1694
+ }
1695
+ function renameStep(from, to) {
1696
+ return {
1697
+ command: `mv ${shellQuote(to)} ${shellQuote(from)}`,
1698
+ run: () => renameSync(to, from)
1699
+ };
1700
+ }
1701
+ function moveProject(source, target) {
1702
+ if (existsSync(target)) throw new CarnetError("WORKSPACE_EXISTS", `Claude Code already has a project folder: ${target}`);
1703
+ renameSync(source, target);
1704
+ return {
1705
+ moves: [{
1706
+ from: source,
1707
+ to: target
1708
+ }],
1709
+ undo: [renameStep(source, target)]
1710
+ };
1711
+ }
1712
+ const MEMORY_INDEX = "MEMORY.md";
1713
+ function mergeProject(source, target, prefix) {
1714
+ const relocation = {
1715
+ moves: [],
1716
+ undo: []
1717
+ };
1718
+ const move = (from, to) => {
1719
+ if (existsSync(to)) throw new CarnetError("WORKSPACE_EXISTS", `Claude Code project file already exists: ${to}`);
1720
+ mkdirSync(dirname(to), { recursive: true });
1721
+ renameSync(from, to);
1722
+ relocation.moves.push({
1723
+ from,
1724
+ to
1725
+ });
1726
+ relocation.undo.push(renameStep(from, to));
1727
+ };
1728
+ for (const entry of readdirSync(source)) if (entry !== "memory") move(join(source, entry), join(target, entry));
1729
+ const memory = join(source, "memory");
1730
+ if (!existsSync(memory)) return removeEmpty(relocation, [source]);
1731
+ const renamed = /* @__PURE__ */ new Map();
1732
+ for (const entry of readdirSync(memory)) {
1733
+ if (entry === MEMORY_INDEX) continue;
1734
+ const name = existsSync(join(target, "memory", entry)) ? `${prefix}-${entry}` : entry;
1735
+ if (name !== entry) renamed.set(entry, name);
1736
+ move(join(memory, entry), join(target, "memory", name));
1737
+ }
1738
+ const fromIndex = join(memory, MEMORY_INDEX);
1739
+ if (existsSync(fromIndex)) {
1740
+ const intoIndex = join(target, "memory", MEMORY_INDEX);
1741
+ if (!existsSync(intoIndex)) move(fromIndex, intoIndex);
1742
+ else {
1743
+ const original = readFileSync(intoIndex, "utf8");
1744
+ const added = [...renamed].reduce((text, [from, to]) => text.replaceAll(`(${from})`, `(${to})`), readFileSync(fromIndex, "utf8"));
1745
+ const separator = original.endsWith("\n") || original === "" ? "" : "\n";
1746
+ writeFileSync(intoIndex, `${original}${separator}\n## Ex-workspace ${prefix}\n\n${added}`);
1747
+ const fromText = readFileSync(fromIndex, "utf8");
1748
+ unlinkSync(fromIndex);
1749
+ relocation.undo.push({
1750
+ command: `# restore ${shellQuote(intoIndex)} and ${shellQuote(fromIndex)} by hand`,
1751
+ run: () => {
1752
+ writeFileSync(fromIndex, fromText);
1753
+ writeFileSync(intoIndex, original);
1754
+ }
1755
+ });
1756
+ }
1757
+ }
1758
+ return removeEmpty(relocation, [memory, source]);
1759
+ }
1760
+ function removeEmpty(relocation, folders) {
1761
+ for (const folder of folders) {
1762
+ if (readdirSync(folder).length > 0) continue;
1763
+ rmdirSync(folder);
1764
+ relocation.undo.push({
1765
+ command: `mkdir -p ${shellQuote(folder)}`,
1766
+ run: () => mkdirSync(folder, { recursive: true })
1767
+ });
1768
+ }
1769
+ return relocation;
1770
+ }
1771
+ function relocateProject(from, to, env, mode = "move") {
1772
+ const source = claudeProjectFolder(from, env);
1773
+ const target = claudeProjectFolder(to, env);
1774
+ if (!existsSync(source)) return null;
1775
+ if (mode === "move") return moveProject(source, target);
1776
+ if (!existsSync(target)) return moveProject(source, target);
1777
+ return mergeProject(source, target, basename(from));
1778
+ }
1779
+ function moveTrust(from, to, env) {
1780
+ const file = claudeConfigFile(env);
1781
+ if (!existsSync(file)) return false;
1782
+ const config = JSON.parse(readFileSync(file, "utf8"));
1783
+ const projects = config.projects;
1784
+ if (!projects || !(from in projects) || to !== null && to in projects) return false;
1785
+ config.projects = Object.fromEntries(Object.entries(projects).flatMap(([key, value]) => key !== from ? [[key, value]] : to === null ? [] : [[to, value]]));
1786
+ const temporary = `${file}.rucher-${process.pid}`;
1787
+ writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: statSync(file).mode });
1788
+ renameSync(temporary, file);
1789
+ return true;
1790
+ }
1137
1791
  const claudeCode = {
1138
1792
  id: "claude-code",
1139
1793
  displayName: "Claude Code",
@@ -1156,6 +1810,14 @@ const claudeCode = {
1156
1810
  session_title: text(data, "session_title")
1157
1811
  };
1158
1812
  },
1813
+ parseStopPayload(json) {
1814
+ const data = payloadObject(json);
1815
+ return {
1816
+ session_id: data.session_id,
1817
+ cwd: text(data, "cwd"),
1818
+ failed: data.hook_event_name === "StopFailure"
1819
+ };
1820
+ },
1159
1821
  parsePromptPayload(json) {
1160
1822
  const data = payloadObject(json);
1161
1823
  return {
@@ -1190,12 +1852,18 @@ const claudeCode = {
1190
1852
  const data = payloadObject(json);
1191
1853
  const toolName = text(data, "tool_name");
1192
1854
  const cwd = text(data, "cwd");
1855
+ const toolInput = typeof data.tool_input === "object" && data.tool_input !== null ? data.tool_input : {};
1193
1856
  return {
1194
1857
  session_id: data.session_id,
1195
1858
  cwd,
1196
1859
  tool_name: toolName,
1197
1860
  agent_id: text(data, "agent_id"),
1198
- path: touchedPath(toolName, data.tool_input, cwd)
1861
+ agent_type: text(data, "agent_type"),
1862
+ path: touchedPath(toolName, data.tool_input, cwd),
1863
+ file_path: text(toolInput, "file_path") ?? text(toolInput, "notebook_path"),
1864
+ command: text(toolInput, "command"),
1865
+ subagent_type: text(toolInput, "subagent_type"),
1866
+ launched_names: launchedNames(toolInput)
1199
1867
  };
1200
1868
  },
1201
1869
  subagentInheritsContext(payload) {
@@ -1252,7 +1920,7 @@ const claudeCode = {
1252
1920
  },
1253
1921
  transcriptFiles(session, env = process.env) {
1254
1922
  if (!session.cwd) return [];
1255
- const project = join(projectsDirectory(env), session.cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1923
+ const project = claudeProjectFolder(session.cwd, env);
1256
1924
  return [join(project, `${session.id}.jsonl`), join(project, session.id)].filter((path) => existsSync(path));
1257
1925
  },
1258
1926
  hasConversation(session, env = process.env) {
@@ -1260,10 +1928,17 @@ const claudeCode = {
1260
1928
  if (!existsSync(projects)) return false;
1261
1929
  return readdirSync(projects).some((project) => existsSync(join(projects, project, `${session.id}.jsonl`)));
1262
1930
  },
1931
+ continues(parent, childId, env = process.env) {
1932
+ if (!parent.cwd) return false;
1933
+ const project = claudeProjectFolder(parent.cwd, env);
1934
+ return continuesConversation(join(project, `${parent.id}.jsonl`), join(project, `${childId}.jsonl`), parent.id, childId);
1935
+ },
1263
1936
  renameInstruction(name) {
1264
1937
  return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
1265
1938
  },
1266
- renderRunDirectory: renderClaudeRunDirectory
1939
+ renderRunDirectory: renderClaudeRunDirectory,
1940
+ relocateProject,
1941
+ moveTrust
1267
1942
  };
1268
1943
  // src/hosts/host.ts
1269
1944
  const DEFAULT_HOST = "claude-code";
@@ -1278,7 +1953,7 @@ function hostById(id) {
1278
1953
  }
1279
1954
  // src/workspace-rows.ts
1280
1955
  function inTransaction(db, run) {
1281
- db.exec("BEGIN");
1956
+ db.exec("BEGIN IMMEDIATE");
1282
1957
  try {
1283
1958
  const result = run();
1284
1959
  db.exec("COMMIT");
@@ -1289,13 +1964,11 @@ function inTransaction(db, run) {
1289
1964
  }
1290
1965
  }
1291
1966
  function sessionWorkspaceName(db, sessionId) {
1292
- const row = db.prepare("SELECT workspace FROM sessions WHERE id = ?").get(sessionId);
1293
- return row ? row.workspace : void 0;
1967
+ return db.prepare("SELECT workspace FROM sessions WHERE id = ?").get(sessionId)?.workspace;
1294
1968
  }
1295
1969
  function archiveWorkspaceSessions(db, name, at) {
1296
1970
  return inTransaction(db, () => {
1297
- db.prepare(`UPDATE agents SET status = 'closed', updated_at = ?
1298
- WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE workspace = ?)`).run(at, name);
1971
+ closeAgentsWhere(db, "session IN (SELECT id FROM sessions WHERE workspace = ?)", [name], at);
1299
1972
  return Number(db.prepare(`UPDATE sessions SET status = 'archived', last_active_at = ?
1300
1973
  WHERE workspace = ? AND status != 'archived'`).run(at, name).changes);
1301
1974
  });
@@ -1305,9 +1978,87 @@ function deleteWorkspaceNotes(db, name) {
1305
1978
  }
1306
1979
  function workspaceSessionCounts(db) {
1307
1980
  const rows = db.prepare(`SELECT workspace, COUNT(*) AS count FROM sessions
1308
- WHERE workspace IS NOT NULL AND status != 'archived' GROUP BY workspace`).all();
1981
+ WHERE status != 'archived' GROUP BY workspace`).all();
1309
1982
  return new Map(rows.map((row) => [row.workspace, Number(row.count)]));
1310
1983
  }
1984
+ function workspaceLastActive(db) {
1985
+ const rows = db.prepare("SELECT workspace, MAX(last_active_at) AS at FROM sessions GROUP BY workspace").all();
1986
+ return new Map(rows.map((row) => [row.workspace, row.at]));
1987
+ }
1988
+ function rewritePrefix(db, table, column, from, to) {
1989
+ return Number(db.prepare(`UPDATE ${table} SET ${column} = ? || substr(${column}, length(?) + 1)
1990
+ WHERE ${column} = ? OR substr(${column}, 1, length(?) + 1) = ? || '/'`).run(to, from, from, from, from).changes);
1991
+ }
1992
+ function rewriteRunDirectory(db, from, to) {
1993
+ return [
1994
+ ["sessions", "cwd"],
1995
+ ["agents", "report_path"],
1996
+ ["agents", "sandbox"],
1997
+ ["events", "link"]
1998
+ ].reduce((total, [table, column]) => total + rewritePrefix(db, table, column, from, to), 0);
1999
+ }
2000
+ function workspaceRowCounts(db, name) {
2001
+ const count = (table) => Number(db.prepare(`SELECT COUNT(*) AS total FROM ${table} WHERE workspace = ?`).get(name).total);
2002
+ return {
2003
+ sessions: count("sessions"),
2004
+ notes: count("notes"),
2005
+ activeDays: count("active_days")
2006
+ };
2007
+ }
2008
+ function runningWorkspaceSessions(db, name) {
2009
+ return db.prepare(`SELECT id, name, host_pid FROM sessions
2010
+ WHERE workspace = ? AND status = 'running' AND host_pid IS NOT NULL`).all(name).map((row) => ({
2011
+ id: row.id,
2012
+ name: row.name,
2013
+ hostPid: Number(row.host_pid)
2014
+ }));
2015
+ }
2016
+ function renameWorkspaceRows(db, names, runDirectories) {
2017
+ return inTransaction(db, () => {
2018
+ const counts = workspaceRowCounts(db, names.from);
2019
+ for (const table of [
2020
+ "sessions",
2021
+ "notes",
2022
+ "active_days"
2023
+ ]) db.prepare(`UPDATE ${table} SET workspace = ? WHERE workspace = ?`).run(names.to, names.from);
2024
+ return {
2025
+ ...counts,
2026
+ paths: rewriteRunDirectory(db, runDirectories.from, runDirectories.to)
2027
+ };
2028
+ });
2029
+ }
2030
+ function nextNoteNumber(db, name) {
2031
+ const row = db.prepare("SELECT COALESCE(MAX(number), 0) AS top FROM notes WHERE workspace = ?").get(name);
2032
+ return Number(row.top) + 1;
2033
+ }
2034
+ function mergeWorkspaceRows(db, input) {
2035
+ const { from, into } = input.names;
2036
+ return inTransaction(db, () => {
2037
+ const counts = workspaceRowCounts(db, from);
2038
+ for (const [fromName, intoName] of input.repos) {
2039
+ db.prepare(`UPDATE note_repos SET repo = ?
2040
+ WHERE repo = ? AND note IN (SELECT id FROM notes WHERE workspace = ?)`).run(intoName, fromName, from);
2041
+ db.prepare(`UPDATE session_repos SET repo = ?
2042
+ WHERE repo = ? AND session IN (SELECT id FROM sessions WHERE workspace = ?)`).run(intoName, fromName, from);
2043
+ db.prepare("UPDATE sessions SET repo = ? WHERE repo = ? AND workspace = ?").run(intoName, fromName, from);
2044
+ }
2045
+ const firstNumber = nextNoteNumber(db, into);
2046
+ db.prepare("UPDATE notes SET workspace = ?, number = number + ? WHERE workspace = ?").run(into, firstNumber - 1, from);
2047
+ db.prepare("UPDATE sessions SET workspace = ? WHERE workspace = ?").run(into, from);
2048
+ db.prepare("INSERT OR IGNORE INTO active_days (workspace, day) SELECT ?, day FROM active_days WHERE workspace = ?").run(into, from);
2049
+ db.prepare("DELETE FROM active_days WHERE workspace = ?").run(from);
2050
+ for (const [oldPath, newPath] of input.paths) for (const [table, column] of [
2051
+ ["agents", "report_path"],
2052
+ ["agents", "sandbox"],
2053
+ ["events", "link"]
2054
+ ]) db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ?`).run(newPath, oldPath);
2055
+ rewriteRunDirectory(db, input.runDirectories.from, input.runDirectories.into);
2056
+ return {
2057
+ ...counts,
2058
+ firstNumber
2059
+ };
2060
+ });
2061
+ }
1311
2062
  // src/workspace/locate.ts
1312
2063
  function isInside(directory, path) {
1313
2064
  const relativePath = relative(directory, path);
@@ -1334,31 +2085,9 @@ function namedWorkspace(name, env) {
1334
2085
  function byRunDirectory(workspaces, directories) {
1335
2086
  return workspaces.find((workspace) => directories.some((directory) => isInside(workspace.runDirectory, directory)));
1336
2087
  }
1337
- function byRepo(workspaces, directory) {
1338
- let best = [];
1339
- for (const workspace of workspaces) for (const repo of workspace.repos) {
1340
- if (!isInside(repo.path, directory)) continue;
1341
- const length = best[0]?.repo.path.length ?? -1;
1342
- if (repo.path.length > length) best = [{
1343
- workspace,
1344
- repo
1345
- }];
1346
- else if (repo.path.length === length) best.push({
1347
- workspace,
1348
- repo
1349
- });
1350
- }
1351
- const names = [...new Set(best.map((match) => match.workspace.name))];
1352
- if (names.length > 1) throw new CarnetError("WORKSPACE_AMBIGUOUS", `${directory} is in repos of several workspaces (${names.join(", ")}): pass --ws`);
1353
- return best[0];
1354
- }
1355
2088
  function resolveWorkspace({ db, sessionId, workspace, cwd = process.cwd(), env = process.env } = {}) {
1356
2089
  if (db && sessionId) {
1357
2090
  const name = sessionWorkspaceName(db, sessionId);
1358
- if (name === null) return {
1359
- workspace: null,
1360
- origin: "session"
1361
- };
1362
2091
  if (name !== void 0 && workspaceExists(name, env)) return {
1363
2092
  workspace: loadWorkspace(name, env),
1364
2093
  origin: "session"
@@ -1374,20 +2103,11 @@ function resolveWorkspace({ db, sessionId, workspace, cwd = process.cwd(), env =
1374
2103
  };
1375
2104
  const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
1376
2105
  const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
1377
- const workspaces = listWorkspaces(env);
1378
- const runDirectoryWorkspace = byRunDirectory(workspaces, directories);
2106
+ const runDirectoryWorkspace = byRunDirectory(listWorkspaces(env), directories);
1379
2107
  if (runDirectoryWorkspace) return {
1380
2108
  workspace: runDirectoryWorkspace,
1381
2109
  origin: "run-directory"
1382
2110
  };
1383
- for (const directory of directories) {
1384
- const match = byRepo(workspaces, directory);
1385
- if (match) return {
1386
- workspace: match.workspace,
1387
- origin: "repo",
1388
- repo: match.repo
1389
- };
1390
- }
1391
2111
  return {
1392
2112
  workspace: null,
1393
2113
  origin: "none"
@@ -1398,10 +2118,7 @@ function workspaceLabel(workspace) {
1398
2118
  }
1399
2119
  function requireWorkspace(workspace) {
1400
2120
  if (workspace) return workspace;
1401
- throw new CarnetError("NO_WORKSPACE", "No Rucher workspace here: pass --ws, or run this from a repo or run directory of a workspace");
1402
- }
1403
- function ambiguousWorkspaceContext(reason) {
1404
- return `Rucher could not tell which workspace this session belongs to, so Carnet records nothing for it: ${reason}.`;
2121
+ throw new CarnetError("NO_WORKSPACE", "No Rucher workspace here: pass --ws <name>, or run this from a workspace's run directory");
1405
2122
  }
1406
2123
  // src/notes.ts
1407
2124
  const NOTE_KINDS = [
@@ -1518,7 +2235,7 @@ const CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citation
1518
2235
  note_citations.agent, note_citations.why, note_citations.at`;
1519
2236
  function citationsOf(ctx, number) {
1520
2237
  return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
1521
- WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.workspace, number);
2238
+ WHERE notes.workspace IS ? AND notes.number = ? ORDER BY note_citations.at, note_citations.rowid`).all(ctx.workspace, number);
1522
2239
  }
1523
2240
  function weightOf(citations, days, halfLifeDays) {
1524
2241
  const latest = /* @__PURE__ */ new Map();
@@ -1798,12 +2515,12 @@ function mergeSessions(ctx, fromId, intoId) {
1798
2515
  try {
1799
2516
  const moveAgent = ctx.db.prepare("UPDATE agents SET session = ?, updated_at = ? WHERE session = ? AND name = ?");
1800
2517
  for (const name of movedAgents) moveAgent.run(intoId, at, fromId, name);
1801
- ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, fromId);
2518
+ closeAgentsWhere(ctx.db, "session = ?", [fromId], at);
1802
2519
  const movedEvents = Number(ctx.db.prepare("UPDATE events SET session = ? WHERE session = ?").run(intoId, fromId).changes);
1803
2520
  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;
1804
2521
  ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(fromId);
1805
2522
  const keepName = into.name === null && from.name !== null;
1806
- ctx.db.prepare("UPDATE sessions SET status = 'archived', kind = 'temp', name = NULL, last_active_at = ? WHERE id = ?").run(at, fromId);
2523
+ ctx.db.prepare("UPDATE sessions SET status = 'archived', kind = 'temp', name = NULL, turn = NULL, turn_started_at = NULL, last_active_at = ? WHERE id = ?").run(at, fromId);
1807
2524
  ctx.db.prepare(`UPDATE sessions
1808
2525
  SET name = COALESCE(?, name), purpose = COALESCE(purpose, ?), last_active_at = ?,
1809
2526
  kind = CASE WHEN ? THEN ? ELSE kind END
@@ -1821,6 +2538,38 @@ function mergeSessions(ctx, fromId, intoId) {
1821
2538
  throw error;
1822
2539
  }
1823
2540
  }
2541
+ // src/sandbox.ts
2542
+ function strictlyInside(path, folder) {
2543
+ const rest = relative(folder, path);
2544
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute(rest);
2545
+ }
2546
+ function resolveSandbox(workspace, path) {
2547
+ if (!workspace) throw new CarnetError("INVALID_SANDBOX", "A sandbox needs a workspace: none is resolved");
2548
+ const root = sandboxesDirectory(workspace);
2549
+ const expanded = path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
2550
+ const resolved = resolve(workspace.runDirectory, expanded);
2551
+ if (!strictlyInside(resolved, root)) throw new CarnetError("INVALID_SANDBOX", `${path} is not a folder under ${root}: a sandbox lives in the workspace's sandboxes folder`);
2552
+ if (existsSync(resolved)) {
2553
+ if (!lstatSync(resolved).isDirectory() || readdirSync(resolved).length > 0) throw new CarnetError("INVALID_SANDBOX", `${resolved} already exists and is not empty`);
2554
+ }
2555
+ return resolved;
2556
+ }
2557
+ function sandboxRemovedSuffix(removed) {
2558
+ return removed ? ", sandbox removed" : "";
2559
+ }
2560
+ function createSandbox(path) {
2561
+ mkdirSync(path, { recursive: true });
2562
+ }
2563
+ function removeSandbox(workspace, path) {
2564
+ if (!workspace || !path) return false;
2565
+ const resolved = resolve(path);
2566
+ if (!strictlyInside(resolved, sandboxesDirectory(workspace)) || !existsSync(resolved)) return false;
2567
+ rmSync(resolved, {
2568
+ recursive: true,
2569
+ force: true
2570
+ });
2571
+ return true;
2572
+ }
1824
2573
  // src/purge.ts
1825
2574
  const DEFAULT_PURGE_DAYS = 3;
1826
2575
  const DAY_MILLISECONDS = 864e5;
@@ -1829,7 +2578,7 @@ function purgeDays(value) {
1829
2578
  return Number.isFinite(days) && days > 0 ? days : 3;
1830
2579
  }
1831
2580
  const PURGEABLE = `
1832
- workspace IS ? AND id != ? AND last_active_at < ?
2581
+ workspace = ? AND id != ? AND last_active_at < ?
1833
2582
  AND NOT EXISTS (
1834
2583
  SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
1835
2584
  )
@@ -1860,13 +2609,44 @@ function purgeSessions(ctx, keepId, days) {
1860
2609
  }
1861
2610
  }
1862
2611
  // src/status/render.ts
1863
- const MAIN_WORKING_SUFFIX = "(main working, not ready)";
2612
+ const MAIN_HEADER = "Main";
2613
+ const MAIN_WORKING_SUFFIX = "(main working)";
2614
+ const BLOCKED_HEADER = "Waiting on agents";
2615
+ const MAIN_WAITING_SUFFIX = "(waiting on you)";
2616
+ const MAIN_FAILED_SUFFIX = "(turn failed)";
1864
2617
  function renderTableLine(item) {
1865
- if (item.mainWorking) return `${MAIN_WORKING_EMOJI} ${item.text} ${MAIN_WORKING_SUFFIX}`;
1866
2618
  return `${EMOJI[item.status ?? "discussing"]} ${item.text}`;
1867
2619
  }
1868
- function renderAgentLine(line) {
1869
- return line.note ? `${line.emoji} ${line.name} — ${line.note}` : `${line.emoji} ${line.name}`;
2620
+ const TURN_MARKS = {
2621
+ working: {
2622
+ emoji: MAIN_WORKING_EMOJI,
2623
+ suffix: MAIN_WORKING_SUFFIX,
2624
+ alone: "main working"
2625
+ },
2626
+ waiting: {
2627
+ emoji: "⏸",
2628
+ suffix: MAIN_WAITING_SUFFIX,
2629
+ alone: "waiting on you"
2630
+ },
2631
+ failed: {
2632
+ emoji: "⚠",
2633
+ suffix: MAIN_FAILED_SUFFIX,
2634
+ alone: "turn failed"
2635
+ }
2636
+ };
2637
+ const MAIN_IDLE = "idle";
2638
+ function renderMainLine(item, turn) {
2639
+ if (!turn) return item ? renderTableLine(item) : MAIN_IDLE;
2640
+ const mark = TURN_MARKS[turn];
2641
+ return item ? `${mark.emoji} ${item.text} ${mark.suffix}` : `${mark.emoji} ${mark.alone}`;
2642
+ }
2643
+ function renderAgentLine(line, nameWidth = 0) {
2644
+ const head = `${line.emoji} ${kindTag(line.kind)} ${line.name}`;
2645
+ const action = line.action ? ` ${" ".repeat(Math.max(nameWidth - line.name.length, 0))} ${line.action}` : "";
2646
+ return line.note ? `${head}${action} — ${line.note}` : `${head}${action}`;
2647
+ }
2648
+ function nameWidth(lines) {
2649
+ return Math.max(0, ...lines.map((line) => line.name.length));
1870
2650
  }
1871
2651
  const NOTES_HEADER = "Notes";
1872
2652
  const NOTES_FOLD_LINES = 5;
@@ -1877,7 +2657,7 @@ const ACTIVITY_MARK = {
1877
2657
  };
1878
2658
  const LABEL_WIDTH = 8;
1879
2659
  const SIMILAR_PREFIX = "similar to ";
1880
- function plural(count, word) {
2660
+ function plural$1(count, word) {
1881
2661
  return `${count} ${word}${count > 1 ? "s" : ""}`;
1882
2662
  }
1883
2663
  function renderNotesSummary(notes) {
@@ -1887,7 +2667,7 @@ function renderNotesSummary(notes) {
1887
2667
  count("added") && `${count("added")} added`,
1888
2668
  count("cited") && `${count("cited")} cited`,
1889
2669
  count("dropped") && `${count("dropped")} dropped`,
1890
- duplicates && plural(duplicates, "possible duplicate")
2670
+ duplicates && plural$1(duplicates, "possible duplicate")
1891
2671
  ].filter(Boolean);
1892
2672
  return `${NOTES_HEADER} ${parts.join(" · ")}`;
1893
2673
  }
@@ -1907,15 +2687,22 @@ function renderNotes(notes, mode = "full") {
1907
2687
  }
1908
2688
  function renderSections(view, options = {}) {
1909
2689
  const out = [];
1910
- if (view.table) out.push("On the table", ` ${renderTableLine(view.table)}`, "");
2690
+ out.push(MAIN_HEADER, ` ${renderMainLine(view.table, view.turn)}`, "");
1911
2691
  out.push("Waiting on you");
1912
2692
  if (view.waiting.length === 0) out.push(" nothing");
2693
+ const waitingWidth = nameWidth(view.waiting);
1913
2694
  view.waiting.forEach((line, index) => {
1914
- out.push(` ${index + 1}. ${renderAgentLine(line)}`);
2695
+ out.push(` ${index + 1}.${line.pinned ? "📌" : ""} ${renderAgentLine(line, waitingWidth)}`);
1915
2696
  });
2697
+ if (view.blocked.length > 0) {
2698
+ out.push("", BLOCKED_HEADER);
2699
+ const blockedWidth = nameWidth(view.blocked);
2700
+ for (const line of view.blocked) out.push(` ${renderAgentLine(line, blockedWidth)}`);
2701
+ }
1916
2702
  out.push("", "Running");
1917
2703
  if (view.running.length === 0) out.push(" nothing");
1918
- for (const line of view.running) out.push(` ${renderAgentLine(line)}`);
2704
+ const runningWidth = nameWidth(view.running);
2705
+ for (const line of view.running) out.push(` ${renderAgentLine(line, runningWidth)}`);
1919
2706
  const notes = renderNotes(view.notes, options.notes);
1920
2707
  if (notes.length > 0) out.push("", ...notes);
1921
2708
  return out.join("\n");
@@ -1926,6 +2713,7 @@ function renderStatus(view, options) {
1926
2713
  "",
1927
2714
  renderSections(view, options),
1928
2715
  "",
2716
+ KIND_LEGEND,
1929
2717
  LEGEND
1930
2718
  ].join("\n");
1931
2719
  }
@@ -1935,33 +2723,106 @@ function toItem(row) {
1935
2723
  session: row.session,
1936
2724
  text: row.text,
1937
2725
  status: row.status,
1938
- mainWorking: row.main_working === 1,
1939
2726
  updatedAt: row.updated_at
1940
2727
  };
1941
2728
  }
2729
+ function tableIsAbout(item, name) {
2730
+ const text = item?.text;
2731
+ return text?.startsWith(name) === true && !/[\w-]/.test(text.charAt(name.length));
2732
+ }
1942
2733
  function getTable(ctx, session) {
1943
2734
  const row = ctx.db.prepare("SELECT * FROM table_items WHERE session = ?").get(session);
1944
2735
  return row && toItem(row);
1945
2736
  }
1946
2737
  function setTable(ctx, session, input) {
1947
- const mainWorking = input.mainWorking ?? (input.status ? false : getTable(ctx, session)?.mainWorking ?? false);
1948
- if (mainWorking && input.status) throw new CarnetError("TABLE_STATUS_WITH_MAIN_WORKING", "A user-action status cannot be set while main is working");
1949
2738
  if (input.status !== void 0 && !isUserActionStatus(input.status)) throw new CarnetError("INVALID_STATUS", `Invalid table status "${String(input.status)}"`);
1950
- ctx.db.prepare(`INSERT INTO table_items (session, text, status, main_working, updated_at) VALUES (?, ?, ?, ?, ?)
2739
+ ctx.db.prepare(`INSERT INTO table_items (session, text, status, updated_at) VALUES (?, ?, ?, ?)
1951
2740
  ON CONFLICT(session) DO UPDATE SET text = excluded.text, status = excluded.status,
1952
- main_working = excluded.main_working, updated_at = excluded.updated_at`).run(session, sanitizeNote(input.text), input.status ?? null, mainWorking ? 1 : 0, nowIso(ctx));
2741
+ updated_at = excluded.updated_at`).run(session, sanitizeNote(input.text), input.status ?? null, nowIso(ctx));
1953
2742
  return getTable(ctx, session);
1954
2743
  }
1955
2744
  function clearTable(ctx, session) {
1956
2745
  ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(session);
1957
2746
  }
2747
+ // src/turn.ts
2748
+ const TURNS = [
2749
+ "working",
2750
+ "waiting",
2751
+ "failed"
2752
+ ];
2753
+ function getTurn(ctx, session) {
2754
+ return ctx.db.prepare("SELECT turn FROM sessions WHERE id = ?").get(session)?.turn ?? null;
2755
+ }
2756
+ function setTurn(ctx, session, turn) {
2757
+ ctx.db.prepare(`UPDATE sessions SET turn = ?1,
2758
+ turn_started_at = CASE
2759
+ WHEN ?1 IS NULL THEN NULL
2760
+ WHEN ?1 <> 'failed' AND turn IN ('working', 'waiting') THEN turn_started_at
2761
+ ELSE ?2 END
2762
+ WHERE id = ?3 AND turn IS NOT ?1`).run(turn, nowIso(ctx), session);
2763
+ }
2764
+ function startTurn(ctx, session) {
2765
+ setTurn(ctx, session, "working");
2766
+ }
2767
+ function waitTurn(ctx, session) {
2768
+ setTurn(ctx, session, "waiting");
2769
+ }
2770
+ function failTurn(ctx, session) {
2771
+ setTurn(ctx, session, "failed");
2772
+ }
2773
+ function endTurn(ctx, session) {
2774
+ setTurn(ctx, session, null);
2775
+ }
1958
2776
  // src/status/view.ts
1959
- const BUCKET = {
1960
- answer: 0,
1961
- review: 1
2777
+ const ACTION_RANK = {
2778
+ test: 0,
2779
+ answer: 1,
2780
+ validate: 2,
2781
+ triage: 3,
2782
+ apply: 4,
2783
+ inject: 5
1962
2784
  };
1963
- function bucketOf(status) {
1964
- return BUCKET[status] ?? 2;
2785
+ function plural(count, word) {
2786
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
2787
+ }
2788
+ function actionWord(agent) {
2789
+ const { kind, status } = agent;
2790
+ if (status === "answer") return kind === "plan" ? "validate" : "answer";
2791
+ if (status === "review" && kind !== "implement") return KIND_ACTIONS[kind];
2792
+ if (status === "apply" && kind === "implement") return "apply";
2793
+ if (status === "test") return status;
2794
+ return status === "discussing" ? "discuss" : status;
2795
+ }
2796
+ function actionDetail(ctx, agent, word) {
2797
+ if (word === "validate" || word === "answer") {
2798
+ const open = listQuestions(ctx, agent.session, agent.name, true).length;
2799
+ if (open > 0) return plural(open, "question");
2800
+ if (agent.status === "answer") return "questions";
2801
+ return "plan";
2802
+ }
2803
+ if (word === "triage") {
2804
+ const pending = listFindings(ctx, agent.session, agent.name, true);
2805
+ const blocking = pending.filter((finding) => finding.severity === "blocking").length;
2806
+ const parts = [
2807
+ pending.length > 0 ? plural(pending.length, "finding") : null,
2808
+ blocking > 0 ? `(${blocking} blocking)` : null,
2809
+ agent.target ? `→ ${agent.target}` : null
2810
+ ].filter(Boolean);
2811
+ return parts.length > 0 ? parts.join(" ") : null;
2812
+ }
2813
+ return null;
2814
+ }
2815
+ function waitingAction(ctx, agent) {
2816
+ const word = actionWord(agent);
2817
+ const detail = actionDetail(ctx, agent, word);
2818
+ return detail ? `${word} · ${detail}` : word;
2819
+ }
2820
+ function runningAction(agent) {
2821
+ return agent.promotedFrom ? `promoted from ${agent.promotedFrom}` : null;
2822
+ }
2823
+ function rankOf(agent) {
2824
+ if (agent.status === "answer") return ACTION_RANK.answer;
2825
+ return ACTION_RANK[actionWord(agent)] ?? Object.keys(ACTION_RANK).length;
1965
2826
  }
1966
2827
  function compareWaiting(left, right) {
1967
2828
  if (left.queueOrder !== null || right.queueOrder !== null) {
@@ -1969,28 +2830,38 @@ function compareWaiting(left, right) {
1969
2830
  if (right.queueOrder === null) return -1;
1970
2831
  return left.queueOrder - right.queueOrder;
1971
2832
  }
1972
- return bucketOf(left.status) - bucketOf(right.status) || left.startedAt.localeCompare(right.startedAt);
2833
+ return rankOf(left) - rankOf(right) || left.statusSince.localeCompare(right.statusSince) || left.name.localeCompare(right.name);
1973
2834
  }
1974
- function toLine(agent) {
2835
+ function toLine(agent, action) {
1975
2836
  return {
1976
2837
  name: agent.name,
2838
+ kind: agent.kind,
1977
2839
  status: agent.status,
1978
2840
  emoji: agent.status === "closed" ? "" : EMOJI[agent.status],
1979
- note: agent.note
2841
+ action,
2842
+ note: agent.note,
2843
+ pinned: agent.queueOrder !== null
1980
2844
  };
1981
2845
  }
1982
2846
  function formatClock(date) {
1983
2847
  return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
1984
2848
  }
1985
- function buildStatusView(ctx, session) {
1986
- const agents = listAgents(ctx, session.id);
1987
- const waiting = agents.filter((agent) => isUserActionStatus(agent.status)).sort(compareWaiting).map(toLine);
1988
- const running = agents.filter((agent) => agent.status === "running").map(toLine);
2849
+ function buildStatusView(ctx, session, options = {}) {
2850
+ const all = listAgents(ctx, session.id);
2851
+ const open = new Set(all.map((agent) => agent.name));
2852
+ const isBlocked = (agent) => agent.blockedOn !== null && open.has(agent.blockedOn);
2853
+ const agents = all.filter((agent) => !options.kind || agent.kind === options.kind);
2854
+ const table = getTable(ctx, session.id) ?? null;
2855
+ const waiting = agents.filter((agent) => isUserActionStatus(agent.status)).filter((agent) => !isBlocked(agent) && !tableIsAbout(table, agent.name)).sort(compareWaiting).map((agent) => toLine(agent, waitingAction(ctx, agent)));
2856
+ const blocked = agents.filter(isBlocked).map((agent) => toLine(agent, `→ ${agent.blockedOn}`));
2857
+ const running = agents.filter((agent) => agent.status === "running" && !isBlocked(agent)).map((agent) => toLine(agent, runningAction(agent)));
1989
2858
  return {
1990
2859
  time: formatClock(ctx.now()),
1991
2860
  sessionName: session.name,
1992
- table: getTable(ctx, session.id) ?? null,
2861
+ table,
2862
+ turn: getTurn(ctx, session.id),
1993
2863
  waiting,
2864
+ blocked,
1994
2865
  running,
1995
2866
  notes: sessionNoteActivity(ctx, session.id)
1996
2867
  };
@@ -2002,16 +2873,54 @@ function byHostAgentId(ctx, session, hostAgentId) {
2002
2873
  const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND host_agent_id = ?").get(session, hostAgentId);
2003
2874
  return row && toAgent(row);
2004
2875
  }
2005
- function pairSubagent(ctx, session, hostAgentId) {
2876
+ function unpairedByName(ctx, session, names) {
2877
+ for (const name of names) {
2878
+ const row = ctx.db.prepare(`SELECT * FROM agents
2879
+ WHERE session = ? AND name = ? AND status != 'closed' AND host_agent_id IS NULL`).get(session, name);
2880
+ if (row) return row;
2881
+ }
2882
+ }
2883
+ function unpairedAgent(ctx, session, names) {
2884
+ const row = unpairedByName(ctx, session, names);
2885
+ return row && toAgent(row);
2886
+ }
2887
+ function pendingPlanAgent(ctx, session) {
2888
+ const row = ctx.db.prepare(`SELECT * FROM agents
2889
+ WHERE session = ? AND kind = 'plan' AND status = 'running' AND host_agent_id IS NULL
2890
+ ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session);
2891
+ return row && toAgent(row);
2892
+ }
2893
+ function requestLaunch(ctx, session, name) {
2894
+ ctx.db.prepare("UPDATE agents SET launch_requested_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
2895
+ }
2896
+ function pairsByFallback(agentType) {
2897
+ return agentType === void 0 || agentType === "fork" || /^rucher[\w-]*:/.test(agentType);
2898
+ }
2899
+ function openByName(ctx, session, names) {
2900
+ for (const name of names) {
2901
+ const row = ctx.db.prepare(`SELECT * FROM agents WHERE session = ? AND name = ? AND status != 'closed'`).get(session, name);
2902
+ if (row) return row;
2903
+ }
2904
+ }
2905
+ function pairWith(ctx, session, name, hostAgentId) {
2906
+ ctx.db.prepare("UPDATE agents SET host_agent_id = ?, launch_requested_at = NULL WHERE session = ? AND name = ?").run(hostAgentId, session, name);
2907
+ return byHostAgentId(ctx, session, hostAgentId);
2908
+ }
2909
+ function pairSubagent(ctx, session, hostAgentId, names = [], agentType) {
2006
2910
  const paired = byHostAgentId(ctx, session, hostAgentId);
2007
2911
  if (paired) return paired;
2912
+ const named = openByName(ctx, session, names);
2913
+ if (named) return pairWith(ctx, session, named.name, hostAgentId);
2914
+ if (!pairsByFallback(agentType)) return void 0;
2008
2915
  const since = (/* @__PURE__ */ new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS)).toISOString();
2009
2916
  const row = ctx.db.prepare(`SELECT * FROM agents
2010
- WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND started_at >= ?
2011
- ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session, since);
2012
- if (!row) return void 0;
2013
- ctx.db.prepare("UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?").run(hostAgentId, session, row.name);
2014
- return byHostAgentId(ctx, session, hostAgentId);
2917
+ WHERE session = ? AND status != 'closed' AND host_agent_id IS NULL
2918
+ AND launch_requested_at >= ?
2919
+ ORDER BY launch_requested_at ASC, rowid ASC LIMIT 1`).get(session, since) ?? ctx.db.prepare(`SELECT * FROM agents
2920
+ WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND blocked_on IS NULL
2921
+ AND started_at >= ?
2922
+ ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session, since);
2923
+ return row && pairWith(ctx, session, row.name, hostAgentId);
2015
2924
  }
2016
2925
  function byName(ctx, session, name) {
2017
2926
  const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND name = ?").get(session, name);
@@ -2035,7 +2944,7 @@ function stopSubagent(ctx, session, hostAgentId, names = []) {
2035
2944
  publishPending(ctx, session, agent.name);
2036
2945
  return byHostAgentId(ctx, session, hostAgentId);
2037
2946
  }
2038
- ctx.db.prepare("UPDATE agents SET status = 'review', note = ?, updated_at = ? WHERE session = ? AND name = ?").run(STOPPED_NOTE, nowIso(ctx), session, agent.name);
2947
+ moveAgentStatus(ctx, session, agent.name, "review", STOPPED_NOTE);
2039
2948
  logEvent(ctx, session, {
2040
2949
  type: "finished",
2041
2950
  agent: agent.name,
@@ -2057,6 +2966,9 @@ var Carnet = class {
2057
2966
  workspace: workspace?.name ?? null
2058
2967
  };
2059
2968
  }
2969
+ now() {
2970
+ return this.ctx.now();
2971
+ }
2060
2972
  requireWorkspace() {
2061
2973
  return requireWorkspace(this.workspace);
2062
2974
  }
@@ -2067,15 +2979,25 @@ var Carnet = class {
2067
2979
  ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.workspace ?? void 0),
2068
2980
  upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.workspace, payload, env),
2069
2981
  touch: (id) => touchSession(this.ctx, id),
2070
- merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
2982
+ merge: (fromId, intoId) => {
2983
+ const result = mergeSessions(this.ctx, fromId, intoId);
2984
+ this.releaseClosedSandboxes(fromId);
2985
+ this.releaseClosedSandboxes(intoId);
2986
+ return result;
2987
+ },
2071
2988
  purge: (keepId, days) => purgeSessions(this.ctx, keepId, days),
2072
2989
  name: (id, name, purpose) => nameSession(this.ctx, id, name, purpose),
2073
2990
  adoptTitle: (id, title) => adoptTitle(this.ctx, id, title),
2074
2991
  list: (options) => listSessions(this.ctx, options),
2075
- drop: (id) => dropSession(this.ctx, id),
2992
+ drop: (id) => {
2993
+ const session = dropSession(this.ctx, id);
2994
+ this.releaseClosedSandboxes(id);
2995
+ return session;
2996
+ },
2076
2997
  default: () => defaultSession(this.ctx),
2077
2998
  byName: (name) => sessionByName(this.ctx, name),
2078
2999
  byHostProcess: (host, processId) => sessionByHostProcess(this.ctx, host, processId),
3000
+ recordPluginVersion: (id, version) => recordPluginVersion(this.ctx, id, version),
2079
3001
  recordPromptVersion: (id, version) => recordPromptVersion(this.ctx, id, version),
2080
3002
  setParent: (id, parentId) => setParent(this.ctx, id, parentId),
2081
3003
  setStatus: (id, status) => setSessionStatus(this.ctx, id, status),
@@ -2088,28 +3010,87 @@ var Carnet = class {
2088
3010
  staleTemp: (olderThanMilliseconds) => staleTempSessions(this.ctx, olderThanMilliseconds),
2089
3011
  resetDead: (isAlive) => resetDeadSessions(this.ctx, isAlive)
2090
3012
  };
3013
+ releaseSandbox(agent) {
3014
+ if (!agent.sandbox) return {
3015
+ ...agent,
3016
+ sandboxRemoved: false
3017
+ };
3018
+ const sandboxRemoved = removeSandbox(this.workspace, agent.sandbox);
3019
+ clearSandbox(this.ctx, agent.session, agent.name);
3020
+ return {
3021
+ ...agent,
3022
+ sandbox: null,
3023
+ sandboxRemoved
3024
+ };
3025
+ }
3026
+ releaseClosedSandboxes(session) {
3027
+ let removed = 0;
3028
+ for (const row of closedSandboxes(this.ctx, session)) {
3029
+ if (removeSandbox(this.workspace, row.sandbox)) removed += 1;
3030
+ clearSandbox(this.ctx, row.session, row.name);
3031
+ }
3032
+ return removed;
3033
+ }
2091
3034
  agents = {
2092
3035
  get: (session, name) => getAgent(this.ctx, session, name),
2093
- start: (session, input) => startAgent(this.ctx, session, input),
3036
+ start: (session, input) => {
3037
+ const sandbox = input.sandbox ? resolveSandbox(this.workspace, input.sandbox) : void 0;
3038
+ const agent = startAgent(this.ctx, session, {
3039
+ ...input,
3040
+ sandbox
3041
+ });
3042
+ if (sandbox) createSandbox(sandbox);
3043
+ return agent;
3044
+ },
2094
3045
  update: (session, name, input) => updateAgent(this.ctx, session, name, input),
2095
3046
  finish: (session, name, input) => finishAgent(this.ctx, session, name, input),
2096
- drop: (session, name, reason) => dropAgent(this.ctx, session, name, reason),
3047
+ drop: (session, name, reason) => this.releaseSandbox(dropAgent(this.ctx, session, name, reason)),
3048
+ close: (session, name, event) => this.releaseSandbox(closeAgent(this.ctx, session, name, event)),
3049
+ promote: (session, name, input) => {
3050
+ const agent = promoteAgent(this.ctx, session, name, input);
3051
+ return agent.kind === "implement" ? this.releaseSandbox(agent) : {
3052
+ ...agent,
3053
+ sandboxRemoved: false
3054
+ };
3055
+ },
2097
3056
  list: (session, options) => listAgents(this.ctx, session, options),
2098
3057
  reorderQueue: (session, names) => reorderQueue(this.ctx, session, names),
2099
- pairSubagent: (session, hostAgentId) => pairSubagent(this.ctx, session, hostAgentId),
3058
+ byHostAgentId: (session, hostAgentId) => byHostAgentId(this.ctx, session, hostAgentId),
3059
+ pairSubagent: (session, hostAgentId, names, agentType) => pairSubagent(this.ctx, session, hostAgentId, names, agentType),
3060
+ unpaired: (session, names) => unpairedAgent(this.ctx, session, names),
3061
+ pendingPlan: (session) => pendingPlanAgent(this.ctx, session),
3062
+ requestLaunch: (session, name) => requestLaunch(this.ctx, session, name),
2100
3063
  stopSubagent: (session, hostAgentId, names) => stopSubagent(this.ctx, session, hostAgentId, names)
2101
3064
  };
3065
+ questions = {
3066
+ list: (session, agent, openOnly) => listQuestions(this.ctx, session, agent, openOnly),
3067
+ add: (session, agent, inputs) => addQuestions(this.ctx, session, agent, inputs),
3068
+ answer: (session, agent, answers) => answerQuestions(this.ctx, session, agent, answers)
3069
+ };
3070
+ findings = {
3071
+ list: (session, agent, pendingOnly) => listFindings(this.ctx, session, agent, pendingOnly),
3072
+ replace: (session, agent, inputs) => replaceFindings(this.ctx, session, agent, inputs),
3073
+ decide: (session, agent, decisions) => decideFindings(this.ctx, session, agent, decisions)
3074
+ };
2102
3075
  table = {
2103
3076
  get: (session) => getTable(this.ctx, session),
2104
3077
  set: (session, input) => setTable(this.ctx, session, input),
2105
3078
  clear: (session) => clearTable(this.ctx, session)
2106
3079
  };
3080
+ turn = {
3081
+ get: (session) => getTurn(this.ctx, session),
3082
+ start: (session) => startTurn(this.ctx, session),
3083
+ wait: (session) => waitTurn(this.ctx, session),
3084
+ fail: (session) => failTurn(this.ctx, session),
3085
+ end: (session) => endTurn(this.ctx, session)
3086
+ };
2107
3087
  events = {
2108
3088
  log: (session, input) => logEvent(this.ctx, session, input),
2109
- read: (session, limit, agentOnly) => readEvents(this.ctx, {
3089
+ read: (session, limit, agentOnly, kind) => readEvents(this.ctx, {
2110
3090
  session,
2111
3091
  limit,
2112
- agentOnly
3092
+ agentOnly,
3093
+ kind
2113
3094
  })
2114
3095
  };
2115
3096
  notes = {
@@ -2130,8 +3111,8 @@ var Carnet = class {
2130
3111
  copyRepos: (from, into) => copyInjectedRepos(this.ctx, from, into)
2131
3112
  };
2132
3113
  status = {
2133
- view: (session) => buildStatusView(this.ctx, session),
2134
- render: (session, options) => renderStatus(buildStatusView(this.ctx, session), options),
3114
+ view: (session, options) => buildStatusView(this.ctx, session, options),
3115
+ render: (session, options) => renderStatus(buildStatusView(this.ctx, session, options), options),
2135
3116
  sections: (session) => renderSections(buildStatusView(this.ctx, session))
2136
3117
  };
2137
3118
  close() {
@@ -2165,6 +3146,347 @@ function openResolvedCarnet(options = {}) {
2165
3146
  function openWorkspaceCarnet(workspace, options = {}) {
2166
3147
  return new Carnet(openStore(options), workspace, options);
2167
3148
  }
3149
+ // src/report.ts
3150
+ const HEADING = /^##\s+(.+?)\s*$/;
3151
+ const FENCE = /^\s*(```|~~~)/;
3152
+ function normalize(text) {
3153
+ return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "");
3154
+ }
3155
+ function hasSection(markdown, names) {
3156
+ return extractSection(markdown, names) !== void 0;
3157
+ }
3158
+ function headings(lines) {
3159
+ let fenced = false;
3160
+ return lines.map((line) => {
3161
+ if (FENCE.test(line)) fenced = !fenced;
3162
+ return fenced ? void 0 : HEADING.exec(line)?.[1];
3163
+ });
3164
+ }
3165
+ function headingTitle(heading) {
3166
+ const [title = ""] = normalize(heading).replace(/^\d+[.)]\s*/, "").replace(/[*_`]/g, "").split(/[:(]/);
3167
+ return title.trim();
3168
+ }
3169
+ function escape(text) {
3170
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3171
+ }
3172
+ function matchRank(heading, names) {
3173
+ const title = headingTitle(heading);
3174
+ if (names.some((name) => title === name || title === `${name}s`)) return 1;
3175
+ return names.some((name) => new RegExp(`(^|[^a-z0-9])${escape(name)}s?($|[^a-z0-9])`).test(title)) ? 2 : 0;
3176
+ }
3177
+ function extractSection(markdown, names) {
3178
+ const wanted = names.map(normalize);
3179
+ const lines = markdown.split("\n");
3180
+ const titles = headings(lines);
3181
+ const ranks = titles.map((heading) => heading === void 0 ? 0 : matchRank(heading, wanted));
3182
+ const exact = ranks.indexOf(1);
3183
+ const start = exact !== -1 ? exact : ranks.indexOf(2);
3184
+ if (start === -1) return void 0;
3185
+ const end = titles.findIndex((heading, index) => index > start && heading !== void 0);
3186
+ return lines.slice(start + 1, end === -1 ? void 0 : end).join("\n").trim();
3187
+ }
3188
+ function readReport(path) {
3189
+ return path && existsSync(path) ? readFileSync(path, "utf8") : void 0;
3190
+ }
3191
+ function appendToReport(path, markdown) {
3192
+ const current = readReport(path);
3193
+ if (current === void 0 || !path) return;
3194
+ const separator = current.endsWith("\n\n") ? "" : current.endsWith("\n") ? "\n" : "\n\n";
3195
+ appendFileSync(path, `${separator}${markdown.trimEnd()}\n`);
3196
+ }
3197
+ function keptReportPath(report, kind) {
3198
+ return report.replace(/(\.md)?$/, kind === "plan" ? ".plan.md" : ".research.md");
3199
+ }
3200
+ // src/kinds.ts
3201
+ function kindAction(agent) {
3202
+ return KIND_ACTIONS[agent.kind];
3203
+ }
3204
+ function finishWithItems(carnet, session, name, input) {
3205
+ const agent = requireAgent(carnet, session, name);
3206
+ if (input.findings?.length && agent.kind !== "review") throw new CarnetError("INVALID_KIND", `Only a review agent reports findings; ${name} is ${agent.kind}`);
3207
+ const report = readReport(input.reportPath);
3208
+ if (input.questions?.length) {
3209
+ const open = carnet.questions.add(session, name, input.questions).filter((question) => question.answer === null);
3210
+ if (report !== void 0 && !hasSection(report, ["questions"])) appendToReport(input.reportPath, renderQuestions(open));
3211
+ }
3212
+ if (input.findings?.length) {
3213
+ const findings = carnet.findings.replace(session, name, input.findings);
3214
+ if (report !== void 0 && !hasSection(report, ["findings"])) appendToReport(input.reportPath, renderFindings(findings));
3215
+ }
3216
+ const openQuestions = carnet.questions.list(session, name, true).length;
3217
+ return carnet.agents.finish(session, name, {
3218
+ reportPath: input.reportPath,
3219
+ hasQuestions: openQuestions > 0 || input.hasQuestions === true
3220
+ });
3221
+ }
3222
+ function requireAgent(carnet, session, name) {
3223
+ const agent = carnet.agents.get(session, name);
3224
+ if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
3225
+ return agent;
3226
+ }
3227
+ function locateAgent(carnet, name) {
3228
+ const found = carnet.sessions.list({ includeTemp: true }).flatMap((session) => {
3229
+ const agent = carnet.agents.get(session.id, name);
3230
+ return agent ? [{
3231
+ session,
3232
+ agent
3233
+ }] : [];
3234
+ });
3235
+ const open = found.filter((entry) => entry.agent.status !== "closed");
3236
+ const only = found.length === 1 ? found[0] : open.length === 1 ? open[0] : void 0;
3237
+ if (only) return only;
3238
+ if (found.length === 0) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in the open sessions of this workspace`);
3239
+ throw new CarnetError("AGENT_AMBIGUOUS", `"${name}" is in several sessions: ${found.map((entry) => entry.session.name ?? shortId(entry.session.id)).join(", ")}; pass --session`);
3240
+ }
3241
+ function nextAgent(carnet, session, prefix) {
3242
+ if (!prefix) return carnet.status.view(carnet.sessions.require(session)).waiting[0]?.name;
3243
+ if (carnet.agents.get(session, prefix)) return prefix;
3244
+ const matches = carnet.agents.list(session, { includeClosed: true }).filter((agent) => agent.name.startsWith(prefix)).map((agent) => agent.name);
3245
+ if (matches.length === 1) return matches[0];
3246
+ if (matches.length === 0) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${prefix}" in this session`);
3247
+ throw new CarnetError("AGENT_AMBIGUOUS", `"${prefix}" matches ${matches.join(", ")}: which one?`);
3248
+ }
3249
+ function formatQuestion(question) {
3250
+ const lines = [`${question.n}/${question.total} ${question.text}`];
3251
+ if (question.context) lines.push(` context: ${question.context}`);
3252
+ lines.push(` recommended: ${question.recommendation}`);
3253
+ if (question.alternatives.length) lines.push(` alternatives: ${question.alternatives.join(" | ")}`);
3254
+ return lines.join("\n");
3255
+ }
3256
+ function openQuestionsText(carnet, session, name) {
3257
+ requireAgent(carnet, session, name);
3258
+ const open = carnet.questions.list(session, name, true);
3259
+ if (!open.length) return `${name}: no open questions`;
3260
+ const total = open[0]?.total ?? open.length;
3261
+ return [`${name}: ${open.length} of ${total} open`, ...open.map(formatQuestion)].join("\n");
3262
+ }
3263
+ function today(carnet) {
3264
+ return carnet.now().toISOString().slice(0, 10);
3265
+ }
3266
+ function answerQuestionsText(carnet, session, name, answers) {
3267
+ const agent = requireAgent(carnet, session, name);
3268
+ const questions = carnet.questions.answer(session, name, answers);
3269
+ const lines = [...answers].sort((a, b) => a.n - b.n).map((answer) => `${answer.n}. ${answer.answer.trim()}`);
3270
+ appendToReport(agent.reportPath, `## Answers (${today(carnet)})\n\n${lines.join("\n")}`);
3271
+ const open = questions.filter((question) => question.answer === null).length;
3272
+ if (open) return `answered ${answers.length} · ${open} of ${questions.length} open`;
3273
+ const next = statusAfterAnswers(agent.kind);
3274
+ carnet.events.log(session, {
3275
+ type: "answered",
3276
+ agent: name
3277
+ });
3278
+ carnet.agents.update(session, name, {
3279
+ status: next,
3280
+ note: null
3281
+ });
3282
+ return `all ${questions.length} answered · ${EMOJI[next]} ${name} ${next}`;
3283
+ }
3284
+ const FOR_MAIN = ["for the main", "pour le main"];
3285
+ const PLAN = ["plan"];
3286
+ function injectReport(carnet, session, name, input) {
3287
+ const agent = requireAgent(carnet, session, name);
3288
+ const report = readReport(agent.reportPath);
3289
+ if (report === void 0) throw new CarnetError("REPORT_MISSING", `${name} has no report to inject yet`);
3290
+ const names = input.section ? [input.section] : agent.kind === "plan" || agent.promotedFrom === "plan" ? PLAN : FOR_MAIN;
3291
+ const text = input.full ? report.trim() : extractSection(report, names);
3292
+ if (text === void 0) throw new CarnetError("SECTION_NOT_FOUND", `No "## ${names[0]}" section in ${name}'s report; pass section or full`);
3293
+ const lineCount = text.split("\n").length;
3294
+ const note = `${input.full ? "full report" : names[0]}, ${lineCount} lines`;
3295
+ let removed = false;
3296
+ if (agent.kind === "research" && agent.status !== "closed") removed = carnet.agents.close(session, name, {
3297
+ type: "injected",
3298
+ note,
3299
+ link: agent.reportPath ?? void 0
3300
+ }).sandboxRemoved;
3301
+ else carnet.events.log(session, {
3302
+ type: "injected",
3303
+ agent: name,
3304
+ note
3305
+ });
3306
+ const confirmation = `${name} injected (${lineCount} lines)${sandboxRemovedSuffix(removed)}`;
3307
+ return input.echo === false ? confirmation : `${confirmation}\n${text}`;
3308
+ }
3309
+ function firstLines(text, max) {
3310
+ if (!text) return [];
3311
+ const lines = text.split("\n").filter((line) => line.trim() !== "");
3312
+ return lines.length > max ? [...lines.slice(0, max), "…"] : lines;
3313
+ }
3314
+ function firstParagraph(text, max) {
3315
+ return firstLines(text?.split(/\n\s*\n/)[0], max);
3316
+ }
3317
+ const TOP_LEVEL_ITEM = /^(-|\*|\d+\.)\s|^\*\*/;
3318
+ function topLevelItems(text, max) {
3319
+ return firstLines(text?.split("\n").filter((line) => TOP_LEVEL_ITEM.test(line)).join("\n"), max);
3320
+ }
3321
+ function planSteps(plan) {
3322
+ if (!plan) return [];
3323
+ const headings = plan.split("\n").filter((line) => /^###\s/.test(line));
3324
+ return (headings.length > 0 ? headings : plan.split("\n").filter((line) => /^\d+\.\s/.test(line))).map((line) => line.replace(/^###\s+/, "").trim());
3325
+ }
3326
+ function block(title, lines) {
3327
+ return lines.length > 0 ? [`${title}:`, ...lines] : [];
3328
+ }
3329
+ function reportSummary(carnet, session, name) {
3330
+ const agent = requireAgent(carnet, session, name);
3331
+ const report = readReport(agent.reportPath);
3332
+ if (report === void 0) throw new CarnetError("REPORT_MISSING", `${name} has no report yet`);
3333
+ const section = (...names) => extractSection(report, names);
3334
+ const emoji = agent.status === "closed" ? "" : `${EMOJI[agent.status]} `;
3335
+ const lines = [`${name} ${kindTag(agent.kind)} ${emoji}→ ${kindAction(agent)}`];
3336
+ if (agent.kind === "research") lines.push(...block("For the main", firstLines(section(...FOR_MAIN), 15)), ...block("Gaps", firstLines(section("gaps"), 3)));
3337
+ else if (agent.kind === "plan") {
3338
+ const plan = section(...PLAN);
3339
+ const steps = planSteps(plan);
3340
+ const open = carnet.questions.list(session, name, true).length;
3341
+ const understanding = section("understanding");
3342
+ 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`);
3343
+ } 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)));
3344
+ else {
3345
+ const pending = carnet.findings.list(session, name, true);
3346
+ const bySeverity = [
3347
+ "blocking",
3348
+ "to_fix",
3349
+ "suggestion"
3350
+ ].map((severity) => [severity, pending.filter((f) => f.severity === severity).length]).filter(([, count]) => count > 0).map(([severity, count]) => `${count} ${severity.replace("_", " ")}`);
3351
+ lines.push(...block("Verdict", firstLines(section("verdict"), 1)), `Findings: ${bySeverity.length > 0 ? bySeverity.join(", ") : "none pending"}`, ...block("Not verified", firstLines(section("not verified"), 3)));
3352
+ }
3353
+ if (!hasSection(report, [
3354
+ ...FOR_MAIN,
3355
+ ...PLAN,
3356
+ "understanding",
3357
+ "done",
3358
+ "verdict"
3359
+ ])) lines.push(...block("Report", firstLines(report.replace(/^#[^\n]*\n/, ""), 10)));
3360
+ lines.push(`report: ${agent.reportPath}`);
3361
+ return lines.join("\n");
3362
+ }
3363
+ function decisions(questions) {
3364
+ return questions.flatMap((question) => [
3365
+ `${question.n}. ${question.text}`,
3366
+ ` Recommended: ${question.recommendation}`,
3367
+ ` Answered: ${question.answer ?? "open"}`
3368
+ ]);
3369
+ }
3370
+ function reportDocument(carnet, session, name) {
3371
+ const agent = requireAgent(carnet, session, name);
3372
+ const report = readReport(agent.reportPath);
3373
+ if (report === void 0 || !agent.reportPath) throw new CarnetError("REPORT_MISSING", `${name} has no report yet`);
3374
+ const understanding = extractSection(report, ["understanding"]);
3375
+ const plan = extractSection(report, PLAN);
3376
+ if (agent.kind !== "plan" || plan === void 0) return {
3377
+ text: report.trimEnd(),
3378
+ path: agent.reportPath
3379
+ };
3380
+ const questions = carnet.questions.list(session, name);
3381
+ const lines = [`# ${name} ${kindTag(agent.kind)}: the plan as answered`];
3382
+ if (understanding !== void 0) lines.push("", "## Understanding", "", understanding);
3383
+ lines.push("", "## Plan", "", plan);
3384
+ if (questions.length > 0) lines.push("", "## Decisions", "", ...decisions(questions));
3385
+ return {
3386
+ text: lines.join("\n"),
3387
+ path: agent.reportPath
3388
+ };
3389
+ }
3390
+ function promoteText(carnet, session, name, input) {
3391
+ const current = requireAgent(carnet, session, name);
3392
+ const agent = carnet.agents.promote(session, name, input);
3393
+ const lines = [`${EMOJI.running} ${name} promoted to ${agent.kind}`];
3394
+ const from = current.kind;
3395
+ if ((from === "research" || from === "plan") && current.reportPath) {
3396
+ if (existsSync(current.reportPath)) {
3397
+ const kept = keptReportPath(current.reportPath, from);
3398
+ copyFileSync(current.reportPath, kept);
3399
+ lines.push(`${from === "plan" ? "plan" : "research"} kept: ${kept}`);
3400
+ }
3401
+ }
3402
+ if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);
3403
+ if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);
3404
+ if (agent.sandbox) lines.push(`sandbox kept: ${agent.sandbox}`);
3405
+ if (agent.sandboxRemoved) lines.push("sandbox removed");
3406
+ return lines.join("\n");
3407
+ }
3408
+ function reviewContext(carnet, session, target) {
3409
+ const range = mainTargetRange(target);
3410
+ if (range !== void 0) return range ? `target main, commits ${range}` : "target main, the uncommitted changes of the main repo";
3411
+ const agent = requireAgent(carnet, session, target);
3412
+ if (agent.kind !== "implement") throw new CarnetError("INVALID_TARGET", `${target} is ${agent.kind}, not implement`);
3413
+ const lines = [`target ${target} (implement${agent.promotedFrom ? `, promoted from ${agent.promotedFrom}` : ""}, ${agent.status})`];
3414
+ if (agent.task) lines.push(`task: ${agent.task}`);
3415
+ if (agent.reportPath) lines.push(`report: ${agent.reportPath}`);
3416
+ if (agent.worktree) lines.push(`worktree: ${agent.worktree}`);
3417
+ if (agent.baseCommit) lines.push(`base: ${agent.baseCommit}`);
3418
+ for (const kind of ["research", "plan"]) {
3419
+ const kept = agent.reportPath ? keptReportPath(agent.reportPath, kind) : null;
3420
+ if (kept && existsSync(kept)) lines.push(`${kind === "plan" ? "plan" : "research"}: ${kept}`);
3421
+ }
3422
+ const answered = carnet.questions.list(session, target).filter((question) => question.answer);
3423
+ if (answered.length) {
3424
+ lines.push("answers:");
3425
+ for (const question of answered) lines.push(` ${question.n}. ${question.text} → ${question.answer}`);
3426
+ }
3427
+ return lines.join("\n");
3428
+ }
3429
+ function findingsText(carnet, session, name, pendingOnly) {
3430
+ const agent = requireAgent(carnet, session, name);
3431
+ const findings = carnet.findings.list(session, name, pendingOnly);
3432
+ const all = carnet.findings.list(session, name);
3433
+ if (!findings.length) return `${name}: ${all.length ? "no pending findings" : "no findings"}`;
3434
+ const pending = all.filter((finding) => finding.decision === null).length;
3435
+ const target = agent.target ? ` · target ${agent.target}` : "";
3436
+ const header = `${name}: ${pending} of ${all.length} pending${target}`;
3437
+ const sendable = canSendBack(carnet, session, agent.target);
3438
+ return [header, ...findings.map((finding) => {
3439
+ const after = finding.decision ? ` → ${finding.decision}${finding.reason ? ` (${finding.reason})` : ""}` : ` · route: ${recommendedRoute(finding.severity, sendable)}`;
3440
+ return `${formatFinding(finding)}${after}`;
3441
+ })].join("\n");
3442
+ }
3443
+ function canSendBack(carnet, session, target) {
3444
+ if (!target || mainTargetRange(target) !== void 0) return false;
3445
+ const source = carnet.agents.get(session, target);
3446
+ return !!source && source.status !== "test" && source.status !== "closed";
3447
+ }
3448
+ const BRIEF_VERBS = {
3449
+ implement: "fix",
3450
+ plan: "plan the fix of",
3451
+ research: "confirm the cause of"
3452
+ };
3453
+ function findingsBrief(carnet, session, name, numbers, kind) {
3454
+ const agent = requireAgent(carnet, session, name);
3455
+ if (agent.kind !== "review") throw new CarnetError("INVALID_KIND", `${name} is ${agent.kind}, not review`);
3456
+ if (!SPAWN_KINDS.includes(kind)) throw new CarnetError("INVALID_KIND", `An agent for findings is ${SPAWN_KINDS.join(", ")}`);
3457
+ const findings = carnet.findings.list(session, name);
3458
+ const missing = numbers.filter((n) => !findings.some((finding) => finding.n === n));
3459
+ if (missing.length) throw new CarnetError("FINDING_NOT_FOUND", `No finding ${missing.join(", ")} for ${name}; review_findings lists them`);
3460
+ const report = agent.reportPath ? ` (report: ${agent.reportPath})` : "";
3461
+ const lines = [`From review ${name} of ${agent.target ?? "its target"}${report}.`];
3462
+ if (agent.target) lines.push(reviewContext(carnet, session, agent.target));
3463
+ lines.push(`Findings to ${BRIEF_VERBS[kind]}:`);
3464
+ for (const finding of findings.filter((item) => numbers.includes(item.n))) {
3465
+ const location = finding.location ? ` ${finding.location}` : "";
3466
+ lines.push(`${finding.n}. [${finding.severity}]${location} — ${finding.text}`);
3467
+ if (finding.fix) lines.push(` Proposed fix: ${finding.fix}`);
3468
+ }
3469
+ return lines.join("\n");
3470
+ }
3471
+ function decideText(carnet, session, name, decisions) {
3472
+ const agent = requireAgent(carnet, session, name);
3473
+ if (agent.kind !== "review") throw new CarnetError("INVALID_KIND", `${name} is ${agent.kind}, not review`);
3474
+ 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`);
3475
+ const findings = carnet.findings.decide(session, name, decisions);
3476
+ const pending = findings.filter((finding) => finding.decision === null).length;
3477
+ if (pending) return `decided ${decisions.length} · ${pending} of ${findings.length} pending`;
3478
+ const count = (decision) => findings.filter((finding) => finding.decision === decision).length;
3479
+ const note = `${count("sent")} sent, ${count("fixed")} fixed, ${count("ignored")} ignored`;
3480
+ carnet.agents.close(session, name, {
3481
+ type: "triaged",
3482
+ note,
3483
+ link: agent.reportPath ?? void 0
3484
+ });
3485
+ const lines = [`${name} triaged: ${note}, closed`];
3486
+ const sent = findings.filter((finding) => finding.decision === "sent");
3487
+ if (sent.length && agent.target) lines.push(`send to ${agent.target}:`, ...sent.map(formatFinding));
3488
+ return lines.join("\n");
3489
+ }
2168
3490
  // src/resume.ts
2169
3491
  const RESUME_EVENTS = 20;
2170
3492
  const RESUME_MAX_CHARACTERS = 2e3;
@@ -2202,28 +3524,29 @@ const AGENT_STEPS = [
2202
3524
  "dropped"
2203
3525
  ];
2204
3526
  const DEFAULT_NEXT = {
2205
- answered: "apply",
2206
3527
  applied: "test",
2207
- tested: "commit"
3528
+ tested: "test"
2208
3529
  };
2209
- function tableIsAbout(carnet, session, name) {
2210
- const text = carnet.table.get(session)?.text;
2211
- return text?.startsWith(name) === true && !/[\w-]/.test(text.charAt(name.length));
2212
- }
2213
3530
  function clearTableOf(carnet, session, name) {
2214
- if (tableIsAbout(carnet, session, name)) carnet.table.clear(session);
3531
+ if (tableIsAbout(carnet.table.get(session), name)) carnet.table.clear(session);
2215
3532
  }
2216
3533
  function stepAgent(carnet, session, input) {
2217
3534
  const { name, step, commit, note } = input;
2218
- if (!carnet.agents.get(session, name)) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
3535
+ const agent = carnet.agents.get(session, name);
3536
+ if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
2219
3537
  switch (step) {
2220
- case "applying":
2221
- carnet.table.set(session, {
2222
- text: `${name} applying`,
2223
- mainWorking: true
3538
+ case "applying": {
3539
+ if (agent.kind !== "implement") throw new CarnetError("INVALID_KIND", `${name} is ${agent.kind}: only an implement agent is applied`);
3540
+ carnet.table.set(session, { text: `${name} applying` });
3541
+ carnet.agents.update(session, name, {
3542
+ status: agent.status,
3543
+ note: note ?? null,
3544
+ blockedOn: null
2224
3545
  });
2225
- return `⚙️ ${name} applying`;
2226
- case "committed":
3546
+ const reviews = carnet.agents.list(session).filter((other) => other.kind === "review" && other.target === name);
3547
+ return `⚙️ ${name} applying${reviews.length ? `\nwarning: review ${reviews.map((review) => review.name).join(", ")} not triaged yet` : ""}`;
3548
+ }
3549
+ case "committed": {
2227
3550
  if (!commit) throw new CarnetError("COMMIT_REQUIRED", "The committed step needs the commit");
2228
3551
  carnet.events.log(session, {
2229
3552
  type: "committed",
@@ -2231,30 +3554,32 @@ function stepAgent(carnet, session, input) {
2231
3554
  commit,
2232
3555
  note
2233
3556
  });
2234
- carnet.agents.drop(session, name, `committed ${commit}`);
3557
+ const closed = carnet.agents.drop(session, name, `committed ${commit}`);
2235
3558
  clearTableOf(carnet, session, name);
2236
- return `${EMOJI.commit} ${name} committed ${commit}, closed`;
2237
- case "dropped":
2238
- carnet.agents.drop(session, name, note);
3559
+ return `✅ ${name} committed ${commit}, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;
3560
+ }
3561
+ case "dropped": {
3562
+ const closed = carnet.agents.drop(session, name, note);
2239
3563
  clearTableOf(carnet, session, name);
2240
- return `${name} dropped, closed`;
3564
+ return `${name} dropped, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;
3565
+ }
2241
3566
  default: {
2242
- const next = input.next ?? DEFAULT_NEXT[step];
3567
+ const next = input.next ?? (step === "answered" ? statusAfterAnswers(agent.kind) : DEFAULT_NEXT[step]);
2243
3568
  carnet.events.log(session, {
2244
3569
  type: step,
2245
3570
  agent: name,
2246
3571
  note
2247
3572
  });
2248
- carnet.agents.update(session, name, { status: next });
2249
- if (next === "running") clearTableOf(carnet, session, name);
2250
- else if (step !== "answered") carnet.table.set(session, {
2251
- text: `${name} ${step}, ${next} next`,
2252
- status: next
3573
+ carnet.agents.update(session, name, {
3574
+ status: next,
3575
+ note: note ?? null,
3576
+ blockedOn: null
2253
3577
  });
3578
+ if (next === "running" || step !== "answered") clearTableOf(carnet, session, name);
2254
3579
  return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;
2255
3580
  }
2256
3581
  }
2257
3582
  }
2258
- export { workspaceSessionCounts as $, migrations as $t, memoryMaxCharacters as A, addWorkspaceRepo as At, sessionNoteActivity as B, workspaceHosts as Bt, renderNotesSummary as C, workspaceRules as Ct, DEFAULT_PURGE_DAYS as D, AGENTS_FILE as Dt, renderTableLine as E, shortId as Et, NOTE_TEXT_LIMIT as F, isWorkspaceName as Ft, repoNameFor as G, reportPath as Gt, workspaceRepoNames as H, databasePath as Ht, STALE_AFTER_ACTIVE_DAYS as I, listWorkspaces as It, resolveWorkspace as J, workspaceDefinition as Jt, repoPathFor as K, reportsDirectory as Kt, isNoteKind as L, loadWorkspace as Lt, DEFAULT_HALF_LIFE_DAYS as M, definitionInstructions as Mt, DUPLICATE_SIMILARITY as N, dropWorkspace as Nt, purgeDays as O, INSTRUCTIONS_FILE as Ot, NOTE_KINDS as P, expandHome as Pt, sessionWorkspaceName as Q, migrate as Qt, localDay as R, removeWorkspaceRepo as Rt, renderNotes as S, rulesVersion as St, renderStatus as T, MINIMUM_ID_PREFIX as Tt, ambiguousWorkspaceContext as U, defaultRunDirectory as Ut, similarity as V, corePromptPath as Vt, isInside as W, promptsDirectory as Wt, archiveWorkspaceSessions as X, MEMORY_DB as Xt, workspaceLabel as Y, workspacesDirectory as Yt, deleteWorkspaceNotes as Z, openDatabase as Zt, NOTES_FOLD_LINES as _, assemblePrompt as _t, formatEventLine as a, AGENT_STATUSES as an, workspaceSettings as at, renderAgentLine as b, outsideRucherContext as bt, Carnet as c, MAIN_WORKING_EMOJI as cn, markdownCopy as ct, openWorkspaceCarnet as d, isAgentStatus as dn, writeGenerated as dt, schemaVersion as en, DEFAULT_HOST as et, PAIRING_WINDOW_MILLISECONDS as f, isUserActionStatus as fn, OUTSIDE_RUCHER_NOTICE as ft, MAIN_WORKING_SUFFIX as g, CarnetError as gn, appendPromptFile as gt, formatClock as h, isEventType as hn, SUBAGENT_RULES as ht, RESUME_MAX_CHARACTERS as i, sanitizeNote as in, transcriptTitle as it, renderMemory as j, createWorkspace as jt, MEMORY_MAX_CHARACTERS as k, WORKSPACE_FILE as kt, openCarnet as l, OPEN_AGENT_STATUSES as ln, mergeSettings as lt, buildStatusView as m, SESSION_EVENT_TYPES as mn, RULES_UPDATED_NOTICE as mt, stepAgent as n, REPORTING_NOTE as nn, hostById as nt, resumeContext as o, EMOJI as on, GENERATED_MARKER as ot, STOPPED_NOTE as p, EVENT_TYPES as pn, PROMPT_FILE as pt, requireWorkspace as q, rucherPaths as qt, RESUME_EVENTS as r, NOTE_MAX as rn, claudeCode as rt, sessionLabel as s, LEGEND as sn, MARKDOWN_MARKER as st, AGENT_STEPS as t, PUBLISH_FALLBACK_MILLISECONDS as tn, allHosts as tt, openResolvedCarnet as u, USER_ACTION_STATUSES as un, removeStaleCopies as ut, NOTES_HEADER as v, baseRules as vt, renderSections as w, CORE_RULES as wt, renderNoteLine as x, rulesText as xt, SIMILAR_PREFIX as y, compactReminder as yt, memoryHalfLife as z, workspaceExists as zt };
3583
+ export { renderMemory as $, MAIN_FAILED_EMOJI as $n, rulesText as $t, TURNS as A, workspaceDefinition as An, claudeCode as At, renderAgentLine as B, PUBLISH_FALLBACK_MILLISECONDS as Bn, markdownCopy as Bt, openCarnet as C, databasePath as Cn, sessionWorkspaceName as Ct, STOPPED_NOTE as D, reportsDirectory as Dn, DEFAULT_HOST as Dt, PAIRING_WINDOW_MILLISECONDS as E, reportPath as En, workspaceSessionCounts as Et, MAIN_WAITING_SUFFIX as F, migrations as Fn, UndoList as Ft, renderSections as G, NOTE_MAX as Gn, PROMPT_FILE as Gt, renderNoteLine as H, SANDBOX_KINDS as Hn, removeStaleCopies as Ht, MAIN_WORKING_SUFFIX as I, schemaVersion as In, moveTracked as It, DEFAULT_PURGE_DAYS as J, EMOJI as Jn, appendPromptFile as Jt, renderStatus as K, sanitizeNote as Kn, RULES_UPDATED_NOTICE as Kt, NOTES_FOLD_LINES as L, AGENT_KINDS as Ln, relocateFailed as Lt, MAIN_FAILED_SUFFIX as M, MEMORY_DB as Mn, claudeProjectFolder as Mt, MAIN_HEADER as N, openDatabase as Nn, transcriptTitle as Nt, buildStatusView as O, rucherPaths as On, allHosts as Ot, MAIN_IDLE as P, migrate as Pn, workspaceSettings as Pt, memoryMaxCharacters as Q, LEGEND as Qn, outsideRucherContext as Qt, NOTES_HEADER as R, KIND_REQUIRED as Rn, GENERATED_MARKER as Rt, Carnet as S, corePromptPath as Sn, runningWorkspaceSessions as St, openWorkspaceCarnet as T, promptsDirectory as Tn, workspaceRowCounts as Tt, renderNotes as U, isAgentKind as Un, writeGenerated as Ut, renderMainLine as V, REPORTING_NOTE as Vn, mergeSettings as Vt, renderNotesSummary as W, statusWhenDone as Wn, OUTSIDE_RUCHER_NOTICE as Wt, sandboxRemovedSuffix as X, KIND_LEGEND as Xn, baseRules as Xt, purgeDays as Y, KIND_ABBREVIATIONS as Yn, assemblePrompt as Yt, MEMORY_MAX_CHARACTERS as Z, KIND_TAG_PATTERN as Zn, compactReminder as Zt, openQuestionsText as _, workspaceExists as _n, archiveWorkspaceSessions as _t, formatEventLine as a, AGENTS_FILE as an, isUserActionStatus as ar, isNoteKind as at, reportSummary as b, FINDING_SEVERITIES as bn, nextNoteNumber as bt, answerQuestionsText as c, addWorkspaceRepo as cn, SESSION_EVENT_TYPES as cr, sessionNoteActivity as ct, findingsText as d, dropWorkspace as dn, isInside as dt, rulesVersion as en, MAIN_WAITING_EMOJI as er, DEFAULT_HALF_LIFE_DAYS as et, finishWithItems as f, expandHome as fn, repoNameFor as ft, nextAgent as g, removeWorkspaceRepo as gn, workspaceLabel as gt, locateAgent as h, loadWorkspace as hn, resolveWorkspace as ht, RESUME_MAX_CHARACTERS as i, shortId as in, isAgentStatus as ir, STALE_AFTER_ACTIVE_DAYS as it, BLOCKED_HEADER as j, workspacesDirectory as jn, claudeConfigFile as jt, formatClock as k, sandboxesDirectory as kn, hostById as kt, decideText as l, createWorkspace as ln, isEventType as lr, similarity as lt, kindAction as m, listWorkspaces as mn, requireWorkspace as mt, stepAgent as n, CORE_RULES as nn, OPEN_AGENT_STATUSES as nr, NOTE_KINDS as nt, resumeContext as o, INSTRUCTIONS_FILE as on, kindTag as or, localDay as ot, injectReport as p, isWorkspaceName as pn, repoPathFor as pt, renderTableLine as q, AGENT_STATUSES as qn, SUBAGENT_RULES as qt, RESUME_EVENTS as r, MINIMUM_ID_PREFIX as rn, USER_ACTION_STATUSES as rr, NOTE_TEXT_LIMIT as rt, sessionLabel as s, WORKSPACE_FILE as sn, EVENT_TYPES as sr, memoryHalfLife as st, AGENT_STEPS as t, workspaceRules as tn, MAIN_WORKING_EMOJI as tr, DUPLICATE_SIMILARITY as tt, findingsBrief as u, definitionInstructions as un, CarnetError as ur, workspaceRepoNames as ut, promoteText as v, workspaceHosts as vn, deleteWorkspaceNotes as vt, openResolvedCarnet as w, defaultRunDirectory as wn, workspaceLastActive as wt, reviewContext as x, SPAWN_KINDS as xn, renameWorkspaceRows as xt, reportDocument as y, FINDING_DECISIONS as yn, mergeWorkspaceRows as yt, SIMILAR_PREFIX as z, PROMOTE_KIND_REQUIRED as zn, MARKDOWN_MARKER as zt };
2259
3584
 
2260
- //# sourceMappingURL=steps-4ZTrBzcd.mjs.map
3585
+ //# sourceMappingURL=steps-DhCnOGCU.mjs.map