@rucher/carnet 0.2.0-beta.6 → 0.2.0-beta.8

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.
@@ -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
+ analyze: "an",
96
+ implement: "im",
97
+ review: "rv"
98
+ };
99
+ function kindTag(kind) {
100
+ return `[${KIND_ABBREVIATIONS[kind]}]`;
101
+ }
102
+ const KIND_TAG_PATTERN = /\[(?:rs|an|im|rv)\]/;
103
+ const KIND_LEGEND = "[rs] research · [an] analyze · [im] implement · [rv] review";
93
104
  function isAgentStatus(value) {
94
105
  return typeof value === "string" && AGENT_STATUSES.includes(value);
95
106
  }
@@ -112,10 +123,35 @@ 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
+ "analyze",
129
+ "implement",
130
+ "review"
131
+ ];
132
+ const DEFAULT_AGENT_KIND = "analyze";
133
+ const FINAL_ACTIONS = {
134
+ research: "inject",
135
+ analyze: "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
+ }
115
147
  function toAgent(row) {
116
148
  return {
117
149
  session: row.session,
118
150
  name: row.name,
151
+ kind: row.kind,
152
+ promotedFrom: row.promoted_from,
153
+ target: row.target,
154
+ blockedOn: row.blocked_on,
119
155
  task: row.task,
120
156
  status: row.status,
121
157
  note: row.note,
@@ -157,14 +193,27 @@ function requireAgent(ctx, session, name) {
157
193
  if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
158
194
  return agent;
159
195
  }
196
+ function checkReviewTarget(ctx, session, target) {
197
+ if (mainTargetRange(target) !== void 0) return;
198
+ const agent = getAgent(ctx, session, target);
199
+ 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>]`);
200
+ if (agent.status === "running") throw new CarnetError("INVALID_TARGET", `Target "${target}" is still running`);
201
+ if (agent.status === "closed") throw new CarnetError("INVALID_TARGET", `Target "${target}" is closed; review main[:<range>] instead`);
202
+ }
160
203
  function startAgent(ctx, session, input) {
161
204
  const name = sanitizeNote(input.name);
205
+ const kind = input.kind ?? "analyze";
206
+ const target = input.target?.trim() || null;
207
+ if (kind === "review" && !target) throw new CarnetError("INVALID_TARGET", "A review needs a target: an implement agent name, or main[:<range>]");
208
+ if (kind !== "review" && target) throw new CarnetError("INVALID_TARGET", "Only a review agent takes a target");
209
+ if (target) checkReviewTarget(ctx, session, target);
162
210
  const existing = getAgent(ctx, session, name);
163
211
  if (existing && existing.status !== "closed") throw new CarnetError("AGENT_EXISTS", `Agent "${name}" is already open in this session`);
164
212
  if (existing) ctx.db.prepare("DELETE FROM agents WHERE session = ? AND name = ?").run(session, name);
165
213
  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);
214
+ ctx.db.prepare(`INSERT INTO agents (session, name, kind, target, task, status, base_commit, worktree,
215
+ started_at, updated_at)
216
+ VALUES (?, ?, ?, ?, ?, 'running', ?, ?, ?, ?)`).run(session, name, kind, target, input.task, input.baseCommit ?? null, input.worktree ?? null, at, at);
168
217
  logEvent(ctx, session, {
169
218
  type: "started",
170
219
  agent: name,
@@ -172,30 +221,74 @@ function startAgent(ctx, session, input) {
172
221
  });
173
222
  return requireAgent(ctx, session, name);
174
223
  }
224
+ function checkBlocker(ctx, session, name, blocker) {
225
+ if (blocker === name) throw new CarnetError("INVALID_BLOCKER", `Agent "${name}" can't wait on itself`);
226
+ const seen = /* @__PURE__ */ new Set([name]);
227
+ let current = getAgent(ctx, session, blocker);
228
+ if (!current || current.status === "closed") throw new CarnetError("INVALID_BLOCKER", `"${blocker}" is not an open agent of this session`);
229
+ while (current?.blockedOn && current.status !== "closed") {
230
+ if (seen.has(current.blockedOn)) throw new CarnetError("INVALID_BLOCKER", `"${blocker}" already waits on "${name}", directly or through another agent`);
231
+ seen.add(current.name);
232
+ current = getAgent(ctx, session, current.blockedOn);
233
+ }
234
+ }
175
235
  function updateAgent(ctx, session, name, input) {
176
236
  const current = requireAgent(ctx, session, name);
177
237
  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);
238
+ let note;
239
+ if (input.note !== void 0) note = input.note === null ? null : sanitizeNote(input.note);
240
+ else note = current.status === "running" && input.status !== "running" ? null : current.note;
241
+ let blockedOn = current.blockedOn;
242
+ if (input.blockedOn !== void 0) {
243
+ blockedOn = input.blockedOn === null ? null : sanitizeNote(input.blockedOn);
244
+ if (blockedOn) checkBlocker(ctx, session, name, blockedOn);
245
+ }
179
246
  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);
247
+ ctx.db.prepare("UPDATE agents SET note = ?, status = ?, report_path = COALESCE(?, report_path), blocked_on = ?, updated_at = ? WHERE session = ? AND name = ?").run(note, input.status, input.reportPath ?? null, blockedOn, nowIso(ctx), session, name);
181
248
  return requireAgent(ctx, session, name);
182
249
  }
250
+ function statusWhenDone(kind, hasQuestions) {
251
+ if (hasQuestions) return "answer";
252
+ return kind === "implement" ? "apply" : "review";
253
+ }
183
254
  function finishAgent(ctx, session, name, input) {
184
255
  const agent = requireAgent(ctx, session, name);
185
- const status = input.hasQuestions ? "answer" : "review";
256
+ const status = statusWhenDone(agent.kind, input.hasQuestions);
186
257
  const at = nowIso(ctx);
187
258
  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
259
  if (!agent.hostAgentId) publishPending(ctx, session, name);
189
260
  return requireAgent(ctx, session, name);
190
261
  }
