@rucher/carnet 0.1.0 → 0.2.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/carnet--axAq8FF.d.mts +451 -0
- package/dist/carnet--axAq8FF.d.mts.map +1 -0
- package/dist/index.d.mts +48 -8
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +209 -7
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +2 -2
- package/dist/mcp.d.mts.map +1 -1
- package/dist/mcp.mjs +137 -41
- package/dist/mcp.mjs.map +1 -1
- package/dist/resume-D2FFakCl.mjs +1792 -0
- package/dist/resume-D2FFakCl.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/carnet-CSdqWDas.d.mts +0 -261
- package/dist/carnet-CSdqWDas.d.mts.map +0 -1
- package/dist/resume-Daotqfdq.mjs +0 -985
- package/dist/resume-Daotqfdq.mjs.map +0 -1
|
@@ -0,0 +1,1792 @@
|
|
|
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 groupsWithRepo(paths, env) {
|
|
780
|
+
const groups = [];
|
|
781
|
+
for (const reference of readRegistry(env)) {
|
|
782
|
+
if (!isGroupRoot(reference.path)) continue;
|
|
783
|
+
const group = loadGroup(reference.path);
|
|
784
|
+
if (paths.some((path) => group.repos.some((repo) => isInside(repo, path)))) groups.push(group);
|
|
785
|
+
}
|
|
786
|
+
return groups;
|
|
787
|
+
}
|
|
788
|
+
function knowsSession(group, sessionId) {
|
|
789
|
+
if (!existsSync(group.dbPath)) return false;
|
|
790
|
+
const db = new DatabaseSync(group.dbPath, { readOnly: true });
|
|
791
|
+
try {
|
|
792
|
+
return db.prepare("SELECT 1 FROM sessions WHERE id = ?").get(sessionId) !== void 0;
|
|
793
|
+
} catch {
|
|
794
|
+
return false;
|
|
795
|
+
} finally {
|
|
796
|
+
db.close();
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
function pinnedGroup(env) {
|
|
800
|
+
const root = env.RUCHER_GROUP_ROOT;
|
|
801
|
+
return root && isGroupRoot(resolve(root)) ? loadGroup(resolve(root)) : null;
|
|
802
|
+
}
|
|
803
|
+
function locateGroup({ cwd = process.cwd(), env = process.env, sessionId } = {}) {
|
|
804
|
+
const pinned = pinnedGroup(env);
|
|
805
|
+
if (pinned) return pinned;
|
|
806
|
+
const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
|
|
807
|
+
const candidates = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
|
|
808
|
+
for (const directory of candidates) {
|
|
809
|
+
const root = findGroupRoot(directory);
|
|
810
|
+
if (root) return loadGroup(root);
|
|
811
|
+
}
|
|
812
|
+
const matches = groupsWithRepo(candidates, env);
|
|
813
|
+
const [only] = matches;
|
|
814
|
+
if (matches.length === 1 && only) return only;
|
|
815
|
+
if (matches.length > 1) {
|
|
816
|
+
const owners = sessionId ? matches.filter((group) => knowsSession(group, sessionId)) : [];
|
|
817
|
+
const [owner] = owners;
|
|
818
|
+
if (owners.length === 1 && owner) return owner;
|
|
819
|
+
throw new CarnetError("GROUP_AMBIGUOUS", `${cwd} is in repos of several groups (${matches.map((group) => group.name).join(", ")}): launch with "rucher new" or "rucher resume", or start from the group's meta directory`);
|
|
820
|
+
}
|
|
821
|
+
throw new CarnetError("NO_GROUP", `No Rucher group for ${cwd}: run "rucher init" in a meta directory, or "rucher group add <this repo>" there`);
|
|
822
|
+
}
|
|
823
|
+
function ambiguousGroupContext(reason) {
|
|
824
|
+
return `Rucher could not tell which group this session belongs to, so Carnet records nothing for it: ${reason}.`;
|
|
825
|
+
}
|
|
826
|
+
// src/notes.ts
|
|
827
|
+
const NOTE_KINDS = [
|
|
828
|
+
"dead_end",
|
|
829
|
+
"decision",
|
|
830
|
+
"learning"
|
|
831
|
+
];
|
|
832
|
+
const NOTE_TEXT_LIMIT = 200;
|
|
833
|
+
const DUPLICATE_SIMILARITY = .6;
|
|
834
|
+
const DEFAULT_HALF_LIFE_DAYS = 20;
|
|
835
|
+
const STALE_AFTER_ACTIVE_DAYS = 40;
|
|
836
|
+
const SIMILAR_SHOWN = 3;
|
|
837
|
+
function isNoteKind(value) {
|
|
838
|
+
return NOTE_KINDS.includes(value);
|
|
839
|
+
}
|
|
840
|
+
function memoryHalfLife(value) {
|
|
841
|
+
const days = Number(value);
|
|
842
|
+
return Number.isFinite(days) && days > 0 ? days : 20;
|
|
843
|
+
}
|
|
844
|
+
const MARKDOWN = /\*\*|__|\[[^\]]*\]\([^)]*\)|^#{1,6}\s|^[-*+]\s/;
|
|
845
|
+
function cleanText(value, label) {
|
|
846
|
+
const text = value.trim().replace(/[ \t]+/g, " ");
|
|
847
|
+
if (!text) throw new CarnetError("INVALID_NOTE", `${label} is empty`);
|
|
848
|
+
if (text.length >= 200) throw new CarnetError("INVALID_NOTE", `${label} must stay under 200 characters (${text.length})`);
|
|
849
|
+
if (/[\r\n]/.test(text)) throw new CarnetError("INVALID_NOTE", `${label} must be one line`);
|
|
850
|
+
if (text.includes("`")) throw new CarnetError("INVALID_NOTE", `${label} must not use backticks`);
|
|
851
|
+
if (MARKDOWN.test(text)) throw new CarnetError("INVALID_NOTE", `${label} must not use markdown`);
|
|
852
|
+
return text;
|
|
853
|
+
}
|
|
854
|
+
function groupRepoNames(group) {
|
|
855
|
+
return group.repos.map((repo) => basename(repo));
|
|
856
|
+
}
|
|
857
|
+
function cleanRepos(group, repos) {
|
|
858
|
+
const known = groupRepoNames(group);
|
|
859
|
+
const unique = [...new Set((repos ?? []).map((repo) => repo.trim()).filter(Boolean))];
|
|
860
|
+
const unknown = unique.filter((repo) => !known.includes(repo));
|
|
861
|
+
if (unknown.length) throw new CarnetError("INVALID_NOTE", `Unknown repo ${unknown.join(", ")} (group repos: ${known.join(", ") || "none"})`);
|
|
862
|
+
return unique;
|
|
863
|
+
}
|
|
864
|
+
function words(text) {
|
|
865
|
+
return new Set(text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
|
|
866
|
+
}
|
|
867
|
+
function similarity(first, second) {
|
|
868
|
+
const left = words(first);
|
|
869
|
+
const right = words(second);
|
|
870
|
+
if (left.size === 0 && right.size === 0) return 0;
|
|
871
|
+
let shared = 0;
|
|
872
|
+
for (const word of left) if (right.has(word)) shared++;
|
|
873
|
+
return shared / (left.size + right.size - shared);
|
|
874
|
+
}
|
|
875
|
+
function localDay(date) {
|
|
876
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
877
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
878
|
+
return `${date.getFullYear()}-${month}-${day}`;
|
|
879
|
+
}
|
|
880
|
+
function recordActiveDay(ctx) {
|
|
881
|
+
ctx.db.prepare("INSERT OR IGNORE INTO active_days (day) VALUES (?)").run(localDay(ctx.now()));
|
|
882
|
+
}
|
|
883
|
+
function activeDays(ctx) {
|
|
884
|
+
return ctx.db.prepare("SELECT day FROM active_days ORDER BY day").all().map((row) => row.day);
|
|
885
|
+
}
|
|
886
|
+
function activeDaysSince(days, at) {
|
|
887
|
+
const since = localDay(new Date(at));
|
|
888
|
+
return days.filter((day) => day > since).length;
|
|
889
|
+
}
|
|
890
|
+
function reposOf(ctx, note) {
|
|
891
|
+
return ctx.db.prepare("SELECT repo FROM note_repos WHERE note = ? ORDER BY repo").all(note).map((row) => row.repo);
|
|
892
|
+
}
|
|
893
|
+
function toNote(ctx, row) {
|
|
894
|
+
return {
|
|
895
|
+
id: row.id,
|
|
896
|
+
kind: row.kind,
|
|
897
|
+
text: row.text,
|
|
898
|
+
repos: reposOf(ctx, row.id),
|
|
899
|
+
session: row.session,
|
|
900
|
+
agent: row.agent,
|
|
901
|
+
similarNotes: row.similar_notes ? JSON.parse(row.similar_notes) : [],
|
|
902
|
+
createdAt: row.created_at,
|
|
903
|
+
droppedAt: row.dropped_at,
|
|
904
|
+
droppedReason: row.dropped_reason,
|
|
905
|
+
droppedSession: row.dropped_session,
|
|
906
|
+
replacedBy: row.replaced_by
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
function getNote(ctx, id) {
|
|
910
|
+
const row = ctx.db.prepare("SELECT * FROM notes WHERE id = ?").get(id);
|
|
911
|
+
return row ? toNote(ctx, row) : null;
|
|
912
|
+
}
|
|
913
|
+
function requireNote(ctx, id) {
|
|
914
|
+
const note = getNote(ctx, id);
|
|
915
|
+
if (!note) throw new CarnetError("NOTE_NOT_FOUND", `Unknown note #${id}`);
|
|
916
|
+
return note;
|
|
917
|
+
}
|
|
918
|
+
function requireActiveNote(ctx, id) {
|
|
919
|
+
const note = requireNote(ctx, id);
|
|
920
|
+
if (note.droppedAt) throw new CarnetError("INVALID_NOTE", `Note #${id} is dropped`);
|
|
921
|
+
return note;
|
|
922
|
+
}
|
|
923
|
+
function citationsOf(ctx, note) {
|
|
924
|
+
return ctx.db.prepare("SELECT id, note, session, agent, why, at FROM note_citations WHERE note = ? ORDER BY at").all(note);
|
|
925
|
+
}
|
|
926
|
+
function weightOf(citations, days, halfLifeDays) {
|
|
927
|
+
const latest = /* @__PURE__ */ new Map();
|
|
928
|
+
for (const citation of citations) {
|
|
929
|
+
const key = citation.session ?? `citation-${citation.id}`;
|
|
930
|
+
const previous = latest.get(key);
|
|
931
|
+
if (!previous || citation.at > previous) latest.set(key, citation.at);
|
|
932
|
+
}
|
|
933
|
+
let weight = 0;
|
|
934
|
+
for (const at of latest.values()) weight += .5 ** (activeDaysSince(days, at) / halfLifeDays);
|
|
935
|
+
return weight;
|
|
936
|
+
}
|
|
937
|
+
function weigh(ctx, note, days, halfLifeDays) {
|
|
938
|
+
const citations = citationsOf(ctx, note.id);
|
|
939
|
+
return {
|
|
940
|
+
...note,
|
|
941
|
+
weight: weightOf(citations, days, halfLifeDays),
|
|
942
|
+
citationCount: citations.length
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
function compareNotes(first, second) {
|
|
946
|
+
const kind = NOTE_KINDS.indexOf(first.kind) - NOTE_KINDS.indexOf(second.kind);
|
|
947
|
+
if (kind !== 0) return kind;
|
|
948
|
+
if (first.weight !== second.weight) return second.weight - first.weight;
|
|
949
|
+
return second.id - first.id;
|
|
950
|
+
}
|
|
951
|
+
function activeNotesOfKind(ctx, kind) {
|
|
952
|
+
return ctx.db.prepare("SELECT * FROM notes WHERE kind = ? AND dropped_at IS NULL").all(kind).map((row) => toNote(ctx, row));
|
|
953
|
+
}
|
|
954
|
+
function addNote(ctx, group, input) {
|
|
955
|
+
if (!isNoteKind(input.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${input.kind}" (use ${NOTE_KINDS.join(", ")})`);
|
|
956
|
+
const kind = input.kind;
|
|
957
|
+
const text = cleanText(input.text, "Note text");
|
|
958
|
+
const repos = cleanRepos(group, input.repos);
|
|
959
|
+
const similar = activeNotesOfKind(ctx, kind).map((note) => ({
|
|
960
|
+
note,
|
|
961
|
+
score: similarity(text, note.text)
|
|
962
|
+
})).filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY).sort((first, second) => second.score - first.score).slice(0, SIMILAR_SHOWN).map((candidate) => candidate.note);
|
|
963
|
+
ctx.db.exec("BEGIN");
|
|
964
|
+
try {
|
|
965
|
+
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));
|
|
966
|
+
const id = Number(result.lastInsertRowid);
|
|
967
|
+
const addRepo = ctx.db.prepare("INSERT INTO note_repos (note, repo) VALUES (?, ?)");
|
|
968
|
+
for (const repo of repos) addRepo.run(id, repo);
|
|
969
|
+
ctx.db.exec("COMMIT");
|
|
970
|
+
return {
|
|
971
|
+
note: requireNote(ctx, id),
|
|
972
|
+
similar
|
|
973
|
+
};
|
|
974
|
+
} catch (error) {
|
|
975
|
+
ctx.db.exec("ROLLBACK");
|
|
976
|
+
throw error;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
function listNotes(ctx, options = {}) {
|
|
980
|
+
if (options.kind !== void 0 && !isNoteKind(options.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${options.kind}"`);
|
|
981
|
+
const conditions = [];
|
|
982
|
+
const parameters = [];
|
|
983
|
+
if (!options.includeDropped) conditions.push("dropped_at IS NULL");
|
|
984
|
+
if (options.kind) {
|
|
985
|
+
conditions.push("kind = ?");
|
|
986
|
+
parameters.push(options.kind);
|
|
987
|
+
}
|
|
988
|
+
if (options.repo) {
|
|
989
|
+
conditions.push("id IN (SELECT note FROM note_repos WHERE repo = ?)");
|
|
990
|
+
parameters.push(options.repo);
|
|
991
|
+
}
|
|
992
|
+
if (options.general) conditions.push("id NOT IN (SELECT note FROM note_repos)");
|
|
993
|
+
if (options.query) {
|
|
994
|
+
conditions.push("LOWER(text) LIKE ? ESCAPE '\\'");
|
|
995
|
+
parameters.push(`%${options.query.toLowerCase().replace(/[\\%_]/g, "\\$&")}%`);
|
|
996
|
+
}
|
|
997
|
+
const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
998
|
+
const rows = ctx.db.prepare(`SELECT * FROM notes ${where}`).all(...parameters);
|
|
999
|
+
const days = activeDays(ctx);
|
|
1000
|
+
const halfLifeDays = options.halfLifeDays ?? 20;
|
|
1001
|
+
return rows.map((row) => weigh(ctx, toNote(ctx, row), days, halfLifeDays)).sort(compareNotes);
|
|
1002
|
+
}
|
|
1003
|
+
function noteDetail(ctx, id, halfLifeDays = 20) {
|
|
1004
|
+
const note = requireNote(ctx, id);
|
|
1005
|
+
const citations = citationsOf(ctx, id);
|
|
1006
|
+
return {
|
|
1007
|
+
...note,
|
|
1008
|
+
weight: weightOf(citations, activeDays(ctx), halfLifeDays),
|
|
1009
|
+
citationCount: citations.length,
|
|
1010
|
+
citations
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
function staleNotes(ctx, halfLifeDays = 20) {
|
|
1014
|
+
const days = activeDays(ctx);
|
|
1015
|
+
return listNotes(ctx, { halfLifeDays }).filter((note) => activeDaysSince(days, note.createdAt) > 40 && (note.citationCount === 0 || note.weight < .05));
|
|
1016
|
+
}
|
|
1017
|
+
function dropNote(ctx, id, input) {
|
|
1018
|
+
requireActiveNote(ctx, id);
|
|
1019
|
+
const reason = cleanText(input.reason, "Drop reason");
|
|
1020
|
+
if (input.replacedBy !== void 0) {
|
|
1021
|
+
if (input.replacedBy === id) throw new CarnetError("INVALID_NOTE", `Note #${id} cannot replace itself`);
|
|
1022
|
+
requireActiveNote(ctx, input.replacedBy);
|
|
1023
|
+
}
|
|
1024
|
+
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);
|
|
1025
|
+
return requireNote(ctx, id);
|
|
1026
|
+
}
|
|
1027
|
+
function citeNote(ctx, id, input) {
|
|
1028
|
+
requireActiveNote(ctx, id);
|
|
1029
|
+
const why = cleanText(input.why, "Citation reason");
|
|
1030
|
+
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));
|
|
1031
|
+
return ctx.db.prepare("SELECT id, note, session, agent, why, at FROM note_citations WHERE id = ?").get(Number(result.lastInsertRowid));
|
|
1032
|
+
}
|
|
1033
|
+
const ACTIVITY_ORDER = {
|
|
1034
|
+
dropped: 0,
|
|
1035
|
+
cited: 1,
|
|
1036
|
+
added: 2
|
|
1037
|
+
};
|
|
1038
|
+
function activeIds(ctx, json) {
|
|
1039
|
+
if (!json) return [];
|
|
1040
|
+
const active = ctx.db.prepare("SELECT 1 FROM notes WHERE id = ? AND dropped_at IS NULL");
|
|
1041
|
+
return JSON.parse(json).filter((id) => active.get(id) !== void 0);
|
|
1042
|
+
}
|
|
1043
|
+
function sessionNoteActivity(ctx, session) {
|
|
1044
|
+
const added = ctx.db.prepare("SELECT id, kind, text, similar_notes, created_at FROM notes WHERE session = ?").all(session);
|
|
1045
|
+
const cited = ctx.db.prepare(`SELECT note_citations.note, notes.kind, note_citations.why, note_citations.at
|
|
1046
|
+
FROM note_citations JOIN notes ON notes.id = note_citations.note
|
|
1047
|
+
WHERE note_citations.session = ?`).all(session);
|
|
1048
|
+
const dropped = ctx.db.prepare("SELECT id, kind, dropped_reason, replaced_by, dropped_at FROM notes WHERE dropped_session = ?").all(session);
|
|
1049
|
+
return [
|
|
1050
|
+
...added.map((row) => ({
|
|
1051
|
+
activity: "added",
|
|
1052
|
+
note: row.id,
|
|
1053
|
+
kind: row.kind,
|
|
1054
|
+
text: row.text,
|
|
1055
|
+
similarNotes: activeIds(ctx, row.similar_notes),
|
|
1056
|
+
replacedBy: null,
|
|
1057
|
+
at: row.created_at
|
|
1058
|
+
})),
|
|
1059
|
+
...cited.map((row) => ({
|
|
1060
|
+
activity: "cited",
|
|
1061
|
+
note: row.note,
|
|
1062
|
+
kind: row.kind,
|
|
1063
|
+
text: row.why,
|
|
1064
|
+
similarNotes: [],
|
|
1065
|
+
replacedBy: null,
|
|
1066
|
+
at: row.at
|
|
1067
|
+
})),
|
|
1068
|
+
...dropped.map((row) => ({
|
|
1069
|
+
activity: "dropped",
|
|
1070
|
+
note: row.id,
|
|
1071
|
+
kind: row.kind,
|
|
1072
|
+
text: row.dropped_reason ?? "",
|
|
1073
|
+
similarNotes: [],
|
|
1074
|
+
replacedBy: row.replaced_by,
|
|
1075
|
+
at: row.dropped_at ?? ""
|
|
1076
|
+
}))
|
|
1077
|
+
].sort((first, second) => second.at.localeCompare(first.at) || ACTIVITY_ORDER[first.activity] - ACTIVITY_ORDER[second.activity] || second.note - first.note);
|
|
1078
|
+
}
|
|
1079
|
+
// src/memory.ts
|
|
1080
|
+
const MEMORY_MAX_CHARACTERS = 2e3;
|
|
1081
|
+
const KIND_TITLES = {
|
|
1082
|
+
dead_end: "Dead ends",
|
|
1083
|
+
decision: "Decisions",
|
|
1084
|
+
learning: "Learnings"
|
|
1085
|
+
};
|
|
1086
|
+
const CUT_ORDER = [
|
|
1087
|
+
"learning",
|
|
1088
|
+
"decision",
|
|
1089
|
+
"dead_end"
|
|
1090
|
+
];
|
|
1091
|
+
function memoryMaxCharacters(value) {
|
|
1092
|
+
const characters = Number(value);
|
|
1093
|
+
return Number.isInteger(characters) && characters > 0 ? characters : MEMORY_MAX_CHARACTERS;
|
|
1094
|
+
}
|
|
1095
|
+
function noteLine(note) {
|
|
1096
|
+
const repos = note.repos.length ? `[${note.repos.join(", ")}] ` : "";
|
|
1097
|
+
return ` #${String(note.id).padEnd(4)}${repos}${note.text}`;
|
|
1098
|
+
}
|
|
1099
|
+
function render(scope, kept) {
|
|
1100
|
+
const total = scope.notes.length;
|
|
1101
|
+
const leftOut = total - kept.length;
|
|
1102
|
+
const count = `${total} note${total > 1 ? "s" : ""}`;
|
|
1103
|
+
const pointer = leftOut ? `${leftOut} left out, note_list for the rest` : "note_list for details";
|
|
1104
|
+
const lines = [`${scope.title} (${count}, ${pointer}):`];
|
|
1105
|
+
for (const kind of NOTE_KINDS) {
|
|
1106
|
+
const ofKind = kept.filter((note) => note.kind === kind);
|
|
1107
|
+
if (!ofKind.length) continue;
|
|
1108
|
+
lines.push("", KIND_TITLES[kind], ...ofKind.map(noteLine));
|
|
1109
|
+
}
|
|
1110
|
+
return lines.join("\n");
|
|
1111
|
+
}
|
|
1112
|
+
function renderMemory(scope, maxCharacters = MEMORY_MAX_CHARACTERS) {
|
|
1113
|
+
const kept = [...scope.notes];
|
|
1114
|
+
let text = render(scope, kept);
|
|
1115
|
+
while (text.length > maxCharacters && kept.length) {
|
|
1116
|
+
const kind = CUT_ORDER.find((candidate) => kept.some((note) => note.kind === candidate));
|
|
1117
|
+
const lowest = kept.findLastIndex((note) => note.kind === kind);
|
|
1118
|
+
kept.splice(lowest, 1);
|
|
1119
|
+
text = render(scope, kept);
|
|
1120
|
+
}
|
|
1121
|
+
return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;
|
|
1122
|
+
}
|
|
1123
|
+
function injectedRepos(ctx, session) {
|
|
1124
|
+
return ctx.db.prepare("SELECT repo FROM session_repos WHERE session = ? ORDER BY injected_at, repo").all(session).map((row) => row.repo);
|
|
1125
|
+
}
|
|
1126
|
+
function recordRepo(ctx, session, repo) {
|
|
1127
|
+
ctx.db.prepare("INSERT OR IGNORE INTO session_repos (session, repo, injected_at) VALUES (?, ?, ?)").run(session, repo, nowIso(ctx));
|
|
1128
|
+
}
|
|
1129
|
+
function notesFor(ctx, repos, general, halfLifeDays) {
|
|
1130
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1131
|
+
const add = (notes) => notes.forEach((note) => byId.set(note.id, note));
|
|
1132
|
+
if (general) add(listNotes(ctx, {
|
|
1133
|
+
general: true,
|
|
1134
|
+
halfLifeDays
|
|
1135
|
+
}));
|
|
1136
|
+
for (const repo of repos) add(listNotes(ctx, {
|
|
1137
|
+
repo,
|
|
1138
|
+
halfLifeDays
|
|
1139
|
+
}));
|
|
1140
|
+
return [...byId.values()].sort(compareNotes);
|
|
1141
|
+
}
|
|
1142
|
+
function groupTitle(group) {
|
|
1143
|
+
return `Rucher memory of the ${group.name} group`;
|
|
1144
|
+
}
|
|
1145
|
+
function sessionStartMemory(ctx, group, session, options = {}) {
|
|
1146
|
+
const halfLifeDays = options.halfLifeDays ?? 20;
|
|
1147
|
+
const repos = session.repo ? [session.repo] : [];
|
|
1148
|
+
const notes = notesFor(ctx, repos, true, halfLifeDays);
|
|
1149
|
+
if (!notes.length) return void 0;
|
|
1150
|
+
for (const repo of repos) if (notes.some((note) => note.repos.includes(repo))) recordRepo(ctx, session.id, repo);
|
|
1151
|
+
return renderMemory({
|
|
1152
|
+
title: groupTitle(group),
|
|
1153
|
+
notes
|
|
1154
|
+
}, options.maxCharacters);
|
|
1155
|
+
}
|
|
1156
|
+
function sessionMemory(ctx, group, session, options = {}) {
|
|
1157
|
+
const halfLifeDays = options.halfLifeDays ?? 20;
|
|
1158
|
+
const notes = notesFor(ctx, injectedRepos(ctx, session.id), true, halfLifeDays);
|
|
1159
|
+
if (!notes.length) return void 0;
|
|
1160
|
+
return renderMemory({
|
|
1161
|
+
title: groupTitle(group),
|
|
1162
|
+
notes
|
|
1163
|
+
}, options.maxCharacters);
|
|
1164
|
+
}
|
|
1165
|
+
function repoMemory(ctx, session, repo, options = {}) {
|
|
1166
|
+
const injected = injectedRepos(ctx, session.id);
|
|
1167
|
+
if (injected.includes(repo)) return void 0;
|
|
1168
|
+
const notes = listNotes(ctx, {
|
|
1169
|
+
repo,
|
|
1170
|
+
halfLifeDays: options.halfLifeDays ?? 20
|
|
1171
|
+
}).filter((note) => !note.repos.some((other) => injected.includes(other)));
|
|
1172
|
+
if (!notes.length) return void 0;
|
|
1173
|
+
recordRepo(ctx, session.id, repo);
|
|
1174
|
+
return renderMemory({
|
|
1175
|
+
title: `Rucher memory, repo ${repo}`,
|
|
1176
|
+
notes
|
|
1177
|
+
}, options.maxCharacters);
|
|
1178
|
+
}
|
|
1179
|
+
function copyInjectedRepos(ctx, from, into) {
|
|
1180
|
+
for (const repo of injectedRepos(ctx, from)) recordRepo(ctx, into, repo);
|
|
1181
|
+
}
|
|
1182
|
+
// src/sessions.ts
|
|
1183
|
+
const COLUMNS = `id, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
|
|
1184
|
+
parent_id, prompt_version, created_at, last_active_at, ended_at`;
|
|
1185
|
+
function toSession(row) {
|
|
1186
|
+
return {
|
|
1187
|
+
id: row.id,
|
|
1188
|
+
name: row.name,
|
|
1189
|
+
purpose: row.purpose,
|
|
1190
|
+
kind: row.kind,
|
|
1191
|
+
status: row.status,
|
|
1192
|
+
cwd: row.cwd,
|
|
1193
|
+
repo: row.repo,
|
|
1194
|
+
host: row.host,
|
|
1195
|
+
hostPid: row.host_pid,
|
|
1196
|
+
hookedAt: row.hooked_at,
|
|
1197
|
+
lastTitle: row.last_title,
|
|
1198
|
+
parentId: row.parent_id,
|
|
1199
|
+
promptVersion: row.prompt_version,
|
|
1200
|
+
createdAt: row.created_at,
|
|
1201
|
+
lastActiveAt: row.last_active_at,
|
|
1202
|
+
endedAt: row.ended_at
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
function getSession(ctx, id) {
|
|
1206
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id);
|
|
1207
|
+
return row && toSession(row);
|
|
1208
|
+
}
|
|
1209
|
+
function requireSession(ctx, id) {
|
|
1210
|
+
const session = getSession(ctx, id);
|
|
1211
|
+
if (!session) throw new CarnetError("SESSION_NOT_FOUND", `Unknown session ${id}`);
|
|
1212
|
+
return session;
|
|
1213
|
+
}
|
|
1214
|
+
function ensureSession(ctx, id, cwd, group) {
|
|
1215
|
+
const existing = getSession(ctx, id);
|
|
1216
|
+
if (existing) return existing;
|
|
1217
|
+
const at = nowIso(ctx);
|
|
1218
|
+
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);
|
|
1219
|
+
return requireSession(ctx, id);
|
|
1220
|
+
}
|
|
1221
|
+
function nameTaken(error, name) {
|
|
1222
|
+
if (name && error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
1223
|
+
throw error;
|
|
1224
|
+
}
|
|
1225
|
+
function createSession(ctx, input) {
|
|
1226
|
+
if (input.kind === "active" && !input.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
1227
|
+
const at = nowIso(ctx);
|
|
1228
|
+
try {
|
|
1229
|
+
ctx.db.prepare(`INSERT INTO sessions (id, name, kind, status, cwd, repo, host, last_title,
|
|
1230
|
+
created_at, last_active_at)
|
|
1231
|
+
VALUES (?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(input.id, input.name ?? null, input.kind, input.cwd, input.repo ?? null, input.host ?? "claude-code", input.name ?? null, at, at);
|
|
1232
|
+
} catch (error) {
|
|
1233
|
+
nameTaken(error, input.name);
|
|
1234
|
+
}
|
|
1235
|
+
return requireSession(ctx, input.id);
|
|
1236
|
+
}
|
|
1237
|
+
function setSessionKind(ctx, id, kind, name) {
|
|
1238
|
+
const session = requireSession(ctx, id);
|
|
1239
|
+
const nextName = name ?? session.name;
|
|
1240
|
+
if (kind === "active" && !nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
1241
|
+
try {
|
|
1242
|
+
ctx.db.prepare("UPDATE sessions SET kind = ?, name = ?, last_title = ? WHERE id = ?").run(kind, nextName, nextName ?? session.lastTitle, id);
|
|
1243
|
+
} catch (error) {
|
|
1244
|
+
nameTaken(error, nextName);
|
|
1245
|
+
}
|
|
1246
|
+
return requireSession(ctx, id);
|
|
1247
|
+
}
|
|
1248
|
+
function endSession(ctx, id) {
|
|
1249
|
+
const session = requireSession(ctx, id);
|
|
1250
|
+
if (session.status !== "running") return session;
|
|
1251
|
+
const ended = setSessionStatus(ctx, id, "idle");
|
|
1252
|
+
logEvent(ctx, id, { type: "session.ended" });
|
|
1253
|
+
return ended;
|
|
1254
|
+
}
|
|
1255
|
+
function titleAvailable(ctx, id, title) {
|
|
1256
|
+
const owner = sessionByName(ctx, title);
|
|
1257
|
+
return !owner || owner.id === id;
|
|
1258
|
+
}
|
|
1259
|
+
function adoptTitle(ctx, id, rawTitle) {
|
|
1260
|
+
const session = requireSession(ctx, id);
|
|
1261
|
+
const title = rawTitle?.trim() || null;
|
|
1262
|
+
if (title === null || title === session.lastTitle) return session;
|
|
1263
|
+
ctx.db.prepare("UPDATE sessions SET last_title = ? WHERE id = ?").run(title, id);
|
|
1264
|
+
if (title === session.name || !titleAvailable(ctx, id, title)) return requireSession(ctx, id);
|
|
1265
|
+
ctx.db.prepare(`UPDATE sessions
|
|
1266
|
+
SET name = ?, kind = CASE WHEN name IS NULL THEN 'active' ELSE kind END
|
|
1267
|
+
WHERE id = ?`).run(title, id);
|
|
1268
|
+
return requireSession(ctx, id);
|
|
1269
|
+
}
|
|
1270
|
+
function upsertFromHook(ctx, group, payload, env = {}) {
|
|
1271
|
+
const at = nowIso(ctx);
|
|
1272
|
+
const host = env.host ?? "claude-code";
|
|
1273
|
+
const hostPid = env.processId ?? null;
|
|
1274
|
+
const repo = repoNameFor(group, payload.cwd);
|
|
1275
|
+
const existing = getSession(ctx, payload.session_id);
|
|
1276
|
+
if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, cwd, repo, host, host_pid, hooked_at, created_at, last_active_at)
|
|
1277
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, payload.cwd ?? null, repo, host, hostPid, at, at, at);
|
|
1278
|
+
else ctx.db.prepare(`UPDATE sessions
|
|
1279
|
+
SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
|
|
1280
|
+
WHERE id = ?`).run(at, at, payload.cwd ?? existing.cwd, repo ?? existing.repo, host, hostPid ?? existing.hostPid, payload.session_id);
|
|
1281
|
+
return adoptTitle(ctx, payload.session_id, payload.session_title);
|
|
1282
|
+
}
|
|
1283
|
+
function touchSession(ctx, id) {
|
|
1284
|
+
ctx.db.prepare("UPDATE sessions SET last_active_at = ? WHERE id = ?").run(nowIso(ctx), id);
|
|
1285
|
+
}
|
|
1286
|
+
function nameSession(ctx, id, name, purpose) {
|
|
1287
|
+
requireSession(ctx, id);
|
|
1288
|
+
try {
|
|
1289
|
+
ctx.db.prepare(`UPDATE sessions
|
|
1290
|
+
SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,
|
|
1291
|
+
kind = 'active'
|
|
1292
|
+
WHERE id = ?`).run(name, purpose ?? null, nowIso(ctx), id);
|
|
1293
|
+
} catch (error) {
|
|
1294
|
+
if (error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
1295
|
+
throw error;
|
|
1296
|
+
}
|
|
1297
|
+
return requireSession(ctx, id);
|
|
1298
|
+
}
|
|
1299
|
+
function listSessions(ctx, options = {}) {
|
|
1300
|
+
const conditions = [];
|
|
1301
|
+
if (!options.includeTemp) conditions.push("kind != 'temp'");
|
|
1302
|
+
if (!options.includeArchived) conditions.push("status != 'archived'");
|
|
1303
|
+
const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1304
|
+
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions ${where} ORDER BY last_active_at DESC`).all().map(toSession);
|
|
1305
|
+
}
|
|
1306
|
+
function dropSession(ctx, id) {
|
|
1307
|
+
requireSession(ctx, id);
|
|
1308
|
+
const at = nowIso(ctx);
|
|
1309
|
+
ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, id);
|
|
1310
|
+
ctx.db.prepare("UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?").run(at, id);
|
|
1311
|
+
return requireSession(ctx, id);
|
|
1312
|
+
}
|
|
1313
|
+
function defaultSession(ctx) {
|
|
1314
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE status != 'archived' ORDER BY last_active_at DESC LIMIT 1`).get();
|
|
1315
|
+
return row && toSession(row);
|
|
1316
|
+
}
|
|
1317
|
+
function sessionByName(ctx, name) {
|
|
1318
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE name = ?`).get(name);
|
|
1319
|
+
return row && toSession(row);
|
|
1320
|
+
}
|
|
1321
|
+
const MINIMUM_ID_PREFIX = 4;
|
|
1322
|
+
function shortId(id) {
|
|
1323
|
+
return id.slice(0, 8);
|
|
1324
|
+
}
|
|
1325
|
+
function findSession(ctx, reference) {
|
|
1326
|
+
const byName = sessionByName(ctx, reference);
|
|
1327
|
+
if (byName) return byName;
|
|
1328
|
+
const byId = getSession(ctx, reference);
|
|
1329
|
+
if (byId) return byId;
|
|
1330
|
+
const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
|
|
1331
|
+
if (isIdPrefix && reference.length >= 4) {
|
|
1332
|
+
const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id LIKE ? ORDER BY last_active_at DESC`).all(`${reference.toLowerCase()}%`);
|
|
1333
|
+
const [only, ...others] = rows;
|
|
1334
|
+
if (only && others.length === 0) return toSession(only);
|
|
1335
|
+
if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
|
|
1336
|
+
}
|
|
1337
|
+
throw new CarnetError("SESSION_NOT_FOUND", `Unknown session "${reference}"${isIdPrefix && reference.length < 4 ? ` (an id prefix needs at least 4 characters)` : ""}`);
|
|
1338
|
+
}
|
|
1339
|
+
function sessionByHostProcess(ctx, host, processId) {
|
|
1340
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
1341
|
+
WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL
|
|
1342
|
+
ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
|
|
1343
|
+
return row && toSession(row);
|
|
1344
|
+
}
|
|
1345
|
+
function recordPromptVersion(ctx, id, version) {
|
|
1346
|
+
requireSession(ctx, id);
|
|
1347
|
+
ctx.db.prepare("UPDATE sessions SET prompt_version = ? WHERE id = ?").run(version, id);
|
|
1348
|
+
return requireSession(ctx, id);
|
|
1349
|
+
}
|
|
1350
|
+
function setParent(ctx, id, parentId) {
|
|
1351
|
+
requireSession(ctx, id);
|
|
1352
|
+
requireSession(ctx, parentId);
|
|
1353
|
+
ctx.db.prepare("UPDATE sessions SET parent_id = ? WHERE id = ?").run(parentId, id);
|
|
1354
|
+
return requireSession(ctx, id);
|
|
1355
|
+
}
|
|
1356
|
+
function setSessionStatus(ctx, id, status) {
|
|
1357
|
+
requireSession(ctx, id);
|
|
1358
|
+
const at = nowIso(ctx);
|
|
1359
|
+
ctx.db.prepare(`UPDATE sessions
|
|
1360
|
+
SET status = ?, last_active_at = ?,
|
|
1361
|
+
ended_at = CASE WHEN ? = 'running' THEN NULL WHEN ? = 'idle' THEN ? ELSE ended_at END
|
|
1362
|
+
WHERE id = ?`).run(status, at, status, status, at, id);
|
|
1363
|
+
return requireSession(ctx, id);
|
|
1364
|
+
}
|
|
1365
|
+
function refuseWhileRunning(session, action) {
|
|
1366
|
+
if (session.status === "running") throw new CarnetError("SESSION_RUNNING", `Session ${session.name ?? shortId(session.id)} is running: ${action} it once it has ended`);
|
|
1367
|
+
}
|
|
1368
|
+
function renameSession(ctx, id, name) {
|
|
1369
|
+
refuseWhileRunning(requireSession(ctx, id), "rename");
|
|
1370
|
+
try {
|
|
1371
|
+
ctx.db.prepare("UPDATE sessions SET name = ? WHERE id = ?").run(name, id);
|
|
1372
|
+
} catch (error) {
|
|
1373
|
+
nameTaken(error, name);
|
|
1374
|
+
}
|
|
1375
|
+
return requireSession(ctx, id);
|
|
1376
|
+
}
|
|
1377
|
+
function promoteSession(ctx, id, name) {
|
|
1378
|
+
const session = requireSession(ctx, id);
|
|
1379
|
+
if (session.kind === "active") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name} is already active`);
|
|
1380
|
+
const nextName = name ?? session.name;
|
|
1381
|
+
if (!nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
1382
|
+
if (nextName !== session.name) refuseWhileRunning(session, "rename");
|
|
1383
|
+
try {
|
|
1384
|
+
ctx.db.prepare("UPDATE sessions SET kind = 'active', name = ? WHERE id = ?").run(nextName, id);
|
|
1385
|
+
} catch (error) {
|
|
1386
|
+
nameTaken(error, nextName);
|
|
1387
|
+
}
|
|
1388
|
+
return requireSession(ctx, id);
|
|
1389
|
+
}
|
|
1390
|
+
function demoteSession(ctx, id) {
|
|
1391
|
+
const session = requireSession(ctx, id);
|
|
1392
|
+
if (session.kind === "temp") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name ?? shortId(session.id)} is already temp`);
|
|
1393
|
+
ctx.db.prepare("UPDATE sessions SET kind = 'temp' WHERE id = ?").run(id);
|
|
1394
|
+
return requireSession(ctx, id);
|
|
1395
|
+
}
|
|
1396
|
+
function staleTempSessions(ctx, olderThanMilliseconds) {
|
|
1397
|
+
const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
|
|
1398
|
+
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
1399
|
+
WHERE kind = 'temp' AND status = 'idle' AND last_active_at < ?
|
|
1400
|
+
ORDER BY last_active_at ASC`).all(before).map(toSession);
|
|
1401
|
+
}
|
|
1402
|
+
function resetDeadSessions(ctx, isAlive) {
|
|
1403
|
+
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));
|
|
1404
|
+
}
|
|
1405
|
+
// src/merge.ts
|
|
1406
|
+
function namesOf(ctx, session) {
|
|
1407
|
+
return ctx.db.prepare("SELECT name FROM agents WHERE session = ?").all(session).map((row) => row.name);
|
|
1408
|
+
}
|
|
1409
|
+
function mergeSessions(ctx, fromId, intoId) {
|
|
1410
|
+
if (fromId === intoId) throw new CarnetError("SESSION_MERGE_INVALID", "Cannot merge a session into itself");
|
|
1411
|
+
const from = requireSession(ctx, fromId);
|
|
1412
|
+
const into = requireSession(ctx, intoId);
|
|
1413
|
+
const at = nowIso(ctx);
|
|
1414
|
+
const taken = new Set(namesOf(ctx, intoId));
|
|
1415
|
+
const fromNames = namesOf(ctx, fromId);
|
|
1416
|
+
const movedAgents = fromNames.filter((name) => !taken.has(name));
|
|
1417
|
+
const closedAgents = fromNames.filter((name) => taken.has(name));
|
|
1418
|
+
ctx.db.exec("BEGIN");
|
|
1419
|
+
try {
|
|
1420
|
+
const moveAgent = ctx.db.prepare("UPDATE agents SET session = ?, updated_at = ? WHERE session = ? AND name = ?");
|
|
1421
|
+
for (const name of movedAgents) moveAgent.run(intoId, at, fromId, name);
|
|
1422
|
+
ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, fromId);
|
|
1423
|
+
const movedEvents = Number(ctx.db.prepare("UPDATE events SET session = ? WHERE session = ?").run(intoId, fromId).changes);
|
|
1424
|
+
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;
|
|
1425
|
+
ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(fromId);
|
|
1426
|
+
const keepName = into.name === null && from.name !== null;
|
|
1427
|
+
ctx.db.prepare("UPDATE sessions SET status = 'archived', kind = 'temp', name = NULL, last_active_at = ? WHERE id = ?").run(at, fromId);
|
|
1428
|
+
ctx.db.prepare(`UPDATE sessions
|
|
1429
|
+
SET name = COALESCE(?, name), purpose = COALESCE(purpose, ?), last_active_at = ?,
|
|
1430
|
+
kind = CASE WHEN ? THEN ? ELSE kind END
|
|
1431
|
+
WHERE id = ?`).run(keepName ? from.name : null, from.purpose, at, keepName ? 1 : 0, from.kind, intoId);
|
|
1432
|
+
ctx.db.exec("COMMIT");
|
|
1433
|
+
return {
|
|
1434
|
+
session: requireSession(ctx, intoId),
|
|
1435
|
+
movedAgents,
|
|
1436
|
+
closedAgents,
|
|
1437
|
+
movedEvents,
|
|
1438
|
+
movedTable
|
|
1439
|
+
};
|
|
1440
|
+
} catch (error) {
|
|
1441
|
+
ctx.db.exec("ROLLBACK");
|
|
1442
|
+
throw error;
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
// src/purge.ts
|
|
1446
|
+
const DEFAULT_PURGE_DAYS = 3;
|
|
1447
|
+
const DAY_MILLISECONDS = 864e5;
|
|
1448
|
+
function purgeDays(value) {
|
|
1449
|
+
const days = Number(value);
|
|
1450
|
+
return Number.isFinite(days) && days > 0 ? days : 3;
|
|
1451
|
+
}
|
|
1452
|
+
const PURGEABLE = `
|
|
1453
|
+
id != ? AND last_active_at < ?
|
|
1454
|
+
AND NOT EXISTS (
|
|
1455
|
+
SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
|
|
1456
|
+
)
|
|
1457
|
+
AND (
|
|
1458
|
+
status = 'archived'
|
|
1459
|
+
OR (kind = 'temp' AND NOT EXISTS (SELECT 1 FROM agents WHERE agents.session = sessions.id))
|
|
1460
|
+
)`;
|
|
1461
|
+
function purgeSessions(ctx, keepId, days) {
|
|
1462
|
+
const cutoff = (/* @__PURE__ */ new Date(ctx.now().getTime() - days * DAY_MILLISECONDS)).toISOString();
|
|
1463
|
+
ctx.db.exec("BEGIN");
|
|
1464
|
+
try {
|
|
1465
|
+
const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(keepId, cutoff).map((row) => row.id);
|
|
1466
|
+
for (const table of [
|
|
1467
|
+
"table_items",
|
|
1468
|
+
"agents",
|
|
1469
|
+
"events"
|
|
1470
|
+
]) {
|
|
1471
|
+
const statement = ctx.db.prepare(`DELETE FROM ${table} WHERE session = ?`);
|
|
1472
|
+
for (const id of ids) statement.run(id);
|
|
1473
|
+
}
|
|
1474
|
+
const deleteSession = ctx.db.prepare("DELETE FROM sessions WHERE id = ?");
|
|
1475
|
+
for (const id of ids) deleteSession.run(id);
|
|
1476
|
+
ctx.db.exec("COMMIT");
|
|
1477
|
+
return ids;
|
|
1478
|
+
} catch (error) {
|
|
1479
|
+
ctx.db.exec("ROLLBACK");
|
|
1480
|
+
throw error;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
// src/status/render.ts
|
|
1484
|
+
const MAIN_WORKING_SUFFIX = "(main working, not ready)";
|
|
1485
|
+
function renderTableLine(item) {
|
|
1486
|
+
if (item.mainWorking) return `${MAIN_WORKING_EMOJI} ${item.text} ${MAIN_WORKING_SUFFIX}`;
|
|
1487
|
+
return `${EMOJI[item.status ?? "discussing"]} ${item.text}`;
|
|
1488
|
+
}
|
|
1489
|
+
function renderAgentLine(line) {
|
|
1490
|
+
return line.note ? `${line.emoji} ${line.name} — ${line.note}` : `${line.emoji} ${line.name}`;
|
|
1491
|
+
}
|
|
1492
|
+
const NOTES_HEADER = "Notes";
|
|
1493
|
+
const NOTES_FOLD_LINES = 5;
|
|
1494
|
+
const ACTIVITY_MARK = {
|
|
1495
|
+
added: "+",
|
|
1496
|
+
cited: "★",
|
|
1497
|
+
dropped: "−"
|
|
1498
|
+
};
|
|
1499
|
+
const LABEL_WIDTH = 8;
|
|
1500
|
+
const SIMILAR_PREFIX = "similar to ";
|
|
1501
|
+
function plural(count, word) {
|
|
1502
|
+
return `${count} ${word}${count > 1 ? "s" : ""}`;
|
|
1503
|
+
}
|
|
1504
|
+
function renderNotesSummary(notes) {
|
|
1505
|
+
const count = (activity) => notes.filter((item) => item.activity === activity).length;
|
|
1506
|
+
const duplicates = notes.filter((item) => item.activity === "added" && item.similarNotes.length > 0).length;
|
|
1507
|
+
const parts = [
|
|
1508
|
+
count("added") && `${count("added")} added`,
|
|
1509
|
+
count("cited") && `${count("cited")} cited`,
|
|
1510
|
+
count("dropped") && `${count("dropped")} dropped`,
|
|
1511
|
+
duplicates && plural(duplicates, "possible duplicate")
|
|
1512
|
+
].filter(Boolean);
|
|
1513
|
+
return `${NOTES_HEADER} ${parts.join(" · ")}`;
|
|
1514
|
+
}
|
|
1515
|
+
function renderNoteLine(item, idWidth) {
|
|
1516
|
+
const id = `#${item.note}`.padEnd(idWidth);
|
|
1517
|
+
const label = (item.activity === "added" ? item.kind : item.activity).padEnd(LABEL_WIDTH);
|
|
1518
|
+
let text = item.text;
|
|
1519
|
+
if (item.activity === "added" && item.similarNotes.length > 0) text = `${SIMILAR_PREFIX}${item.similarNotes.map((note) => `#${note}`).join(", ")} · ${text}`;
|
|
1520
|
+
if (item.activity === "dropped" && item.replacedBy !== null) text = `replaced by #${item.replacedBy}`;
|
|
1521
|
+
return `${ACTIVITY_MARK[item.activity]} ${id} ${label} ${text}`;
|
|
1522
|
+
}
|
|
1523
|
+
function renderNotes(notes, mode = "full") {
|
|
1524
|
+
if (notes.length === 0) return [];
|
|
1525
|
+
if (mode === "summary" || mode === "full" && notes.length > 5) return [renderNotesSummary(notes)];
|
|
1526
|
+
const idWidth = Math.max(...notes.map((item) => `#${item.note}`.length));
|
|
1527
|
+
return [NOTES_HEADER, ...notes.map((item) => ` ${renderNoteLine(item, idWidth)}`)];
|
|
1528
|
+
}
|
|
1529
|
+
function renderSections(view, options = {}) {
|
|
1530
|
+
const out = [];
|
|
1531
|
+
if (view.table) out.push("On the table", ` ${renderTableLine(view.table)}`, "");
|
|
1532
|
+
out.push("Waiting on you");
|
|
1533
|
+
if (view.waiting.length === 0) out.push(" nothing");
|
|
1534
|
+
view.waiting.forEach((line, index) => {
|
|
1535
|
+
out.push(` ${index + 1}. ${renderAgentLine(line)}`);
|
|
1536
|
+
});
|
|
1537
|
+
out.push("", "Running");
|
|
1538
|
+
if (view.running.length === 0) out.push(" nothing");
|
|
1539
|
+
for (const line of view.running) out.push(` ${renderAgentLine(line)}`);
|
|
1540
|
+
const notes = renderNotes(view.notes, options.notes);
|
|
1541
|
+
if (notes.length > 0) out.push("", ...notes);
|
|
1542
|
+
return out.join("\n");
|
|
1543
|
+
}
|
|
1544
|
+
function renderStatus(view, options) {
|
|
1545
|
+
return [
|
|
1546
|
+
view.time,
|
|
1547
|
+
"",
|
|
1548
|
+
renderSections(view, options),
|
|
1549
|
+
"",
|
|
1550
|
+
LEGEND
|
|
1551
|
+
].join("\n");
|
|
1552
|
+
}
|
|
1553
|
+
// src/table.ts
|
|
1554
|
+
function toItem(row) {
|
|
1555
|
+
return {
|
|
1556
|
+
session: row.session,
|
|
1557
|
+
text: row.text,
|
|
1558
|
+
status: row.status,
|
|
1559
|
+
mainWorking: row.main_working === 1,
|
|
1560
|
+
updatedAt: row.updated_at
|
|
1561
|
+
};
|
|
1562
|
+
}
|
|
1563
|
+
function getTable(ctx, session) {
|
|
1564
|
+
const row = ctx.db.prepare("SELECT * FROM table_items WHERE session = ?").get(session);
|
|
1565
|
+
return row && toItem(row);
|
|
1566
|
+
}
|
|
1567
|
+
function setTable(ctx, session, input) {
|
|
1568
|
+
if (input.mainWorking && input.status) throw new CarnetError("TABLE_STATUS_WITH_MAIN_WORKING", "A user-action status cannot be set while main is working");
|
|
1569
|
+
if (input.status !== void 0 && !isUserActionStatus(input.status)) throw new CarnetError("INVALID_STATUS", `Invalid table status "${String(input.status)}"`);
|
|
1570
|
+
ctx.db.prepare(`INSERT INTO table_items (session, text, status, main_working, updated_at) VALUES (?, ?, ?, ?, ?)
|
|
1571
|
+
ON CONFLICT(session) DO UPDATE SET text = excluded.text, status = excluded.status,
|
|
1572
|
+
main_working = excluded.main_working, updated_at = excluded.updated_at`).run(session, sanitizeNote(input.text), input.status ?? null, input.mainWorking ? 1 : 0, nowIso(ctx));
|
|
1573
|
+
return getTable(ctx, session);
|
|
1574
|
+
}
|
|
1575
|
+
function clearTable(ctx, session) {
|
|
1576
|
+
ctx.db.prepare("DELETE FROM table_items WHERE session = ?").run(session);
|
|
1577
|
+
}
|
|
1578
|
+
// src/status/view.ts
|
|
1579
|
+
const BUCKET = {
|
|
1580
|
+
answer: 0,
|
|
1581
|
+
review: 1
|
|
1582
|
+
};
|
|
1583
|
+
function bucketOf(status) {
|
|
1584
|
+
return BUCKET[status] ?? 2;
|
|
1585
|
+
}
|
|
1586
|
+
function compareWaiting(left, right) {
|
|
1587
|
+
if (left.queueOrder !== null || right.queueOrder !== null) {
|
|
1588
|
+
if (left.queueOrder === null) return 1;
|
|
1589
|
+
if (right.queueOrder === null) return -1;
|
|
1590
|
+
return left.queueOrder - right.queueOrder;
|
|
1591
|
+
}
|
|
1592
|
+
return bucketOf(left.status) - bucketOf(right.status) || left.startedAt.localeCompare(right.startedAt);
|
|
1593
|
+
}
|
|
1594
|
+
function toLine(agent) {
|
|
1595
|
+
return {
|
|
1596
|
+
name: agent.name,
|
|
1597
|
+
status: agent.status,
|
|
1598
|
+
emoji: agent.status === "closed" ? "" : EMOJI[agent.status],
|
|
1599
|
+
note: agent.note
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
function formatClock(date) {
|
|
1603
|
+
return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
|
|
1604
|
+
}
|
|
1605
|
+
function buildStatusView(ctx, session) {
|
|
1606
|
+
const agents = listAgents(ctx, session.id);
|
|
1607
|
+
const waiting = agents.filter((agent) => isUserActionStatus(agent.status)).sort(compareWaiting).map(toLine);
|
|
1608
|
+
const running = agents.filter((agent) => agent.status === "running").map(toLine);
|
|
1609
|
+
return {
|
|
1610
|
+
time: formatClock(ctx.now()),
|
|
1611
|
+
sessionName: session.name,
|
|
1612
|
+
table: getTable(ctx, session.id) ?? null,
|
|
1613
|
+
waiting,
|
|
1614
|
+
running,
|
|
1615
|
+
notes: sessionNoteActivity(ctx, session.id)
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
// src/subagents.ts
|
|
1619
|
+
const PAIRING_WINDOW_MILLISECONDS = 6e4;
|
|
1620
|
+
const STOPPED_NOTE = "stopped without agent_done";
|
|
1621
|
+
function byHostAgentId(ctx, session, hostAgentId) {
|
|
1622
|
+
const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND host_agent_id = ?").get(session, hostAgentId);
|
|
1623
|
+
return row && toAgent(row);
|
|
1624
|
+
}
|
|
1625
|
+
function pairSubagent(ctx, session, hostAgentId) {
|
|
1626
|
+
const paired = byHostAgentId(ctx, session, hostAgentId);
|
|
1627
|
+
if (paired) return paired;
|
|
1628
|
+
const since = (/* @__PURE__ */ new Date(ctx.now().getTime() - PAIRING_WINDOW_MILLISECONDS)).toISOString();
|
|
1629
|
+
const row = ctx.db.prepare(`SELECT * FROM agents
|
|
1630
|
+
WHERE session = ? AND status = 'running' AND host_agent_id IS NULL AND started_at >= ?
|
|
1631
|
+
ORDER BY started_at ASC, rowid ASC LIMIT 1`).get(session, since);
|
|
1632
|
+
if (!row) return void 0;
|
|
1633
|
+
ctx.db.prepare("UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?").run(hostAgentId, session, row.name);
|
|
1634
|
+
return byHostAgentId(ctx, session, hostAgentId);
|
|
1635
|
+
}
|
|
1636
|
+
function byName(ctx, session, name) {
|
|
1637
|
+
const row = ctx.db.prepare("SELECT * FROM agents WHERE session = ? AND name = ?").get(session, name);
|
|
1638
|
+
return row && toAgent(row);
|
|
1639
|
+
}
|
|
1640
|
+
function setHostAgentId(ctx, session, name, hostAgentId) {
|
|
1641
|
+
ctx.db.prepare("UPDATE agents SET host_agent_id = ? WHERE session = ? AND name = ?").run(hostAgentId, session, name);
|
|
1642
|
+
}
|
|
1643
|
+
function repairByName(ctx, session, hostAgentId, names) {
|
|
1644
|
+
const named = names.map((name) => byName(ctx, session, name)).find(Boolean);
|
|
1645
|
+
if (!named || named.hostAgentId === hostAgentId) return;
|
|
1646
|
+
const holder = byHostAgentId(ctx, session, hostAgentId);
|
|
1647
|
+
if (holder) setHostAgentId(ctx, session, holder.name, named.hostAgentId);
|
|
1648
|
+
setHostAgentId(ctx, session, named.name, hostAgentId);
|
|
1649
|
+
}
|
|
1650
|
+
function stopSubagent(ctx, session, hostAgentId, names = []) {
|
|
1651
|
+
repairByName(ctx, session, hostAgentId, names);
|
|
1652
|
+
const agent = byHostAgentId(ctx, session, hostAgentId);
|
|
1653
|
+
if (!agent || agent.status !== "running") return void 0;
|
|
1654
|
+
if (agent.pendingStatus) {
|
|
1655
|
+
publishPending(ctx, session, agent.name);
|
|
1656
|
+
return byHostAgentId(ctx, session, hostAgentId);
|
|
1657
|
+
}
|
|
1658
|
+
ctx.db.prepare("UPDATE agents SET status = 'review', note = ?, updated_at = ? WHERE session = ? AND name = ?").run(STOPPED_NOTE, nowIso(ctx), session, agent.name);
|
|
1659
|
+
logEvent(ctx, session, {
|
|
1660
|
+
type: "finished",
|
|
1661
|
+
agent: agent.name,
|
|
1662
|
+
note: STOPPED_NOTE
|
|
1663
|
+
});
|
|
1664
|
+
return byHostAgentId(ctx, session, hostAgentId);
|
|
1665
|
+
}
|
|
1666
|
+
// src/carnet.ts
|
|
1667
|
+
var Carnet = class {
|
|
1668
|
+
group;
|
|
1669
|
+
db;
|
|
1670
|
+
ctx;
|
|
1671
|
+
constructor(group, db, options = {}) {
|
|
1672
|
+
this.group = group;
|
|
1673
|
+
this.db = db;
|
|
1674
|
+
this.ctx = {
|
|
1675
|
+
db,
|
|
1676
|
+
now: options.now ?? (() => /* @__PURE__ */ new Date())
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
sessions = {
|
|
1680
|
+
get: (id) => getSession(this.ctx, id),
|
|
1681
|
+
find: (reference) => findSession(this.ctx, reference),
|
|
1682
|
+
require: (id) => requireSession(this.ctx, id),
|
|
1683
|
+
ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group),
|
|
1684
|
+
upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.group, payload, env),
|
|
1685
|
+
touch: (id) => touchSession(this.ctx, id),
|
|
1686
|
+
merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
|
|
1687
|
+
purge: (keepId, days) => purgeSessions(this.ctx, keepId, days),
|
|
1688
|
+
name: (id, name, purpose) => nameSession(this.ctx, id, name, purpose),
|
|
1689
|
+
adoptTitle: (id, title) => adoptTitle(this.ctx, id, title),
|
|
1690
|
+
list: (options) => listSessions(this.ctx, options),
|
|
1691
|
+
drop: (id) => dropSession(this.ctx, id),
|
|
1692
|
+
default: () => defaultSession(this.ctx),
|
|
1693
|
+
byName: (name) => sessionByName(this.ctx, name),
|
|
1694
|
+
byHostProcess: (host, processId) => sessionByHostProcess(this.ctx, host, processId),
|
|
1695
|
+
recordPromptVersion: (id, version) => recordPromptVersion(this.ctx, id, version),
|
|
1696
|
+
setParent: (id, parentId) => setParent(this.ctx, id, parentId),
|
|
1697
|
+
setStatus: (id, status) => setSessionStatus(this.ctx, id, status),
|
|
1698
|
+
create: (input) => createSession(this.ctx, input),
|
|
1699
|
+
setKind: (id, kind, name) => setSessionKind(this.ctx, id, kind, name),
|
|
1700
|
+
end: (id) => endSession(this.ctx, id),
|
|
1701
|
+
rename: (id, name) => renameSession(this.ctx, id, name),
|
|
1702
|
+
promote: (id, name) => promoteSession(this.ctx, id, name),
|
|
1703
|
+
demote: (id) => demoteSession(this.ctx, id),
|
|
1704
|
+
staleTemp: (olderThanMilliseconds) => staleTempSessions(this.ctx, olderThanMilliseconds),
|
|
1705
|
+
resetDead: (isAlive) => resetDeadSessions(this.ctx, isAlive)
|
|
1706
|
+
};
|
|
1707
|
+
agents = {
|
|
1708
|
+
get: (session, name) => getAgent(this.ctx, session, name),
|
|
1709
|
+
start: (session, input) => startAgent(this.ctx, session, input),
|
|
1710
|
+
update: (session, name, input) => updateAgent(this.ctx, session, name, input),
|
|
1711
|
+
finish: (session, name, input) => finishAgent(this.ctx, session, name, input),
|
|
1712
|
+
drop: (session, name, reason) => dropAgent(this.ctx, session, name, reason),
|
|
1713
|
+
list: (session, options) => listAgents(this.ctx, session, options),
|
|
1714
|
+
reorderQueue: (session, names) => reorderQueue(this.ctx, session, names),
|
|
1715
|
+
pairSubagent: (session, hostAgentId) => pairSubagent(this.ctx, session, hostAgentId),
|
|
1716
|
+
stopSubagent: (session, hostAgentId, names) => stopSubagent(this.ctx, session, hostAgentId, names)
|
|
1717
|
+
};
|
|
1718
|
+
table = {
|
|
1719
|
+
get: (session) => getTable(this.ctx, session),
|
|
1720
|
+
set: (session, input) => setTable(this.ctx, session, input),
|
|
1721
|
+
clear: (session) => clearTable(this.ctx, session)
|
|
1722
|
+
};
|
|
1723
|
+
events = {
|
|
1724
|
+
log: (session, input) => logEvent(this.ctx, session, input),
|
|
1725
|
+
read: (session, limit, agentOnly) => readEvents(this.ctx, {
|
|
1726
|
+
session,
|
|
1727
|
+
limit,
|
|
1728
|
+
agentOnly
|
|
1729
|
+
})
|
|
1730
|
+
};
|
|
1731
|
+
notes = {
|
|
1732
|
+
add: (input) => addNote(this.ctx, this.group, input),
|
|
1733
|
+
get: (id) => getNote(this.ctx, id),
|
|
1734
|
+
show: (id, halfLifeDays) => noteDetail(this.ctx, id, halfLifeDays),
|
|
1735
|
+
list: (options) => listNotes(this.ctx, options),
|
|
1736
|
+
stale: (halfLifeDays) => staleNotes(this.ctx, halfLifeDays),
|
|
1737
|
+
drop: (id, input) => dropNote(this.ctx, id, input),
|
|
1738
|
+
cite: (id, input) => citeNote(this.ctx, id, input),
|
|
1739
|
+
recordActiveDay: () => recordActiveDay(this.ctx),
|
|
1740
|
+
activity: (session) => sessionNoteActivity(this.ctx, session)
|
|
1741
|
+
};
|
|
1742
|
+
memory = {
|
|
1743
|
+
atStart: (session, options) => sessionStartMemory(this.ctx, this.group, session, options),
|
|
1744
|
+
ofSession: (session, options) => sessionMemory(this.ctx, this.group, session, options),
|
|
1745
|
+
forRepo: (session, repo, options) => repoMemory(this.ctx, session, repo, options),
|
|
1746
|
+
copyRepos: (from, into) => copyInjectedRepos(this.ctx, from, into)
|
|
1747
|
+
};
|
|
1748
|
+
status = {
|
|
1749
|
+
view: (session) => buildStatusView(this.ctx, session),
|
|
1750
|
+
render: (session, options) => renderStatus(buildStatusView(this.ctx, session), options),
|
|
1751
|
+
sections: (session) => renderSections(buildStatusView(this.ctx, session))
|
|
1752
|
+
};
|
|
1753
|
+
close() {
|
|
1754
|
+
this.db.close();
|
|
1755
|
+
}
|
|
1756
|
+
};
|
|
1757
|
+
function openCarnet(options = {}) {
|
|
1758
|
+
return openGroupCarnet(locateGroup(options), options);
|
|
1759
|
+
}
|
|
1760
|
+
function openGroupCarnet(group, options = {}) {
|
|
1761
|
+
return new Carnet(group, openDatabase(options.dbPath ?? group.dbPath), options);
|
|
1762
|
+
}
|
|
1763
|
+
// src/resume.ts
|
|
1764
|
+
const RESUME_EVENTS = 20;
|
|
1765
|
+
const RESUME_MAX_CHARACTERS = 2e3;
|
|
1766
|
+
function formatEventLine(event) {
|
|
1767
|
+
return [
|
|
1768
|
+
formatClock(new Date(event.at)),
|
|
1769
|
+
event.type,
|
|
1770
|
+
event.agent,
|
|
1771
|
+
event.link ?? event.note,
|
|
1772
|
+
event.commit?.slice(0, 7)
|
|
1773
|
+
].filter(Boolean).join(" ");
|
|
1774
|
+
}
|
|
1775
|
+
function sessionLabel(session) {
|
|
1776
|
+
const name = session.name ?? session.id;
|
|
1777
|
+
return session.purpose ? `${name} (${session.purpose})` : name;
|
|
1778
|
+
}
|
|
1779
|
+
function resumeContext(carnet, session, { events = 20, maxCharacters = RESUME_MAX_CHARACTERS } = {}) {
|
|
1780
|
+
const head = `Rucher session ${sessionLabel(session)}, state when resumed:\n\n${carnet.status.render(session, { notes: "summary" })}`;
|
|
1781
|
+
const lines = carnet.events.read(session.id, events, true).map(formatEventLine);
|
|
1782
|
+
const build = () => lines.length ? `${head}\n\nLast events\n${lines.map((line) => ` ${line}`).join("\n")}` : head;
|
|
1783
|
+
let text = build();
|
|
1784
|
+
while (text.length > maxCharacters && lines.length > 0) {
|
|
1785
|
+
lines.shift();
|
|
1786
|
+
text = build();
|
|
1787
|
+
}
|
|
1788
|
+
return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;
|
|
1789
|
+
}
|
|
1790
|
+
export { repoNameFor as $, renderMemory as A, MAIN_WORKING_EMOJI as At, sessionNoteActivity as B, renderTableLine as C, PUBLISH_FALLBACK_MILLISECONDS as Ct, shortId as D, AGENT_STATUSES as Dt, MINIMUM_ID_PREFIX as E, sanitizeNote as Et, STALE_AFTER_ACTIVE_DAYS as F, EVENT_TYPES as Ft, REPORTS_DIRECTORY as G, DB_FILE as H, groupRepoNames as I, SESSION_EVENT_TYPES as It, isGroupRoot as J, ambiguousGroupContext as K, isNoteKind as L, isEventType as Lt, DUPLICATE_SIMILARITY as M, USER_ACTION_STATUSES as Mt, NOTE_KINDS as N, isAgentStatus as Nt, MEMORY_MAX_CHARACTERS as O, EMOJI as Ot, NOTE_TEXT_LIMIT as P, isUserActionStatus as Pt, pinnedGroup as Q, localDay as R, CarnetError as Rt, renderStatus as S, schemaVersion as St, purgeDays as T, NOTE_MAX as Tt, GROUP_DIRECTORY as U, similarity as V, GROUP_FILE as W, loadGroup as X, isInside as Y, locateGroup as Z, renderAgentLine as _, transcriptTitle as _t, sessionLabel as a, rucherHome as at, renderNotesSummary as b, migrate as bt, openGroupCarnet as c, allHosts as ct, buildStatusView as d, REPOS_START as dt, repoPathFor as et, formatClock as f, claudeCode as ft, SIMILAR_PREFIX as g, reposBlock as gt, NOTES_HEADER as h, replaceReposBlock as ht, resumeContext as i, registerGroup as it, DEFAULT_HALF_LIFE_DAYS as j, OPEN_AGENT_STATUSES as jt, memoryMaxCharacters as k, LEGEND as kt, PAIRING_WINDOW_MILLISECONDS as l, hostById as lt, NOTES_FOLD_LINES as m, groupSettings as mt, RESUME_MAX_CHARACTERS as n, reportsDirectoryOf as nt, Carnet as o, unregisterGroups as ot, MAIN_WORKING_SUFFIX as p, groupInstructions as pt, findGroupRoot as q, formatEventLine as r, readRegistry as rt, openCarnet as s, DEFAULT_HOST as st, RESUME_EVENTS as t, reportPathFor as tt, STOPPED_NOTE as u, REPOS_END as ut, renderNoteLine as v, MEMORY_DB as vt, DEFAULT_PURGE_DAYS as w, REPORTING_NOTE as wt, renderSections as x, migrations as xt, renderNotes as y, openDatabase as yt, memoryHalfLife as z };
|
|
1791
|
+
|
|
1792
|
+
//# sourceMappingURL=resume-D2FFakCl.mjs.map
|