@rucher/carnet 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1764 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, relative, resolve } from "node:path";
4
+ import { homedir } from "node:os";
5
+ // src/context.ts
6
+ function nowIso(ctx) {
7
+ return ctx.now().toISOString();
8
+ }
9
+ // src/errors.ts
10
+ var CarnetError = class extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ this.name = "CarnetError";
16
+ }
17
+ };
18
+ // src/events.ts
19
+ const EVENT_TYPES = [
20
+ "started",
21
+ "finished",
22
+ "answered",
23
+ "applied",
24
+ "tested",
25
+ "committed",
26
+ "dropped"
27
+ ];
28
+ const SESSION_EVENT_TYPES = [
29
+ "session.started",
30
+ "session.resumed",
31
+ "session.ended",
32
+ "session.forked"
33
+ ];
34
+ const ALL_EVENT_TYPES = [...EVENT_TYPES, ...SESSION_EVENT_TYPES];
35
+ function isEventType(value) {
36
+ return typeof value === "string" && ALL_EVENT_TYPES.includes(value);
37
+ }
38
+ function toEvent(row) {
39
+ return {
40
+ id: row.id,
41
+ session: row.session,
42
+ at: row.at,
43
+ type: row.type,
44
+ agent: row.agent,
45
+ commit: row.commit_sha,
46
+ link: row.link,
47
+ note: row.note
48
+ };
49
+ }
50
+ function logEvent(ctx, session, input) {
51
+ if (!isEventType(input.type)) throw new CarnetError("INVALID_EVENT_TYPE", `Unknown event type "${String(input.type)}"`);
52
+ 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);
53
+ return toEvent(ctx.db.prepare("SELECT * FROM events WHERE id = ?").get(result.lastInsertRowid));
54
+ }
55
+ function readEvents(ctx, { session, limit = 20, agentOnly = false }) {
56
+ const filter = agentOnly ? "AND type NOT LIKE 'session.%'" : "";
57
+ return ctx.db.prepare(`SELECT * FROM (SELECT * FROM events WHERE session = ? ${filter} ORDER BY id DESC LIMIT ?) ORDER BY id ASC`).all(session, limit).map(toEvent);
58
+ }
59
+ // src/status/model.ts
60
+ const AGENT_STATUSES = [
61
+ "running",
62
+ "discussing",
63
+ "answer",
64
+ "review",
65
+ "apply",
66
+ "test",
67
+ "commit",
68
+ "branch",
69
+ "closed"
70
+ ];
71
+ const USER_ACTION_STATUSES = [
72
+ "discussing",
73
+ "answer",
74
+ "review",
75
+ "apply",
76
+ "test",
77
+ "commit",
78
+ "branch"
79
+ ];
80
+ const EMOJI = {
81
+ running: "⏳",
82
+ discussing: "💬",
83
+ answer: "❓",
84
+ review: "👀",
85
+ apply: "📥",
86
+ test: "🧪",
87
+ commit: "✅",
88
+ branch: "🌿"
89
+ };
90
+ const MAIN_WORKING_EMOJI = "⚙️";
91
+ const LEGEND = "⚙️ main working · 💬 discussing · ❓ answer · 👀 review · 📥 apply · 🧪 test · ✅ commit · 🌿 branch · ⏳ running";
92
+ function isAgentStatus(value) {
93
+ return typeof value === "string" && AGENT_STATUSES.includes(value);
94
+ }
95
+ function isUserActionStatus(value) {
96
+ return typeof value === "string" && USER_ACTION_STATUSES.includes(value);
97
+ }
98
+ const OPEN_AGENT_STATUSES = ["running", ...USER_ACTION_STATUSES];
99
+ // src/status/note.ts
100
+ const NOTE_MAX = 60;
101
+ const PATH_PREFIX = /^(\/|\.\.?\/|~\/)/;
102
+ const FILE_AFTER_SLASH = /\/[^/\s]+\.[A-Za-z0-9]+$/;
103
+ function looksLikePath(token) {
104
+ if (PATH_PREFIX.test(token)) return true;
105
+ const slashes = token.split("/").length - 1;
106
+ return slashes >= 2 || slashes === 1 && FILE_AFTER_SLASH.test(token);
107
+ }
108
+ function sanitizeNote(text) {
109
+ const cleaned = text.replaceAll("`", "").split(/\s+/).filter((token) => token && !looksLikePath(token)).join(" ").trim();
110
+ if (cleaned.length <= 60) return cleaned;
111
+ return `${cleaned.slice(0, 59).trimEnd()}…`;
112
+ }
113
+ // src/agents.ts
114
+ function toAgent(row) {
115
+ return {
116
+ session: row.session,
117
+ name: row.name,
118
+ task: row.task,
119
+ status: row.status,
120
+ note: row.note,
121
+ reportPath: row.report_path,
122
+ baseCommit: row.base_commit,
123
+ worktree: row.worktree,
124
+ queueOrder: row.queue_order,
125
+ hostAgentId: row.host_agent_id,
126
+ pendingStatus: row.pending_status,
127
+ doneAt: row.done_at,
128
+ startedAt: row.started_at,
129
+ updatedAt: row.updated_at
130
+ };
131
+ }
132
+ const REPORTING_NOTE = "reporting";
133
+ const PUBLISH_FALLBACK_MILLISECONDS = 12e4;
134
+ function publishPending(ctx, session, name) {
135
+ const row = ctx.db.prepare("SELECT pending_status, report_path FROM agents WHERE session = ? AND name = ?").get(session, name);
136
+ if (!row?.pending_status) return;
137
+ ctx.db.prepare("UPDATE agents SET status = pending_status, pending_status = NULL, note = NULL, updated_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
138
+ logEvent(ctx, session, {
139
+ type: "finished",
140
+ agent: name,
141
+ link: row.report_path ?? void 0
142
+ });
143
+ }
144
+ function publishOverdue(ctx, session) {
145
+ const before = (/* @__PURE__ */ new Date(ctx.now().getTime() - PUBLISH_FALLBACK_MILLISECONDS)).toISOString();
146
+ const rows = ctx.db.prepare("SELECT name FROM agents WHERE session = ? AND pending_status IS NOT NULL AND done_at <= ?").all(session, before);
147
+ for (const row of rows) publishPending(ctx, session, row.name);
148
+ }
149
+ function getAgent(ctx, session, name) {
150
+ publishOverdue(ctx, session);
151
+ const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND name = ?").get(session, name);
152
+ return row && toAgent(row);
153
+ }
154
+ function requireAgent(ctx, session, name) {
155
+ const agent = getAgent(ctx, session, name);
156
+ if (!agent) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
157
+ return agent;
158
+ }
159
+ function startAgent(ctx, session, input) {
160
+ const name = sanitizeNote(input.name);
161
+ const existing = getAgent(ctx, session, name);
162
+ if (existing && existing.status !== "closed") throw new CarnetError("AGENT_EXISTS", `Agent "${name}" is already open in this session`);
163
+ if (existing) ctx.db.prepare("DELETE FROM agents WHERE session = ? AND name = ?").run(session, name);
164
+ const at = nowIso(ctx);
165
+ ctx.db.prepare(`INSERT INTO agents (session, name, task, status, base_commit, worktree, started_at, updated_at)
166
+ VALUES (?, ?, ?, 'running', ?, ?, ?, ?)`).run(session, name, input.task, input.baseCommit ?? null, input.worktree ?? null, at, at);
167
+ logEvent(ctx, session, {
168
+ type: "started",
169
+ agent: name,
170
+ note: input.task
171
+ });
172
+ return requireAgent(ctx, session, name);
173
+ }
174
+ function updateAgent(ctx, session, name, input) {
175
+ const current = requireAgent(ctx, session, name);
176
+ if (!isAgentStatus(input.status) || input.status === "closed") throw new CarnetError("INVALID_STATUS", `Invalid agent status "${input.status}"; use agent_drop to close`);
177
+ const note = input.note === void 0 ? null : sanitizeNote(input.note);
178
+ if (current.pendingStatus) publishPending(ctx, session, name);
179
+ ctx.db.prepare("UPDATE agents SET note = COALESCE(?, CASE WHEN status = 'running' AND ? <> 'running' THEN NULL ELSE note END), status = ?, report_path = COALESCE(?, report_path), updated_at = ? WHERE session = ? AND name = ?").run(note, input.status, input.status, input.reportPath ?? null, nowIso(ctx), session, name);
180
+ return requireAgent(ctx, session, name);
181
+ }
182
+ function finishAgent(ctx, session, name, input) {
183
+ const agent = requireAgent(ctx, session, name);
184
+ const status = input.hasQuestions ? "answer" : "review";
185
+ const at = nowIso(ctx);
186
+ 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);
187
+ if (!agent.hostAgentId) publishPending(ctx, session, name);
188
+ return requireAgent(ctx, session, name);
189
+ }
190
+ function dropAgent(ctx, session, name, reason) {
191
+ requireAgent(ctx, session, name);
192
+ ctx.db.prepare("UPDATE agents SET status = 'closed', queue_order = NULL, updated_at = ? WHERE session = ? AND name = ?").run(nowIso(ctx), session, name);
193
+ logEvent(ctx, session, {
194
+ type: "dropped",
195
+ agent: name,
196
+ note: reason
197
+ });
198
+ return requireAgent(ctx, session, name);
199
+ }
200
+ function listAgents(ctx, session, options = {}) {
201
+ publishOverdue(ctx, session);
202
+ const where = options.includeClosed ? "" : "AND status != 'closed'";
203
+ return ctx.db.prepare(`SELECT * FROM agents WHERE session = ? ${where} ORDER BY started_at ASC, name ASC`).all(session).map(toAgent);
204
+ }
205
+ function reorderQueue(ctx, session, names) {
206
+ const at = nowIso(ctx);
207
+ ctx.db.prepare("UPDATE agents SET queue_order = NULL WHERE session = ?").run(session);
208
+ const update = ctx.db.prepare("UPDATE agents SET queue_order = ?, updated_at = ? WHERE session = ? AND name = ?");
209
+ names.forEach((name, index) => {
210
+ update.run(index + 1, at, session, sanitizeNote(name));
211
+ });
212
+ return listAgents(ctx, session);
213
+ }
214
+ // src/db/schema.ts
215
+ const migrations = [
216
+ `
217
+ CREATE TABLE sessions (
218
+ id TEXT PRIMARY KEY,
219
+ name TEXT UNIQUE,
220
+ purpose TEXT,
221
+ status TEXT NOT NULL DEFAULT 'temporary'
222
+ CHECK (status IN ('temporary', 'active', 'dropped')),
223
+ cwd TEXT,
224
+ repo TEXT,
225
+ claude_pid INTEGER,
226
+ created_at TEXT NOT NULL,
227
+ last_active_at TEXT NOT NULL
228
+ );
229
+
230
+ CREATE TABLE agents (
231
+ session TEXT NOT NULL REFERENCES sessions(id),
232
+ name TEXT NOT NULL,
233
+ task TEXT,
234
+ status TEXT NOT NULL
235
+ CHECK (status IN ('running', 'discussing', 'answer', 'review', 'apply', 'test', 'commit', 'branch', 'closed')),
236
+ note TEXT,
237
+ report_path TEXT,
238
+ base_commit TEXT,
239
+ worktree TEXT,
240
+ queue_order INTEGER,
241
+ started_at TEXT NOT NULL,
242
+ updated_at TEXT NOT NULL,
243
+ PRIMARY KEY (session, name)
244
+ );
245
+
246
+ CREATE TABLE table_items (
247
+ session TEXT PRIMARY KEY REFERENCES sessions(id),
248
+ text TEXT NOT NULL,
249
+ status TEXT,
250
+ main_working INTEGER NOT NULL DEFAULT 0,
251
+ updated_at TEXT NOT NULL
252
+ );
253
+
254
+ CREATE TABLE events (
255
+ id INTEGER PRIMARY KEY,
256
+ session TEXT NOT NULL REFERENCES sessions(id),
257
+ at TEXT NOT NULL,
258
+ type TEXT NOT NULL
259
+ CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped')),
260
+ agent TEXT,
261
+ commit_sha TEXT,
262
+ link TEXT,
263
+ note TEXT
264
+ );
265
+
266
+ CREATE INDEX events_session_at ON events(session, at);
267
+ CREATE INDEX agents_session_status ON agents(session, status);
268
+ `,
269
+ `
270
+ ALTER TABLE agents ADD COLUMN claude_agent_id TEXT;
271
+ `,
272
+ `
273
+ ALTER TABLE sessions ADD COLUMN hooked_at TEXT;
274
+ CREATE INDEX sessions_claude_pid ON sessions(claude_pid, hooked_at);
275
+ `,
276
+ `
277
+ ALTER TABLE agents ADD COLUMN pending_status TEXT;
278
+ ALTER TABLE agents ADD COLUMN done_at TEXT;
279
+ `,
280
+ `
281
+ UPDATE sessions SET status = 'active' WHERE status = 'paused';
282
+ `,
283
+ `
284
+ ALTER TABLE sessions RENAME COLUMN claude_pid TO host_pid;
285
+ ALTER TABLE sessions ADD COLUMN host TEXT NOT NULL DEFAULT 'claude-code';
286
+ ALTER TABLE agents RENAME COLUMN claude_agent_id TO host_agent_id;
287
+ DROP INDEX sessions_claude_pid;
288
+ CREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);
289
+ `,
290
+ `
291
+ CREATE TABLE sessions_new (
292
+ id TEXT PRIMARY KEY,
293
+ name TEXT UNIQUE,
294
+ purpose TEXT,
295
+ kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),
296
+ status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),
297
+ cwd TEXT,
298
+ repo TEXT,
299
+ host TEXT NOT NULL DEFAULT 'claude-code',
300
+ host_pid INTEGER,
301
+ hooked_at TEXT,
302
+ last_title TEXT,
303
+ parent_id TEXT REFERENCES sessions(id),
304
+ prompt_version TEXT,
305
+ created_at TEXT NOT NULL,
306
+ last_active_at TEXT NOT NULL,
307
+ ended_at TEXT,
308
+ CHECK (kind = 'temp' OR name IS NOT NULL)
309
+ );
310
+ INSERT INTO sessions_new (id, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at,
311
+ last_title, created_at, last_active_at)
312
+ SELECT id, name, purpose,
313
+ CASE WHEN status = 'active' AND name IS NOT NULL THEN 'active'
314
+ WHEN status = 'dropped' AND name IS NOT NULL THEN 'active'
315
+ ELSE 'temp' END,
316
+ CASE WHEN status = 'dropped' THEN 'archived' ELSE 'idle' END,
317
+ cwd, repo, host, host_pid, hooked_at, name, created_at, last_active_at
318
+ FROM sessions;
319
+ DROP TABLE sessions;
320
+ ALTER TABLE sessions_new RENAME TO sessions;
321
+ CREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);
322
+
323
+ CREATE TABLE events_new (
324
+ id INTEGER PRIMARY KEY,
325
+ session TEXT NOT NULL REFERENCES sessions(id),
326
+ at TEXT NOT NULL,
327
+ type TEXT NOT NULL
328
+ CHECK (type IN ('started', 'finished', 'answered', 'applied', 'tested', 'committed', 'dropped',
329
+ 'session.started', 'session.resumed', 'session.ended', 'session.forked')),
330
+ agent TEXT,
331
+ commit_sha TEXT,
332
+ link TEXT,
333
+ note TEXT
334
+ );
335
+ INSERT INTO events_new SELECT id, session, at, type, agent, commit_sha, link, note FROM events;
336
+ DROP TABLE events;
337
+ ALTER TABLE events_new RENAME TO events;
338
+ CREATE INDEX events_session_at ON events(session, at);
339
+ `,
340
+ `
341
+ CREATE TABLE notes (
342
+ id INTEGER PRIMARY KEY,
343
+ kind TEXT NOT NULL CHECK (kind IN ('learning', 'dead_end', 'decision')),
344
+ text TEXT NOT NULL,
345
+ session TEXT REFERENCES sessions(id) ON DELETE SET NULL,
346
+ agent TEXT,
347
+ similar_notes TEXT,
348
+ created_at TEXT NOT NULL,
349
+ dropped_at TEXT,
350
+ dropped_reason TEXT,
351
+ dropped_session TEXT REFERENCES sessions(id) ON DELETE SET NULL,
352
+ replaced_by INTEGER REFERENCES notes(id)
353
+ );
354
+
355
+ CREATE INDEX notes_active ON notes(dropped_at, kind);
356
+ CREATE INDEX notes_session ON notes(session);
357
+
358
+ CREATE TABLE note_repos (
359
+ note INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
360
+ repo TEXT NOT NULL,
361
+ PRIMARY KEY (note, repo)
362
+ );
363
+
364
+ CREATE INDEX note_repos_repo ON note_repos(repo);
365
+
366
+ CREATE TABLE note_citations (
367
+ id INTEGER PRIMARY KEY,
368
+ note INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
369
+ session TEXT REFERENCES sessions(id) ON DELETE SET NULL,
370
+ agent TEXT,
371
+ why TEXT NOT NULL,
372
+ at TEXT NOT NULL
373
+ );
374
+
375
+ CREATE INDEX note_citations_note_at ON note_citations(note, at);
376
+ CREATE INDEX note_citations_session ON note_citations(session);
377
+
378
+ CREATE TABLE active_days (
379
+ day TEXT PRIMARY KEY
380
+ );
381
+
382
+ CREATE TABLE session_repos (
383
+ session TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
384
+ repo TEXT NOT NULL,
385
+ injected_at TEXT NOT NULL,
386
+ PRIMARY KEY (session, repo)
387
+ );
388
+ `
389
+ ];
390
+ function schemaVersion(db) {
391
+ return db.prepare("PRAGMA user_version").get().user_version;
392
+ }
393
+ function foreignKeyViolations(db) {
394
+ return db.prepare("PRAGMA foreign_key_check").all().length;
395
+ }
396
+ function migrate(db) {
397
+ const current = schemaVersion(db);
398
+ if (current >= migrations.length) return;
399
+ const foreignKeys = db.prepare("PRAGMA foreign_keys").get();
400
+ db.exec("PRAGMA foreign_keys = OFF");
401
+ try {
402
+ for (const [version, migration] of migrations.entries()) {
403
+ if (version < current) continue;
404
+ db.exec("BEGIN");
405
+ try {
406
+ db.exec(migration);
407
+ if (foreignKeyViolations(db) > 0) throw new Error(`Migration ${version + 1} broke foreign keys`);
408
+ db.exec(`PRAGMA user_version = ${version + 1}`);
409
+ db.exec("COMMIT");
410
+ } catch (error) {
411
+ db.exec("ROLLBACK");
412
+ throw error;
413
+ }
414
+ }
415
+ } finally {
416
+ db.exec(`PRAGMA foreign_keys = ${foreignKeys.foreign_keys ? "ON" : "OFF"}`);
417
+ }
418
+ }
419
+ // src/db/open.ts
420
+ const MEMORY_DB = ":memory:";
421
+ function openDatabase(path) {
422
+ const db = new DatabaseSync(path);
423
+ if (path !== ":memory:") db.exec("PRAGMA journal_mode = WAL");
424
+ db.exec("PRAGMA foreign_keys = ON");
425
+ db.exec("PRAGMA busy_timeout = 5000");
426
+ migrate(db);
427
+ return db;
428
+ }
429
+ // src/hosts/claude-code.ts
430
+ const TRANSCRIPT_TAIL_BYTES = 262144;
431
+ const TITLE_PATTERN = /"type":"custom-title","customTitle":("(?:[^"\\]|\\.)*")/g;
432
+ const FORK_NAME_PATTERN = /You are fork `([^`]+)`/;
433
+ const REPOS_START = "<!-- rucher:repos start -->";
434
+ const REPOS_END = "<!-- rucher:repos end -->";
435
+ function payloadObject(json) {
436
+ const data = JSON.parse(json);
437
+ if (typeof data.session_id !== "string" || !data.session_id) throw new TypeError("Hook payload has no session_id");
438
+ return data;
439
+ }
440
+ function text(data, key) {
441
+ const value = data[key];
442
+ return typeof value === "string" ? value : void 0;
443
+ }
444
+ function touchedPath(toolName, input, cwd) {
445
+ const fields = typeof input === "object" && input !== null ? input : {};
446
+ if (toolName === "Read" || toolName === "Edit" || toolName === "Write") return text(fields, "file_path");
447
+ if (toolName === "Grep" || toolName === "Glob") return text(fields, "path") ?? cwd;
448
+ if (toolName === "Bash") return cwd;
449
+ }
450
+ function ownTaskDescription(data, agentId) {
451
+ const tasks = data.background_tasks;
452
+ if (!Array.isArray(tasks)) return void 0;
453
+ const own = tasks.find((task) => typeof task === "object" && task !== null && task.id === agentId);
454
+ return own ? text(own, "description") : void 0;
455
+ }
456
+ function subagentMetadataDescription(transcriptPath) {
457
+ try {
458
+ return text(JSON.parse(readFileSync(transcriptPath.replace(/\.jsonl$/, ".meta.json"), "utf8")), "description");
459
+ } catch {
460
+ return;
461
+ }
462
+ }
463
+ function subagentPromptName(transcriptPath) {
464
+ try {
465
+ const firstLine = readFileSync(transcriptPath, "utf8").split("\n", 1)[0] ?? "";
466
+ return FORK_NAME_PATTERN.exec(firstLine)?.[1];
467
+ } catch {
468
+ return;
469
+ }
470
+ }
471
+ function transcriptTitle(path) {
472
+ let descriptor;
473
+ try {
474
+ descriptor = openSync(path, "r");
475
+ const size = fstatSync(descriptor).size;
476
+ const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
477
+ const buffer = Buffer.alloc(length);
478
+ readSync(descriptor, buffer, 0, length, size - length);
479
+ const last = [...buffer.toString("utf8").matchAll(TITLE_PATTERN)].at(-1)?.[1];
480
+ return last === void 0 ? void 0 : JSON.parse(last);
481
+ } catch {
482
+ return;
483
+ } finally {
484
+ if (descriptor !== void 0) closeSync(descriptor);
485
+ }
486
+ }
487
+ function reposBlock(group) {
488
+ const repos = group.repos.length ? group.repos.map((repo) => `- \`${basename(repo)}\`: ${repo}`).join("\n") : "- (none yet: `rucher group add <path>`)";
489
+ return `${REPOS_START}\n## Repos\n\n${repos}\n${REPOS_END}`;
490
+ }
491
+ function replaceReposBlock(content, group) {
492
+ const start = content.indexOf(REPOS_START);
493
+ const end = content.indexOf(REPOS_END);
494
+ if (start === -1 || end === -1 || end < start) return null;
495
+ return content.slice(0, start) + reposBlock(group) + content.slice(end + 25);
496
+ }
497
+ function groupInstructions(group) {
498
+ return `# ${group.name}
499
+
500
+ Meta directory of the ${group.name} group: context only, the repos live at their own paths below and are reachable through \`.claude/settings.json\`. Start Claude Code sessions here.
501
+
502
+ ${reposBlock(group)}
503
+
504
+ ## Multi-agent work
505
+
506
+ Use the rucher tools (Carnet) for agent statuses and the journal, and the rucher skill for the workflow.
507
+
508
+ ## Shared instructions
509
+
510
+ (what every session of this group should know)
511
+ `;
512
+ }
513
+ function groupSettings(group) {
514
+ return `${JSON.stringify({ permissions: { additionalDirectories: group.repos } }, null, 2)}\n`;
515
+ }
516
+ const instructionsFile = {
517
+ path: "CLAUDE.md",
518
+ sync(group) {
519
+ const path = join(group.root, "CLAUDE.md");
520
+ if (!existsSync(path)) {
521
+ writeFileSync(path, groupInstructions(group));
522
+ return "written";
523
+ }
524
+ const content = readFileSync(path, "utf8");
525
+ const next = replaceReposBlock(content, group);
526
+ if (next === null) return "no-markers";
527
+ if (next === content) return "unchanged";
528
+ writeFileSync(path, next);
529
+ return "updated";
530
+ }
531
+ };
532
+ const settingsFile = {
533
+ path: ".claude/settings.json",
534
+ sync(group, mode) {
535
+ const path = join(group.root, ".claude", "settings.json");
536
+ if (!existsSync(path)) {
537
+ if (group.repos.length === 0) return "unchanged";
538
+ mkdirSync(dirname(path), { recursive: true });
539
+ writeFileSync(path, groupSettings(group));
540
+ return "written";
541
+ }
542
+ const settings = JSON.parse(readFileSync(path, "utf8"));
543
+ const current = settings.permissions?.additionalDirectories ?? [];
544
+ const next = mode === "exact" ? group.repos : [...current, ...group.repos.filter((repo) => !current.includes(repo))];
545
+ if (next.length === current.length && next.every((repo, index) => repo === current[index])) return "unchanged";
546
+ settings.permissions = {
547
+ ...settings.permissions,
548
+ additionalDirectories: next
549
+ };
550
+ writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`);
551
+ return "updated";
552
+ }
553
+ };
554
+ function launchArguments(options = {}) {
555
+ return [
556
+ ...options.name ? ["--name", options.name] : [],
557
+ ...options.appendPromptFile ? ["--append-system-prompt-file", options.appendPromptFile] : [],
558
+ ...options.passthrough ?? []
559
+ ];
560
+ }
561
+ const RENDERING_SOURCES = /* @__PURE__ */ new Set([
562
+ "startup",
563
+ "clear",
564
+ "compact",
565
+ "fork"
566
+ ]);
567
+ const claudeCode = {
568
+ id: "claude-code",
569
+ displayName: "Claude Code",
570
+ processId(env) {
571
+ const processId = Number(env.CLAUDE_PID);
572
+ return Number.isInteger(processId) && processId > 0 ? processId : null;
573
+ },
574
+ sessionIdFromEnvironment(env) {
575
+ return env.CLAUDE_CODE_SESSION_ID || void 0;
576
+ },
577
+ projectDirectory(env) {
578
+ return env.CLAUDE_PROJECT_DIR || void 0;
579
+ },
580
+ parseSessionPayload(json) {
581
+ const data = payloadObject(json);
582
+ return {
583
+ session_id: data.session_id,
584
+ cwd: text(data, "cwd"),
585
+ source: text(data, "source"),
586
+ session_title: text(data, "session_title")
587
+ };
588
+ },
589
+ parsePromptPayload(json) {
590
+ const data = payloadObject(json);
591
+ return {
592
+ session_id: data.session_id,
593
+ cwd: text(data, "cwd"),
594
+ session_title: text(data, "session_title"),
595
+ transcript_path: text(data, "transcript_path")
596
+ };
597
+ },
598
+ parseSubagentPayload(json) {
599
+ const data = payloadObject(json);
600
+ const agentId = text(data, "agent_id");
601
+ if (!agentId) throw new TypeError("Hook payload has no agent_id");
602
+ return {
603
+ session_id: data.session_id,
604
+ agent_id: agentId,
605
+ agent_type: text(data, "agent_type"),
606
+ cwd: text(data, "cwd"),
607
+ description: ownTaskDescription(data, agentId),
608
+ agent_transcript_path: text(data, "agent_transcript_path")
609
+ };
610
+ },
611
+ parseSessionEndPayload(json) {
612
+ const data = payloadObject(json);
613
+ return {
614
+ session_id: data.session_id,
615
+ cwd: text(data, "cwd"),
616
+ reason: text(data, "reason")
617
+ };
618
+ },
619
+ parseToolPayload(json) {
620
+ const data = payloadObject(json);
621
+ const toolName = text(data, "tool_name");
622
+ const cwd = text(data, "cwd");
623
+ return {
624
+ session_id: data.session_id,
625
+ cwd,
626
+ tool_name: toolName,
627
+ agent_id: text(data, "agent_id"),
628
+ path: touchedPath(toolName, data.tool_input, cwd)
629
+ };
630
+ },
631
+ subagentInheritsContext(payload) {
632
+ return payload.agent_type === "fork";
633
+ },
634
+ rendersSystemPrompt(source) {
635
+ return RENDERING_SOURCES.has(source);
636
+ },
637
+ subagentNames(payload) {
638
+ const transcript = payload.agent_transcript_path;
639
+ const candidates = [
640
+ payload.description,
641
+ transcript && subagentMetadataDescription(transcript),
642
+ transcript && subagentPromptName(transcript)
643
+ ];
644
+ return [...new Set(candidates.filter((name) => Boolean(name)))];
645
+ },
646
+ promptTitle(payload) {
647
+ return payload.session_title ?? (payload.transcript_path ? transcriptTitle(payload.transcript_path) : void 0);
648
+ },
649
+ launchCommand(sessionId, options) {
650
+ return {
651
+ command: "claude",
652
+ args: [
653
+ "--session-id",
654
+ sessionId,
655
+ ...launchArguments(options)
656
+ ]
657
+ };
658
+ },
659
+ resumeCommand(session, options) {
660
+ return {
661
+ command: "claude",
662
+ args: [
663
+ "--resume",
664
+ session.id,
665
+ ...launchArguments({
666
+ name: session.name,
667
+ ...options
668
+ })
669
+ ]
670
+ };
671
+ },
672
+ forkCommand(parent, options) {
673
+ return {
674
+ command: "claude",
675
+ args: [
676
+ "--resume",
677
+ parent.id,
678
+ "--fork-session",
679
+ ...launchArguments(options)
680
+ ]
681
+ };
682
+ },
683
+ transcriptFiles(session, env = process.env) {
684
+ if (!session.cwd) return [];
685
+ const root = env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
686
+ const project = join(root, "projects", session.cwd.replace(/[^a-zA-Z0-9]/g, "-"));
687
+ return [join(project, `${session.id}.jsonl`), join(project, session.id)].filter((path) => existsSync(path));
688
+ },
689
+ renameInstruction(name) {
690
+ return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
691
+ },
692
+ contextFiles: [settingsFile, instructionsFile]
693
+ };
694
+ // src/hosts/host.ts
695
+ const DEFAULT_HOST = "claude-code";
696
+ const HOSTS = { [claudeCode.id]: claudeCode };
697
+ function allHosts() {
698
+ return Object.values(HOSTS);
699
+ }
700
+ function hostById(id) {
701
+ const host = HOSTS[id];
702
+ if (!host) throw new CarnetError("UNKNOWN_HOST", `Unknown host "${id}" (available: ${Object.keys(HOSTS).join(", ")})`);
703
+ return host;
704
+ }
705
+ // src/group/registry.ts
706
+ function rucherHome(env = process.env) {
707
+ return env.RUCHER_HOME ?? join(homedir(), ".rucher");
708
+ }
709
+ function registryPath(env) {
710
+ return join(rucherHome(env), "groups.json");
711
+ }
712
+ function readRegistry(env) {
713
+ const file = registryPath(env);
714
+ if (!existsSync(file)) return [];
715
+ return JSON.parse(readFileSync(file, "utf8")).groups ?? [];
716
+ }
717
+ function writeRegistry(groups, env) {
718
+ groups.sort((left, right) => left.name.localeCompare(right.name) || left.path.localeCompare(right.path));
719
+ mkdirSync(rucherHome(env), { recursive: true });
720
+ writeFileSync(registryPath(env), `${JSON.stringify({ groups }, null, 2)}\n`);
721
+ return groups;
722
+ }
723
+ function registerGroup(reference, env) {
724
+ return writeRegistry([...readRegistry(env).filter((group) => group.path !== reference.path), reference], env);
725
+ }
726
+ function unregisterGroups(paths, env) {
727
+ return writeRegistry(readRegistry(env).filter((group) => !paths.includes(group.path)), env);
728
+ }
729
+ // src/group/locate.ts
730
+ const GROUP_DIRECTORY = ".rucher";
731
+ const REPORTS_DIRECTORY = "reports";
732
+ const GROUP_FILE = "group.json";
733
+ const DB_FILE = "carnet.db";
734
+ function isInside(directory, path) {
735
+ const relativePath = relative(directory, path);
736
+ return relativePath === "" || !relativePath.startsWith("..") && !resolve(relativePath).startsWith(relativePath);
737
+ }
738
+ function repoNameFor(group, path) {
739
+ if (!path) return null;
740
+ const repo = group.repos.find((repo) => isInside(repo, resolve(path)));
741
+ return repo ? basename(repo) : null;
742
+ }
743
+ function repoPathFor(group, path) {
744
+ if (!path) return null;
745
+ const absolutePath = resolve(path);
746
+ const repo = group.repos.find((candidate) => isInside(candidate, absolutePath));
747
+ if (!repo) return null;
748
+ const relativePath = relative(repo, absolutePath);
749
+ return relativePath ? join(basename(repo), relativePath) : basename(repo);
750
+ }
751
+ function findGroupRoot(from) {
752
+ let directory = resolve(from);
753
+ for (;;) {
754
+ if (isGroupRoot(directory)) return directory;
755
+ const parent = dirname(directory);
756
+ if (parent === directory) return null;
757
+ directory = parent;
758
+ }
759
+ }
760
+ function reportsDirectoryOf(group) {
761
+ return join(group.root, GROUP_DIRECTORY, REPORTS_DIRECTORY);
762
+ }
763
+ function reportPathFor(group, agentName) {
764
+ return join(reportsDirectoryOf(group), `${agentName}.md`);
765
+ }
766
+ function isGroupRoot(directory) {
767
+ return existsSync(join(directory, GROUP_DIRECTORY, GROUP_FILE));
768
+ }
769
+ function loadGroup(root) {
770
+ const file = JSON.parse(readFileSync(join(root, GROUP_DIRECTORY, GROUP_FILE), "utf8"));
771
+ return {
772
+ root,
773
+ name: file.name,
774
+ repos: (file.repos ?? []).map((repo) => resolve(root, repo)),
775
+ hosts: file.hosts?.length ? file.hosts : [DEFAULT_HOST],
776
+ dbPath: join(root, GROUP_DIRECTORY, DB_FILE)
777
+ };
778
+ }
779
+ function groupByRepo(path, env) {
780
+ for (const reference of readRegistry(env)) {
781
+ if (!isGroupRoot(reference.path)) continue;
782
+ const group = loadGroup(reference.path);
783
+ if (group.repos.some((repo) => isInside(repo, path))) return group;
784
+ }
785
+ return null;
786
+ }
787
+ function locateGroup({ cwd = process.cwd(), env = process.env } = {}) {
788
+ const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
789
+ const candidates = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
790
+ for (const directory of candidates) {
791
+ const root = findGroupRoot(directory);
792
+ if (root) return loadGroup(root);
793
+ }
794
+ for (const directory of candidates) {
795
+ const group = groupByRepo(directory, env);
796
+ if (group) return group;
797
+ }
798
+ throw new CarnetError("NO_GROUP", `No Rucher group for ${cwd}: run "rucher init" in a meta directory, or "rucher group add <this repo>" there`);
799
+ }
800
+ // src/notes.ts
801
+ const NOTE_KINDS = [
802
+ "dead_end",
803
+ "decision",
804
+ "learning"
805
+ ];
806
+ const NOTE_TEXT_LIMIT = 200;
807
+ const DUPLICATE_SIMILARITY = .6;
808
+ const DEFAULT_HALF_LIFE_DAYS = 20;
809
+ const STALE_AFTER_ACTIVE_DAYS = 40;
810
+ const SIMILAR_SHOWN = 3;
811
+ function isNoteKind(value) {
812
+ return NOTE_KINDS.includes(value);
813
+ }
814
+ function memoryHalfLife(value) {
815
+ const days = Number(value);
816
+ return Number.isFinite(days) && days > 0 ? days : 20;
817
+ }
818
+ const MARKDOWN = /\*\*|__|\[[^\]]*\]\([^)]*\)|^#{1,6}\s|^[-*+]\s/;
819
+ function cleanText(value, label) {
820
+ const text = value.trim().replace(/[ \t]+/g, " ");
821
+ if (!text) throw new CarnetError("INVALID_NOTE", `${label} is empty`);
822
+ if (text.length >= 200) throw new CarnetError("INVALID_NOTE", `${label} must stay under 200 characters (${text.length})`);
823
+ if (/[\r\n]/.test(text)) throw new CarnetError("INVALID_NOTE", `${label} must be one line`);
824
+ if (text.includes("`")) throw new CarnetError("INVALID_NOTE", `${label} must not use backticks`);
825
+ if (MARKDOWN.test(text)) throw new CarnetError("INVALID_NOTE", `${label} must not use markdown`);
826
+ return text;
827
+ }
828
+ function groupRepoNames(group) {
829
+ return group.repos.map((repo) => basename(repo));
830
+ }
831
+ function cleanRepos(group, repos) {
832
+ const known = groupRepoNames(group);
833
+ const unique = [...new Set((repos ?? []).map((repo) => repo.trim()).filter(Boolean))];
834
+ const unknown = unique.filter((repo) => !known.includes(repo));
835
+ if (unknown.length) throw new CarnetError("INVALID_NOTE", `Unknown repo ${unknown.join(", ")} (group repos: ${known.join(", ") || "none"})`);
836
+ return unique;
837
+ }
838
+ function words(text) {
839
+ return new Set(text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
840
+ }
841
+ function similarity(first, second) {
842
+ const left = words(first);
843
+ const right = words(second);
844
+ if (left.size === 0 && right.size === 0) return 0;
845
+ let shared = 0;
846
+ for (const word of left) if (right.has(word)) shared++;
847
+ return shared / (left.size + right.size - shared);
848
+ }
849
+ function localDay(date) {
850
+ const month = String(date.getMonth() + 1).padStart(2, "0");
851
+ const day = String(date.getDate()).padStart(2, "0");
852
+ return `${date.getFullYear()}-${month}-${day}`;
853
+ }
854
+ function recordActiveDay(ctx) {
855
+ ctx.db.prepare("INSERT OR IGNORE INTO active_days (day) VALUES (?)").run(localDay(ctx.now()));
856
+ }
857
+ function activeDays(ctx) {
858
+ return ctx.db.prepare("SELECT day FROM active_days ORDER BY day").all().map((row) => row.day);
859
+ }
860
+ function activeDaysSince(days, at) {
861
+ const since = localDay(new Date(at));
862
+ return days.filter((day) => day > since).length;
863
+ }
864
+ function reposOf(ctx, note) {
865
+ return ctx.db.prepare("SELECT repo FROM note_repos WHERE note = ? ORDER BY repo").all(note).map((row) => row.repo);
866
+ }
867
+ function toNote(ctx, row) {
868
+ return {
869
+ id: row.id,
870
+ kind: row.kind,
871
+ text: row.text,
872
+ repos: reposOf(ctx, row.id),
873
+ session: row.session,
874
+ agent: row.agent,
875
+ similarNotes: row.similar_notes ? JSON.parse(row.similar_notes) : [],
876
+ createdAt: row.created_at,
877
+ droppedAt: row.dropped_at,
878
+ droppedReason: row.dropped_reason,
879
+ droppedSession: row.dropped_session,
880
+ replacedBy: row.replaced_by
881
+ };
882
+ }
883
+ function getNote(ctx, id) {
884
+ const row = ctx.db.prepare("SELECT * FROM notes WHERE id = ?").get(id);
885
+ return row ? toNote(ctx, row) : null;
886
+ }
887
+ function requireNote(ctx, id) {
888
+ const note = getNote(ctx, id);
889
+ if (!note) throw new CarnetError("NOTE_NOT_FOUND", `Unknown note #${id}`);
890
+ return note;
891
+ }
892
+ function requireActiveNote(ctx, id) {
893
+ const note = requireNote(ctx, id);
894
+ if (note.droppedAt) throw new CarnetError("INVALID_NOTE", `Note #${id} is dropped`);
895
+ return note;
896
+ }
897
+ function citationsOf(ctx, note) {
898
+ return ctx.db.prepare("SELECT id, note, session, agent, why, at FROM note_citations WHERE note = ? ORDER BY at").all(note);
899
+ }
900
+ function weightOf(citations, days, halfLifeDays) {
901
+ const latest = /* @__PURE__ */ new Map();
902
+ for (const citation of citations) {
903
+ const key = citation.session ?? `citation-${citation.id}`;
904
+ const previous = latest.get(key);
905
+ if (!previous || citation.at > previous) latest.set(key, citation.at);
906
+ }
907
+ let weight = 0;
908
+ for (const at of latest.values()) weight += .5 ** (activeDaysSince(days, at) / halfLifeDays);
909
+ return weight;
910
+ }
911
+ function weigh(ctx, note, days, halfLifeDays) {
912
+ const citations = citationsOf(ctx, note.id);
913
+ return {
914
+ ...note,
915
+ weight: weightOf(citations, days, halfLifeDays),
916
+ citationCount: citations.length
917
+ };
918
+ }
919
+ function compareNotes(first, second) {
920
+ const kind = NOTE_KINDS.indexOf(first.kind) - NOTE_KINDS.indexOf(second.kind);
921
+ if (kind !== 0) return kind;
922
+ if (first.weight !== second.weight) return second.weight - first.weight;
923
+ return second.id - first.id;
924
+ }
925
+ function activeNotesOfKind(ctx, kind) {
926
+ return ctx.db.prepare("SELECT * FROM notes WHERE kind = ? AND dropped_at IS NULL").all(kind).map((row) => toNote(ctx, row));
927
+ }
928
+ function addNote(ctx, group, input) {
929
+ if (!isNoteKind(input.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${input.kind}" (use ${NOTE_KINDS.join(", ")})`);
930
+ const kind = input.kind;
931
+ const text = cleanText(input.text, "Note text");
932
+ const repos = cleanRepos(group, input.repos);
933
+ const similar = activeNotesOfKind(ctx, kind).map((note) => ({
934
+ note,
935
+ score: similarity(text, note.text)
936
+ })).filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY).sort((first, second) => second.score - first.score).slice(0, SIMILAR_SHOWN).map((candidate) => candidate.note);
937
+ ctx.db.exec("BEGIN");
938
+ try {
939
+ const result = ctx.db.prepare("INSERT INTO notes (kind, text, session, agent, similar_notes, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(kind, text, input.session ?? null, input.agent ?? null, similar.length ? JSON.stringify(similar.map((note) => note.id)) : null, nowIso(ctx));
940
+ const id = Number(result.lastInsertRowid);
941
+ const addRepo = ctx.db.prepare("INSERT INTO note_repos (note, repo) VALUES (?, ?)");
942
+ for (const repo of repos) addRepo.run(id, repo);
943
+ ctx.db.exec("COMMIT");
944
+ return {
945
+ note: requireNote(ctx, id),
946
+ similar
947
+ };
948
+ } catch (error) {
949
+ ctx.db.exec("ROLLBACK");
950
+ throw error;
951
+ }
952
+ }
953
+ function listNotes(ctx, options = {}) {
954
+ if (options.kind !== void 0 && !isNoteKind(options.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${options.kind}"`);
955
+ const conditions = [];
956
+ const parameters = [];
957
+ if (!options.includeDropped) conditions.push("dropped_at IS NULL");
958
+ if (options.kind) {
959
+ conditions.push("kind = ?");
960
+ parameters.push(options.kind);
961
+ }
962
+ if (options.repo) {
963
+ conditions.push("id IN (SELECT note FROM note_repos WHERE repo = ?)");
964
+ parameters.push(options.repo);
965
+ }
966
+ if (options.general) conditions.push("id NOT IN (SELECT note FROM note_repos)");
967
+ if (options.query) {
968
+ conditions.push("LOWER(text) LIKE ? ESCAPE '\\'");
969
+ parameters.push(`%${options.query.toLowerCase().replace(/[\\%_]/g, "\\$&")}%`);
970
+ }
971
+ const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
972
+ const rows = ctx.db.prepare(`SELECT * FROM notes ${where}`).all(...parameters);
973
+ const days = activeDays(ctx);
974
+ const halfLifeDays = options.halfLifeDays ?? 20;
975
+ return rows.map((row) => weigh(ctx, toNote(ctx, row), days, halfLifeDays)).sort(compareNotes);
976
+ }
977
+ function noteDetail(ctx, id, halfLifeDays = 20) {
978
+ const note = requireNote(ctx, id);
979
+ const citations = citationsOf(ctx, id);
980
+ return {
981
+ ...note,
982
+ weight: weightOf(citations, activeDays(ctx), halfLifeDays),
983
+ citationCount: citations.length,
984
+ citations
985
+ };
986
+ }
987
+ function staleNotes(ctx, halfLifeDays = 20) {
988
+ const days = activeDays(ctx);
989
+ return listNotes(ctx, { halfLifeDays }).filter((note) => activeDaysSince(days, note.createdAt) > 40 && (note.citationCount === 0 || note.weight < .05));
990
+ }
991
+ function dropNote(ctx, id, input) {
992
+ requireActiveNote(ctx, id);
993
+ const reason = cleanText(input.reason, "Drop reason");
994
+ if (input.replacedBy !== void 0) {
995
+ if (input.replacedBy === id) throw new CarnetError("INVALID_NOTE", `Note #${id} cannot replace itself`);
996
+ requireActiveNote(ctx, input.replacedBy);
997
+ }
998
+ ctx.db.prepare("UPDATE notes SET dropped_at = ?, dropped_reason = ?, dropped_session = ?, replaced_by = ? WHERE id = ?").run(nowIso(ctx), reason, input.session ?? null, input.replacedBy ?? null, id);
999
+ return requireNote(ctx, id);
1000
+ }
1001
+ function citeNote(ctx, id, input) {
1002
+ requireActiveNote(ctx, id);
1003
+ const why = cleanText(input.why, "Citation reason");
1004
+ const result = ctx.db.prepare("INSERT INTO note_citations (note, session, agent, why, at) VALUES (?, ?, ?, ?, ?)").run(id, input.session ?? null, input.agent ?? null, why, nowIso(ctx));
1005
+ return ctx.db.prepare("SELECT id, note, session, agent, why, at FROM note_citations WHERE id = ?").get(Number(result.lastInsertRowid));
1006
+ }
1007
+ const ACTIVITY_ORDER = {
1008
+ dropped: 0,
1009
+ cited: 1,
1010
+ added: 2
1011
+ };
1012
+ function activeIds(ctx, json) {
1013
+ if (!json) return [];
1014
+ const active = ctx.db.prepare("SELECT 1 FROM notes WHERE id = ? AND dropped_at IS NULL");
1015
+ return JSON.parse(json).filter((id) => active.get(id) !== void 0);
1016
+ }
1017
+ function sessionNoteActivity(ctx, session) {
1018
+ const added = ctx.db.prepare("SELECT id, kind, text, similar_notes, created_at FROM notes WHERE session = ?").all(session);
1019
+ const cited = ctx.db.prepare(`SELECT note_citations.note, notes.kind, note_citations.why, note_citations.at
1020
+ FROM note_citations JOIN notes ON notes.id = note_citations.note
1021
+ WHERE note_citations.session = ?`).all(session);
1022
+ const dropped = ctx.db.prepare("SELECT id, kind, dropped_reason, replaced_by, dropped_at FROM notes WHERE dropped_session = ?").all(session);
1023
+ return [
1024
+ ...added.map((row) => ({
1025
+ activity: "added",
1026
+ note: row.id,
1027
+ kind: row.kind,
1028
+ text: row.text,
1029
+ similarNotes: activeIds(ctx, row.similar_notes),
1030
+ replacedBy: null,
1031
+ at: row.created_at
1032
+ })),
1033
+ ...cited.map((row) => ({
1034
+ activity: "cited",
1035
+ note: row.note,
1036
+ kind: row.kind,
1037
+ text: row.why,
1038
+ similarNotes: [],
1039
+ replacedBy: null,
1040
+ at: row.at
1041
+ })),
1042
+ ...dropped.map((row) => ({
1043
+ activity: "dropped",
1044
+ note: row.id,
1045
+ kind: row.kind,
1046
+ text: row.dropped_reason ?? "",
1047
+ similarNotes: [],
1048
+ replacedBy: row.replaced_by,
1049
+ at: row.dropped_at ?? ""
1050
+ }))
1051
+ ].sort((first, second) => second.at.localeCompare(first.at) || ACTIVITY_ORDER[first.activity] - ACTIVITY_ORDER[second.activity] || second.note - first.note);
1052
+ }
1053
+ // src/memory.ts
1054
+ const MEMORY_MAX_CHARACTERS = 2e3;
1055
+ const KIND_TITLES = {
1056
+ dead_end: "Dead ends",
1057
+ decision: "Decisions",
1058
+ learning: "Learnings"
1059
+ };
1060
+ const CUT_ORDER = [
1061
+ "learning",
1062
+ "decision",
1063
+ "dead_end"
1064
+ ];
1065
+ function memoryMaxCharacters(value) {
1066
+ const characters = Number(value);
1067
+ return Number.isInteger(characters) && characters > 0 ? characters : MEMORY_MAX_CHARACTERS;
1068
+ }
1069
+ function noteLine(note) {
1070
+ const repos = note.repos.length ? `[${note.repos.join(", ")}] ` : "";
1071
+ return ` #${String(note.id).padEnd(4)}${repos}${note.text}`;
1072
+ }
1073
+ function render(scope, kept) {
1074
+ const total = scope.notes.length;
1075
+ const leftOut = total - kept.length;
1076
+ const count = `${total} note${total > 1 ? "s" : ""}`;
1077
+ const pointer = leftOut ? `${leftOut} left out, note_list for the rest` : "note_list for details";
1078
+ const lines = [`${scope.title} (${count}, ${pointer}):`];
1079
+ for (const kind of NOTE_KINDS) {
1080
+ const ofKind = kept.filter((note) => note.kind === kind);
1081
+ if (!ofKind.length) continue;
1082
+ lines.push("", KIND_TITLES[kind], ...ofKind.map(noteLine));
1083
+ }
1084
+ return lines.join("\n");
1085
+ }
1086
+ function renderMemory(scope, maxCharacters = MEMORY_MAX_CHARACTERS) {
1087
+ const kept = [...scope.notes];
1088
+ let text = render(scope, kept);
1089
+ while (text.length > maxCharacters && kept.length) {
1090
+ const kind = CUT_ORDER.find((candidate) => kept.some((note) => note.kind === candidate));
1091
+ const lowest = kept.findLastIndex((note) => note.kind === kind);
1092
+ kept.splice(lowest, 1);
1093
+ text = render(scope, kept);
1094
+ }
1095
+ return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;
1096
+ }
1097
+ function injectedRepos(ctx, session) {
1098
+ return ctx.db.prepare("SELECT repo FROM session_repos WHERE session = ? ORDER BY injected_at, repo").all(session).map((row) => row.repo);
1099
+ }
1100
+ function recordRepo(ctx, session, repo) {
1101
+ ctx.db.prepare("INSERT OR IGNORE INTO session_repos (session, repo, injected_at) VALUES (?, ?, ?)").run(session, repo, nowIso(ctx));
1102
+ }
1103
+ function notesFor(ctx, repos, general, halfLifeDays) {
1104
+ const byId = /* @__PURE__ */ new Map();
1105
+ const add = (notes) => notes.forEach((note) => byId.set(note.id, note));
1106
+ if (general) add(listNotes(ctx, {
1107
+ general: true,
1108
+ halfLifeDays
1109
+ }));
1110
+ for (const repo of repos) add(listNotes(ctx, {
1111
+ repo,
1112
+ halfLifeDays
1113
+ }));
1114
+ return [...byId.values()].sort(compareNotes);
1115
+ }
1116
+ function groupTitle(group) {
1117
+ return `Rucher memory of the ${group.name} group`;
1118
+ }
1119
+ function sessionStartMemory(ctx, group, session, options = {}) {
1120
+ const halfLifeDays = options.halfLifeDays ?? 20;
1121
+ const repos = session.repo ? [session.repo] : [];
1122
+ const notes = notesFor(ctx, repos, true, halfLifeDays);
1123
+ if (!notes.length) return void 0;
1124
+ for (const repo of repos) if (notes.some((note) => note.repos.includes(repo))) recordRepo(ctx, session.id, repo);
1125
+ return renderMemory({
1126
+ title: groupTitle(group),
1127
+ notes
1128
+ }, options.maxCharacters);
1129
+ }
1130
+ function sessionMemory(ctx, group, session, options = {}) {
1131
+ const halfLifeDays = options.halfLifeDays ?? 20;
1132
+ const notes = notesFor(ctx, injectedRepos(ctx, session.id), true, halfLifeDays);
1133
+ if (!notes.length) return void 0;
1134
+ return renderMemory({
1135
+ title: groupTitle(group),
1136
+ notes
1137
+ }, options.maxCharacters);
1138
+ }
1139
+ function repoMemory(ctx, session, repo, options = {}) {
1140
+ const injected = injectedRepos(ctx, session.id);
1141
+ if (injected.includes(repo)) return void 0;
1142
+ const notes = listNotes(ctx, {
1143
+ repo,
1144
+ halfLifeDays: options.halfLifeDays ?? 20
1145
+ }).filter((note) => !note.repos.some((other) => injected.includes(other)));
1146
+ if (!notes.length) return void 0;
1147
+ recordRepo(ctx, session.id, repo);
1148
+ return renderMemory({
1149
+ title: `Rucher memory, repo ${repo}`,
1150
+ notes
1151
+ }, options.maxCharacters);
1152
+ }
1153
+ function copyInjectedRepos(ctx, from, into) {
1154
+ for (const repo of injectedRepos(ctx, from)) recordRepo(ctx, into, repo);
1155
+ }
1156
+ // src/sessions.ts
1157
+ const COLUMNS = `id, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
1158
+ parent_id, prompt_version, created_at, last_active_at, ended_at`;
1159
+ function toSession(row) {
1160
+ return {
1161
+ id: row.id,
1162
+ name: row.name,
1163
+ purpose: row.purpose,
1164
+ kind: row.kind,
1165
+ status: row.status,
1166
+ cwd: row.cwd,
1167
+ repo: row.repo,
1168
+ host: row.host,
1169
+ hostPid: row.host_pid,
1170
+ hookedAt: row.hooked_at,
1171
+ lastTitle: row.last_title,
1172
+ parentId: row.parent_id,
1173
+ promptVersion: row.prompt_version,
1174
+ createdAt: row.created_at,
1175
+ lastActiveAt: row.last_active_at,
1176
+ endedAt: row.ended_at
1177
+ };
1178
+ }
1179
+ function getSession(ctx, id) {
1180
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id);
1181
+ return row && toSession(row);
1182
+ }
1183
+ function requireSession(ctx, id) {
1184
+ const session = getSession(ctx, id);
1185
+ if (!session) throw new CarnetError("SESSION_NOT_FOUND", `Unknown session ${id}`);
1186
+ return session;
1187
+ }
1188
+ function ensureSession(ctx, id, cwd, group) {
1189
+ const existing = getSession(ctx, id);
1190
+ if (existing) return existing;
1191
+ const at = nowIso(ctx);
1192
+ ctx.db.prepare("INSERT INTO sessions (id, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?)").run(id, cwd ?? null, group ? repoNameFor(group, cwd) : null, at, at);
1193
+ return requireSession(ctx, id);
1194
+ }
1195
+ function nameTaken(error, name) {
1196
+ if (name && error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
1197
+ throw error;
1198
+ }
1199
+ function createSession(ctx, input) {
1200
+ if (input.kind === "active" && !input.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
1201
+ const at = nowIso(ctx);
1202
+ try {
1203
+ ctx.db.prepare(`INSERT INTO sessions (id, name, kind, status, cwd, repo, host, last_title,
1204
+ created_at, last_active_at)
1205
+ VALUES (?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(input.id, input.name ?? null, input.kind, input.cwd, input.repo ?? null, input.host ?? "claude-code", input.name ?? null, at, at);
1206
+ } catch (error) {
1207
+ nameTaken(error, input.name);
1208
+ }
1209
+ return requireSession(ctx, input.id);
1210
+ }
1211
+ function setSessionKind(ctx, id, kind, name) {
1212
+ const session = requireSession(ctx, id);
1213
+ const nextName = name ?? session.name;
1214
+ if (kind === "active" && !nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
1215
+ try {
1216
+ ctx.db.prepare("UPDATE sessions SET kind = ?, name = ?, last_title = ? WHERE id = ?").run(kind, nextName, nextName ?? session.lastTitle, id);
1217
+ } catch (error) {
1218
+ nameTaken(error, nextName);
1219
+ }
1220
+ return requireSession(ctx, id);
1221
+ }
1222
+ function endSession(ctx, id) {
1223
+ const session = requireSession(ctx, id);
1224
+ if (session.status !== "running") return session;
1225
+ const ended = setSessionStatus(ctx, id, "idle");
1226
+ logEvent(ctx, id, { type: "session.ended" });
1227
+ return ended;
1228
+ }
1229
+ function titleAvailable(ctx, id, title) {
1230
+ const owner = sessionByName(ctx, title);
1231
+ return !owner || owner.id === id;
1232
+ }
1233
+ function adoptTitle(ctx, id, rawTitle) {
1234
+ const session = requireSession(ctx, id);
1235
+ const title = rawTitle?.trim() || null;
1236
+ if (title === null || title === session.lastTitle) return session;
1237
+ ctx.db.prepare("UPDATE sessions SET last_title = ? WHERE id = ?").run(title, id);
1238
+ if (title === session.name || !titleAvailable(ctx, id, title)) return requireSession(ctx, id);
1239
+ ctx.db.prepare(`UPDATE sessions
1240
+ SET name = ?, kind = CASE WHEN name IS NULL THEN 'active' ELSE kind END
1241
+ WHERE id = ?`).run(title, id);
1242
+ return requireSession(ctx, id);
1243
+ }
1244
+ function upsertFromHook(ctx, group, payload, env = {}) {
1245
+ const at = nowIso(ctx);
1246
+ const host = env.host ?? "claude-code";
1247
+ const hostPid = env.processId ?? null;
1248
+ const repo = repoNameFor(group, payload.cwd);
1249
+ const existing = getSession(ctx, payload.session_id);
1250
+ if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, cwd, repo, host, host_pid, hooked_at, created_at, last_active_at)
1251
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, payload.cwd ?? null, repo, host, hostPid, at, at, at);
1252
+ else ctx.db.prepare(`UPDATE sessions
1253
+ SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
1254
+ WHERE id = ?`).run(at, at, payload.cwd ?? existing.cwd, repo ?? existing.repo, host, hostPid ?? existing.hostPid, payload.session_id);
1255
+ return adoptTitle(ctx, payload.session_id, payload.session_title);
1256
+ }
1257
+ function touchSession(ctx, id) {
1258
+ ctx.db.prepare("UPDATE sessions SET last_active_at = ? WHERE id = ?").run(nowIso(ctx), id);
1259
+ }
1260
+ function nameSession(ctx, id, name, purpose) {
1261
+ requireSession(ctx, id);
1262
+ try {
1263
+ ctx.db.prepare(`UPDATE sessions
1264
+ SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,
1265
+ kind = 'active'
1266
+ WHERE id = ?`).run(name, purpose ?? null, nowIso(ctx), id);
1267
+ } catch (error) {
1268
+ if (error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
1269
+ throw error;
1270
+ }
1271
+ return requireSession(ctx, id);
1272
+ }
1273
+ function listSessions(ctx, options = {}) {
1274
+ const conditions = [];
1275
+ if (!options.includeTemp) conditions.push("kind != 'temp'");
1276
+ if (!options.includeArchived) conditions.push("status != 'archived'");
1277
+ const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
1278
+ return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions ${where} ORDER BY last_active_at DESC`).all().map(toSession);
1279
+ }
1280
+ function dropSession(ctx, id) {
1281
+ requireSession(ctx, id);
1282
+ const at = nowIso(ctx);
1283
+ ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, id);
1284
+ ctx.db.prepare("UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?").run(at, id);
1285
+ return requireSession(ctx, id);
1286
+ }
1287
+ function defaultSession(ctx) {
1288
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE status != 'archived' ORDER BY last_active_at DESC LIMIT 1`).get();
1289
+ return row && toSession(row);
1290
+ }
1291
+ function sessionByName(ctx, name) {
1292
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE name = ?`).get(name);
1293
+ return row && toSession(row);
1294
+ }
1295
+ const MINIMUM_ID_PREFIX = 4;
1296
+ function shortId(id) {
1297
+ return id.slice(0, 8);
1298
+ }
1299
+ function findSession(ctx, reference) {
1300
+ const byName = sessionByName(ctx, reference);
1301
+ if (byName) return byName;
1302
+ const byId = getSession(ctx, reference);
1303
+ if (byId) return byId;
1304
+ const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
1305
+ if (isIdPrefix && reference.length >= 4) {
1306
+ const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id LIKE ? ORDER BY last_active_at DESC`).all(`${reference.toLowerCase()}%`);
1307
+ const [only, ...others] = rows;
1308
+ if (only && others.length === 0) return toSession(only);
1309
+ if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
1310
+ }
1311
+ throw new CarnetError("SESSION_NOT_FOUND", `Unknown session "${reference}"${isIdPrefix && reference.length < 4 ? ` (an id prefix needs at least 4 characters)` : ""}`);
1312
+ }
1313
+ function sessionByHostProcess(ctx, host, processId) {
1314
+ const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
1315
+ WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL
1316
+ ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
1317
+ return row && toSession(row);
1318
+ }
1319
+ function recordPromptVersion(ctx, id, version) {
1320
+ requireSession(ctx, id);
1321
+ ctx.db.prepare("UPDATE sessions SET prompt_version = ? WHERE id = ?").run(version, id);
1322
+ return requireSession(ctx, id);
1323
+ }
1324
+ function setParent(ctx, id, parentId) {
1325
+ requireSession(ctx, id);
1326
+ requireSession(ctx, parentId);
1327
+ ctx.db.prepare("UPDATE sessions SET parent_id = ? WHERE id = ?").run(parentId, id);
1328
+ return requireSession(ctx, id);
1329
+ }
1330
+ function setSessionStatus(ctx, id, status) {
1331
+ requireSession(ctx, id);
1332
+ const at = nowIso(ctx);
1333
+ ctx.db.prepare(`UPDATE sessions
1334
+ SET status = ?, last_active_at = ?,
1335
+ ended_at = CASE WHEN ? = 'running' THEN NULL WHEN ? = 'idle' THEN ? ELSE ended_at END
1336
+ WHERE id = ?`).run(status, at, status, status, at, id);
1337
+ return requireSession(ctx, id);
1338
+ }
1339
+ function refuseWhileRunning(session, action) {
1340
+ if (session.status === "running") throw new CarnetError("SESSION_RUNNING", `Session ${session.name ?? shortId(session.id)} is running: ${action} it once it has ended`);
1341
+ }
1342
+ function renameSession(ctx, id, name) {
1343
+ refuseWhileRunning(requireSession(ctx, id), "rename");
1344
+ try {
1345
+ ctx.db.prepare("UPDATE sessions SET name = ? WHERE id = ?").run(name, id);
1346
+ } catch (error) {
1347
+ nameTaken(error, name);
1348
+ }
1349
+ return requireSession(ctx, id);
1350
+ }
1351
+ function promoteSession(ctx, id, name) {
1352
+ const session = requireSession(ctx, id);
1353
+ if (session.kind === "active") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name} is already active`);
1354
+ const nextName = name ?? session.name;
1355
+ if (!nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
1356
+ if (nextName !== session.name) refuseWhileRunning(session, "rename");
1357
+ try {
1358
+ ctx.db.prepare("UPDATE sessions SET kind = 'active', name = ? WHERE id = ?").run(nextName, id);
1359
+ } catch (error) {
1360
+ nameTaken(error, nextName);
1361
+ }
1362
+ return requireSession(ctx, id);
1363
+ }
1364
+ function demoteSession(ctx, id) {
1365
+ const session = requireSession(ctx, id);
1366
+ if (session.kind === "temp") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name ?? shortId(session.id)} is already temp`);
1367
+ ctx.db.prepare("UPDATE sessions SET kind = 'temp' WHERE id = ?").run(id);
1368
+ return requireSession(ctx, id);
1369
+ }
1370
+ function staleTempSessions(ctx, olderThanMilliseconds) {
1371
+ const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
1372
+ return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
1373
+ WHERE kind = 'temp' AND status = 'idle' AND last_active_at < ?
1374
+ ORDER BY last_active_at ASC`).all(before).map(toSession);
1375
+ }
1376
+ function resetDeadSessions(ctx, isAlive) {
1377
+ return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE status = 'running'`).all().map(toSession).filter((session) => session.hostPid === null || !isAlive(session.hostPid)).map((session) => endSession(ctx, session.id));
1378
+ }
1379
+ // src/merge.ts
1380
+ function namesOf(ctx, session) {
1381
+ return ctx.db.prepare("SELECT name FROM agents WHERE session = ?").all(session).map((row) => row.name);
1382
+ }
1383
+ function mergeSessions(ctx, fromId, intoId) {
1384
+ if (fromId === intoId) throw new CarnetError("SESSION_MERGE_INVALID", "Cannot merge a session into itself");
1385
+ const from = requireSession(ctx, fromId);
1386
+ const into = requireSession(ctx, intoId);
1387
+ const at = nowIso(ctx);
1388
+ const taken = new Set(namesOf(ctx, intoId));
1389
+ const fromNames = namesOf(ctx, fromId);
1390
+ const movedAgents = fromNames.filter((name) => !taken.has(name));
1391
+ const closedAgents = fromNames.filter((name) => taken.has(name));
1392
+ ctx.db.exec("BEGIN");
1393
+ try {
1394
+ const moveAgent = ctx.db.prepare("UPDATE agents SET session = ?, updated_at = ? WHERE session = ? AND name = ?");
1395
+ for (const name of movedAgents) moveAgent.run(intoId, at, fromId, name);
1396
+ ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, fromId);
1397
+ const movedEvents = Number(ctx.db.prepare("UPDATE events SET session = ? WHERE session = ?").run(intoId, fromId).changes);
1398
+ 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;
1399
+ ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(fromId);
1400
+ const keepName = into.name === null && from.name !== null;
1401
+ ctx.db.prepare("UPDATE sessions SET status = 'archived', kind = 'temp', name = NULL, last_active_at = ? WHERE id = ?").run(at, fromId);
1402
+ ctx.db.prepare(`UPDATE sessions
1403
+ SET name = COALESCE(?, name), purpose = COALESCE(purpose, ?), last_active_at = ?,
1404
+ kind = CASE WHEN ? THEN ? ELSE kind END
1405
+ WHERE id = ?`).run(keepName ? from.name : null, from.purpose, at, keepName ? 1 : 0, from.kind, intoId);
1406
+ ctx.db.exec("COMMIT");
1407
+ return {
1408
+ session: requireSession(ctx, intoId),
1409
+ movedAgents,
1410
+ closedAgents,
1411
+ movedEvents,
1412
+ movedTable
1413
+ };
1414
+ } catch (error) {
1415
+ ctx.db.exec("ROLLBACK");
1416
+ throw error;
1417
+ }
1418
+ }
1419
+ // src/purge.ts
1420
+ const DEFAULT_PURGE_DAYS = 3;
1421
+ const DAY_MILLISECONDS = 864e5;
1422
+ function purgeDays(value) {
1423
+ const days = Number(value);
1424
+ return Number.isFinite(days) && days > 0 ? days : 3;
1425
+ }
1426
+ const PURGEABLE = `
1427
+ id != ? AND last_active_at < ?
1428
+ AND NOT EXISTS (
1429
+ SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
1430
+ )
1431
+ AND (
1432
+ status = 'archived'
1433
+ OR (kind = 'temp' AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id))
1434
+ )`;
1435
+ function purgeSessions(ctx, keepId, days) {
1436
+ const cutoff = (/* @__PURE__ */ new Date(ctx.now().getTime() - days * DAY_MILLISECONDS)).toISOString();
1437
+ ctx.db.exec("BEGIN");
1438
+ try {
1439
+ const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(keepId, cutoff).map((row) => row.id);
1440
+ for (const table of [
1441
+ "table_items",
1442
+ "agents",
1443
+ "events"
1444
+ ]) {
1445
+ const statement = ctx.db.prepare(`DELETE FROM ${table} WHERE session = ?`);
1446
+ for (const id of ids) statement.run(id);
1447
+ }
1448
+ const deleteSession = ctx.db.prepare("DELETE FROM sessions WHERE id = ?");
1449
+ for (const id of ids) deleteSession.run(id);
1450
+ ctx.db.exec("COMMIT");
1451
+ return ids;
1452
+ } catch (error) {
1453
+ ctx.db.exec("ROLLBACK");
1454
+ throw error;
1455
+ }
1456
+ }
1457
+ // src/status/render.ts
1458
+ const MAIN_WORKING_SUFFIX = "(main working, not ready)";
1459
+ function renderTableLine(item) {
1460
+ if (item.mainWorking) return `${MAIN_WORKING_EMOJI} ${item.text} ${MAIN_WORKING_SUFFIX}`;
1461
+ return `${EMOJI[item.status ?? "discussing"]} ${item.text}`;
1462
+ }
1463
+ function renderAgentLine(line) {
1464
+ return line.note ? `${line.emoji} ${line.name} — ${line.note}` : `${line.emoji} ${line.name}`;
1465
+ }
1466
+ const NOTES_HEADER = "Notes";
1467
+ const NOTES_FOLD_LINES = 5;
1468
+ const ACTIVITY_MARK = {
1469
+ added: "+",
1470
+ cited: "★",
1471
+ dropped: "−"
1472
+ };
1473
+ const LABEL_WIDTH = 8;
1474
+ const SIMILAR_PREFIX = "similar to ";
1475
+ function plural(count, word) {
1476
+ return `${count} ${word}${count > 1 ? "s" : ""}`;
1477
+ }
1478
+ function renderNotesSummary(notes) {
1479
+ const count = (activity) => notes.filter((item) => item.activity === activity).length;
1480
+ const duplicates = notes.filter((item) => item.activity === "added" && item.similarNotes.length > 0).length;
1481
+ const parts = [
1482
+ count("added") && `${count("added")} added`,
1483
+ count("cited") && `${count("cited")} cited`,
1484
+ count("dropped") && `${count("dropped")} dropped`,
1485
+ duplicates && plural(duplicates, "possible duplicate")
1486
+ ].filter(Boolean);
1487
+ return `${NOTES_HEADER} ${parts.join(" · ")}`;
1488
+ }
1489
+ function renderNoteLine(item, idWidth) {
1490
+ const id = `#${item.note}`.padEnd(idWidth);
1491
+ const label = (item.activity === "added" ? item.kind : item.activity).padEnd(LABEL_WIDTH);
1492
+ let text = item.text;
1493
+ if (item.activity === "added" && item.similarNotes.length > 0) text = `${SIMILAR_PREFIX}${item.similarNotes.map((note) => `#${note}`).join(", ")} · ${text}`;
1494
+ if (item.activity === "dropped" && item.replacedBy !== null) text = `replaced by #${item.replacedBy}`;
1495
+ return `${ACTIVITY_MARK[item.activity]} ${id} ${label} ${text}`;
1496
+ }
1497
+ function renderNotes(notes, mode = "full") {
1498
+ if (notes.length === 0) return [];
1499
+ if (mode === "summary" || mode === "full" && notes.length > 5) return [renderNotesSummary(notes)];
1500
+ const idWidth = Math.max(...notes.map((item) => `#${item.note}`.length));
1501
+ return [NOTES_HEADER, ...notes.map((item) => ` ${renderNoteLine(item, idWidth)}`)];
1502
+ }
1503
+ function renderSections(view, options = {}) {
1504
+ const out = [];
1505
+ if (view.table) out.push("On the table", ` ${renderTableLine(view.table)}`, "");
1506
+ out.push("Waiting on you");
1507
+ if (view.waiting.length === 0) out.push(" nothing");
1508
+ view.waiting.forEach((line, index) => {
1509
+ out.push(` ${index + 1}. ${renderAgentLine(line)}`);
1510
+ });
1511
+ out.push("", "Running");
1512
+ if (view.running.length === 0) out.push(" nothing");
1513
+ for (const line of view.running) out.push(` ${renderAgentLine(line)}`);
1514
+ const notes = renderNotes(view.notes, options.notes);
1515
+ if (notes.length > 0) out.push("", ...notes);
1516
+ return out.join("\n");
1517
+ }
1518
+ function renderStatus(view, options) {
1519
+ return [
1520
+ view.time,
1521
+ "",
1522
+ renderSections(view, options),
1523
+ "",
1524
+ LEGEND
1525
+ ].join("\n");
1526
+ }
1527
+ // src/table.ts
1528
+ function toItem(row) {
1529
+ return {
1530
+ session: row.session,
1531
+ text: row.text,
1532
+ status: row.status,
1533
+ mainWorking: row.main_working === 1,
1534
+ updatedAt: row.updated_at
1535
+ };
1536
+ }
1537
+ function getTable(ctx, session) {
1538
+ const row = ctx.db.prepare("SELECT * FROM table_items WHERE session = ?").get(session);
1539
+ return row && toItem(row);
1540
+ }
1541
+ function setTable(ctx, session, input) {
1542
+ if (input.mainWorking && input.status) throw new CarnetError("TABLE_STATUS_WITH_MAIN_WORKING", "A user-action status cannot be set while main is working");
1543
+ if (input.status !== void 0 && !isUserActionStatus(input.status)) throw new CarnetError("INVALID_STATUS", `Invalid table status "${String(input.status)}"`);
1544
+ ctx.db.prepare(`INSERT INTO table_items (session, text, status, main_working, updated_at) VALUES (?, ?, ?, ?, ?)
1545
+ ON CONFLICT(session) DO UPDATE SET text = excluded.text, status = excluded.status,
1546
+ main_working = excluded.main_working, updated_at = excluded.updated_at`).run(session, sanitizeNote(input.text), input.status ?? null, input.mainWorking ? 1 : 0, nowIso(ctx));
1547
+ return getTable(ctx, session);
1548
+ }
1549
+ function clearTable(ctx, session) {
1550
+ ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(session);
1551
+ }
1552
+ // src/status/view.ts
1553
+ const BUCKET = {
1554
+ answer: 0,
1555
+ review: 1
1556
+ };
1557
+ function bucketOf(status) {
1558
+ return BUCKET[status] ?? 2;
1559
+ }
1560
+ function compareWaiting(left, right) {
1561
+ if (left.queueOrder !== null || right.queueOrder !== null) {
1562
+ if (left.queueOrder === null) return 1;
1563
+ if (right.queueOrder === null) return -1;
1564
+ return left.queueOrder - right.queueOrder;
1565
+ }
1566
+ return bucketOf(left.status) - bucketOf(right.status) || left.startedAt.localeCompare(right.startedAt);
1567
+ }
1568
+ function toLine(agent) {
1569
+ return {
1570
+ name: agent.name,
1571
+ status: agent.status,
1572
+ emoji: agent.status === "closed" ? "" : EMOJI[agent.status],
1573
+ note: agent.note
1574
+ };
1575
+ }
1576
+ function formatClock(date) {
1577
+ return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
1578
+ }
1579
+ function buildStatusView(ctx, session) {
1580
+ const agents = listAgents(ctx, session.id);
1581
+ const waiting = agents.filter((agent) => isUserActionStatus(agent.status)).sort(compareWaiting).map(toLine);
1582
+ const running = agents.filter((agent) => agent.status === "running").map(toLine);
1583
+ return {
1584
+ time: formatClock(ctx.now()),
1585
+ sessionName: session.name,
1586
+ table: getTable(ctx, session.id) ?? null,
1587
+ waiting,
1588
+ running,
1589
+ notes: sessionNoteActivity(ctx, session.id)
1590
+ };
1591
+ }
1592
+ // src/subagents.ts
1593
+ const PAIRING_WINDOW_MILLISECONDS = 6e4;
1594
+ const STOPPED_NOTE = "stopped without agent_done";
1595
+ function byHostAgentId(ctx, session, hostAgentId) {
1596
+ const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND host_agent_id = ?").get(session, hostAgentId);
1597
+ return row && toAgent(row);
1598
+ }
1599
+ function pairSubagent(ctx, session, hostAgentId) {
1600
+ const paired = byHostAgentId(ctx, session, hostAgentId);
1601
+ if (paired) return paired;
1602
+ const since = (/* @__PURE__ */ new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS)).toISOString();
1603
+ const row = ctx.db.prepare(`SELECT * FROM agents
1604
+ WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND started_at >= ?
1605
+ ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session, since);
1606
+ if (!row) return void 0;
1607
+ ctx.db.prepare("UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?").run(hostAgentId, session, row.name);
1608
+ return byHostAgentId(ctx, session, hostAgentId);
1609
+ }
1610
+ function byName(ctx, session, name) {
1611
+ const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND name = ?").get(session, name);
1612
+ return row && toAgent(row);
1613
+ }
1614
+ function setHostAgentId(ctx, session, name, hostAgentId) {
1615
+ ctx.db.prepare("UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?").run(hostAgentId, session, name);
1616
+ }
1617
+ function repairByName(ctx, session, hostAgentId, names) {
1618
+ const named = names.map((name) => byName(ctx, session, name)).find(Boolean);
1619
+ if (!named || named.hostAgentId === hostAgentId) return;
1620
+ const holder = byHostAgentId(ctx, session, hostAgentId);
1621
+ if (holder) setHostAgentId(ctx, session, holder.name, named.hostAgentId);
1622
+ setHostAgentId(ctx, session, named.name, hostAgentId);
1623
+ }
1624
+ function stopSubagent(ctx, session, hostAgentId, names = []) {
1625
+ repairByName(ctx, session, hostAgentId, names);
1626
+ const agent = byHostAgentId(ctx, session, hostAgentId);
1627
+ if (!agent || agent.status !== "running") return void 0;
1628
+ if (agent.pendingStatus) {
1629
+ publishPending(ctx, session, agent.name);
1630
+ return byHostAgentId(ctx, session, hostAgentId);
1631
+ }
1632
+ ctx.db.prepare("UPDATE agents SET status = 'review', note = ?, updated_at = ? WHERE session = ? AND name = ?").run(STOPPED_NOTE, nowIso(ctx), session, agent.name);
1633
+ logEvent(ctx, session, {
1634
+ type: "finished",
1635
+ agent: agent.name,
1636
+ note: STOPPED_NOTE
1637
+ });
1638
+ return byHostAgentId(ctx, session, hostAgentId);
1639
+ }
1640
+ // src/carnet.ts
1641
+ var Carnet = class {
1642
+ group;
1643
+ db;
1644
+ ctx;
1645
+ constructor(group, db, options = {}) {
1646
+ this.group = group;
1647
+ this.db = db;
1648
+ this.ctx = {
1649
+ db,
1650
+ now: options.now ?? (() => /* @__PURE__ */ new Date())
1651
+ };
1652
+ }
1653
+ sessions = {
1654
+ get: (id) => getSession(this.ctx, id),
1655
+ find: (reference) => findSession(this.ctx, reference),
1656
+ require: (id) => requireSession(this.ctx, id),
1657
+ ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group),
1658
+ upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.group, payload, env),
1659
+ touch: (id) => touchSession(this.ctx, id),
1660
+ merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
1661
+ purge: (keepId, days) => purgeSessions(this.ctx, keepId, days),
1662
+ name: (id, name, purpose) => nameSession(this.ctx, id, name, purpose),
1663
+ adoptTitle: (id, title) => adoptTitle(this.ctx, id, title),
1664
+ list: (options) => listSessions(this.ctx, options),
1665
+ drop: (id) => dropSession(this.ctx, id),
1666
+ default: () => defaultSession(this.ctx),
1667
+ byName: (name) => sessionByName(this.ctx, name),
1668
+ byHostProcess: (host, processId) => sessionByHostProcess(this.ctx, host, processId),
1669
+ recordPromptVersion: (id, version) => recordPromptVersion(this.ctx, id, version),
1670
+ setParent: (id, parentId) => setParent(this.ctx, id, parentId),
1671
+ setStatus: (id, status) => setSessionStatus(this.ctx, id, status),
1672
+ create: (input) => createSession(this.ctx, input),
1673
+ setKind: (id, kind, name) => setSessionKind(this.ctx, id, kind, name),
1674
+ end: (id) => endSession(this.ctx, id),
1675
+ rename: (id, name) => renameSession(this.ctx, id, name),
1676
+ promote: (id, name) => promoteSession(this.ctx, id, name),
1677
+ demote: (id) => demoteSession(this.ctx, id),
1678
+ staleTemp: (olderThanMilliseconds) => staleTempSessions(this.ctx, olderThanMilliseconds),
1679
+ resetDead: (isAlive) => resetDeadSessions(this.ctx, isAlive)
1680
+ };
1681
+ agents = {
1682
+ get: (session, name) => getAgent(this.ctx, session, name),
1683
+ start: (session, input) => startAgent(this.ctx, session, input),
1684
+ update: (session, name, input) => updateAgent(this.ctx, session, name, input),
1685
+ finish: (session, name, input) => finishAgent(this.ctx, session, name, input),
1686
+ drop: (session, name, reason) => dropAgent(this.ctx, session, name, reason),
1687
+ list: (session, options) => listAgents(this.ctx, session, options),
1688
+ reorderQueue: (session, names) => reorderQueue(this.ctx, session, names),
1689
+ pairSubagent: (session, hostAgentId) => pairSubagent(this.ctx, session, hostAgentId),
1690
+ stopSubagent: (session, hostAgentId, names) => stopSubagent(this.ctx, session, hostAgentId, names)
1691
+ };
1692
+ table = {
1693
+ get: (session) => getTable(this.ctx, session),
1694
+ set: (session, input) => setTable(this.ctx, session, input),
1695
+ clear: (session) => clearTable(this.ctx, session)
1696
+ };
1697
+ events = {
1698
+ log: (session, input) => logEvent(this.ctx, session, input),
1699
+ read: (session, limit, agentOnly) => readEvents(this.ctx, {
1700
+ session,
1701
+ limit,
1702
+ agentOnly
1703
+ })
1704
+ };
1705
+ notes = {
1706
+ add: (input) => addNote(this.ctx, this.group, input),
1707
+ get: (id) => getNote(this.ctx, id),
1708
+ show: (id, halfLifeDays) => noteDetail(this.ctx, id, halfLifeDays),
1709
+ list: (options) => listNotes(this.ctx, options),
1710
+ stale: (halfLifeDays) => staleNotes(this.ctx, halfLifeDays),
1711
+ drop: (id, input) => dropNote(this.ctx, id, input),
1712
+ cite: (id, input) => citeNote(this.ctx, id, input),
1713
+ recordActiveDay: () => recordActiveDay(this.ctx),
1714
+ activity: (session) => sessionNoteActivity(this.ctx, session)
1715
+ };
1716
+ memory = {
1717
+ atStart: (session, options) => sessionStartMemory(this.ctx, this.group, session, options),
1718
+ ofSession: (session, options) => sessionMemory(this.ctx, this.group, session, options),
1719
+ forRepo: (session, repo, options) => repoMemory(this.ctx, session, repo, options),
1720
+ copyRepos: (from, into) => copyInjectedRepos(this.ctx, from, into)
1721
+ };
1722
+ status = {
1723
+ view: (session) => buildStatusView(this.ctx, session),
1724
+ render: (session, options) => renderStatus(buildStatusView(this.ctx, session), options),
1725
+ sections: (session) => renderSections(buildStatusView(this.ctx, session))
1726
+ };
1727
+ close() {
1728
+ this.db.close();
1729
+ }
1730
+ };
1731
+ function openCarnet(options = {}) {
1732
+ const group = locateGroup(options);
1733
+ return new Carnet(group, openDatabase(options.dbPath ?? group.dbPath), options);
1734
+ }
1735
+ // src/resume.ts
1736
+ const RESUME_EVENTS = 20;
1737
+ const RESUME_MAX_CHARACTERS = 2e3;
1738
+ function formatEventLine(event) {
1739
+ return [
1740
+ formatClock(new Date(event.at)),
1741
+ event.type,
1742
+ event.agent,
1743
+ event.link ?? event.note,
1744
+ event.commit?.slice(0, 7)
1745
+ ].filter(Boolean).join(" ");
1746
+ }
1747
+ function sessionLabel(session) {
1748
+ const name = session.name ?? session.id;
1749
+ return session.purpose ? `${name} (${session.purpose})` : name;
1750
+ }
1751
+ function resumeContext(carnet, session, { events = 20, maxCharacters = RESUME_MAX_CHARACTERS } = {}) {
1752
+ const head = `Rucher session ${sessionLabel(session)}, state when resumed:\n\n${carnet.status.render(session, { notes: "summary" })}`;
1753
+ const lines = carnet.events.read(session.id, events, true).map(formatEventLine);
1754
+ const build = () => lines.length ? `${head}\n\nLast events\n${lines.map((line) => ` ${line}`).join("\n")}` : head;
1755
+ let text = build();
1756
+ while (text.length > maxCharacters && lines.length > 0) {
1757
+ lines.shift();
1758
+ text = build();
1759
+ }
1760
+ return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;
1761
+ }
1762
+ export { reportsDirectoryOf as $, DEFAULT_HALF_LIFE_DAYS as A, isAgentStatus as At, similarity as B, DEFAULT_PURGE_DAYS as C, sanitizeNote as Ct, MEMORY_MAX_CHARACTERS as D, MAIN_WORKING_EMOJI as Dt, shortId as E, LEGEND as Et, groupRepoNames as F, CarnetError as Ft, findGroupRoot as G, GROUP_DIRECTORY as H, isNoteKind as I, loadGroup as J, isGroupRoot as K, localDay as L, NOTE_KINDS as M, EVENT_TYPES as Mt, NOTE_TEXT_LIMIT as N, SESSION_EVENT_TYPES as Nt, memoryMaxCharacters as O, OPEN_AGENT_STATUSES as Ot, STALE_AFTER_ACTIVE_DAYS as P, isEventType as Pt, reportPathFor as Q, memoryHalfLife as R, renderTableLine as S, NOTE_MAX as St, MINIMUM_ID_PREFIX as T, EMOJI as Tt, GROUP_FILE as U, DB_FILE as V, REPORTS_DIRECTORY as W, repoNameFor as X, locateGroup as Y, repoPathFor as Z, renderNoteLine as _, migrate as _t, sessionLabel as a, allHosts as at, renderSections as b, PUBLISH_FALLBACK_MILLISECONDS as bt, PAIRING_WINDOW_MILLISECONDS as c, REPOS_START as ct, formatClock as d, groupSettings as dt, readRegistry as et, MAIN_WORKING_SUFFIX as f, replaceReposBlock as ft, renderAgentLine as g, openDatabase as gt, SIMILAR_PREFIX as h, MEMORY_DB as ht, resumeContext as i, DEFAULT_HOST as it, DUPLICATE_SIMILARITY as j, isUserActionStatus as jt, renderMemory as k, USER_ACTION_STATUSES as kt, STOPPED_NOTE as l, claudeCode as lt, NOTES_HEADER as m, transcriptTitle as mt, RESUME_MAX_CHARACTERS as n, rucherHome as nt, Carnet as o, hostById as ot, NOTES_FOLD_LINES as p, reposBlock as pt, isInside as q, formatEventLine as r, unregisterGroups as rt, openCarnet as s, REPOS_END as st, RESUME_EVENTS as t, registerGroup as tt, buildStatusView as u, groupInstructions as ut, renderNotes as v, migrations as vt, purgeDays as w, AGENT_STATUSES as wt, renderStatus as x, REPORTING_NOTE as xt, renderNotesSummary as y, schemaVersion as yt, sessionNoteActivity as z };
1763
+
1764
+ //# sourceMappingURL=resume-CQRf2jIa.mjs.map