191
- function dropAgent(ctx, session, name, reason) {
262
+ function statusAfterAnswers(kind) {
263
+ return kind === "implement" ? "apply" : "review";
264
+ }
265
+ function closeAgent(ctx, session, name, event) {
192
266
  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);
267
+ ctx.db.prepare("UPDATE agents SET status = 'closed', pending_status = NULL, queue_order = NULL, blocked_on = NULL, updated_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
194
268
  logEvent(ctx, session, {
269
+ ...event,
270
+ agent: name
271
+ });
272
+ return requireAgent(ctx, session, name);
273
+ }
274
+ function dropAgent(ctx, session, name, reason) {
275
+ return closeAgent(ctx, session, name, {
195
276
  type: "dropped",
196
- agent: name,
197
277
  note: reason
198
278
  });
279
+ }
280
+ function promoteAgent(ctx, session, name, input) {
281
+ const agent = requireAgent(ctx, session, name);
282
+ if (agent.kind !== "analyze") throw new CarnetError("INVALID_KIND", `Only an analyze agent is promoted; ${name} is ${agent.kind}`);
283
+ ctx.db.prepare(`UPDATE agents SET kind = 'implement', promoted_from = 'analyze', status = 'running',
284
+ pending_status = NULL, note = NULL, blocked_on = NULL, worktree = COALESCE(?, worktree),
285
+ base_commit = COALESCE(?, base_commit), updated_at = ?
286
+ WHERE session = ? AND name = ?`).run(input.worktree ?? null, input.baseCommit ?? null, nowIso(ctx), session, name);
287
+ logEvent(ctx, session, {
288
+ type: "promoted",
289
+ agent: name,
290
+ note: "analyze to implement"
291
+ });
199
292
  return requireAgent(ctx, session, name);
200
293
  }
201
294
  function listAgents(ctx, session, options = {}) {
@@ -213,6 +306,14 @@ function reorderQueue(ctx, session, names) {
213
306
  return listAgents(ctx, session);
214
307
  }
215
308
  // src/db/schema.ts
309
+ const DISPOSABLE_SESSION = `workspace IS NULL
310
+ AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id)
311
+ AND NOT EXISTS (
312
+ SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
313
+ )
314
+ AND NOT EXISTS (SELECT 1 FROM notes WHERE notes.session = sessions.id OR notes.dropped_session = sessions.id)
315
+ AND NOT EXISTS (SELECT 1 FROM note_citations WHERE note_citations.session = sessions.id)
316
+ AND NOT EXISTS (SELECT 1 FROM sessions AS child WHERE child.parent_id = sessions.id)`;
216
317
  const migrations = [
217
318
  `
218
319
  CREATE TABLE sessions (
@@ -449,8 +550,150 @@ CREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_activ
449
550
  CREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name)
450
551
  WHERE workspace IS NOT NULL AND name IS NOT NULL;
451
552
  CREATE UNIQUE INDEX notes_workspace_number ON notes(workspace, number);
553
+ `,
554
+ `
555
+ DELETE FROM events WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});
556
+ DELETE FROM table_items WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});
557
+ DELETE FROM session_repos WHERE session IN (SELECT id FROM sessions WHERE ${DISPOSABLE_SESSION});
558
+ DELETE FROM sessions WHERE ${DISPOSABLE_SESSION};
559
+
560
+ CREATE TABLE sessions_new (
561
+ id TEXT PRIMARY KEY,
562
+ workspace TEXT NOT NULL,
563
+ name TEXT,
564
+ purpose TEXT,
565
+ kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),
566
+ status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),
567
+ cwd TEXT,
568
+ repo TEXT,
569
+ host TEXT NOT NULL DEFAULT 'claude-code',
570
+ host_pid INTEGER,
571
+ hooked_at TEXT,
572
+ last_title TEXT,
573
+ parent_id TEXT REFERENCES sessions(id),
574
+ prompt_version TEXT,
575
+ created_at TEXT NOT NULL,
576
+ last_active_at TEXT NOT NULL,
577
+ ended_at TEXT,
578
+ turn TEXT CHECK (turn IN ('working', 'waiting', 'failed')),
579
+ turn_started_at TEXT,
580
+ CHECK (kind = 'temp' OR name IS NOT NULL)
581
+ );
582
+ INSERT INTO sessions_new (id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,
583
+ hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)
584
+ SELECT id, workspace, name, purpose, kind, status, cwd, repo, host, host_pid,
585
+ hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at
586
+ FROM sessions;
587
+ DROP TABLE sessions;
588
+ ALTER TABLE sessions_new RENAME TO sessions;
589
+ CREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);
590
+ CREATE INDEX sessions_workspace_status ON sessions(workspace, status, last_active_at);
591
+ CREATE UNIQUE INDEX sessions_workspace_name ON sessions(workspace, name) WHERE name IS NOT NULL;
592
+
593
+ ALTER TABLE table_items DROP COLUMN main_working;
594
+
595
+ ALTER TABLE agents ADD COLUMN kind TEXT NOT NULL DEFAULT 'analyze'
596
+ CHECK (kind IN ('research', 'analyze', 'implement', 'review'));
597
+ ALTER TABLE agents ADD COLUMN promoted_from TEXT
598
+ CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review'));
599
+ ALTER TABLE agents ADD COLUMN target TEXT;
600
+ -- Older agents waiting on code steps, or given a worktree, wrote code.
601
+ UPDATE agents SET kind = 'implement'
602
+ WHERE (status IN ('apply', 'test', 'commit')) OR worktree IS NOT NULL;
603
+
604
+ CREATE TABLE agent_questions (
605
+ session TEXT NOT NULL,
606
+ agent TEXT NOT NULL,
607
+ n INTEGER NOT NULL CHECK (n >= 1),
608
+ text TEXT NOT NULL,
609
+ context TEXT,
610
+ recommendation TEXT NOT NULL,
611
+ alternatives TEXT NOT NULL DEFAULT '[]',
612
+ answer TEXT,
613
+ answered_at TEXT,
614
+ PRIMARY KEY (session, agent, n),
615
+ FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE
616
+ );
617
+
618
+ CREATE TABLE review_findings (
619
+ session TEXT NOT NULL,
620
+ agent TEXT NOT NULL,
621
+ n INTEGER NOT NULL CHECK (n >= 1),
622
+ severity TEXT NOT NULL CHECK (severity IN ('blocking', 'to_fix', 'suggestion')),
623
+ location TEXT,
624
+ text TEXT NOT NULL,
625
+ fix TEXT,
626
+ decision TEXT CHECK (decision IN ('sent', 'fixed', 'ignored')),
627
+ reason TEXT,
628
+ decided_at TEXT,
629
+ PRIMARY KEY (session, agent, n),
630
+ FOREIGN KEY (session, agent) REFERENCES agents(session, name) ON UPDATE CASCADE ON DELETE CASCADE
631
+ );
632
+
633
+ CREATE TABLE events_new (
634
+ id INTEGER PRIMARY KEY,
635
+ session TEXT NOT NULL REFERENCES sessions(id),
636
+ at TEXT NOT NULL,
637
+ type TEXT NOT NULL
638
+ CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped',
639
+ 'injected', 'promoted', 'triaged',
640
+ 'session.started', 'session.resumed', 'session.ended', 'session.forked')),
641
+ agent TEXT,
642
+ commit_sha TEXT,
643
+ link TEXT,
644
+ note TEXT
645
+ );
646
+ INSERT INTO events_new SELECT id, session, at, type, agent, commit_sha, link, note FROM events;
647
+ DROP TABLE events;
648
+ ALTER TABLE events_new RENAME TO events;
649
+ CREATE INDEX events_session_at ON events(session, at);
650
+ `,
651
+ `
652
+ -- Testing and committing are one human step, and no step ever led to branch.
653
+ UPDATE agents SET status = 'test' WHERE status IN ('commit', 'branch');
654
+ UPDATE agents SET pending_status = 'test' WHERE pending_status IN ('commit', 'branch');
655
+ UPDATE table_items SET status = 'test' WHERE status IN ('commit', 'branch');
656
+ CREATE TABLE agents_new (
657
+ session TEXT NOT NULL REFERENCES sessions(id),
658
+ name TEXT NOT NULL,
659
+ task TEXT,
660
+ status TEXT NOT NULL
661
+ CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),
662
+ note TEXT,
663
+ report_path TEXT,
664
+ base_commit TEXT,
665
+ worktree TEXT,
666
+ queue_order INTEGER,
667
+ started_at TEXT NOT NULL,
668
+ updated_at TEXT NOT NULL,
669
+ host_agent_id TEXT,
670
+ pending_status TEXT,
671
+ done_at TEXT,
672
+ kind TEXT NOT NULL DEFAULT 'analyze'
673
+ CHECK (kind IN ('research', 'analyze', 'implement', 'review')),
674
+ promoted_from TEXT CHECK (promoted_from IN ('research', 'analyze', 'implement', 'review')),
675
+ target TEXT,
676
+ blocked_on TEXT,
677
+ PRIMARY KEY (session, name)
678
+ );
679
+ INSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,
680
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target)
681
+ SELECT session, name, task, status, note, report_path, base_commit, worktree,
682
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from, target
683
+ FROM agents;
684
+ DROP TABLE agents;
685
+ ALTER TABLE agents_new RENAME TO agents;
686
+ CREATE INDEX agents_session_status ON agents(session, status);
687
+ -- The CLI and the plugin update separately; the pane warns when the hooks lag behind.
688
+ ALTER TABLE sessions ADD COLUMN plugin_version TEXT;
452
689
  `
453
690
  ];
691
+ const preconditions = { 11: (db) => {
692
+ const kept = db.prepare(`SELECT id, name FROM sessions WHERE workspace IS NULL AND NOT (${DISPOSABLE_SESSION})`).all();
693
+ if (kept.length === 0) return;
694
+ const list = kept.map((row) => row.name ?? row.id).join(", ");
695
+ 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>'`);
696
+ } };
454
697
  function schemaVersion(db) {
455
698
  return db.prepare("PRAGMA user_version").get().user_version;
456
699
  }
@@ -467,6 +710,7 @@ function migrate(db) {
467
710
  if (version < current) continue;
468
711
  db.exec("BEGIN");
469
712
  try {
713
+ preconditions[version + 1]?.(db);
470
714
  db.exec(migration);
471
715
  if (foreignKeyViolations(db) > 0) throw new Error(`Migration ${version + 1} broke foreign keys`);
472
716
  db.exec(`PRAGMA user_version = ${version + 1}`);
@@ -537,6 +781,101 @@ function reportsDirectory(workspace) {
537
781
  function reportPath(workspace, agentName) {
538
782
  return join(reportsDirectory(workspace), `${agentName}.md`);
539
783
  }
784
+ // src/findings.ts
785
+ const FINDING_SEVERITIES = [
786
+ "blocking",
787
+ "to_fix",
788
+ "suggestion"
789
+ ];
790
+ const FINDING_DECISIONS = [
791
+ "sent",
792
+ "fixed",
793
+ "ignored"
794
+ ];
795
+ function listFindings(ctx, session, agent, pendingOnly = false) {
796
+ const rows = ctx.db.prepare("SELECT * FROM review_findings WHERE session = ? AND agent = ? ORDER BY n").all(session, agent);
797
+ const total = rows.length;
798
+ return rows.filter((row) => !pendingOnly || row.decision === null).map((row) => ({
799
+ ...row,
800
+ total
801
+ }));
802
+ }
803
+ function replaceFindings(ctx, session, agent, inputs) {
804
+ const sorted = [...inputs].sort((a, b) => FINDING_SEVERITIES.indexOf(a.severity) - FINDING_SEVERITIES.indexOf(b.severity));
805
+ ctx.db.prepare("DELETE FROM review_findings WHERE session = ? AND agent = ?").run(session, agent);
806
+ const insert = ctx.db.prepare(`INSERT INTO review_findings (session, agent, n, severity, location, text, fix)
807
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);
808
+ sorted.forEach((input, index) => {
809
+ insert.run(session, agent, index + 1, input.severity, input.location?.trim() || null, input.text.trim(), input.fix?.trim() || null);
810
+ });
811
+ return listFindings(ctx, session, agent);
812
+ }
813
+ function decideFindings(ctx, session, agent, decisions) {
814
+ const known = new Set(listFindings(ctx, session, agent).map((finding) => finding.n));
815
+ const missing = decisions.filter((item) => !known.has(item.n)).map((item) => item.n);
816
+ if (missing.length) throw new CarnetError("FINDING_NOT_FOUND", `No finding ${missing.join(", ")} for ${agent}; review_findings lists them`);
817
+ const unexplained = decisions.filter((item) => item.decision === "ignored" && !item.reason?.trim());
818
+ if (unexplained.length) throw new CarnetError("REASON_REQUIRED", `Ignoring finding ${unexplained.map((item) => item.n).join(", ")} needs a short reason`);
819
+ const at = nowIso(ctx);
820
+ const update = ctx.db.prepare("UPDATE review_findings SET decision = ?, reason = ?, decided_at = ? WHERE session = ? AND agent = ? AND n = ?");
821
+ for (const item of decisions) update.run(item.decision, item.reason?.trim() || null, at, session, agent, item.n);
822
+ return listFindings(ctx, session, agent);
823
+ }
824
+ function formatFinding(finding) {
825
+ const location = finding.location ? ` ${finding.location}` : "";
826
+ const fix = finding.fix ? ` (fix: ${finding.fix})` : "";
827
+ return `${finding.n}/${finding.total} [${finding.severity}]${location} — ${finding.text}${fix}`;
828
+ }
829
+ function renderFindings(findings) {
830
+ return `## Findings\n\n${findings.map((finding) => {
831
+ const location = finding.location ? ` \`${finding.location}\`` : "";
832
+ const fix = finding.fix ? `\n Fix: ${finding.fix}` : "";
833
+ return `${finding.n}. **${finding.severity}**${location}: ${finding.text}${fix}`;
834
+ }).join("\n")}`;
835
+ }
836
+ function listQuestions(ctx, session, agent, openOnly = false) {
837
+ const rows = ctx.db.prepare("SELECT * FROM agent_questions WHERE session = ? AND agent = ? ORDER BY n").all(session, agent);
838
+ const total = rows.length;
839
+ return rows.filter((row) => !openOnly || row.answer === null).map((row) => ({
840
+ n: row.n,
841
+ total,
842
+ text: row.text,
843
+ context: row.context,
844
+ recommendation: row.recommendation,
845
+ alternatives: JSON.parse(row.alternatives),
846
+ answer: row.answer,
847
+ answeredAt: row.answered_at
848
+ }));
849
+ }
850
+ function addQuestions(ctx, session, agent, inputs) {
851
+ 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`);
852
+ ctx.db.prepare("DELETE FROM agent_questions WHERE session = ? AND agent = ? AND answer IS NULL").run(session, agent);
853
+ const last = ctx.db.prepare("SELECT COALESCE(MAX(n), 0) AS n FROM agent_questions WHERE session = ? AND agent = ?").get(session, agent);
854
+ const insert = ctx.db.prepare(`INSERT INTO agent_questions (session, agent, n, text, context, recommendation, alternatives)
855
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);
856
+ inputs.forEach((input, index) => {
857
+ insert.run(session, agent, last.n + index + 1, input.text.trim(), input.context?.trim() || null, input.recommendation.trim(), JSON.stringify(input.alternatives ?? []));
858
+ });
859
+ return listQuestions(ctx, session, agent);
860
+ }
861
+ function answerQuestions(ctx, session, agent, answers) {
862
+ const known = new Set(listQuestions(ctx, session, agent).map((question) => question.n));
863
+ const missing = answers.filter((answer) => !known.has(answer.n)).map((answer) => answer.n);
864
+ if (missing.length) throw new CarnetError("QUESTION_NOT_FOUND", `No question ${missing.join(", ")} for ${agent}; agent_questions lists them`);
865
+ const at = nowIso(ctx);
866
+ const update = ctx.db.prepare("UPDATE agent_questions SET answer = ?, answered_at = ? WHERE session = ? AND agent = ? AND n = ?");
867
+ for (const answer of answers) update.run(answer.answer.trim(), at, session, agent, answer.n);
868
+ return listQuestions(ctx, session, agent);
869
+ }
870
+ function renderQuestions(questions) {
871
+ return `## Questions\n\n${questions.map((question) => {
872
+ const lines = [`${question.n}. ${question.text}`];
873
+ if (question.context) lines.push(` Context: ${question.context}`);
874
+ lines.push(` Recommendation: ${question.recommendation}`);
875
+ if (question.alternatives.length) lines.push(` Alternatives: ${question.alternatives.join(" · ")}`);
876
+ return lines.join("\n");
877
+ }).join("\n")}`;
878
+ }
540
879
  // src/workspace/workspace.ts
541
880
  const WORKSPACE_FILE = "workspace.json";
542
881
  const INSTRUCTIONS_FILE = "CLAUDE.md";
@@ -671,7 +1010,7 @@ function dropWorkspace(name, options = {}) {
671
1010
  }
672
1011
  // src/sessions.ts
673
1012
  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`;
1013
+ parent_id, prompt_version, plugin_version, created_at, last_active_at, ended_at`;
675
1014
  function toSession(row) {
676
1015
  return {
677
1016
  id: row.id,
@@ -688,11 +1027,16 @@ function toSession(row) {
688
1027
  lastTitle: row.last_title,
689
1028
  parentId: row.parent_id,
690
1029
  promptVersion: row.prompt_version,
1030
+ pluginVersion: row.plugin_version,
691
1031
  createdAt: row.created_at,
692
1032
  lastActiveAt: row.last_active_at,
693
1033
  endedAt: row.ended_at
694
1034
  };
695
1035
  }
1036
+ function workspaceOf(ctx) {
1037
+ if (ctx.workspace !== null) return ctx.workspace;
1038
+ throw new CarnetError("NO_WORKSPACE", "A session belongs to a workspace: there is none here");
1039
+ }
696
1040
  function getSession(ctx, id) {
697
1041
  const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id);
698
1042
  return row && toSession(row);
@@ -706,7 +1050,7 @@ function ensureSession(ctx, id, cwd, workspace) {
706
1050
  const existing = getSession(ctx, id);
707
1051
  if (existing) return existing;
708
1052
  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);
1053
+ 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
1054
  return requireSession(ctx, id);
711
1055
  }
712
1056
  function nameTaken(error, name) {
@@ -719,7 +1063,7 @@ function createSession(ctx, input) {
719
1063
  try {
720
1064
  ctx.db.prepare(`INSERT INTO sessions (id, workspace, name, kind, status, cwd, repo, host, last_title,
721
1065
  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);
1066
+ 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
1067
  } catch (error) {
724
1068
  nameTaken(error, input.name);
725
1069
  }
