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