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

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.
@@ -92,15 +92,15 @@ const MAIN_FAILED_EMOJI = "⚠";
92
92
  const LEGEND = "⚙️ main working · ⏸ waiting on you · ⚠ turn failed · 💬 discussing · ❓ answer · 👀 review · 📥 apply · 🧪 test · ⏳ running";
93
93
  const KIND_ABBREVIATIONS = {
94
94
  research: "rs",
95
- analyze: "an",
95
+ plan: "pl",
96
96
  implement: "im",
97
97
  review: "rv"
98
98
  };
99
99
  function kindTag(kind) {
100
100
  return `[${KIND_ABBREVIATIONS[kind]}]`;
101
101
  }
102
- const KIND_TAG_PATTERN = /\[(?:rs|an|im|rv)\]/;
103
- const KIND_LEGEND = "[rs] research · [an] analyze · [im] implement · [rv] review";
102
+ const KIND_TAG_PATTERN = /\[(?:rs|pl|im|rv)\]/;
103
+ const KIND_LEGEND = "[rs] research · [pl] plan · [im] implement · [rv] review";
104
104
  function isAgentStatus(value) {
105
105
  return typeof value === "string" && AGENT_STATUSES.includes(value);
106
106
  }
@@ -125,14 +125,14 @@ function sanitizeNote(text) {
125
125
  // src/agents.ts
126
126
  const AGENT_KINDS = [
127
127
  "research",
128
- "analyze",
128
+ "plan",
129
129
  "implement",
130
130
  "review"
131
131
  ];
132
- const DEFAULT_AGENT_KIND = "analyze";
133
- const FINAL_ACTIONS = {
132
+ const KIND_REQUIRED = "kind is required: research, plan, implement or review";
133
+ const KIND_ACTIONS = {
134
134
  research: "inject",
135
- analyze: "validate",
135
+ plan: "validate",
136
136
  implement: "apply",
137
137
  review: "triage"
138
138
  };
@@ -144,6 +144,7 @@ function mainTargetRange(target) {
144
144
  const match = MAIN_TARGET.exec(target);
145
145
  return match ? match[1]?.trim() ?? null : void 0;
146
146
  }
147
+ const SANDBOX_KINDS = ["research", "plan"];
147
148
  function toAgent(row) {
148
149
  return {
149
150
  session: row.session,
@@ -158,20 +159,34 @@ function toAgent(row) {
158
159
  reportPath: row.report_path,
159
160
  baseCommit: row.base_commit,
160
161
  worktree: row.worktree,
162
+ sandbox: row.sandbox,
161
163
  queueOrder: row.queue_order,
162
164
  hostAgentId: row.host_agent_id,
163
165
  pendingStatus: row.pending_status,
164
166
  doneAt: row.done_at,
165
167
  startedAt: row.started_at,
166
- updatedAt: row.updated_at
168
+ updatedAt: row.updated_at,
169
+ statusSince: row.status_since ?? row.updated_at
167
170
  };
168
171
  }
169
172
  const REPORTING_NOTE = "reporting";
170
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
+ }
171
185
  function publishPending(ctx, session, name) {
172
186
  const row = ctx.db.prepare("SELECT pending_status, report_path FROM agents WHERE session = ? AND name = ?").get(session, name);
173
187
  if (!row?.pending_status) return;
174
- 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);
188
+ ctx.db.prepare(`UPDATE agents SET status = pending_status, pending_status = NULL, note = NULL,
189
+ ${statusChangeSql("pending_status")}, updated_at = ? WHERE session = ? AND name = ?`).run(nowIso(ctx), nowIso(ctx), session, name);
175
190
  logEvent(ctx, session, {
176
191
  type: "finished",
177
192
  agent: name,
@@ -202,18 +217,21 @@ function checkReviewTarget(ctx, session, target) {
202
217
  }
203
218
  function startAgent(ctx, session, input) {
204
219
  const name = sanitizeNote(input.name);
205
- const kind = input.kind ?? "analyze";
220
+ const kind = input.kind;
221
+ if (!isAgentKind(kind)) throw new CarnetError("INVALID_KIND", KIND_REQUIRED);
222
+ 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`);
206
223
  const target = input.target?.trim() || null;
207
224
  if (kind === "review" && !target) throw new CarnetError("INVALID_TARGET", "A review needs a target: an implement agent name, or main[:<range>]");
208
225
  if (kind !== "review" && target) throw new CarnetError("INVALID_TARGET", "Only a review agent takes a target");
209
226
  if (target) checkReviewTarget(ctx, session, target);
227
+ if (input.sandbox) checkSandbox(ctx, session, name, kind, input.sandbox);
210
228
  const existing = getAgent(ctx, session, name);
211
229
  if (existing && existing.status !== "closed") throw new CarnetError("AGENT_EXISTS", `Agent "${name}" is already open in this session`);
212
230
  if (existing) ctx.db.prepare("DELETE FROM agents WHERE session = ? AND name = ?").run(session, name);
213
231
  const at = nowIso(ctx);
214
232
  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);
233
+ sandbox, started_at, updated_at, status_since)
234
+ VALUES (?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(session, name, kind, target, input.task, input.baseCommit ?? null, input.worktree ?? null, input.sandbox ?? null, at, at, at);
217
235
  logEvent(ctx, session, {
218
236
  type: "started",
219
237
  agent: name,
@@ -221,6 +239,21 @@ function startAgent(ctx, session, input) {
221
239
  });
222
240
  return requireAgent(ctx, session, name);
223
241
  }
242
+ function checkSandbox(ctx, session, name, kind, sandbox) {
243
+ if (!SANDBOX_KINDS.includes(kind)) throw new CarnetError("INVALID_KIND", `Only a research or plan agent gets a sandbox; ${name} is ${kind}`);
244
+ const holder = ctx.db.prepare(`SELECT agents.name FROM agents JOIN sessions ON sessions.id = agents.session
245
+ WHERE agents.sandbox = ? AND sessions.workspace = (SELECT workspace FROM sessions WHERE id = ?)
246
+ AND NOT (agents.session = ? AND agents.name = ?)`).get(sandbox, session, session, name);
247
+ if (holder) throw new CarnetError("INVALID_SANDBOX", `${sandbox} is already the sandbox of ${holder.name}`);
248
+ }
249
+ function clearSandbox(ctx, session, name) {
250
+ ctx.db.prepare("UPDATE agents SET sandbox = NULL WHERE session = ? AND name = ?").run(session, name);
251
+ }
252
+ function closedSandboxes(ctx, session) {
253
+ const where = session ? "agents.session = ?" : "agents.session IN (SELECT id FROM sessions WHERE workspace = ?)";
254
+ return ctx.db.prepare(`SELECT session, name, sandbox FROM agents
255
+ WHERE ${where} AND status = 'closed' AND sandbox IS NOT NULL`).all(session ?? ctx.workspace);
256
+ }
224
257
  function checkBlocker(ctx, session, name, blocker) {
225
258
  if (blocker === name) throw new CarnetError("INVALID_BLOCKER", `Agent "${name}" can't wait on itself`);
226
259
  const seen = /* @__PURE__ */ new Set([name]);
@@ -244,7 +277,8 @@ function updateAgent(ctx, session, name, input) {
244
277
  if (blockedOn) checkBlocker(ctx, session, name, blockedOn);
245
278
  }
246
279
  if (current.pendingStatus) publishPending(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);
280
+ ctx.db.prepare(`UPDATE agents SET note = ?, ${statusChangeSql("?")}, status = ?,
281
+ 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);
248
282
  return requireAgent(ctx, session, name);
249
283
  }
250
284
  function statusWhenDone(kind, hasQuestions) {
@@ -264,7 +298,7 @@ function statusAfterAnswers(kind) {
264
298
  }
265
299
  function closeAgent(ctx, session, name, event) {
266
300
  requireAgent(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);
301
+ ctx.db.prepare("UPDATE agents SET status = 'closed', pending_status = NULL, queue_order = NULL, blocked_on = NULL, status_since = ?, updated_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), nowIso(ctx), session, name);
268
302
  logEvent(ctx, session, {
269
303
  ...event,
270
304
  agent: name
@@ -277,17 +311,26 @@ function dropAgent(ctx, session, name, reason) {
277
311
  note: reason
278
312
  });
279
313
  }
314
+ const PROMOTIONS = {
315
+ research: ["plan", "implement"],
316
+ plan: ["implement"]
317
+ };
318
+ const PROMOTE_KIND_REQUIRED = "kind is required: plan or implement for a research agent, implement for a plan one";
280
319
  function promoteAgent(ctx, session, name, input) {
281
320
  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',
321
+ const target = input.kind;
322
+ if (!isAgentKind(target)) throw new CarnetError("INVALID_KIND", PROMOTE_KIND_REQUIRED);
323
+ const allowed = PROMOTIONS[agent.kind] ?? [];
324
+ 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}`);
325
+ if (input.worktree && target !== "implement") throw new CarnetError("INVALID_KIND", `A worktree means an implement agent: promote ${name} with kind implement`);
326
+ ctx.db.prepare(`UPDATE agents SET kind = ?, promoted_from = ?, status = 'running',
284
327
  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);
328
+ base_commit = COALESCE(?, base_commit), queue_order = NULL, status_since = ?, updated_at = ?
329
+ WHERE session = ? AND name = ?`).run(target, agent.kind, input.worktree ?? null, input.baseCommit ?? null, nowIso(ctx), nowIso(ctx), session, name);
287
330
  logEvent(ctx, session, {
288
331
  type: "promoted",
289
332
  agent: name,
290
- note: "analyze to implement"
333
+ note: `${agent.kind} to ${target}`
291
334
  });
292
335
  return requireAgent(ctx, session, name);
293
336
  }
@@ -686,6 +729,55 @@ ALTER TABLE agents_new RENAME TO agents;
686
729
  CREATE INDEX agents_session_status ON agents(session, status);
687
730
  -- The CLI and the plugin update separately; the pane warns when the hooks lag behind.
688
731
  ALTER TABLE sessions ADD COLUMN plugin_version TEXT;
732
+ `,
733
+ `
734
+ -- A research or analyze agent's throwaway folder under the run directory, writable through the guard.
735
+ ALTER TABLE agents ADD COLUMN sandbox TEXT;
736
+ `,
737
+ `
738
+ -- The analyze kind is now plan. launch_requested_at marks the Agent call that launches an agent,
739
+ -- so the next subagent pairs with it rather than with an older registered one.
740
+ CREATE TABLE agents_new (
741
+ session TEXT NOT NULL REFERENCES sessions(id),
742
+ name TEXT NOT NULL,
743
+ task TEXT,
744
+ status TEXT NOT NULL
745
+ CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'closed')),
746
+ note TEXT,
747
+ report_path TEXT,
748
+ base_commit TEXT,
749
+ worktree TEXT,
750
+ queue_order INTEGER,
751
+ started_at TEXT NOT NULL,
752
+ updated_at TEXT NOT NULL,
753
+ host_agent_id TEXT,
754
+ pending_status TEXT,
755
+ done_at TEXT,
756
+ kind TEXT NOT NULL CHECK (kind IN ('research', 'plan', 'implement', 'review')),
757
+ promoted_from TEXT CHECK (promoted_from IN ('research', 'plan', 'implement', 'review')),
758
+ target TEXT,
759
+ blocked_on TEXT,
760
+ sandbox TEXT,
761
+ launch_requested_at TEXT,
762
+ PRIMARY KEY (session, name)
763
+ );
764
+ INSERT INTO agents_new (session, name, task, status, note, report_path, base_commit, worktree,
765
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at, kind, promoted_from,
766
+ target, blocked_on, sandbox)
767
+ SELECT session, name, task, status, note, report_path, base_commit, worktree,
768
+ queue_order, started_at, updated_at, host_agent_id, pending_status, done_at,
769
+ CASE kind WHEN 'analyze' THEN 'plan' ELSE kind END,
770
+ CASE promoted_from WHEN 'analyze' THEN 'plan' ELSE promoted_from END,
771
+ target, blocked_on, sandbox
772
+ FROM agents;
773
+ DROP TABLE agents;
774
+ ALTER TABLE agents_new RENAME TO agents;
775
+ CREATE INDEX agents_session_status ON agents(session, status);
776
+ `,
777
+ `
778
+ -- When the status last changed; rows from before it start from their last update.
779
+ ALTER TABLE agents ADD COLUMN status_since TEXT;
780
+ UPDATE agents SET status_since = updated_at;
689
781
  `
690
782
  ];
691
783
  const preconditions = { 11: (db) => {
@@ -778,6 +870,9 @@ function corePromptPath(env) {
778
870
  function reportsDirectory(workspace) {
779
871
  return join(workspace.runDirectory, "reports");
780
872
  }
873
+ function sandboxesDirectory(workspace) {
874
+ return join(workspace.runDirectory, "sandboxes");
875
+ }
781
876
  function reportPath(workspace, agentName) {
782
877
  return join(reportsDirectory(workspace), `${agentName}.md`);
783
878
  }
@@ -1244,9 +1339,9 @@ function resetDeadSessions(ctx, isAlive) {
1244
1339
  }
1245
1340
  // src/prompt/core-rules.ts
1246
1341
  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.
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.
1342
+ - 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.
1248
1343
  - 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.
1344
+ - When an agent finishes, say only "<name> finished, report ready". Never summarise, quote or act on its report or final message until the human asks for that report (/rucher:report), even when answering about something else.
1250
1345
  - 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
1346
  - To launch agents or handle their results, load the rucher skill: it holds the full workflow.`;
1252
1347
  // src/prompt/prompt.ts
@@ -1256,7 +1351,7 @@ function readIfPresent(path) {
1256
1351
  return readFileSync(path, "utf8").trim() || void 0;
1257
1352
  }
1258
1353
  function baseRules(env = process.env) {
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.";
1354
+ return readIfPresent(corePromptPath(env)) ?? "- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches agents, asks for their report and its next action (inject, validate, apply, triage), applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the Main line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When an agent finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that report (/rucher:report), even when answering about something else.\n- Agents never commit, push, stash or record notes. An agent follows its kind's contract, writes its report to a file ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- To launch agents or handle their results, load the rucher skill: it holds the full workflow.";
1260
1355
  }
1261
1356
  function workspaceRules(workspace) {
1262
1357
  return workspace ? readIfPresent(join(workspace.definition, PROMPT_FILE)) : void 0;
@@ -1389,6 +1484,11 @@ function subagentMetadataDescription(transcriptPath) {
1389
1484
  return;
1390
1485
  }
1391
1486
  }
1487
+ function launchedNames(toolInput) {
1488
+ const prompt = text(toolInput, "prompt");
1489
+ const found = [text(toolInput, "description"), prompt && FORK_NAME_PATTERN.exec(prompt)?.[1]].filter((name) => Boolean(name));
1490
+ return found.length > 0 ? [...new Set(found)] : void 0;
1491
+ }
1392
1492
  function subagentPromptName(transcriptPath) {
1393
1493
  try {
1394
1494
  const firstLine = readFileSync(transcriptPath, "utf8").split("\n", 1)[0] ?? "";
@@ -1574,7 +1674,9 @@ const claudeCode = {
1574
1674
  agent_type: text(data, "agent_type"),
1575
1675
  path: touchedPath(toolName, data.tool_input, cwd),
1576
1676
  file_path: text(toolInput, "file_path") ?? text(toolInput, "notebook_path"),
1577
- command: text(toolInput, "command")
1677
+ command: text(toolInput, "command"),
1678
+ subagent_type: text(toolInput, "subagent_type"),
1679
+ launched_names: launchedNames(toolInput)
1578
1680
  };
1579
1681
  },
1580
1682
  subagentInheritsContext(payload) {
@@ -2174,6 +2276,38 @@ function mergeSessions(ctx, fromId, intoId) {
2174
2276
  throw error;
2175
2277
  }
2176
2278
  }
2279
+ // src/sandbox.ts
2280
+ function strictlyInside(path, folder) {
2281
+ const rest = relative(folder, path);
2282
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute(rest);
2283
+ }
2284
+ function resolveSandbox(workspace, path) {
2285
+ if (!workspace) throw new CarnetError("INVALID_SANDBOX", "A sandbox needs a workspace: none is resolved");
2286
+ const root = sandboxesDirectory(workspace);
2287
+ const expanded = path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
2288
+ const resolved = resolve(workspace.runDirectory, expanded);
2289
+ 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`);
2290
+ if (existsSync(resolved)) {
2291
+ if (!lstatSync(resolved).isDirectory() || readdirSync(resolved).length > 0) throw new CarnetError("INVALID_SANDBOX", `${resolved} already exists and is not empty`);
2292
+ }
2293
+ return resolved;
2294
+ }
2295
+ function sandboxRemovedSuffix(removed) {
2296
+ return removed ? ", sandbox removed" : "";
2297
+ }
2298
+ function createSandbox(path) {
2299
+ mkdirSync(path, { recursive: true });
2300
+ }
2301
+ function removeSandbox(workspace, path) {
2302
+ if (!workspace || !path) return false;
2303
+ const resolved = resolve(path);
2304
+ if (!strictlyInside(resolved, sandboxesDirectory(workspace)) || !existsSync(resolved)) return false;
2305
+ rmSync(resolved, {
2306
+ recursive: true,
2307
+ force: true
2308
+ });
2309
+ return true;
2310
+ }
2177
2311
  // src/purge.ts
2178
2312
  const DEFAULT_PURGE_DAYS = 3;
2179
2313
  const DAY_MILLISECONDS = 864e5;
@@ -2296,7 +2430,7 @@ function renderSections(view, options = {}) {
2296
2430
  if (view.waiting.length === 0) out.push(" nothing");
2297
2431
  const waitingWidth = nameWidth(view.waiting);
2298
2432
  view.waiting.forEach((line, index) => {
2299
- out.push(` ${index + 1}. ${renderAgentLine(line, waitingWidth)}`);
2433
+ out.push(` ${index + 1}.${line.pinned ? "📌" : ""} ${renderAgentLine(line, waitingWidth)}`);
2300
2434
  });
2301
2435
  if (view.blocked.length > 0) {
2302
2436
  out.push("", BLOCKED_HEADER);
@@ -2379,19 +2513,20 @@ function endTurn(ctx, session) {
2379
2513
  }
2380
2514
  // src/status/view.ts
2381
2515
  const ACTION_RANK = {
2382
- validate: 1,
2383
- triage: 2,
2384
- inject: 3,
2516
+ test: 0,
2517
+ answer: 1,
2518
+ validate: 2,
2519
+ triage: 3,
2385
2520
  apply: 4,
2386
- test: 5
2521
+ inject: 5
2387
2522
  };
2388
2523
  function plural(count, word) {
2389
2524
  return `${count} ${word}${count === 1 ? "" : "s"}`;
2390
2525
  }
2391
2526
  function actionWord(agent) {
2392
2527
  const { kind, status } = agent;
2393
- if (status === "answer") return kind === "analyze" ? "validate" : "answer";
2394
- if (status === "review" && kind !== "implement") return FINAL_ACTIONS[kind];
2528
+ if (status === "answer") return kind === "plan" ? "validate" : "answer";
2529
+ if (status === "review" && kind !== "implement") return KIND_ACTIONS[kind];
2395
2530
  if (status === "apply" && kind === "implement") return "apply";
2396
2531
  if (status === "test") return status;
2397
2532
  return status === "discussing" ? "discuss" : status;
@@ -2424,8 +2559,8 @@ function runningAction(agent) {
2424
2559
  return agent.promotedFrom ? `promoted from ${agent.promotedFrom}` : null;
2425
2560
  }
2426
2561
  function rankOf(agent) {
2427
- if (agent.status === "answer") return 0;
2428
- return ACTION_RANK[actionWord(agent)] ?? Object.keys(ACTION_RANK).length + 1;
2562
+ if (agent.status === "answer") return ACTION_RANK.answer;
2563
+ return ACTION_RANK[actionWord(agent)] ?? Object.keys(ACTION_RANK).length;
2429
2564
  }
2430
2565
  function compareWaiting(left, right) {
2431
2566
  if (left.queueOrder !== null || right.queueOrder !== null) {
@@ -2433,7 +2568,7 @@ function compareWaiting(left, right) {
2433
2568
  if (right.queueOrder === null) return -1;
2434
2569
  return left.queueOrder - right.queueOrder;
2435
2570
  }
2436
- return rankOf(left) - rankOf(right) || left.startedAt.localeCompare(right.startedAt);
2571
+ return rankOf(left) - rankOf(right) || left.statusSince.localeCompare(right.statusSince) || left.name.localeCompare(right.name);
2437
2572
  }
2438
2573
  function toLine(agent, action) {
2439
2574
  return {
@@ -2442,7 +2577,8 @@ function toLine(agent, action) {
2442
2577
  status: agent.status,
2443
2578
  emoji: agent.status === "closed" ? "" : EMOJI[agent.status],
2444
2579
  action,
2445
- note: agent.note
2580
+ note: agent.note,
2581
+ pinned: agent.queueOrder !== null
2446
2582
  };
2447
2583
  }
2448
2584
  function formatClock(date) {
@@ -2454,10 +2590,9 @@ function buildStatusView(ctx, session, options = {}) {
2454
2590
  const isBlocked = (agent) => agent.blockedOn !== null && open.has(agent.blockedOn);
2455
2591
  const agents = all.filter((agent) => !options.kind || agent.kind === options.kind);
2456
2592
  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)));
2593
+ 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)));
2594
+ const blocked = agents.filter(isBlocked).map((agent) => toLine(agent, `→ ${agent.blockedOn}`));
2595
+ const running = agents.filter((agent) => agent.status === "running" && !isBlocked(agent)).map((agent) => toLine(agent, runningAction(agent)));
2461
2596
  return {
2462
2597
  time: formatClock(ctx.now()),
2463
2598
  sessionName: session.name,
@@ -2476,15 +2611,39 @@ function byHostAgentId(ctx, session, hostAgentId) {
2476
2611
  const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND host_agent_id = ?").get(session, hostAgentId);
2477
2612
  return row && toAgent(row);
2478
2613
  }
2479
- function pairSubagent(ctx, session, hostAgentId) {
2614
+ function unpairedByName(ctx, session, names) {
2615
+ for (const name of names) {
2616
+ const row = ctx.db.prepare(`SELECT * FROM agents
2617
+ WHERE session = ? AND name = ? AND status != 'closed' AND host_agent_id IS NULL`).get(session, name);
2618
+ if (row) return row;
2619
+ }
2620
+ }
2621
+ function unpairedAgent(ctx, session, names) {
2622
+ const row = unpairedByName(ctx, session, names);
2623
+ return row && toAgent(row);
2624
+ }
2625
+ function pendingPlanAgent(ctx, session) {
2626
+ const row = ctx.db.prepare(`SELECT * FROM agents
2627
+ WHERE session = ? AND kind = 'plan' AND status = 'running' AND host_agent_id IS NULL
2628
+ ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session);
2629
+ return row && toAgent(row);
2630
+ }
2631
+ function requestLaunch(ctx, session, name) {
2632
+ ctx.db.prepare("UPDATE agents SET launch_requested_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
2633
+ }
2634
+ function pairSubagent(ctx, session, hostAgentId, names = []) {
2480
2635
  const paired = byHostAgentId(ctx, session, hostAgentId);
2481
2636
  if (paired) return paired;
2482
2637
  const since = (/* @__PURE__ */ new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS)).toISOString();
2483
- const row = ctx.db.prepare(`SELECT * FROM agents
2484
- WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND started_at >= ?
2485
- ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session, since);
2638
+ const row = unpairedByName(ctx, session, names) ?? ctx.db.prepare(`SELECT * FROM agents
2639
+ WHERE session = ? AND status != 'closed' AND host_agent_id IS NULL
2640
+ AND launch_requested_at >= ?
2641
+ ORDER BY launch_requested_at ASC, rowid ASC LIMIT 1`).get(session, since) ?? ctx.db.prepare(`SELECT * FROM agents
2642
+ WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND blocked_on IS NULL
2643
+ AND started_at >= ?
2644
+ ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session, since);
2486
2645
  if (!row) return void 0;
2487
- ctx.db.prepare("UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?").run(hostAgentId, session, row.name);
2646
+ ctx.db.prepare("UPDATE agents SET host_agent_id = ?, launch_requested_at = NULL WHERE session = ? AND name = ?").run(hostAgentId, session, row.name);
2488
2647
  return byHostAgentId(ctx, session, hostAgentId);
2489
2648
  }
2490
2649
  function byName(ctx, session, name) {
@@ -2544,12 +2703,21 @@ var Carnet = class {
2544
2703
  ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.workspace ?? void 0),
2545
2704
  upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.workspace, payload, env),
2546
2705
  touch: (id) => touchSession(this.ctx, id),
2547
- merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
2706
+ merge: (fromId, intoId) => {
2707
+ const result = mergeSessions(this.ctx, fromId, intoId);
2708
+ this.releaseClosedSandboxes(fromId);
2709
+ this.releaseClosedSandboxes(intoId);
2710
+ return result;
2711
+ },
2548
2712
  purge: (keepId, days) => purgeSessions(this.ctx, keepId, days),
2549
2713
  name: (id, name, purpose) => nameSession(this.ctx, id, name, purpose),
2550
2714
  adoptTitle: (id, title) => adoptTitle(this.ctx, id, title),
2551
2715
  list: (options) => listSessions(this.ctx, options),
2552
- drop: (id) => dropSession(this.ctx, id),
2716
+ drop: (id) => {
2717
+ const session = dropSession(this.ctx, id);
2718
+ this.releaseClosedSandboxes(id);
2719
+ return session;
2720
+ },
2553
2721
  default: () => defaultSession(this.ctx),
2554
2722
  byName: (name) => sessionByName(this.ctx, name),
2555
2723
  byHostProcess: (host, processId) => sessionByHostProcess(this.ctx, host, processId),
@@ -2566,18 +2734,56 @@ var Carnet = class {
2566
2734
  staleTemp: (olderThanMilliseconds) => staleTempSessions(this.ctx, olderThanMilliseconds),
2567
2735
  resetDead: (isAlive) => resetDeadSessions(this.ctx, isAlive)
2568
2736
  };
2737
+ releaseSandbox(agent) {
2738
+ if (!agent.sandbox) return {
2739
+ ...agent,
2740
+ sandboxRemoved: false
2741
+ };
2742
+ const sandboxRemoved = removeSandbox(this.workspace, agent.sandbox);
2743
+ clearSandbox(this.ctx, agent.session, agent.name);
2744
+ return {
2745
+ ...agent,
2746
+ sandbox: null,
2747
+ sandboxRemoved
2748
+ };
2749
+ }
2750
+ releaseClosedSandboxes(session) {
2751
+ let removed = 0;
2752
+ for (const row of closedSandboxes(this.ctx, session)) {
2753
+ if (removeSandbox(this.workspace, row.sandbox)) removed += 1;
2754
+ clearSandbox(this.ctx, row.session, row.name);
2755
+ }
2756
+ return removed;
2757
+ }
2569
2758
  agents = {
2570
2759
  get: (session, name) => getAgent(this.ctx, session, name),
2571
- start: (session, input) => startAgent(this.ctx, session, input),
2760
+ start: (session, input) => {
2761
+ const sandbox = input.sandbox ? resolveSandbox(this.workspace, input.sandbox) : void 0;
2762
+ const agent = startAgent(this.ctx, session, {
2763
+ ...input,
2764
+ sandbox
2765
+ });
2766
+ if (sandbox) createSandbox(sandbox);
2767
+ return agent;
2768
+ },
2572
2769
  update: (session, name, input) => updateAgent(this.ctx, session, name, input),
2573
2770
  finish: (session, name, input) => finishAgent(this.ctx, session, name, input),
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),
2771
+ drop: (session, name, reason) => this.releaseSandbox(dropAgent(this.ctx, session, name, reason)),
2772
+ close: (session, name, event) => this.releaseSandbox(closeAgent(this.ctx, session, name, event)),
2773
+ promote: (session, name, input) => {
2774
+ const agent = promoteAgent(this.ctx, session, name, input);
2775
+ return agent.kind === "implement" ? this.releaseSandbox(agent) : {
2776
+ ...agent,
2777
+ sandboxRemoved: false
2778
+ };
2779
+ },
2577
2780
  list: (session, options) => listAgents(this.ctx, session, options),
2578
2781
  reorderQueue: (session, names) => reorderQueue(this.ctx, session, names),
2579
2782
  byHostAgentId: (session, hostAgentId) => byHostAgentId(this.ctx, session, hostAgentId),
2580
- pairSubagent: (session, hostAgentId) => pairSubagent(this.ctx, session, hostAgentId),
2783
+ pairSubagent: (session, hostAgentId, names) => pairSubagent(this.ctx, session, hostAgentId, names),
2784
+ unpaired: (session, names) => unpairedAgent(this.ctx, session, names),
2785
+ pendingPlan: (session) => pendingPlanAgent(this.ctx, session),
2786
+ requestLaunch: (session, name) => requestLaunch(this.ctx, session, name),
2581
2787
  stopSubagent: (session, hostAgentId, names) => stopSubagent(this.ctx, session, hostAgentId, names)
2582
2788
  };
2583
2789
  questions = {
@@ -2723,7 +2929,7 @@ function stepAgent(carnet, session, input) {
2723
2929
  const reviews = carnet.agents.list(session).filter((other) => other.kind === "review" && other.target === name);
2724
2930
  return `⚙️ ${name} applying${reviews.length ? `\nwarning: review ${reviews.map((review) => review.name).join(", ")} not triaged yet` : ""}`;
2725
2931
  }
2726
- case "committed":
2932
+ case "committed": {
2727
2933
  if (!commit) throw new CarnetError("COMMIT_REQUIRED", "The committed step needs the commit");
2728
2934
  carnet.events.log(session, {
2729
2935
  type: "committed",
@@ -2731,13 +2937,15 @@ function stepAgent(carnet, session, input) {
2731
2937
  commit,
2732
2938
  note
2733
2939
  });
2734
- carnet.agents.drop(session, name, `committed ${commit}`);
2940
+ const closed = carnet.agents.drop(session, name, `committed ${commit}`);
2735
2941
  clearTableOf(carnet, session, name);
2736
- return `✅ ${name} committed ${commit}, closed`;
2737
- case "dropped":
2738
- carnet.agents.drop(session, name, note);
2942
+ return `✅ ${name} committed ${commit}, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;
2943
+ }
2944
+ case "dropped": {
2945
+ const closed = carnet.agents.drop(session, name, note);
2739
2946
  clearTableOf(carnet, session, name);
2740
- return `${name} dropped, closed`;
2947
+ return `${name} dropped, closed${sandboxRemovedSuffix(closed.sandboxRemoved)}`;
2948
+ }
2741
2949
  default: {
2742
2950
  const next = input.next ?? (step === "answered" ? statusAfterAnswers(agent.kind) : DEFAULT_NEXT[step]);
2743
2951
  carnet.events.log(session, {
@@ -2750,18 +2958,11 @@ function stepAgent(carnet, session, input) {
2750
2958
  note: note ?? null,
2751
2959
  blockedOn: null
2752
2960
  });
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
- }
2961
+ if (next === "running" || step !== "answered") clearTableOf(carnet, session, name);
2761
2962
  return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;
2762
2963
  }
2763
2964
  }
2764
2965
  }
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 };
2966
+ export { repoPathFor as $, renderFindings as $t, renderNotesSummary as A, KIND_ABBREVIATIONS as An, rulesVersion as At, DEFAULT_HALF_LIFE_DAYS as B, isUserActionStatus as Bn, definitionInstructions as Bt, NOTES_FOLD_LINES as C, mainTargetRange as Cn, SUBAGENT_RULES as Ct, renderMainLine as D, sanitizeNote as Dn, compactReminder as Dt, renderAgentLine as E, NOTE_MAX as En, baseRules as Et, purgeDays as F, MAIN_WAITING_EMOJI as Fn, AGENTS_FILE as Ft, isNoteKind as G, CarnetError as Gn, loadWorkspace as Gt, NOTE_KINDS as H, EVENT_TYPES as Hn, expandHome as Ht, sandboxRemovedSuffix as I, MAIN_WORKING_EMOJI as In, INSTRUCTIONS_FILE as It, sessionNoteActivity as J, workspaceHosts as Jt, localDay as K, removeWorkspaceRepo as Kt, MEMORY_MAX_CHARACTERS as L, OPEN_AGENT_STATUSES as Ln, WORKSPACE_FILE as Lt, renderStatus as M, KIND_TAG_PATTERN as Mn, CORE_RULES as Mt, renderTableLine as N, LEGEND as Nn, MINIMUM_ID_PREFIX as Nt, renderNoteLine as O, AGENT_STATUSES as On, outsideRucherContext as Ot, DEFAULT_PURGE_DAYS as P, MAIN_FAILED_EMOJI as Pn, shortId as Pt, repoNameFor as Q, formatFinding as Qt, memoryMaxCharacters as R, USER_ACTION_STATUSES as Rn, addWorkspaceRepo as Rt, MAIN_WORKING_SUFFIX as S, isAgentKind as Sn, RULES_UPDATED_NOTICE as St, SIMILAR_PREFIX as T, statusWhenDone as Tn, assemblePrompt as Tt, NOTE_TEXT_LIMIT as U, SESSION_EVENT_TYPES as Un, isWorkspaceName as Ut, DUPLICATE_SIMILARITY as V, kindTag as Vn, dropWorkspace as Vt, STALE_AFTER_ACTIVE_DAYS as W, isEventType as Wn, listWorkspaces as Wt, workspaceRepoNames as X, FINDING_DECISIONS as Xt, similarity as Y, renderQuestions as Yt, isInside as Z, FINDING_SEVERITIES as Zt, BLOCKED_HEADER as _, KIND_REQUIRED as _n, mergeSettings as _t, formatEventLine as a, reportsDirectory as an, sessionWorkspaceName as at, MAIN_IDLE as b, REPORTING_NOTE as bn, OUTSIDE_RUCHER_NOTICE as bt, Carnet as c, workspaceDefinition as cn, DEFAULT_HOST as ct, openWorkspaceCarnet as d, openDatabase as dn, claudeCode as dt, corePromptPath as en, requireWorkspace as et, PAIRING_WINDOW_MILLISECONDS as f, migrate as fn, transcriptTitle as ft, TURNS as g, KIND_ACTIONS as gn, markdownCopy as gt, formatClock as h, AGENT_KINDS as hn, MARKDOWN_MARKER as ht, RESUME_MAX_CHARACTERS as i, reportPath as in, deleteWorkspaceNotes as it, renderSections as j, KIND_LEGEND as jn, workspaceRules as jt, renderNotes as k, EMOJI as kn, rulesText as kt, openCarnet as l, workspacesDirectory as ln, allHosts as lt, buildStatusView as m, schemaVersion as mn, GENERATED_MARKER as mt, stepAgent as n, defaultRunDirectory as nn, workspaceLabel as nt, resumeContext as o, rucherPaths as on, workspaceLastActive as ot, STOPPED_NOTE as p, migrations as pn, workspaceSettings as pt, memoryHalfLife as q, workspaceExists as qt, RESUME_EVENTS as r, promptsDirectory as rn, archiveWorkspaceSessions as rt, sessionLabel as s, sandboxesDirectory as sn, workspaceSessionCounts as st, AGENT_STEPS as t, databasePath as tn, resolveWorkspace as tt, openResolvedCarnet as u, MEMORY_DB as un, hostById as ut, MAIN_FAILED_SUFFIX as v, PROMOTE_KIND_REQUIRED as vn, removeStaleCopies as vt, NOTES_HEADER as w, statusAfterAnswers as wn, appendPromptFile as wt, MAIN_WAITING_SUFFIX as x, SANDBOX_KINDS as xn, PROMPT_FILE as xt, MAIN_HEADER as y, PUBLISH_FALLBACK_MILLISECONDS as yn, writeGenerated as yt, renderMemory as z, isAgentStatus as zn, createWorkspace as zt };
2766
2967
 
2767
- //# sourceMappingURL=steps-xzr8iVWn.mjs.map
2968
+ //# sourceMappingURL=steps-wNm8GU_c.mjs.map