@@ -766,7 +1110,7 @@ function upsertFromHook(ctx, workspace, payload, env = {}) {
766
1110
  const existing = getSession(ctx, payload.session_id);
767
1111
  if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, workspace, cwd, repo, host, host_pid, hooked_at, created_at,
768
1112
  last_active_at)
769
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, ctx.workspace, payload.cwd ?? null, repo, host, hostPid, at, at, at);
1113
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, workspaceOf(ctx), payload.cwd ?? null, repo, host, hostPid, at, at, at);
770
1114
  else ctx.db.prepare(`UPDATE sessions
771
1115
  SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
772
1116
  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,7 +1133,7 @@ function nameSession(ctx, id, name, purpose) {
789
1133
  return requireSession(ctx, id);
790
1134
  }
791
1135
  function listSessions(ctx, options = {}) {
792
- const conditions = ["workspace IS ?"];
1136
+ const conditions = ["workspace = ?"];
793
1137
  if (!options.includeTemp) conditions.push("kind != 'temp'");
794
1138
  if (!options.includeArchived) conditions.push("status != 'archived'");
795
1139
  return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC`).all(ctx.workspace).map(toSession);
@@ -802,12 +1146,12 @@ function dropSession(ctx, id) {
802
1146
  return requireSession(ctx, id);
803
1147
  }
804
1148
  function defaultSession(ctx) {
805
- const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace IS ? AND status != 'archived'
1149
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND status != 'archived'
806
1150
  ORDER BY last_active_at DESC LIMIT 1`).get(ctx.workspace);
807
1151
  return row && toSession(row);
808
1152
  }
809
1153
  function sessionByName(ctx, name) {
810
- const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace IS ? AND name = ?`).get(ctx.workspace, name);
1154
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND name = ?`).get(ctx.workspace, name);
811
1155
  return row && toSession(row);
812
1156
  }
813
1157
  const MINIMUM_ID_PREFIX = 4;
@@ -821,7 +1165,7 @@ function findSession(ctx, reference) {
821
1165
  if (byId) return byId;
822
1166
  const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
823
1167
  if (isIdPrefix && reference.length >= 4) {
824
- const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace IS ? AND id LIKE ?
1168
+ const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE workspace = ? AND id LIKE ?
825
1169
  ORDER BY last_active_at DESC`).all(ctx.workspace, `${reference.toLowerCase()}%`);
826
1170
  const [only, ...others] = rows;
827
1171
  if (only && others.length === 0) return toSession(only);
@@ -835,6 +1179,9 @@ function sessionByHostProcess(ctx, host, processId) {
835
1179
  ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
836
1180
  return row && toSession(row);
837
1181
  }
1182
+ function recordPluginVersion(ctx, id, version) {
1183
+ ctx.db.prepare("UPDATE sessions SET plugin_version = ? WHERE id = ?").run(version, id);
1184
+ }
838
1185
  function recordPromptVersion(ctx, id, version) {
839
1186
  requireSession(ctx, id);
840
1187
  ctx.db.prepare("UPDATE sessions SET prompt_version = ? WHERE id = ?").run(version, id);
@@ -889,7 +1236,7 @@ function demoteSession(ctx, id) {
889
1236
  function staleTempSessions(ctx, olderThanMilliseconds) {
890
1237
  const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
891
1238
  return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
892
- WHERE workspace IS ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
1239
+ WHERE workspace = ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
893
1240
  ORDER BY last_active_at ASC`).all(ctx.workspace, before).map(toSession);
894
1241
  }
895
1242
  function resetDeadSessions(ctx, isAlive) {
@@ -897,11 +1244,11 @@ function resetDeadSessions(ctx, isAlive) {
897
1244
  }
898
1245
  // src/prompt/core-rules.ts
899
1246
  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.`;
1247
+ - The human keeps the hand: only the human launches agents, triggers their final action (inject, validate, apply, triage), applies, tests and commits. Agents propose, they never push.
1248
+ - 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.
1249
+ - 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 final action, even when answering about something else.
1250
+ - 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.
1251
+ - To launch agents or handle their results, load the rucher skill: it holds the full workflow.`;
905
1252
  // src/prompt/prompt.ts
906
1253
  const PROMPT_FILE = "prompt.md";
907
1254
  function readIfPresent(path) {
@@ -909,7 +1256,7 @@ function readIfPresent(path) {
909
1256
  return readFileSync(path, "utf8").trim() || void 0;
910
1257
  }
911
1258
  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.";
1259
+ 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, triggers their final 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 final action, 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
1260
  }
914
1261
  function workspaceRules(workspace) {
915
1262
  return workspace ? readIfPresent(join(workspace.definition, PROMPT_FILE)) : void 0;
@@ -949,7 +1296,7 @@ function outsideRucherContext(workspace, env = process.env) {
949
1296
  }
950
1297
  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
1298
  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.";
1299
+ 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
1300
  // src/run-directory-files.ts
954
1301
  const GENERATED_MARKER = "generated by rucher, do not edit";
955
1302
  function refuse(path) {
@@ -1011,8 +1358,9 @@ function mergeSettings(base, extra) {
1011
1358
  }
1012
1359
  // src/hosts/claude-code.ts
1013
1360
  const TRANSCRIPT_TAIL_BYTES = 262144;
1361
+ const TRANSCRIPT_HEAD_BYTES = 65536;
1014
1362
  const TITLE_PATTERN = /"type":"custom-title","customTitle":("(?:[^"\\]|\\.)*")/g;
1015
- const FORK_NAME_PATTERN = /You are fork `([^`]+)`/;
1363
+ const FORK_NAME_PATTERN = /You are (?:agent|fork) `([^`]+)`/;
1016
1364
  function payloadObject(json) {
1017
1365
  const data = JSON.parse(json);
1018
1366
  if (typeof data.session_id !== "string" || !data.session_id) throw new TypeError("Hook payload has no session_id");
@@ -1049,22 +1397,41 @@ function subagentPromptName(transcriptPath) {
1049
1397
  return;
1050
1398
  }
1051
1399
  }
1052
- function transcriptTitle(path) {
1400
+ function readSlice(path, from, bytes) {
1053
1401
  let descriptor;
1054
1402
  try {
1055
1403
  descriptor = openSync(path, "r");
1056
1404
  const size = fstatSync(descriptor).size;
1057
- const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
1405
+ const length = Math.min(size, bytes);
1058
1406
  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);
1407
+ readSync(descriptor, buffer, 0, length, from === "end" ? size - length : 0);
1408
+ return buffer.toString("utf8");
1062
1409
  } catch {
1063
1410
  return;
1064
1411
  } finally {
1065
1412
  if (descriptor !== void 0) closeSync(descriptor);
1066
1413
  }
1067
1414
  }
1415
+ function transcriptTitle(path) {
1416
+ const tail = readSlice(path, "end", TRANSCRIPT_TAIL_BYTES);
1417
+ if (tail === void 0) return void 0;
1418
+ const last = [...tail.matchAll(TITLE_PATTERN)].at(-1)?.[1];
1419
+ return last === void 0 ? void 0 : JSON.parse(last);
1420
+ }
1421
+ function records(text) {
1422
+ return (text ?? "").split("\n").flatMap((line) => {
1423
+ try {
1424
+ const value = JSON.parse(line);
1425
+ return value && typeof value === "object" ? [value] : [];
1426
+ } catch {
1427
+ return [];
1428
+ }
1429
+ });
1430
+ }
1431
+ function continuesConversation(parentFile, childFile, parentId, childId) {
1432
+ if (records(readSlice(parentFile, "end", TRANSCRIPT_TAIL_BYTES)).some((record) => record.type === "continued-in" && record.continuedInSessionId === childId)) return true;
1433
+ 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"));
1434
+ }
1068
1435
  const SETTINGS_FILE = join(".claude", "settings.json");
1069
1436
  const BACKEND_NOTES = "backends/claude.md";
1070
1437
  function instructionFiles(workspace) {
@@ -1156,6 +1523,14 @@ const claudeCode = {
1156
1523
  session_title: text(data, "session_title")
1157
1524
  };
1158
1525
  },
1526
+ parseStopPayload(json) {
1527
+ const data = payloadObject(json);
1528
+ return {
1529
+ session_id: data.session_id,
1530
+ cwd: text(data, "cwd"),
1531
+ failed: data.hook_event_name === "StopFailure"
1532
+ };
1533
+ },
1159
1534
  parsePromptPayload(json) {
1160
1535
  const data = payloadObject(json);
1161
1536
  return {
@@ -1190,12 +1565,16 @@ const claudeCode = {
1190
1565
  const data = payloadObject(json);
1191
1566
  const toolName = text(data, "tool_name");
1192
1567
  const cwd = text(data, "cwd");
1568
+ const toolInput = typeof data.tool_input === "object" && data.tool_input !== null ? data.tool_input : {};
1193
1569
  return {
1194
1570
  session_id: data.session_id,
1195
1571
  cwd,
1196
1572
  tool_name: toolName,
1197
1573
  agent_id: text(data, "agent_id"),
1198
- path: touchedPath(toolName, data.tool_input, cwd)
1574
+ agent_type: text(data, "agent_type"),
1575
+ path: touchedPath(toolName, data.tool_input, cwd),
1576
+ file_path: text(toolInput, "file_path") ?? text(toolInput, "notebook_path"),
1577
+ command: text(toolInput, "command")
1199
1578
  };
1200
1579
  },
1201
1580
  subagentInheritsContext(payload) {
@@ -1260,6 +1639,11 @@ const claudeCode = {
1260
1639
  if (!existsSync(projects)) return false;
1261
1640
  return readdirSync(projects).some((project) => existsSync(join(projects, project, `${session.id}.jsonl`)));
1262
1641
  },
1642
+ continues(parent, childId, env = process.env) {
1643
+ if (!parent.cwd) return false;
1644
+ const project = join(projectsDirectory(env), parent.cwd.replace(/[^a-zA-Z0-9]/g, "-"));
1645
+ return continuesConversation(join(project, `${parent.id}.jsonl`), join(project, `${childId}.jsonl`), parent.id, childId);
1646
+ },
1263
1647
  renameInstruction(name) {
1264
1648
  return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
1265
1649
  },
@@ -1289,8 +1673,7 @@ function inTransaction(db, run) {
1289
1673
  }
1290
1674
  }
1291
1675
  function sessionWorkspaceName(db, sessionId) {
1292
- const row = db.prepare("SELECT workspace FROM sessions WHERE id = ?").get(sessionId);
1293
- return row ? row.workspace : void 0;
1676
+ return db.prepare("SELECT workspace FROM sessions WHERE id = ?").get(sessionId)?.workspace;
1294
1677
  }
1295
1678
  function archiveWorkspaceSessions(db, name, at) {
1296
1679
  return inTransaction(db, () => {
@@ -1305,9 +1688,13 @@ function deleteWorkspaceNotes(db, name) {
1305
1688
  }
1306
1689
  function workspaceSessionCounts(db) {
1307
1690
  const rows = db.prepare(`SELECT workspace, COUNT(*) AS count FROM sessions
1308
- WHERE workspace IS NOT NULL AND status != 'archived' GROUP BY workspace`).all();
1691
+ WHERE status != 'archived' GROUP BY workspace`).all();
1309
1692
  return new Map(rows.map((row) => [row.workspace, Number(row.count)]));
1310
1693
  }
1694
+ function workspaceLastActive(db) {
1695
+ const rows = db.prepare("SELECT workspace, MAX(last_active_at) AS at FROM sessions GROUP BY workspace").all();
1696
+ return new Map(rows.map((row) => [row.workspace, row.at]));
1697
+ }
1311
1698
  // src/workspace/locate.ts
1312
1699
  function isInside(directory, path) {
1313
1700
  const relativePath = relative(directory, path);
@@ -1334,31 +1721,9 @@ function namedWorkspace(name, env) {
1334
1721
  function byRunDirectory(workspaces, directories) {
1335
1722
  return workspaces.find((workspace) => directories.some((directory) => isInside(workspace.runDirectory, directory)));
1336
1723
  }
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
1724
  function resolveWorkspace({ db, sessionId, workspace, cwd = process.cwd(), env = process.env } = {}) {
1356
1725
  if (db && sessionId) {
1357
1726
  const name = sessionWorkspaceName(db, sessionId);
1358
- if (name === null) return {
1359
- workspace: null,
1360
- origin: "session"
1361
- };
1362
1727
  if (name !== void 0 && workspaceExists(name, env)) return {
1363
1728
  workspace: loadWorkspace(name, env),
1364
1729
  origin: "session"
@@ -1374,20 +1739,11 @@ function resolveWorkspace({ db, sessionId, workspace, cwd = process.cwd(), env =
1374
1739
  };
1375
1740
  const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
1376
1741
  const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
1377
- const workspaces = listWorkspaces(env);
1378
- const runDirectoryWorkspace = byRunDirectory(workspaces, directories);
1742
+ const runDirectoryWorkspace = byRunDirectory(listWorkspaces(env), directories);
1379
1743
  if (runDirectoryWorkspace) return {
1380
1744
  workspace: runDirectoryWorkspace,
1381
1745
  origin: "run-directory"
1382
1746
  };
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
1747
  return {
1392
1748
  workspace: null,
1393
1749
  origin: "none"
@@ -1398,10 +1754,7 @@ function workspaceLabel(workspace) {
1398
1754
  }
1399
1755
  function requireWorkspace(workspace) {
1400
1756
  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}.`;
1757
+ throw new CarnetError("NO_WORKSPACE", "No Rucher workspace here: pass --ws <name>, or run this from a workspace's run directory");
1405
1758
  }
1406
1759
  // src/notes.ts
1407
1760
  const NOTE_KINDS = [
@@ -1803,7 +2156,7 @@ function mergeSessions(ctx, fromId, intoId) {
1803
2156
  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
2157
  ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(fromId);
1805
2158
  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);
2159
+ 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
2160
  ctx.db.prepare(`UPDATE sessions
1808
2161
  SET name = COALESCE(?, name), purpose = COALESCE(purpose, ?), last_active_at = ?,
1809
2162
  kind = CASE WHEN ? THEN ? ELSE kind END
@@ -1829,7 +2182,7 @@ function purgeDays(value) {
1829
2182
  return Number.isFinite(days) && days > 0 ? days : 3;
1830
2183
  }
1831
2184
  const PURGEABLE = `
1832
- workspace IS ? AND id != ? AND last_active_at < ?
2185
+ workspace = ? AND id != ? AND last_active_at < ?
1833
2186
  AND NOT EXISTS (
1834
2187
  SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
1835
2188
  )
@@ -1860,13 +2213,44 @@ function purgeSessions(ctx, keepId, days) {
1860
2213
  }
1861
2214
  }
1862
2215
  // src/status/render.ts
1863
- const MAIN_WORKING_SUFFIX = "(main working, not ready)";
2216
+ const MAIN_HEADER = "Main";
2217
+ const MAIN_WORKING_SUFFIX = "(main working)";
2218
+ const BLOCKED_HEADER = "Waiting on agents";
2219
+ const MAIN_WAITING_SUFFIX = "(waiting on you)";
2220
+ const MAIN_FAILED_SUFFIX = "(turn failed)";
1864
2221
  function renderTableLine(item) {
1865
- if (item.mainWorking) return `${MAIN_WORKING_EMOJI} ${item.text} ${MAIN_WORKING_SUFFIX}`;
1866
2222
  return `${EMOJI[item.status ?? "discussing"]} ${item.text}`;
1867
2223
  }
1868
- function renderAgentLine(line) {
1869
- return line.note ? `${line.emoji} ${line.name} — ${line.note}` : `${line.emoji} ${line.name}`;
2224
+ const TURN_MARKS = {
2225
+ working: {
2226
+ emoji: MAIN_WORKING_EMOJI,
2227
+ suffix: MAIN_WORKING_SUFFIX,
2228
+ alone: "main working"
2229
+ },
2230
+ waiting: {
2231
+ emoji: "⏸",
2232
+ suffix: MAIN_WAITING_SUFFIX,
2233
+ alone: "waiting on you"
2234
+ },
2235
+ failed: {
2236
+ emoji: "⚠",
2237
+ suffix: MAIN_FAILED_SUFFIX,
2238
+ alone: "turn failed"
2239
+ }
2240
+ };
2241
+ const MAIN_IDLE = "idle";
2242
+ function renderMainLine(item, turn) {
2243
+ if (!turn) return item ? renderTableLine(item) : MAIN_IDLE;
2244
+ const mark = TURN_MARKS[turn];
2245
+ return item ? `${mark.emoji} ${item.text} ${mark.suffix}` : `${mark.emoji} ${mark.alone}`;
2246
+ }
2247
+ function renderAgentLine(line, nameWidth = 0) {
2248
+ const head = `${line.emoji} ${kindTag(line.kind)} ${line.name}`;
2249
+ const action = line.action ? ` ${" ".repeat(Math.max(nameWidth - line.name.length, 0))} ${line.action}` : "";
2250
+ return line.note ? `${head}${action} — ${line.note}` : `${head}${action}`;
2251
+ }
2252
+ function nameWidth(lines) {
2253
+ return Math.max(0, ...lines.map((line) => line.name.length));
1870
2254
  }
1871
2255
  const NOTES_HEADER = "Notes";
1872
2256
  const NOTES_FOLD_LINES = 5;
@@ -1877,7 +2261,7 @@ const ACTIVITY_MARK = {
1877
2261
  };
1878
2262
  const LABEL_WIDTH = 8;
1879
2263
  const SIMILAR_PREFIX = "similar to ";
1880
- function plural(count, word) {
2264
+ function plural$1(count, word) {
1881
2265
  return `${count} ${word}${count > 1 ? "s" : ""}`;
1882
2266
  }
1883
2267
  function renderNotesSummary(notes) {
@@ -1887,7 +2271,7 @@ function renderNotesSummary(notes) {
1887
2271
  count("added") && `${count("added")} added`,
1888
2272
  count("cited") && `${count("cited")} cited`,
1889
2273
  count("dropped") && `${count("dropped")} dropped`,
1890
- duplicates && plural(duplicates, "possible duplicate")
2274
+ duplicates && plural$1(duplicates, "possible duplicate")
1891
2275
  ].filter(Boolean);
1892
2276
  return `${NOTES_HEADER} ${parts.join(" · ")}`;
1893
2277
  }
@@ -1907,15 +2291,22 @@ function renderNotes(notes, mode = "full") {
1907
2291
  }
1908
2292
  function renderSections(view, options = {}) {
1909
2293
  const out = [];
1910
- if (view.table) out.push("On the table", ` ${renderTableLine(view.table)}`, "");
2294
+ out.push(MAIN_HEADER, ` ${renderMainLine(view.table, view.turn)}`, "");
1911
2295
  out.push("Waiting on you");
1912
2296
  if (view.waiting.length === 0) out.push(" nothing");
2297
+ const waitingWidth = nameWidth(view.waiting);
1913
2298
  view.waiting.forEach((line, index) => {
1914
- out.push(` ${index + 1}. ${renderAgentLine(line)}`);
2299
+ out.push(` ${index + 1}. ${renderAgentLine(line, waitingWidth)}`);
1915
2300
  });
2301
+ if (view.blocked.length > 0) {
2302
+ out.push("", BLOCKED_HEADER);
2303
+ const blockedWidth = nameWidth(view.blocked);
2304
+ for (const line of view.blocked) out.push(` ${renderAgentLine(line, blockedWidth)}`);
2305
+ }
1916
2306
  out.push("", "Running");
1917
2307
  if (view.running.length === 0) out.push(" nothing");
1918
- for (const line of view.running) out.push(` ${renderAgentLine(line)}`);
2308
+ const runningWidth = nameWidth(view.running);
2309
+ for (const line of view.running) out.push(` ${renderAgentLine(line, runningWidth)}`);
1919
2310
  const notes = renderNotes(view.notes, options.notes);
1920
2311
  if (notes.length > 0) out.push("", ...notes);
1921
2312
  return out.join("\n");
@@ -1926,6 +2317,7 @@ function renderStatus(view, options) {
1926
2317
  "",
1927
2318
  renderSections(view, options),
1928
2319
  "",
2320
+ KIND_LEGEND,
1929
2321
  LEGEND
1930
2322
  ].join("\n");
1931
2323
  }
@@ -1935,33 +2327,105 @@ function toItem(row) {
1935
2327
  session: row.session,
1936
2328
  text: row.text,
1937
2329
  status: row.status,
1938
- mainWorking: row.main_working === 1,
1939
2330
  updatedAt: row.updated_at
1940
2331
  };
1941
2332
  }
2333
+ function tableIsAbout(item, name) {
2334
+ const text = item?.text;
2335
+ return text?.startsWith(name) === true && !/[\w-]/.test(text.charAt(name.length));
2336
+ }
1942
2337
  function getTable(ctx, session) {
1943
2338
  const row = ctx.db.prepare("SELECT * FROM table_items WHERE session = ?").get(session);
1944
2339
  return row && toItem(row);
1945
2340
  }
1946
2341
  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
2342
  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 (?, ?, ?, ?, ?)
2343
+ ctx.db.prepare(`INSERT INTO table_items (session, text, status, updated_at) VALUES (?, ?, ?, ?)
1951
2344
  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));
2345
+ updated_at = excluded.updated_at`).run(session, sanitizeNote(input.text), input.status ?? null, nowIso(ctx));
1953
2346
  return getTable(ctx, session);
1954
2347
  }
1955
2348
  function clearTable(ctx, session) {
1956
2349
  ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(session);
1957
2350
  }
2351
+ // src/turn.ts
2352
+ const TURNS = [
2353
+ "working",
2354
+ "waiting",
2355
+ "failed"
2356
+ ];
2357
+ function getTurn(ctx, session) {
2358
+ return ctx.db.prepare("SELECT turn FROM sessions WHERE id = ?").get(session)?.turn ?? null;
2359
+ }
2360
+ function setTurn(ctx, session, turn) {
2361
+ ctx.db.prepare(`UPDATE sessions SET turn = ?1,
2362
+ turn_started_at = CASE
2363
+ WHEN ?1 IS NULL THEN NULL
2364
+ WHEN ?1 <> 'failed' AND turn IN ('working', 'waiting') THEN turn_started_at
2365
+ ELSE ?2 END
2366
+ WHERE id = ?3 AND turn IS NOT ?1`).run(turn, nowIso(ctx), session);
2367
+ }
2368
+ function startTurn(ctx, session) {
2369
+ setTurn(ctx, session, "working");
2370
+ }
2371
+ function waitTurn(ctx, session) {
2372
+ setTurn(ctx, session, "waiting");
2373
+ }
2374
+ function failTurn(ctx, session) {
2375
+ setTurn(ctx, session, "failed");
2376
+ }
2377
+ function endTurn(ctx, session) {
2378
+ setTurn(ctx, session, null);
2379
+ }
1958
2380
  // src/status/view.ts
1959
- const BUCKET = {
1960
- answer: 0,
1961
- review: 1
2381
+ const ACTION_RANK = {
2382
+ validate: 1,
2383
+ triage: 2,
2384
+ inject: 3,
2385
+ apply: 4,
2386
+ test: 5
1962
2387
  };
1963
- function bucketOf(status) {
1964
- return BUCKET[status] ?? 2;
2388
+ function plural(count, word) {
2389
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
2390
+ }
2391
+ function actionWord(agent) {
2392
+ const { kind, status } = agent;
2393
+ if (status === "answer") return kind === "analyze" ? "validate" : "answer";
2394
+ if (status === "review" && kind !== "implement") return FINAL_ACTIONS[kind];
2395
+ if (status === "apply" && kind === "implement") return "apply";
2396
+ if (status === "test") return status;
2397
+ return status === "discussing" ? "discuss" : status;
2398
+ }
2399
+ function actionDetail(ctx, agent, word) {
2400
+ if (word === "validate" || word === "answer") {
2401
+ const open = listQuestions(ctx, agent.session, agent.name, true).length;
2402
+ if (open > 0) return plural(open, "question");
2403
+ if (agent.status === "answer") return "questions";
2404
+ return "plan";
2405
+ }
2406
+ if (word === "triage") {
2407
+ const pending = listFindings(ctx, agent.session, agent.name, true);
2408
+ const blocking = pending.filter((finding) => finding.severity === "blocking").length;
2409
+ const parts = [
2410
+ pending.length > 0 ? plural(pending.length, "finding") : null,
2411
+ blocking > 0 ? `(${blocking} blocking)` : null,
2412
+ agent.target ? `→ ${agent.target}` : null
2413
+ ].filter(Boolean);
2414
+ return parts.length > 0 ? parts.join(" ") : null;
2415
+ }
2416
+ return null;
2417
+ }
2418
+ function waitingAction(ctx, agent) {
2419
+ const word = actionWord(agent);
2420
+ const detail = actionDetail(ctx, agent, word);
2421
+ return detail ? `${word} · ${detail}` : word;
2422
+ }
2423
+ function runningAction(agent) {
2424
+ return agent.promotedFrom ? `promoted from ${agent.promotedFrom}` : null;
2425
+ }
2426
+ function rankOf(agent) {
2427
+ if (agent.status === "answer") return 0;
2428
+ return ACTION_RANK[actionWord(agent)] ?? Object.keys(ACTION_RANK).length + 1;
1965
2429
  }
1966
2430
  function compareWaiting(left, right) {
1967
2431
  if (left.queueOrder !== null || right.queueOrder !== null) {
@@ -1969,28 +2433,38 @@ function compareWaiting(left, right) {
1969
2433
  if (right.queueOrder === null) return -1;
1970
2434
  return left.queueOrder - right.queueOrder;
1971
2435
  }
1972
- return bucketOf(left.status) - bucketOf(right.status) || left.startedAt.localeCompare(right.startedAt);
2436
+ return rankOf(left) - rankOf(right) || left.startedAt.localeCompare(right.startedAt);
1973
2437
  }
1974
- function toLine(agent) {
2438
+ function toLine(agent, action) {
1975
2439
  return {
1976
2440
  name: agent.name,
2441
+ kind: agent.kind,
1977
2442
  status: agent.status,
1978
2443
  emoji: agent.status === "closed" ? "" : EMOJI[agent.status],
2444
+ action,
1979
2445
  note: agent.note
1980
2446
  };
1981
2447
  }
1982
2448
  function formatClock(date) {
1983
2449
  return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
1984
2450
  }
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);
2451
+ function buildStatusView(ctx, session, options = {}) {
2452
+ const all = listAgents(ctx, session.id);
2453
+ const open = new Set(all.map((agent) => agent.name));
2454
+ const isBlocked = (agent) => agent.blockedOn !== null && open.has(agent.blockedOn);
2455
+ const agents = all.filter((agent) => !options.kind || agent.kind === options.kind);
2456
+ const table = getTable(ctx, session.id) ?? null;
2457
+ const handed = agents.filter((agent) => isUserActionStatus(agent.status));
2458
+ const waiting = handed.filter((agent) => !isBlocked(agent) && !tableIsAbout(table, agent.name)).sort(compareWaiting).map((agent) => toLine(agent, waitingAction(ctx, agent)));
2459
+ const blocked = handed.filter(isBlocked).map((agent) => toLine(agent, `→ ${agent.blockedOn}`));
2460
+ const running = agents.filter((agent) => agent.status === "running").map((agent) => toLine(agent, runningAction(agent)));
1989
2461
  return {
1990
2462
  time: formatClock(ctx.now()),
1991
2463
  sessionName: session.name,
1992
- table: getTable(ctx, session.id) ?? null,
2464
+ table,
2465
+ turn: getTurn(ctx, session.id),
1993
2466
  waiting,
2467
+ blocked,
1994
2468
  running,
1995
2469
  notes: sessionNoteActivity(ctx, session.id)
1996
2470
  };
@@ -2057,6 +2531,9 @@ var Carnet = class {
2057
2531
  workspace: workspace?.name ?? null
2058
2532
  };
2059
2533
  }
2534
+ now() {
2535
+ return this.ctx.now();
2536
+ }
2060
2537
  requireWorkspace() {
2061
2538
  return requireWorkspace(this.workspace);
2062
2539
  }
@@ -2076,6 +2553,7 @@ var Carnet = class {
2076
2553
  default: () => defaultSession(this.ctx),
2077
2554
  byName: (name) => sessionByName(this.ctx, name),
2078
2555
  byHostProcess: (host, processId) => sessionByHostProcess(this.ctx, host, processId),
2556
+ recordPluginVersion: (id, version) => recordPluginVersion(this.ctx, id, version),
2079
2557
  recordPromptVersion: (id, version) => recordPromptVersion(this.ctx, id, version),
2080
2558
  setParent: (id, parentId) => setParent(this.ctx, id, parentId),
2081
2559
  setStatus: (id, status) => setSessionStatus(this.ctx, id, status),
@@ -2094,22 +2572,43 @@ var Carnet = class {
2094
2572
  update: (session, name, input) => updateAgent(this.ctx, session, name, input),
2095
2573
  finish: (session, name, input) => finishAgent(this.ctx, session, name, input),
2096
2574
  drop: (session, name, reason) => dropAgent(this.ctx, session, name, reason),
2575
+ close: (session, name, event) => closeAgent(this.ctx, session, name, event),
2576
+ promote: (session, name, input) => promoteAgent(this.ctx, session, name, input),
2097
2577
  list: (session, options) => listAgents(this.ctx, session, options),
2098
2578
  reorderQueue: (session, names) => reorderQueue(this.ctx, session, names),
2579
+ byHostAgentId: (session, hostAgentId) => byHostAgentId(this.ctx, session, hostAgentId),
2099
2580
  pairSubagent: (session, hostAgentId) => pairSubagent(this.ctx, session, hostAgentId),
2100
2581
  stopSubagent: (session, hostAgentId, names) => stopSubagent(this.ctx, session, hostAgentId, names)
2101
2582
  };
2583
+ questions = {
2584
+ list: (session, agent, openOnly) => listQuestions(this.ctx, session, agent, openOnly),
2585
+ add: (session, agent, inputs) => addQuestions(this.ctx, session, agent, inputs),
2586
+ answer: (session, agent, answers) => answerQuestions(this.ctx, session, agent, answers)
2587
+ };
2588
+ findings = {
2589
+ list: (session, agent, pendingOnly) => listFindings(this.ctx, session, agent, pendingOnly),
2590
+ replace: (session, agent, inputs) => replaceFindings(this.ctx, session, agent, inputs),
2591
+ decide: (session, agent, decisions) => decideFindings(this.ctx, session, agent, decisions)
2592
+ };
2102
2593
  table = {
2103
2594
  get: (session) => getTable(this.ctx, session),
2104
2595
  set: (session, input) => setTable(this.ctx, session, input),
2105
2596
  clear: (session) => clearTable(this.ctx, session)
2106
2597
  };
2598
+ turn = {
2599
+ get: (session) => getTurn(this.ctx, session),
2600
+ start: (session) => startTurn(this.ctx, session),
2601
+ wait: (session) => waitTurn(this.ctx, session),
2602
+ fail: (session) => failTurn(this.ctx, session),
2603
+ end: (session) => endTurn(this.ctx, session)
2604
+ };
2107
2605
  events = {
2108
2606
  log: (session, input) => logEvent(this.ctx, session, input),
2109
- read: (session, limit, agentOnly) => readEvents(this.ctx, {
2607
+ read: (session, limit, agentOnly, kind) => readEvents(this.ctx, {
2110
2608
  session,
2111
2609
  limit,
2112
- agentOnly
2610
+ agentOnly,
2611
+ kind
2113
2612
  })
2114
2613
  };
2115
2614
  notes = {
@@ -2130,8 +2629,8 @@ var Carnet = class {
2130
2629
  copyRepos: (from, into) => copyInjectedRepos(this.ctx, from, into)
2131
2630
  };
2132
2631
  status = {
2133
- view: (session) => buildStatusView(this.ctx, session),
2134
- render: (session, options) => renderStatus(buildStatusView(this.ctx, session), options),
2632
+ view: (session, options) => buildStatusView(this.ctx, session, options),
2633
+ render: (session, options) => renderStatus(buildStatusView(this.ctx, session, options), options),
2135
2634
  sections: (session) => renderSections(buildStatusView(this.ctx, session))
2136
2635
  };
2137
2636
  close() {
@@ -2202,27 +2701,28 @@ const AGENT_STEPS = [
2202
2701
  "dropped"
2203
2702
  ];
2204
2703
  const DEFAULT_NEXT = {
2205
- answered: "apply",
2206
2704
  applied: "test",
2207
- tested: "commit"
2705
+ tested: "test"
2208
2706
  };
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
2707
  function clearTableOf(carnet, session, name) {
2214
- if (tableIsAbout(carnet, session, name)) carnet.table.clear(session);
2708
+ if (tableIsAbout(carnet.table.get(session), name)) carnet.table.clear(session);
2215
2709
  }
2216
2710
  function stepAgent(carnet, session, input) {
2217
2711
  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`);
2712
+ const agent = carnet.agents.get(session, name);
2713
+ if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
2219
2714
  switch (step) {
2220
- case "applying":
2221
- carnet.table.set(session, {
2222
- text: `${name} applying`,
2223
- mainWorking: true
2715
+ case "applying": {
2716
+ if (agent.kind !== "implement") throw new CarnetError("INVALID_KIND", `${name} is ${agent.kind}: only an implement agent is applied`);
2717
+ carnet.table.set(session, { text: `${name} applying` });
2718
+ carnet.agents.update(session, name, {
2719
+ status: agent.status,
2720
+ note: note ?? null,
2721
+ blockedOn: null
2224
2722
  });
2225
- return `⚙️ ${name} applying`;
2723
+ const reviews = carnet.agents.list(session).filter((other) => other.kind === "review" && other.target === name);
2724
+ return `⚙️ ${name} applying${reviews.length ? `\nwarning: review ${reviews.map((review) => review.name).join(", ")} not triaged yet` : ""}`;
2725
+ }
2226
2726
  case "committed":
2227
2727
  if (!commit) throw new CarnetError("COMMIT_REQUIRED", "The committed step needs the commit");
2228
2728
  carnet.events.log(session, {
@@ -2233,28 +2733,35 @@ function stepAgent(carnet, session, input) {
2233
2733
  });
2234
2734
  carnet.agents.drop(session, name, `committed ${commit}`);
2235
2735
  clearTableOf(carnet, session, name);
2236
- return `${EMOJI.commit} ${name} committed ${commit}, closed`;
2736
+ return `✅ ${name} committed ${commit}, closed`;
2237
2737
  case "dropped":
2238
2738
  carnet.agents.drop(session, name, note);
2239
2739
  clearTableOf(carnet, session, name);
2240
2740
  return `${name} dropped, closed`;
2241
2741
  default: {
2242
- const next = input.next ?? DEFAULT_NEXT[step];
2742
+ const next = input.next ?? (step === "answered" ? statusAfterAnswers(agent.kind) : DEFAULT_NEXT[step]);
2243
2743
  carnet.events.log(session, {
2244
2744
  type: step,
2245
2745
  agent: name,
2246
2746
  note
2247
2747
  });
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
2748
+ carnet.agents.update(session, name, {
2749
+ status: next,
2750
+ note: note ?? null,
2751
+ blockedOn: null
2253
2752
  });
2753
+ if (next === "running") clearTableOf(carnet, session, name);
2754
+ else if (step !== "answered") {
2755
+ const left = step === "tested" ? "commit" : next;
2756
+ carnet.table.set(session, {
2757
+ text: `${name} ${step}, ${left} next`,
2758
+ status: next
2759
+ });
2760
+ }
2254
2761
  return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;
2255
2762
  }
2256
2763
  }
2257
2764
  }
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 };
2765
+ export { requireWorkspace as $, corePromptPath as $t, renderNotesSummary as A, MAIN_FAILED_EMOJI as An, workspaceRules as At, DUPLICATE_SIMILARITY as B, isEventType as Bn, dropWorkspace as Bt, NOTES_FOLD_LINES as C, sanitizeNote as Cn, appendPromptFile as Ct, renderMainLine as D, KIND_LEGEND as Dn, outsideRucherContext as Dt, renderAgentLine as E, KIND_ABBREVIATIONS as En, compactReminder as Et, purgeDays as F, isAgentStatus as Fn, INSTRUCTIONS_FILE as Ft, localDay as G, removeWorkspaceRepo as Gt, NOTE_TEXT_LIMIT as H, isWorkspaceName as Ht, MEMORY_MAX_CHARACTERS as I, isUserActionStatus as In, WORKSPACE_FILE as It, similarity as J, renderQuestions as Jt, memoryHalfLife as K, workspaceExists as Kt, memoryMaxCharacters as L, kindTag as Ln, addWorkspaceRepo as Lt, renderStatus as M, MAIN_WORKING_EMOJI as Mn, MINIMUM_ID_PREFIX as Mt, renderTableLine as N, OPEN_AGENT_STATUSES as Nn, shortId as Nt, renderNoteLine as O, KIND_TAG_PATTERN as On, rulesText as Ot, DEFAULT_PURGE_DAYS as P, USER_ACTION_STATUSES as Pn, AGENTS_FILE as Pt, repoPathFor as Q, renderFindings as Qt, renderMemory as R, EVENT_TYPES as Rn, createWorkspace as Rt, MAIN_WORKING_SUFFIX as S, NOTE_MAX as Sn, SUBAGENT_RULES as St, SIMILAR_PREFIX as T, EMOJI as Tn, baseRules as Tt, STALE_AFTER_ACTIVE_DAYS as U, listWorkspaces as Ut, NOTE_KINDS as V, CarnetError as Vn, expandHome as Vt, isNoteKind as W, loadWorkspace as Wt, isInside as X, FINDING_SEVERITIES as Xt, workspaceRepoNames as Y, FINDING_DECISIONS as Yt, repoNameFor as Z, formatFinding as Zt, BLOCKED_HEADER as _, REPORTING_NOTE as _n, removeStaleCopies as _t, formatEventLine as a, rucherPaths as an, workspaceLastActive as at, MAIN_IDLE as b, statusAfterAnswers as bn, PROMPT_FILE as bt, Carnet as c, MEMORY_DB as cn, allHosts as ct, openWorkspaceCarnet as d, migrations as dn, transcriptTitle as dt, databasePath as en, resolveWorkspace as et, PAIRING_WINDOW_MILLISECONDS as f, schemaVersion as fn, workspaceSettings as ft, TURNS as g, PUBLISH_FALLBACK_MILLISECONDS as gn, mergeSettings as gt, formatClock as h, FINAL_ACTIONS as hn, markdownCopy as ht, RESUME_MAX_CHARACTERS as i, reportsDirectory as in, sessionWorkspaceName as it, renderSections as j, MAIN_WAITING_EMOJI as jn, CORE_RULES as jt, renderNotes as k, LEGEND as kn, rulesVersion as kt, openCarnet as l, openDatabase as ln, hostById as lt, buildStatusView as m, DEFAULT_AGENT_KIND as mn, MARKDOWN_MARKER as mt, stepAgent as n, promptsDirectory as nn, archiveWorkspaceSessions as nt, resumeContext as o, workspaceDefinition as on, workspaceSessionCounts as ot, STOPPED_NOTE as p, AGENT_KINDS as pn, GENERATED_MARKER as pt, sessionNoteActivity as q, workspaceHosts as qt, RESUME_EVENTS as r, reportPath as rn, deleteWorkspaceNotes as rt, sessionLabel as s, workspacesDirectory as sn, DEFAULT_HOST as st, AGENT_STEPS as t, defaultRunDirectory as tn, workspaceLabel as tt, openResolvedCarnet as u, migrate as un, claudeCode as ut, MAIN_FAILED_SUFFIX as v, isAgentKind as vn, writeGenerated as vt, NOTES_HEADER as w, AGENT_STATUSES as wn, assemblePrompt as wt, MAIN_WAITING_SUFFIX as x, statusWhenDone as xn, RULES_UPDATED_NOTICE as xt, MAIN_HEADER as y, mainTargetRange as yn, OUTSIDE_RUCHER_NOTICE as yt, DEFAULT_HALF_LIFE_DAYS as z, SESSION_EVENT_TYPES as zn, definitionInstructions as zt };
2259
2766
 
2260
- //# sourceMappingURL=steps-4ZTrBzcd.mjs.map
2767
+ //# sourceMappingURL=steps-xzr8iVWn.mjs.map