@tekmidian/pai 0.19.0 → 0.20.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/dist/checkpoint-block-Cloxmin5.mjs +1229 -0
- package/dist/checkpoint-block-Cloxmin5.mjs.map +1 -0
- package/dist/checkpoint-block-D75rhsPY.mjs +1253 -0
- package/dist/checkpoint-block-D75rhsPY.mjs.map +1 -0
- package/dist/cli/index.mjs +2 -2
- package/dist/cli/program.mjs +2 -2
- package/dist/daemon/index.mjs +3 -3
- package/dist/daemon-BgUnyB-t.mjs +1576 -0
- package/dist/daemon-BgUnyB-t.mjs.map +1 -0
- package/dist/daemon-Tgfcu9rV.mjs +1576 -0
- package/dist/daemon-Tgfcu9rV.mjs.map +1 -0
- package/dist/pick-B_6bfxD8.mjs +13200 -0
- package/dist/pick-B_6bfxD8.mjs.map +1 -0
- package/dist/pick-CjUxUBL_.mjs +13192 -0
- package/dist/pick-CjUxUBL_.mjs.map +1 -0
- package/dist/pick-O1g16fVb.mjs +13035 -0
- package/dist/pick-O1g16fVb.mjs.map +1 -0
- package/dist/pick-PYANzDSp.mjs +13035 -0
- package/dist/pick-PYANzDSp.mjs.map +1 -0
- package/dist/work-queue-worker-CEMpy89q.mjs +1856 -0
- package/dist/work-queue-worker-CEMpy89q.mjs.map +1 -0
- package/dist/work-queue-worker-DLfFMY8O.mjs +1856 -0
- package/dist/work-queue-worker-DLfFMY8O.mjs.map +1 -0
- package/docs/commands/README.md +1 -0
- package/docs/commands/registry.md +18 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1856 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-95iHPtFO.mjs";
|
|
2
|
+
import { n as openFederation } from "./db-CYmBWcjh.mjs";
|
|
3
|
+
import { l as performScan, n as applyContinue, o as extractAndStoreTriples$1 } from "./checkpoint-block-Cloxmin5.mjs";
|
|
4
|
+
import { O as storageBackend, t as daemonConfig, u as registryDb } from "./state-DTvy-jRB.mjs";
|
|
5
|
+
import { t as detectTopicShift } from "./detector-BGw8SNWe.mjs";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { basename, dirname, join } from "node:path";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { existsSync as existsSync$1, mkdirSync as mkdirSync$1, readFileSync as readFileSync$1, readdirSync as readdirSync$1, renameSync as renameSync$1, writeFileSync as writeFileSync$1 } from "fs";
|
|
11
|
+
import { basename as basename$1, join as join$1, resolve as resolve$1 } from "path";
|
|
12
|
+
import { homedir as homedir$1 } from "os";
|
|
13
|
+
|
|
14
|
+
//#region src/daemon/work-queue.ts
|
|
15
|
+
/**
|
|
16
|
+
* work-queue.ts — Persistent work queue for the PAI Daemon
|
|
17
|
+
*
|
|
18
|
+
* Provides a durable, file-backed queue that survives daemon restarts.
|
|
19
|
+
* Items are processed sequentially to avoid concurrent writes to the same
|
|
20
|
+
* session note. Failed items are retried with exponential backoff.
|
|
21
|
+
*
|
|
22
|
+
* Queue file: ~/.config/pai/work-queue.json
|
|
23
|
+
* Written atomically (write temp → rename) to prevent corruption.
|
|
24
|
+
*/
|
|
25
|
+
const QUEUE_FILE = join(homedir(), ".config", "pai", "work-queue.json");
|
|
26
|
+
const MAX_QUEUE_SIZE = 1e3;
|
|
27
|
+
const MAX_QUEUE_FILE_BYTES = 1024 * 1024;
|
|
28
|
+
const COMPLETED_TTL_MS = 3600 * 1e3;
|
|
29
|
+
const FAILED_TTL_MS = 1440 * 60 * 1e3;
|
|
30
|
+
/** Backoff delays in ms by attempt number (0-indexed). */
|
|
31
|
+
const BACKOFF_MS = [
|
|
32
|
+
5e3,
|
|
33
|
+
3e4,
|
|
34
|
+
3e5
|
|
35
|
+
];
|
|
36
|
+
let _queue = [];
|
|
37
|
+
let _dirty = false;
|
|
38
|
+
/** Load queue from disk. Call once at daemon startup. */
|
|
39
|
+
function loadQueue() {
|
|
40
|
+
if (!existsSync(QUEUE_FILE)) {
|
|
41
|
+
_queue = [];
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
const raw = readFileSync(QUEUE_FILE, "utf-8");
|
|
46
|
+
const parsed = JSON.parse(raw);
|
|
47
|
+
if (!Array.isArray(parsed)) {
|
|
48
|
+
process.stderr.write("[work-queue] Invalid queue file format — starting empty.\n");
|
|
49
|
+
_queue = [];
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
_queue = parsed.map((item) => {
|
|
53
|
+
if (item.status === "processing") return {
|
|
54
|
+
...item,
|
|
55
|
+
status: "pending"
|
|
56
|
+
};
|
|
57
|
+
return item;
|
|
58
|
+
});
|
|
59
|
+
const stats = getStats();
|
|
60
|
+
process.stderr.write(`[work-queue] Loaded ${_queue.length} items from disk (pending=${stats.pending}, failed=${stats.failed}).\n`);
|
|
61
|
+
} catch (e) {
|
|
62
|
+
process.stderr.write(`[work-queue] Could not load queue file: ${e}\n`);
|
|
63
|
+
_queue = [];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Persist queue to disk atomically. */
|
|
67
|
+
function saveQueue() {
|
|
68
|
+
const dir = dirname(QUEUE_FILE);
|
|
69
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
70
|
+
const tmpFile = QUEUE_FILE + ".tmp";
|
|
71
|
+
try {
|
|
72
|
+
writeFileSync(tmpFile, JSON.stringify(_queue, null, 2), "utf-8");
|
|
73
|
+
renameSync(tmpFile, QUEUE_FILE);
|
|
74
|
+
_dirty = false;
|
|
75
|
+
} catch (e) {
|
|
76
|
+
process.stderr.write(`[work-queue] Could not persist queue: ${e}\n`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Persist only if there are unsaved changes. */
|
|
80
|
+
function saveIfDirty() {
|
|
81
|
+
if (_dirty) saveQueue();
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Enforce the maximum queue size cap.
|
|
85
|
+
* Strategy: first drop oldest completed, then oldest low-priority pending.
|
|
86
|
+
*/
|
|
87
|
+
function enforceMaxSize() {
|
|
88
|
+
if (_queue.length <= MAX_QUEUE_SIZE) return;
|
|
89
|
+
const excess = _queue.length - MAX_QUEUE_SIZE;
|
|
90
|
+
const toDropCompleted = _queue.filter((i) => i.status === "completed").sort((a, b) => a.createdAt.localeCompare(b.createdAt)).slice(0, excess);
|
|
91
|
+
const dropIds = new Set(toDropCompleted.map((i) => i.id));
|
|
92
|
+
_queue = _queue.filter((i) => !dropIds.has(i.id));
|
|
93
|
+
if (_queue.length <= MAX_QUEUE_SIZE) return;
|
|
94
|
+
const remainingExcess = _queue.length - MAX_QUEUE_SIZE;
|
|
95
|
+
const toDropLow = _queue.filter((i) => i.status === "pending" && i.priority >= 4).sort((a, b) => a.priority - b.priority || a.createdAt.localeCompare(b.createdAt)).slice(0, remainingExcess);
|
|
96
|
+
const dropLowIds = new Set(toDropLow.map((i) => i.id));
|
|
97
|
+
_queue = _queue.filter((i) => !dropLowIds.has(i.id));
|
|
98
|
+
process.stderr.write(`[work-queue] Pruned queue to ${_queue.length} items (cap=${MAX_QUEUE_SIZE}).\n`);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Add a new work item to the queue.
|
|
102
|
+
* Returns the created WorkItem.
|
|
103
|
+
*/
|
|
104
|
+
function enqueue(params) {
|
|
105
|
+
const item = {
|
|
106
|
+
id: randomUUID(),
|
|
107
|
+
type: params.type,
|
|
108
|
+
priority: params.priority ?? 3,
|
|
109
|
+
payload: params.payload,
|
|
110
|
+
status: "pending",
|
|
111
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
112
|
+
attempts: 0,
|
|
113
|
+
maxAttempts: params.maxAttempts ?? 3
|
|
114
|
+
};
|
|
115
|
+
_queue.push(item);
|
|
116
|
+
enforceMaxSize();
|
|
117
|
+
_dirty = true;
|
|
118
|
+
saveIfDirty();
|
|
119
|
+
process.stderr.write(`[work-queue] Enqueued ${item.type} (id=${item.id}, priority=${item.priority}).\n`);
|
|
120
|
+
return item;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Pick the next pending item that is ready to process (respects nextRetryAt).
|
|
124
|
+
* Returns null if no eligible item exists.
|
|
125
|
+
* Highest priority (lowest number) is processed first; ties broken by createdAt.
|
|
126
|
+
*/
|
|
127
|
+
function dequeue() {
|
|
128
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
129
|
+
const eligible = _queue.filter((i) => {
|
|
130
|
+
if (i.status !== "pending") return false;
|
|
131
|
+
if (i.nextRetryAt && i.nextRetryAt > now) return false;
|
|
132
|
+
return true;
|
|
133
|
+
}).sort((a, b) => {
|
|
134
|
+
if (a.priority !== b.priority) return a.priority - b.priority;
|
|
135
|
+
return a.createdAt.localeCompare(b.createdAt);
|
|
136
|
+
});
|
|
137
|
+
if (eligible.length === 0) return null;
|
|
138
|
+
const item = eligible[0];
|
|
139
|
+
item.status = "processing";
|
|
140
|
+
item.attempts += 1;
|
|
141
|
+
_dirty = true;
|
|
142
|
+
saveIfDirty();
|
|
143
|
+
return item;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Mark an item as completed.
|
|
147
|
+
*/
|
|
148
|
+
function markCompleted(id) {
|
|
149
|
+
const item = _queue.find((i) => i.id === id);
|
|
150
|
+
if (!item) return;
|
|
151
|
+
item.status = "completed";
|
|
152
|
+
item.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
153
|
+
item.error = void 0;
|
|
154
|
+
_dirty = true;
|
|
155
|
+
saveIfDirty();
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Mark an item as failed.
|
|
159
|
+
* If attempts < maxAttempts, schedules a retry with exponential backoff.
|
|
160
|
+
* Otherwise, leaves status as 'failed'.
|
|
161
|
+
*/
|
|
162
|
+
function markFailed(id, errorMsg) {
|
|
163
|
+
const item = _queue.find((i) => i.id === id);
|
|
164
|
+
if (!item) return;
|
|
165
|
+
item.error = errorMsg;
|
|
166
|
+
if (item.attempts < item.maxAttempts) {
|
|
167
|
+
const backoffMs = BACKOFF_MS[item.attempts - 1] ?? BACKOFF_MS[BACKOFF_MS.length - 1];
|
|
168
|
+
item.status = "pending";
|
|
169
|
+
item.nextRetryAt = new Date(Date.now() + backoffMs).toISOString();
|
|
170
|
+
process.stderr.write(`[work-queue] Item ${id} failed (attempt ${item.attempts}/${item.maxAttempts}), retry in ${backoffMs / 1e3}s: ${errorMsg}\n`);
|
|
171
|
+
} else {
|
|
172
|
+
item.status = "failed";
|
|
173
|
+
process.stderr.write(`[work-queue] Item ${id} exhausted retries (${item.maxAttempts} attempts): ${errorMsg}\n`);
|
|
174
|
+
}
|
|
175
|
+
_dirty = true;
|
|
176
|
+
saveIfDirty();
|
|
177
|
+
}
|
|
178
|
+
function getStats() {
|
|
179
|
+
const stats = {
|
|
180
|
+
pending: 0,
|
|
181
|
+
processing: 0,
|
|
182
|
+
completed: 0,
|
|
183
|
+
failed: 0,
|
|
184
|
+
total: _queue.length
|
|
185
|
+
};
|
|
186
|
+
for (const item of _queue) stats[item.status]++;
|
|
187
|
+
return stats;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Returns true if any pending or processing item of the given type exists.
|
|
191
|
+
* Used for debouncing work items that are expensive to run concurrently.
|
|
192
|
+
*/
|
|
193
|
+
function hasPendingOrProcessingOfType(type) {
|
|
194
|
+
return _queue.some((i) => i.type === type && (i.status === "pending" || i.status === "processing"));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Remove completed and permanently-failed items older than their TTL.
|
|
198
|
+
* Also force-cleans all completed items if the queue file exceeds 1 MB.
|
|
199
|
+
*/
|
|
200
|
+
function cleanup() {
|
|
201
|
+
const now = Date.now();
|
|
202
|
+
const before = _queue.length;
|
|
203
|
+
let forceCleanCompleted = false;
|
|
204
|
+
try {
|
|
205
|
+
if (existsSync(QUEUE_FILE)) {
|
|
206
|
+
const { size } = statSync(QUEUE_FILE);
|
|
207
|
+
if (size > MAX_QUEUE_FILE_BYTES) {
|
|
208
|
+
forceCleanCompleted = true;
|
|
209
|
+
process.stderr.write(`[work-queue] Queue file exceeds 1 MB (${size} bytes) — force-cleaning completed items.\n`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
} catch {}
|
|
213
|
+
_queue = _queue.filter((item) => {
|
|
214
|
+
if (item.status === "completed") {
|
|
215
|
+
if (forceCleanCompleted) return false;
|
|
216
|
+
return now - (item.completedAt ? new Date(item.completedAt).getTime() : 0) < COMPLETED_TTL_MS;
|
|
217
|
+
}
|
|
218
|
+
if (item.status === "failed") return now - new Date(item.createdAt).getTime() < FAILED_TTL_MS;
|
|
219
|
+
return true;
|
|
220
|
+
});
|
|
221
|
+
const removed = before - _queue.length;
|
|
222
|
+
const stats = getStats();
|
|
223
|
+
if (removed > 0 || before === 0) process.stderr.write(`[work-queue] Cleanup: removed ${removed} items. Queue stats: pending=${stats.pending}, processing=${stats.processing}, completed=${stats.completed}, failed=${stats.failed}.\n`);
|
|
224
|
+
_dirty = removed > 0;
|
|
225
|
+
saveIfDirty();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region src/hooks/ts/lib/pai-paths.ts
|
|
230
|
+
/**
|
|
231
|
+
* PAI Path Resolution - Single Source of Truth
|
|
232
|
+
*
|
|
233
|
+
* This module provides consistent path resolution across all PAI hooks.
|
|
234
|
+
* It handles PAI_DIR detection whether set explicitly or defaulting to ~/.claude
|
|
235
|
+
*
|
|
236
|
+
* ALSO loads .env file from PAI_DIR so all hooks get environment variables
|
|
237
|
+
* without relying on Claude Code's settings.json injection.
|
|
238
|
+
*
|
|
239
|
+
* Usage in hooks:
|
|
240
|
+
* import { PAI_DIR, HOOKS_DIR, SKILLS_DIR } from './lib/pai-paths';
|
|
241
|
+
*/
|
|
242
|
+
/**
|
|
243
|
+
* Load .env file and inject into process.env
|
|
244
|
+
* Must run BEFORE PAI_DIR resolution so .env can set PAI_DIR if needed
|
|
245
|
+
*/
|
|
246
|
+
function loadEnvFile() {
|
|
247
|
+
const possiblePaths = [resolve$1(process.env.PAI_DIR || "", ".env"), resolve$1(homedir$1(), ".claude", ".env")];
|
|
248
|
+
for (const envPath of possiblePaths) if (existsSync$1(envPath)) try {
|
|
249
|
+
const content = readFileSync$1(envPath, "utf-8");
|
|
250
|
+
for (const line of content.split("\n")) {
|
|
251
|
+
const trimmed = line.trim();
|
|
252
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
253
|
+
const eqIndex = trimmed.indexOf("=");
|
|
254
|
+
if (eqIndex > 0) {
|
|
255
|
+
const key = trimmed.substring(0, eqIndex).trim();
|
|
256
|
+
let value = trimmed.substring(eqIndex + 1).trim();
|
|
257
|
+
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
258
|
+
value = value.replace(/\$HOME/g, homedir$1());
|
|
259
|
+
value = value.replace(/^~(?=\/|$)/, homedir$1());
|
|
260
|
+
if (process.env[key] === void 0) process.env[key] = value;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
break;
|
|
264
|
+
} catch {}
|
|
265
|
+
}
|
|
266
|
+
loadEnvFile();
|
|
267
|
+
/**
|
|
268
|
+
* Smart PAI_DIR detection with fallback
|
|
269
|
+
* Priority:
|
|
270
|
+
* 1. PAI_DIR environment variable (if set)
|
|
271
|
+
* 2. ~/.claude (standard location)
|
|
272
|
+
*/
|
|
273
|
+
const PAI_DIR = process.env.PAI_DIR ? resolve$1(process.env.PAI_DIR) : resolve$1(homedir$1(), ".claude");
|
|
274
|
+
/**
|
|
275
|
+
* Common PAI directories
|
|
276
|
+
*/
|
|
277
|
+
const HOOKS_DIR = join$1(PAI_DIR, "Hooks");
|
|
278
|
+
const SKILLS_DIR = join$1(PAI_DIR, "Skills");
|
|
279
|
+
const AGENTS_DIR = join$1(PAI_DIR, "Agents");
|
|
280
|
+
const HISTORY_DIR = join$1(PAI_DIR, "History");
|
|
281
|
+
const COMMANDS_DIR = join$1(PAI_DIR, "Commands");
|
|
282
|
+
/**
|
|
283
|
+
* Validate PAI directory structure on first import
|
|
284
|
+
* This fails fast with a clear error if PAI is misconfigured
|
|
285
|
+
*/
|
|
286
|
+
function validatePAIStructure() {
|
|
287
|
+
if (!existsSync$1(PAI_DIR)) {
|
|
288
|
+
console.error(`PAI_DIR does not exist: ${PAI_DIR}`);
|
|
289
|
+
console.error(` Expected ~/.claude or set PAI_DIR environment variable`);
|
|
290
|
+
process.exit(1);
|
|
291
|
+
}
|
|
292
|
+
if (!existsSync$1(HOOKS_DIR)) {
|
|
293
|
+
console.error(`PAI hooks directory not found: ${HOOKS_DIR}`);
|
|
294
|
+
console.error(` Your PAI_DIR may be misconfigured`);
|
|
295
|
+
console.error(` Current PAI_DIR: ${PAI_DIR}`);
|
|
296
|
+
process.exit(1);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
validatePAIStructure();
|
|
300
|
+
|
|
301
|
+
//#endregion
|
|
302
|
+
//#region src/hooks/ts/lib/project-utils/paths.ts
|
|
303
|
+
/**
|
|
304
|
+
* Path utilities — encoding, Notes/Sessions directory discovery and creation.
|
|
305
|
+
*/
|
|
306
|
+
const PROJECTS_DIR = join$1(PAI_DIR, "projects");
|
|
307
|
+
/**
|
|
308
|
+
* Encode a path the same way Claude Code does:
|
|
309
|
+
* - Replace / with -
|
|
310
|
+
* - Replace . with -
|
|
311
|
+
* - Replace space with -
|
|
312
|
+
*/
|
|
313
|
+
function encodePath(path) {
|
|
314
|
+
return path.replace(/\//g, "-").replace(/\./g, "-").replace(/ /g, "-");
|
|
315
|
+
}
|
|
316
|
+
/** Get the project directory for a given working directory. */
|
|
317
|
+
function getProjectDir(cwd) {
|
|
318
|
+
return join$1(PROJECTS_DIR, encodePath(cwd));
|
|
319
|
+
}
|
|
320
|
+
/** Get the Notes directory for a project (central location). */
|
|
321
|
+
function getNotesDir(cwd) {
|
|
322
|
+
return join$1(getProjectDir(cwd), "Notes");
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Find Notes directory — checks local first, falls back to central.
|
|
326
|
+
* Does NOT create the directory.
|
|
327
|
+
*/
|
|
328
|
+
function findNotesDir(cwd) {
|
|
329
|
+
if (basename$1(cwd).toLowerCase() === "notes" && existsSync$1(cwd)) return {
|
|
330
|
+
path: cwd,
|
|
331
|
+
isLocal: true
|
|
332
|
+
};
|
|
333
|
+
const localPaths = [
|
|
334
|
+
join$1(cwd, "Notes"),
|
|
335
|
+
join$1(cwd, "notes"),
|
|
336
|
+
join$1(cwd, ".claude", "Notes")
|
|
337
|
+
];
|
|
338
|
+
for (const path of localPaths) if (existsSync$1(path)) return {
|
|
339
|
+
path,
|
|
340
|
+
isLocal: true
|
|
341
|
+
};
|
|
342
|
+
return {
|
|
343
|
+
path: getNotesDir(cwd),
|
|
344
|
+
isLocal: false
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/** Get the sessions/ directory from a project directory path. */
|
|
348
|
+
function getSessionsDirFromProjectDir(projectDir) {
|
|
349
|
+
return join$1(projectDir, "sessions");
|
|
350
|
+
}
|
|
351
|
+
/** Ensure the sessions/ directory exists (from project dir path). */
|
|
352
|
+
function ensureSessionsDirFromProjectDir(projectDir) {
|
|
353
|
+
const sessionsDir = getSessionsDirFromProjectDir(projectDir);
|
|
354
|
+
if (!existsSync$1(sessionsDir)) {
|
|
355
|
+
mkdirSync$1(sessionsDir, { recursive: true });
|
|
356
|
+
console.error(`Created sessions directory: ${sessionsDir}`);
|
|
357
|
+
}
|
|
358
|
+
return sessionsDir;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Move all .jsonl session files from project root to sessions/ subdirectory.
|
|
362
|
+
* Returns the number of files moved.
|
|
363
|
+
*/
|
|
364
|
+
function moveSessionFilesToSessionsDir(projectDir, excludeFile, silent = false) {
|
|
365
|
+
const sessionsDir = ensureSessionsDirFromProjectDir(projectDir);
|
|
366
|
+
if (!existsSync$1(projectDir)) return 0;
|
|
367
|
+
const files = readdirSync$1(projectDir);
|
|
368
|
+
let movedCount = 0;
|
|
369
|
+
for (const file of files) if (file.endsWith(".jsonl") && file !== excludeFile) {
|
|
370
|
+
const sourcePath = join$1(projectDir, file);
|
|
371
|
+
const destPath = join$1(sessionsDir, file);
|
|
372
|
+
try {
|
|
373
|
+
renameSync$1(sourcePath, destPath);
|
|
374
|
+
if (!silent) console.error(`Moved ${file} → sessions/`);
|
|
375
|
+
movedCount++;
|
|
376
|
+
} catch (error) {
|
|
377
|
+
if (!silent) console.error(`Could not move ${file}: ${error}`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return movedCount;
|
|
381
|
+
}
|
|
382
|
+
/** Find TODO.md — check local first, fallback to central. */
|
|
383
|
+
function findTodoPath(cwd) {
|
|
384
|
+
const localPaths = [
|
|
385
|
+
join$1(cwd, "TODO.md"),
|
|
386
|
+
join$1(cwd, "notes", "TODO.md"),
|
|
387
|
+
join$1(cwd, "Notes", "TODO.md"),
|
|
388
|
+
join$1(cwd, ".claude", "TODO.md")
|
|
389
|
+
];
|
|
390
|
+
for (const path of localPaths) if (existsSync$1(path)) return path;
|
|
391
|
+
return join$1(getNotesDir(cwd), "TODO.md");
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
//#endregion
|
|
395
|
+
//#region src/hooks/ts/lib/project-utils/session-notes.ts
|
|
396
|
+
/**
|
|
397
|
+
* Session note creation, editing, checkpointing, renaming, and finalization.
|
|
398
|
+
*/
|
|
399
|
+
/** Get or create the YYYY/MM subdirectory for the current month inside notesDir. */
|
|
400
|
+
function getMonthDir(notesDir) {
|
|
401
|
+
const now = /* @__PURE__ */ new Date();
|
|
402
|
+
const monthDir = join$1(notesDir, String(now.getFullYear()), String(now.getMonth() + 1).padStart(2, "0"));
|
|
403
|
+
if (!existsSync$1(monthDir)) mkdirSync$1(monthDir, { recursive: true });
|
|
404
|
+
return monthDir;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Get the next note number (4-digit format: 0001, 0002, etc.).
|
|
408
|
+
* Numbers are scoped per YYYY/MM directory.
|
|
409
|
+
*/
|
|
410
|
+
function getNextNoteNumber(notesDir) {
|
|
411
|
+
const files = readdirSync$1(getMonthDir(notesDir)).filter((f) => f.match(/^\d{3,4}[\s_-]/)).sort();
|
|
412
|
+
if (files.length === 0) return "0001";
|
|
413
|
+
let maxNumber = 0;
|
|
414
|
+
for (const file of files) {
|
|
415
|
+
const digitMatch = file.match(/^(\d+)/);
|
|
416
|
+
if (digitMatch) {
|
|
417
|
+
const num = parseInt(digitMatch[1], 10);
|
|
418
|
+
if (num > maxNumber) maxNumber = num;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return String(maxNumber + 1).padStart(4, "0");
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Get the current (latest) note file path, or null if none exists.
|
|
425
|
+
* Searches current month → previous month → flat notesDir (legacy).
|
|
426
|
+
*/
|
|
427
|
+
function getCurrentNotePath(notesDir) {
|
|
428
|
+
if (!existsSync$1(notesDir)) return null;
|
|
429
|
+
const findLatestIn = (dir) => {
|
|
430
|
+
if (!existsSync$1(dir)) return null;
|
|
431
|
+
const files = readdirSync$1(dir).filter((f) => f.match(/^\d{3,4}[\s_-].*\.md$/)).sort((a, b) => {
|
|
432
|
+
return parseInt(a.match(/^(\d+)/)?.[1] || "0", 10) - parseInt(b.match(/^(\d+)/)?.[1] || "0", 10);
|
|
433
|
+
});
|
|
434
|
+
if (files.length === 0) return null;
|
|
435
|
+
return join$1(dir, files[files.length - 1]);
|
|
436
|
+
};
|
|
437
|
+
const now = /* @__PURE__ */ new Date();
|
|
438
|
+
const found = findLatestIn(join$1(notesDir, String(now.getFullYear()), String(now.getMonth() + 1).padStart(2, "0")));
|
|
439
|
+
if (found) return found;
|
|
440
|
+
const prevDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
|
441
|
+
const prevFound = findLatestIn(join$1(notesDir, String(prevDate.getFullYear()), String(prevDate.getMonth() + 1).padStart(2, "0")));
|
|
442
|
+
if (prevFound) return prevFound;
|
|
443
|
+
return findLatestIn(notesDir);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Create a new session note.
|
|
447
|
+
* Format: "NNNN - YYYY-MM-DD - New Session.md" filed into YYYY/MM subdirectory.
|
|
448
|
+
* Claude MUST rename at session end with a meaningful description.
|
|
449
|
+
*/
|
|
450
|
+
function createSessionNote(notesDir, description) {
|
|
451
|
+
const noteNumber = getNextNoteNumber(notesDir);
|
|
452
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
453
|
+
const monthDir = getMonthDir(notesDir);
|
|
454
|
+
const filename = `${noteNumber} - ${date} - New Session.md`;
|
|
455
|
+
const filepath = join$1(monthDir, filename);
|
|
456
|
+
writeFileSync$1(filepath, `# Session ${noteNumber}: ${description}
|
|
457
|
+
|
|
458
|
+
**Date:** ${date}
|
|
459
|
+
**Status:** In Progress
|
|
460
|
+
|
|
461
|
+
---
|
|
462
|
+
|
|
463
|
+
## Work Done
|
|
464
|
+
|
|
465
|
+
<!-- PAI will add completed work here during session -->
|
|
466
|
+
|
|
467
|
+
---
|
|
468
|
+
|
|
469
|
+
## Next Steps
|
|
470
|
+
|
|
471
|
+
<!-- To be filled at session end -->
|
|
472
|
+
|
|
473
|
+
---
|
|
474
|
+
|
|
475
|
+
**Tags:** #Session
|
|
476
|
+
`);
|
|
477
|
+
console.error(`Created session note: ${filename}`);
|
|
478
|
+
return filepath;
|
|
479
|
+
}
|
|
480
|
+
/** Append a checkpoint to the current session note. */
|
|
481
|
+
function appendCheckpoint(notePath, checkpoint) {
|
|
482
|
+
if (!existsSync$1(notePath)) {
|
|
483
|
+
console.error(`Note file not found, recreating: ${notePath}`);
|
|
484
|
+
try {
|
|
485
|
+
const parentDir = join$1(notePath, "..");
|
|
486
|
+
if (!existsSync$1(parentDir)) mkdirSync$1(parentDir, { recursive: true });
|
|
487
|
+
const noteFilename = basename$1(notePath);
|
|
488
|
+
const numberMatch = noteFilename.match(/^(\d+)/);
|
|
489
|
+
writeFileSync$1(notePath, `# Session ${numberMatch ? numberMatch[1] : "0000"}: Recovered\n\n**Date:** ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}\n**Status:** In Progress\n\n---\n\n## Work Done\n\n<!-- PAI will add completed work here during session -->\n\n---\n\n## Next Steps\n\n<!-- To be filled at session end -->\n\n---\n\n**Tags:** #Session\n`);
|
|
490
|
+
console.error(`Recreated session note: ${noteFilename}`);
|
|
491
|
+
} catch (err) {
|
|
492
|
+
console.error(`Failed to recreate note: ${err}`);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const content = readFileSync$1(notePath, "utf-8");
|
|
497
|
+
const checkpointText = `\n### Checkpoint ${(/* @__PURE__ */ new Date()).toISOString()}\n\n${checkpoint}\n`;
|
|
498
|
+
const nextStepsIndex = content.indexOf("## Next Steps");
|
|
499
|
+
writeFileSync$1(notePath, nextStepsIndex !== -1 ? content.substring(0, nextStepsIndex) + checkpointText + content.substring(nextStepsIndex) : content + checkpointText);
|
|
500
|
+
console.error(`Checkpoint added to: ${basename$1(notePath)}`);
|
|
501
|
+
}
|
|
502
|
+
/** Add work items to the "Work Done" section of a session note. */
|
|
503
|
+
function addWorkToSessionNote(notePath, workItems, sectionTitle) {
|
|
504
|
+
if (!existsSync$1(notePath)) {
|
|
505
|
+
console.error(`Note file not found: ${notePath}`);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
let content = readFileSync$1(notePath, "utf-8");
|
|
509
|
+
let workText = "";
|
|
510
|
+
if (sectionTitle) workText += `\n### ${sectionTitle}\n\n`;
|
|
511
|
+
for (const item of workItems) {
|
|
512
|
+
const checkbox = item.completed !== false ? "[x]" : "[ ]";
|
|
513
|
+
workText += `- ${checkbox} **${item.title}**\n`;
|
|
514
|
+
if (item.details && item.details.length > 0) for (const detail of item.details) workText += ` - ${detail}\n`;
|
|
515
|
+
}
|
|
516
|
+
const workDoneMatch = content.match(/## Work Done\n\n(<!-- .*? -->)?/);
|
|
517
|
+
if (workDoneMatch) {
|
|
518
|
+
const insertPoint = content.indexOf(workDoneMatch[0]) + workDoneMatch[0].length;
|
|
519
|
+
content = content.substring(0, insertPoint) + workText + content.substring(insertPoint);
|
|
520
|
+
} else {
|
|
521
|
+
const nextStepsIndex = content.indexOf("## Next Steps");
|
|
522
|
+
if (nextStepsIndex !== -1) content = content.substring(0, nextStepsIndex) + workText + "\n" + content.substring(nextStepsIndex);
|
|
523
|
+
}
|
|
524
|
+
writeFileSync$1(notePath, content);
|
|
525
|
+
console.error(`Added ${workItems.length} work item(s) to: ${basename$1(notePath)}`);
|
|
526
|
+
}
|
|
527
|
+
/** Sanitize a string for use in a filename. */
|
|
528
|
+
function sanitizeForFilename(str) {
|
|
529
|
+
return str.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").substring(0, 50);
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Return true if the candidate string should be rejected as a meaningful name.
|
|
533
|
+
* Rejects file paths, shebangs, timestamps, system noise, XML tags, hashes, etc.
|
|
534
|
+
*/
|
|
535
|
+
function isMeaninglessCandidate(text) {
|
|
536
|
+
const t = text.trim();
|
|
537
|
+
if (!t) return true;
|
|
538
|
+
if (t.length < 5) return true;
|
|
539
|
+
if (t.startsWith("/") || t.startsWith("~")) return true;
|
|
540
|
+
if (t.startsWith("#!")) return true;
|
|
541
|
+
if (t.includes("[object Object]")) return true;
|
|
542
|
+
if (/^\d{4}-\d{2}-\d{2}(T[\d:.Z+-]+)?$/.test(t)) return true;
|
|
543
|
+
if (/^\d{1,2}:\d{2}(:\d{2})?(\s*(AM|PM))?$/i.test(t)) return true;
|
|
544
|
+
if (/^<[a-z-]+[\s/>]/i.test(t)) return true;
|
|
545
|
+
if (/^[0-9a-f]{10,}$/i.test(t)) return true;
|
|
546
|
+
if (/^Exit code \d+/i.test(t)) return true;
|
|
547
|
+
if (/^Error:/i.test(t)) return true;
|
|
548
|
+
if (/^This session is being continued/i.test(t)) return true;
|
|
549
|
+
if (/^\(Bash completed/i.test(t)) return true;
|
|
550
|
+
if (/^Task Notification$/i.test(t)) return true;
|
|
551
|
+
if (/^New Session$/i.test(t)) return true;
|
|
552
|
+
if (/^Recovered Session$/i.test(t)) return true;
|
|
553
|
+
if (/^Continued Session$/i.test(t)) return true;
|
|
554
|
+
if (/^Untitled Session$/i.test(t)) return true;
|
|
555
|
+
if (/^Context Compression$/i.test(t)) return true;
|
|
556
|
+
if (/^[A-Fa-f0-9]{8,}\s+Output$/i.test(t)) return true;
|
|
557
|
+
return false;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Extract a meaningful name from session note content and summary.
|
|
561
|
+
* Looks at Work Done section headers, bold text, and summary.
|
|
562
|
+
*/
|
|
563
|
+
function extractMeaningfulName(noteContent, summary) {
|
|
564
|
+
const workDoneMatch = noteContent.match(/## Work Done\n\n([\s\S]*?)(?=\n---|\n## Next)/);
|
|
565
|
+
if (workDoneMatch) {
|
|
566
|
+
const workDoneSection = workDoneMatch[1];
|
|
567
|
+
const subheadings = workDoneSection.match(/### ([^\n]+)/g);
|
|
568
|
+
if (subheadings && subheadings.length > 0) {
|
|
569
|
+
const firstHeading = subheadings[0].replace("### ", "").trim();
|
|
570
|
+
if (!isMeaninglessCandidate(firstHeading) && firstHeading.length > 5 && firstHeading.length < 60) return sanitizeForFilename(firstHeading);
|
|
571
|
+
}
|
|
572
|
+
const boldMatches = workDoneSection.match(/\*\*([^*]+)\*\*/g);
|
|
573
|
+
if (boldMatches && boldMatches.length > 0) {
|
|
574
|
+
const firstBold = boldMatches[0].replace(/\*\*/g, "").trim();
|
|
575
|
+
if (!isMeaninglessCandidate(firstBold) && firstBold.length > 3 && firstBold.length < 50) return sanitizeForFilename(firstBold);
|
|
576
|
+
}
|
|
577
|
+
const numberedItems = workDoneSection.match(/^\d+\.\s+\*\*([^*]+)\*\*/m);
|
|
578
|
+
if (numberedItems && !isMeaninglessCandidate(numberedItems[1])) return sanitizeForFilename(numberedItems[1]);
|
|
579
|
+
}
|
|
580
|
+
if (summary && summary.length > 5 && summary !== "Session completed." && !isMeaninglessCandidate(summary)) {
|
|
581
|
+
const cleanSummary = summary.replace(/[^\w\s-]/g, " ").trim().split(/\s+/).slice(0, 5).join(" ");
|
|
582
|
+
if (cleanSummary.length > 3 && !isMeaninglessCandidate(cleanSummary)) return sanitizeForFilename(cleanSummary);
|
|
583
|
+
}
|
|
584
|
+
return "";
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Rename a session note with a meaningful name.
|
|
588
|
+
* Always uses "NNNN - YYYY-MM-DD - Description.md" format.
|
|
589
|
+
* Returns the new path, or original path if rename fails.
|
|
590
|
+
*/
|
|
591
|
+
function renameSessionNote(notePath, meaningfulName) {
|
|
592
|
+
if (!meaningfulName || !existsSync$1(notePath)) return notePath;
|
|
593
|
+
const dir = join$1(notePath, "..");
|
|
594
|
+
const oldFilename = basename$1(notePath);
|
|
595
|
+
const correctMatch = oldFilename.match(/^(\d{3,4}) - (\d{4}-\d{2}-\d{2}) - .*\.md$/);
|
|
596
|
+
const legacyMatch = oldFilename.match(/^(\d{3,4})_(\d{4}-\d{2}-\d{2})_.*\.md$/);
|
|
597
|
+
const match = correctMatch || legacyMatch;
|
|
598
|
+
if (!match) return notePath;
|
|
599
|
+
const [, noteNumber, date] = match;
|
|
600
|
+
const titleCaseName = meaningfulName.split(/[\s_-]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ").trim();
|
|
601
|
+
const newFilename = `${noteNumber.padStart(4, "0")} - ${date} - ${titleCaseName}.md`;
|
|
602
|
+
const newPath = join$1(dir, newFilename);
|
|
603
|
+
if (newFilename === oldFilename) return notePath;
|
|
604
|
+
try {
|
|
605
|
+
renameSync$1(notePath, newPath);
|
|
606
|
+
console.error(`Renamed note: ${oldFilename} → ${newFilename}`);
|
|
607
|
+
return newPath;
|
|
608
|
+
} catch (error) {
|
|
609
|
+
console.error(`Could not rename note: ${error}`);
|
|
610
|
+
return notePath;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Finalize session note — mark as complete, add summary, rename with meaningful name.
|
|
615
|
+
* IDEMPOTENT: subsequent calls are no-ops if already finalized.
|
|
616
|
+
* Returns the final path (may be renamed).
|
|
617
|
+
*/
|
|
618
|
+
function finalizeSessionNote(notePath, summary) {
|
|
619
|
+
if (!existsSync$1(notePath)) {
|
|
620
|
+
console.error(`Note file not found: ${notePath}`);
|
|
621
|
+
return notePath;
|
|
622
|
+
}
|
|
623
|
+
let content = readFileSync$1(notePath, "utf-8");
|
|
624
|
+
if (content.includes("**Status:** Completed")) {
|
|
625
|
+
console.error(`Note already finalized: ${basename$1(notePath)}`);
|
|
626
|
+
return notePath;
|
|
627
|
+
}
|
|
628
|
+
content = content.replace("**Status:** In Progress", "**Status:** Completed");
|
|
629
|
+
if (!content.includes("**Completed:**")) {
|
|
630
|
+
const completionTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
631
|
+
content = content.replace("---\n\n## Work Done", `**Completed:** ${completionTime}\n\n---\n\n## Work Done`);
|
|
632
|
+
}
|
|
633
|
+
const nextStepsMatch = content.match(/## Next Steps\n\n(<!-- .*? -->)/);
|
|
634
|
+
if (nextStepsMatch) content = content.replace(nextStepsMatch[0], `## Next Steps\n\n${summary || "Session completed."}`);
|
|
635
|
+
writeFileSync$1(notePath, content);
|
|
636
|
+
console.error(`Session note finalized: ${basename$1(notePath)}`);
|
|
637
|
+
const meaningfulName = extractMeaningfulName(content, summary);
|
|
638
|
+
if (meaningfulName) return renameSessionNote(notePath, meaningfulName);
|
|
639
|
+
return notePath;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
//#endregion
|
|
643
|
+
//#region src/hooks/ts/lib/project-utils/todo.ts
|
|
644
|
+
/**
|
|
645
|
+
* TODO.md management — creation, task updates, checkpoints, and Continue section.
|
|
646
|
+
*/
|
|
647
|
+
/**
|
|
648
|
+
* Ensure TODO.md exists. Creates it with default structure if missing.
|
|
649
|
+
* Returns the path to the TODO.md file.
|
|
650
|
+
*/
|
|
651
|
+
function ensureTodoMd(cwd) {
|
|
652
|
+
const todoPath = findTodoPath(cwd);
|
|
653
|
+
if (!existsSync$1(todoPath)) {
|
|
654
|
+
const parentDir = join$1(todoPath, "..");
|
|
655
|
+
if (!existsSync$1(parentDir)) mkdirSync$1(parentDir, { recursive: true });
|
|
656
|
+
writeFileSync$1(todoPath, `# TODO
|
|
657
|
+
|
|
658
|
+
## Current Session
|
|
659
|
+
|
|
660
|
+
- [ ] (Tasks will be tracked here)
|
|
661
|
+
|
|
662
|
+
## Backlog
|
|
663
|
+
|
|
664
|
+
- [ ] (Future tasks)
|
|
665
|
+
|
|
666
|
+
---
|
|
667
|
+
|
|
668
|
+
*Last updated: ${(/* @__PURE__ */ new Date()).toISOString()}*
|
|
669
|
+
`);
|
|
670
|
+
console.error(`Created TODO.md: ${todoPath}`);
|
|
671
|
+
}
|
|
672
|
+
return todoPath;
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Update the ## Continue section at the top of TODO.md.
|
|
676
|
+
*
|
|
677
|
+
* This is the unattended writer: the pre-compact hook and the daemon's
|
|
678
|
+
* work-queue worker both come through here. It used to build its own block and
|
|
679
|
+
* strip the existing section with `/## Continue\n[\s\S]*?\n---\n+/` — a
|
|
680
|
+
* non-greedy match to the first `---`, which cuts a rich checkpoint in half at
|
|
681
|
+
* the first horizontal rule inside its body and leaves the remainder orphaned
|
|
682
|
+
* in the document.
|
|
683
|
+
*
|
|
684
|
+
* More importantly it was the writer that actually destroyed model-authored
|
|
685
|
+
* checkpoints: `pai pause` wrote one, then this ran seconds later on session
|
|
686
|
+
* end and replaced it with `Working directory: … Check the latest session note
|
|
687
|
+
* for details.`
|
|
688
|
+
*
|
|
689
|
+
* It now delegates to the shared checkpoint module in "auto" mode, which means
|
|
690
|
+
* it inherits the preservation rules rather than reimplementing them. Guarding
|
|
691
|
+
* here rather than at each of the three call sites is deliberate: any future
|
|
692
|
+
* caller inherits the behaviour without knowing it exists.
|
|
693
|
+
*/
|
|
694
|
+
function updateTodoContinue(cwd, noteFilename, state, tokenDisplay) {
|
|
695
|
+
ensureTodoMd(cwd);
|
|
696
|
+
const result = applyContinue({
|
|
697
|
+
rootPath: cwd,
|
|
698
|
+
authored: "auto",
|
|
699
|
+
sessionLine: noteFilename.replace(/\.md$/, ""),
|
|
700
|
+
cwd,
|
|
701
|
+
body: state?.trim() || void 0
|
|
702
|
+
});
|
|
703
|
+
if (result.action === "preserved") {
|
|
704
|
+
console.error("TODO.md ## Continue left intact — authored checkpoint for this session");
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
if (result.action === "failed") {
|
|
708
|
+
console.error(`TODO.md ## Continue update failed: ${result.error}`);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
try {
|
|
712
|
+
const todoPath = result.path;
|
|
713
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
714
|
+
let content = readFileSync$1(todoPath, "utf-8");
|
|
715
|
+
content = content.replace(/(\n---\s*)*(\n\*Last updated:.*\*\s*)+$/g, "");
|
|
716
|
+
content = content.trimEnd() + `\n\n---\n\n*Last updated: ${now}*\n`;
|
|
717
|
+
writeFileSync$1(todoPath, content);
|
|
718
|
+
} catch {}
|
|
719
|
+
console.error(result.carriedForward ? "TODO.md ## Continue section updated (previous content carried forward)" : "TODO.md ## Continue section updated");
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
//#endregion
|
|
723
|
+
//#region src/daemon/templates/session-summary-prompt.ts
|
|
724
|
+
/**
|
|
725
|
+
* Build the prompt string to send to the summarizer model.
|
|
726
|
+
*
|
|
727
|
+
* Returns a single string suitable for piping to `claude --model <model> --print`.
|
|
728
|
+
*/
|
|
729
|
+
function buildSessionSummaryPrompt(params) {
|
|
730
|
+
const { userMessages, gitLog, cwd, date, filesModified, existingNote } = params;
|
|
731
|
+
const userSection = userMessages.length > 0 ? userMessages.map((m, i) => `[${i + 1}] ${m}`).join("\n\n") : "(No user messages extracted)";
|
|
732
|
+
const gitSection = gitLog.trim() || "(No git commits during this session)";
|
|
733
|
+
const filesSection = filesModified && filesModified.length > 0 ? filesModified.map((f) => `- ${f}`).join("\n") : "";
|
|
734
|
+
return `You are summarizing a coding session. Given the user messages and git commits below, write a session note.
|
|
735
|
+
|
|
736
|
+
Project directory: ${cwd}
|
|
737
|
+
Date: ${date}
|
|
738
|
+
|
|
739
|
+
Focus on:
|
|
740
|
+
- What problems were encountered and how they were solved
|
|
741
|
+
- Key architectural decisions and their rationale
|
|
742
|
+
- What was built (reference actual files and code patterns)
|
|
743
|
+
- What was left unfinished or needs follow-up
|
|
744
|
+
|
|
745
|
+
Do NOT include:
|
|
746
|
+
- Mechanical metadata (token counts, checkpoint timestamps)
|
|
747
|
+
- System messages or tool results verbatim
|
|
748
|
+
- Generic descriptions — be specific about what happened
|
|
749
|
+
- Markdown frontmatter or YAML headers
|
|
750
|
+
${existingNote ? `\nAn existing session note is provided below. Merge the new information into it,
|
|
751
|
+
preserving what was already written. Add new work items and update the summary.
|
|
752
|
+
Do NOT duplicate existing content.
|
|
753
|
+
|
|
754
|
+
EXISTING NOTE:
|
|
755
|
+
${existingNote}
|
|
756
|
+
` : ""}
|
|
757
|
+
Format your response EXACTLY as follows (no extra text before or after):
|
|
758
|
+
|
|
759
|
+
TOPIC: [A short topic label, max 60 characters, describing the WORK DONE — not quoting user messages. Format as "Topic1, Topic2, and Topic3" if multiple themes. Example: "Session Summary Worker, Topic Detection"]
|
|
760
|
+
|
|
761
|
+
# Session: [Descriptive title summarizing what was ACCOMPLISHED, max 60 characters. Describe the work done, not the user's request. Bad: "Dark Mode Button Does Nothing". Good: "Dark Mode Toggle, Keyboard IPC, and Audio Fix"]
|
|
762
|
+
|
|
763
|
+
**Date:** ${date}
|
|
764
|
+
**Status:** In Progress
|
|
765
|
+
|
|
766
|
+
---
|
|
767
|
+
|
|
768
|
+
## Work Done
|
|
769
|
+
|
|
770
|
+
[Organize by theme, not chronologically. Group related work under descriptive bullet points.
|
|
771
|
+
Use checkbox format: - [x] for completed items, - [ ] for incomplete items.
|
|
772
|
+
Include specific file names, function names, and technical details.]
|
|
773
|
+
|
|
774
|
+
## Key Decisions
|
|
775
|
+
|
|
776
|
+
[List important choices made during the session with brief rationale.
|
|
777
|
+
Skip this section entirely if no significant decisions were made.]
|
|
778
|
+
|
|
779
|
+
## Known Issues
|
|
780
|
+
|
|
781
|
+
[What was left unfinished, bugs discovered, or follow-up items needed.
|
|
782
|
+
Skip this section entirely if nothing is pending.]
|
|
783
|
+
|
|
784
|
+
---
|
|
785
|
+
|
|
786
|
+
USER MESSAGES:
|
|
787
|
+
${userSection}
|
|
788
|
+
|
|
789
|
+
GIT COMMITS:
|
|
790
|
+
${gitSection}
|
|
791
|
+
${filesSection ? `\nFILES MODIFIED:\n${filesSection}` : ""}`;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
//#endregion
|
|
795
|
+
//#region src/daemon/session-summary-worker.ts
|
|
796
|
+
/**
|
|
797
|
+
* session-summary-worker.ts — AI-powered session note generation
|
|
798
|
+
*
|
|
799
|
+
* Processes `session-summary` work items by:
|
|
800
|
+
* 1. Finding the current session's JSONL transcript
|
|
801
|
+
* 2. Extracting user messages and assistant context
|
|
802
|
+
* 3. Gathering git commits from the session period
|
|
803
|
+
* 4. Spawning Claude (sonnet for compaction, opus for session end) to generate a structured summary
|
|
804
|
+
* 5. Comparing the new topic against the existing note's topic
|
|
805
|
+
* 6. Creating a NEW note if the topic shifted, or updating the existing one
|
|
806
|
+
*
|
|
807
|
+
* Topic detection: the summarizer outputs a TOPIC: line as the first line of
|
|
808
|
+
* its response. This is compared against the existing note's title using word
|
|
809
|
+
* overlap. If overlap is below ~30%, a new note is created.
|
|
810
|
+
*
|
|
811
|
+
* Designed to run inside the daemon's work queue worker. All errors are
|
|
812
|
+
* thrown (not swallowed) so the work queue retry logic handles them.
|
|
813
|
+
*/
|
|
814
|
+
/** Minimum interval between summaries for the same project (ms). */
|
|
815
|
+
const SUMMARY_COOLDOWN_MS = 1800 * 1e3;
|
|
816
|
+
/** Maximum JSONL content to feed to the summarizer (characters). */
|
|
817
|
+
/** Max JSONL chars per model. Opus/Sonnet can handle much more than Haiku. */
|
|
818
|
+
const MAX_JSONL_CHARS = {
|
|
819
|
+
haiku: 5e4,
|
|
820
|
+
sonnet: 2e5,
|
|
821
|
+
opus: 5e5
|
|
822
|
+
};
|
|
823
|
+
/** Maximum user messages to include in the prompt. */
|
|
824
|
+
const MAX_USER_MESSAGES = 30;
|
|
825
|
+
/** Timeout for the claude CLI process (ms). */
|
|
826
|
+
const CLAUDE_TIMEOUT_MS = {
|
|
827
|
+
haiku: 6e4,
|
|
828
|
+
sonnet: 12e4,
|
|
829
|
+
opus: 3e5
|
|
830
|
+
};
|
|
831
|
+
/** File tracking last summary timestamps per project. */
|
|
832
|
+
const COOLDOWN_FILE = join(homedir(), ".config", "pai", "summary-cooldowns.json");
|
|
833
|
+
/** Claude Code projects directory. */
|
|
834
|
+
const CLAUDE_PROJECTS_DIR = join(homedir(), ".claude", "projects");
|
|
835
|
+
function loadCooldowns() {
|
|
836
|
+
try {
|
|
837
|
+
if (existsSync(COOLDOWN_FILE)) return JSON.parse(readFileSync(COOLDOWN_FILE, "utf-8"));
|
|
838
|
+
} catch {}
|
|
839
|
+
return {};
|
|
840
|
+
}
|
|
841
|
+
function saveCooldowns(cooldowns) {
|
|
842
|
+
try {
|
|
843
|
+
writeFileSync(COOLDOWN_FILE, JSON.stringify(cooldowns, null, 2), "utf-8");
|
|
844
|
+
} catch {}
|
|
845
|
+
}
|
|
846
|
+
function isOnCooldown(cwd) {
|
|
847
|
+
const lastRun = loadCooldowns()[cwd];
|
|
848
|
+
if (!lastRun) return false;
|
|
849
|
+
return Date.now() - lastRun < SUMMARY_COOLDOWN_MS;
|
|
850
|
+
}
|
|
851
|
+
function markCooldown(cwd) {
|
|
852
|
+
const cooldowns = loadCooldowns();
|
|
853
|
+
cooldowns[cwd] = Date.now();
|
|
854
|
+
const cutoff = Date.now() - 1440 * 60 * 1e3;
|
|
855
|
+
for (const key of Object.keys(cooldowns)) if (cooldowns[key] < cutoff) delete cooldowns[key];
|
|
856
|
+
saveCooldowns(cooldowns);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Encode a cwd path the same way Claude Code does for its project directories.
|
|
860
|
+
* Replaces /, space, dot, and hyphen with -.
|
|
861
|
+
*/
|
|
862
|
+
function encodeProjectPath(cwd) {
|
|
863
|
+
return cwd.replace(/[\/\s.\-]/g, "-");
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Find the most recently modified JSONL file for the given project.
|
|
867
|
+
*
|
|
868
|
+
* Claude Code stores transcripts in:
|
|
869
|
+
* ~/.claude/projects/<encoded-path>/sessions/*.jsonl
|
|
870
|
+
* ~/.claude/projects/<encoded-path>/<uuid>.jsonl (legacy)
|
|
871
|
+
*/
|
|
872
|
+
function findLatestJsonl(cwd) {
|
|
873
|
+
const projectDir = join(CLAUDE_PROJECTS_DIR, encodeProjectPath(cwd));
|
|
874
|
+
if (!existsSync(projectDir)) {
|
|
875
|
+
process.stderr.write(`[session-summary] No Claude project dir found: ${projectDir}\n`);
|
|
876
|
+
return null;
|
|
877
|
+
}
|
|
878
|
+
const candidates = [];
|
|
879
|
+
const sessionsDir = join(projectDir, "sessions");
|
|
880
|
+
if (existsSync(sessionsDir)) try {
|
|
881
|
+
for (const f of readdirSync(sessionsDir)) {
|
|
882
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
883
|
+
const fullPath = join(sessionsDir, f);
|
|
884
|
+
try {
|
|
885
|
+
const st = statSync(fullPath);
|
|
886
|
+
candidates.push({
|
|
887
|
+
path: fullPath,
|
|
888
|
+
mtime: st.mtimeMs
|
|
889
|
+
});
|
|
890
|
+
} catch {}
|
|
891
|
+
}
|
|
892
|
+
} catch {}
|
|
893
|
+
try {
|
|
894
|
+
for (const f of readdirSync(projectDir)) {
|
|
895
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
896
|
+
const fullPath = join(projectDir, f);
|
|
897
|
+
try {
|
|
898
|
+
const st = statSync(fullPath);
|
|
899
|
+
candidates.push({
|
|
900
|
+
path: fullPath,
|
|
901
|
+
mtime: st.mtimeMs
|
|
902
|
+
});
|
|
903
|
+
} catch {}
|
|
904
|
+
}
|
|
905
|
+
} catch {}
|
|
906
|
+
if (candidates.length === 0) {
|
|
907
|
+
process.stderr.write(`[session-summary] No JSONL files found in ${projectDir}\n`);
|
|
908
|
+
return null;
|
|
909
|
+
}
|
|
910
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
911
|
+
return candidates[0].path;
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Parse a JSONL transcript and extract relevant content.
|
|
915
|
+
* Filters noise, truncates to model-appropriate size from the end of the file.
|
|
916
|
+
*/
|
|
917
|
+
function extractFromJsonl(jsonlPath, model = "sonnet") {
|
|
918
|
+
const result = {
|
|
919
|
+
userMessages: [],
|
|
920
|
+
filesModified: [],
|
|
921
|
+
sessionStartTime: ""
|
|
922
|
+
};
|
|
923
|
+
let raw;
|
|
924
|
+
try {
|
|
925
|
+
raw = readFileSync(jsonlPath, "utf-8");
|
|
926
|
+
} catch (e) {
|
|
927
|
+
throw new Error(`Could not read JSONL at ${jsonlPath}: ${e}`);
|
|
928
|
+
}
|
|
929
|
+
const maxChars = MAX_JSONL_CHARS[model] ?? 2e5;
|
|
930
|
+
if (raw.length > maxChars) {
|
|
931
|
+
const truncPoint = raw.indexOf("\n", raw.length - maxChars);
|
|
932
|
+
raw = truncPoint >= 0 ? raw.slice(truncPoint + 1) : raw.slice(-MAX_JSONL_CHARS);
|
|
933
|
+
}
|
|
934
|
+
const lines = raw.trim().split("\n");
|
|
935
|
+
const seenMessages = /* @__PURE__ */ new Set();
|
|
936
|
+
for (const line of lines) {
|
|
937
|
+
if (!line.trim()) continue;
|
|
938
|
+
let entry;
|
|
939
|
+
try {
|
|
940
|
+
entry = JSON.parse(line);
|
|
941
|
+
} catch {
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
if (entry.timestamp && !result.sessionStartTime) result.sessionStartTime = String(entry.timestamp);
|
|
945
|
+
if (entry.type === "user") {
|
|
946
|
+
const msg = entry.message;
|
|
947
|
+
if (msg?.content) {
|
|
948
|
+
const text = contentToText$2(msg.content);
|
|
949
|
+
if (text && !isNoise(text) && !seenMessages.has(text)) {
|
|
950
|
+
seenMessages.add(text);
|
|
951
|
+
result.userMessages.push(text.slice(0, 500));
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
if (entry.type === "assistant") {
|
|
956
|
+
const msg = entry.message;
|
|
957
|
+
if (msg?.content && Array.isArray(msg.content)) {
|
|
958
|
+
for (const block of msg.content) if (block.type === "tool_use") {
|
|
959
|
+
const name = block.name;
|
|
960
|
+
const input = block.input;
|
|
961
|
+
if ((name === "Edit" || name === "Write") && input?.file_path) {
|
|
962
|
+
const fp = String(input.file_path);
|
|
963
|
+
if (!result.filesModified.includes(fp)) result.filesModified.push(fp);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
if (result.userMessages.length > MAX_USER_MESSAGES) result.userMessages = result.userMessages.slice(-MAX_USER_MESSAGES);
|
|
970
|
+
return result;
|
|
971
|
+
}
|
|
972
|
+
/** Convert Claude content (string or content block array) to plain text. */
|
|
973
|
+
function contentToText$2(content) {
|
|
974
|
+
if (typeof content === "string") return content;
|
|
975
|
+
if (Array.isArray(content)) return content.map((c) => {
|
|
976
|
+
if (typeof c === "string") return c;
|
|
977
|
+
const block = c;
|
|
978
|
+
if (block?.text) return String(block.text);
|
|
979
|
+
if (block?.content) return String(block.content);
|
|
980
|
+
return "";
|
|
981
|
+
}).join(" ").trim();
|
|
982
|
+
return "";
|
|
983
|
+
}
|
|
984
|
+
/** Filter out noise entries that shouldn't be included in the summary. */
|
|
985
|
+
function isNoise(text) {
|
|
986
|
+
if (!text || text.length < 3) return true;
|
|
987
|
+
if (text.includes("<task-notification>")) return true;
|
|
988
|
+
if (text.includes("[object Object]")) return true;
|
|
989
|
+
if (text.startsWith("<system-reminder>")) return true;
|
|
990
|
+
if (/^(yes|ok|sure|go|continue|weiter|thanks|thank you)\.?$/i.test(text.trim())) return true;
|
|
991
|
+
if (text.startsWith("Tool Result:") || text.startsWith("tool_result")) return true;
|
|
992
|
+
return false;
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Get git log for the session period.
|
|
996
|
+
* Falls back gracefully if git is not available or the dir is not a repo.
|
|
997
|
+
*/
|
|
998
|
+
async function getGitContext(cwd, sinceTime) {
|
|
999
|
+
let since = "6 hours ago";
|
|
1000
|
+
if (sinceTime) {
|
|
1001
|
+
const asNum = Number(sinceTime);
|
|
1002
|
+
if (!isNaN(asNum) && asNum > 1e9) since = (/* @__PURE__ */ new Date(asNum * 1e3)).toISOString();
|
|
1003
|
+
else since = sinceTime;
|
|
1004
|
+
}
|
|
1005
|
+
try {
|
|
1006
|
+
const { execFile: execFileCb } = await import("node:child_process");
|
|
1007
|
+
const { promisify } = await import("node:util");
|
|
1008
|
+
const { stdout } = await promisify(execFileCb)("git", [
|
|
1009
|
+
"log",
|
|
1010
|
+
"--format=%h %ai %s",
|
|
1011
|
+
`--since=${since}`,
|
|
1012
|
+
"--stat",
|
|
1013
|
+
"--no-color"
|
|
1014
|
+
], {
|
|
1015
|
+
cwd,
|
|
1016
|
+
timeout: 1e4,
|
|
1017
|
+
env: {
|
|
1018
|
+
...process.env,
|
|
1019
|
+
GIT_TERMINAL_PROMPT: "0"
|
|
1020
|
+
}
|
|
1021
|
+
});
|
|
1022
|
+
return stdout.trim();
|
|
1023
|
+
} catch {
|
|
1024
|
+
return "";
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Find the `claude` CLI binary.
|
|
1029
|
+
* Checks PATH first, then common installation locations.
|
|
1030
|
+
*/
|
|
1031
|
+
function findClaudeBinary() {
|
|
1032
|
+
const candidates = [
|
|
1033
|
+
join(homedir(), ".local", "bin", "claude"),
|
|
1034
|
+
join(homedir(), ".claude", "local", "claude"),
|
|
1035
|
+
"/usr/local/bin/claude",
|
|
1036
|
+
"/opt/homebrew/bin/claude"
|
|
1037
|
+
];
|
|
1038
|
+
for (const candidate of candidates) try {
|
|
1039
|
+
if (existsSync(candidate)) return candidate;
|
|
1040
|
+
} catch {}
|
|
1041
|
+
return "claude";
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Spawn a Claude model via the CLI to generate a session summary.
|
|
1045
|
+
* Pipes the prompt via stdin. Model selection:
|
|
1046
|
+
* - opus: session end (best quality for final summary, runs once)
|
|
1047
|
+
* - sonnet: auto-compaction (good quality for incremental checkpoints, runs often)
|
|
1048
|
+
* - haiku: fallback / budget mode
|
|
1049
|
+
* Returns the generated text, or null if spawning fails.
|
|
1050
|
+
*/
|
|
1051
|
+
async function spawnSummarizer(prompt, model = "sonnet") {
|
|
1052
|
+
const claudeBin = findClaudeBinary();
|
|
1053
|
+
if (!claudeBin) {
|
|
1054
|
+
process.stderr.write("[session-summary] Claude CLI not found in PATH or common locations.\n");
|
|
1055
|
+
return null;
|
|
1056
|
+
}
|
|
1057
|
+
const { spawn } = await import("node:child_process");
|
|
1058
|
+
return new Promise((resolve) => {
|
|
1059
|
+
let timer = null;
|
|
1060
|
+
const { ANTHROPIC_API_KEY: _, ...envWithoutApiKey } = process.env;
|
|
1061
|
+
const child = spawn(claudeBin, [
|
|
1062
|
+
"--model",
|
|
1063
|
+
model,
|
|
1064
|
+
"-p",
|
|
1065
|
+
"--no-session-persistence"
|
|
1066
|
+
], {
|
|
1067
|
+
env: envWithoutApiKey,
|
|
1068
|
+
stdio: [
|
|
1069
|
+
"pipe",
|
|
1070
|
+
"pipe",
|
|
1071
|
+
"pipe"
|
|
1072
|
+
]
|
|
1073
|
+
});
|
|
1074
|
+
let stdout = "";
|
|
1075
|
+
let stderr = "";
|
|
1076
|
+
child.stdout.on("data", (chunk) => {
|
|
1077
|
+
stdout += chunk.toString();
|
|
1078
|
+
});
|
|
1079
|
+
child.stderr.on("data", (chunk) => {
|
|
1080
|
+
stderr += chunk.toString();
|
|
1081
|
+
});
|
|
1082
|
+
child.on("error", (err) => {
|
|
1083
|
+
if (timer) {
|
|
1084
|
+
clearTimeout(timer);
|
|
1085
|
+
timer = null;
|
|
1086
|
+
}
|
|
1087
|
+
process.stderr.write(`[session-summary] ${model} spawn error: ${err.message}\n`);
|
|
1088
|
+
resolve(null);
|
|
1089
|
+
});
|
|
1090
|
+
child.on("close", (code) => {
|
|
1091
|
+
if (timer) {
|
|
1092
|
+
clearTimeout(timer);
|
|
1093
|
+
timer = null;
|
|
1094
|
+
}
|
|
1095
|
+
if (code !== 0) {
|
|
1096
|
+
process.stderr.write(`[session-summary] ${model} exited with code ${code}: ${stderr.slice(0, 300)}\n`);
|
|
1097
|
+
resolve(null);
|
|
1098
|
+
} else resolve(stdout.trim() || null);
|
|
1099
|
+
});
|
|
1100
|
+
timer = setTimeout(() => {
|
|
1101
|
+
process.stderr.write(`[session-summary] ${model} timed out — killing process.\n`);
|
|
1102
|
+
child.kill("SIGTERM");
|
|
1103
|
+
resolve(null);
|
|
1104
|
+
}, CLAUDE_TIMEOUT_MS[model] ?? 12e4);
|
|
1105
|
+
child.stdin.write(prompt);
|
|
1106
|
+
child.stdin.end();
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Extract the TOPIC: line from the summarizer output.
|
|
1111
|
+
* Returns the topic string, or null if not found.
|
|
1112
|
+
*/
|
|
1113
|
+
function extractTopic(summaryText) {
|
|
1114
|
+
const match = summaryText.match(/^TOPIC:\s*(.+)$/m);
|
|
1115
|
+
if (!match) return null;
|
|
1116
|
+
return match[1].trim();
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Extract the topic from an existing session note.
|
|
1120
|
+
* First checks for a <!-- TOPIC: ... --> comment (stored by previous summaries).
|
|
1121
|
+
* Falls back to the H1 "# Session NNNN: Title" line.
|
|
1122
|
+
*
|
|
1123
|
+
* The HTML comment is the reliable source because the H1 gets renamed by
|
|
1124
|
+
* renameSessionNote, which can add/change words and cause false topic shifts.
|
|
1125
|
+
*/
|
|
1126
|
+
function extractExistingNoteTitle(notePath) {
|
|
1127
|
+
try {
|
|
1128
|
+
const content = readFileSync(notePath, "utf-8");
|
|
1129
|
+
const topicComment = content.match(/<!-- TOPIC:\s*(.+?)\s*-->/);
|
|
1130
|
+
if (topicComment) return topicComment[1].trim();
|
|
1131
|
+
const match = content.match(/^# Session \d+:\s*(.+)$/m);
|
|
1132
|
+
if (match) return match[1].trim();
|
|
1133
|
+
} catch {}
|
|
1134
|
+
return null;
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Compute word overlap ratio between two topic strings.
|
|
1138
|
+
* Returns a value in [0, 1] — 1.0 means identical word sets.
|
|
1139
|
+
*
|
|
1140
|
+
* Uses lowercased, normalized words. Stop words and very short words
|
|
1141
|
+
* are excluded to avoid false positives on common terms.
|
|
1142
|
+
*/
|
|
1143
|
+
function computeTopicOverlap(topicA, topicB) {
|
|
1144
|
+
const stopWords = new Set([
|
|
1145
|
+
"a",
|
|
1146
|
+
"an",
|
|
1147
|
+
"the",
|
|
1148
|
+
"and",
|
|
1149
|
+
"or",
|
|
1150
|
+
"but",
|
|
1151
|
+
"in",
|
|
1152
|
+
"on",
|
|
1153
|
+
"at",
|
|
1154
|
+
"to",
|
|
1155
|
+
"for",
|
|
1156
|
+
"of",
|
|
1157
|
+
"with",
|
|
1158
|
+
"by",
|
|
1159
|
+
"from",
|
|
1160
|
+
"is",
|
|
1161
|
+
"was",
|
|
1162
|
+
"are",
|
|
1163
|
+
"were",
|
|
1164
|
+
"be",
|
|
1165
|
+
"been",
|
|
1166
|
+
"being",
|
|
1167
|
+
"have",
|
|
1168
|
+
"has",
|
|
1169
|
+
"had",
|
|
1170
|
+
"do",
|
|
1171
|
+
"does",
|
|
1172
|
+
"did",
|
|
1173
|
+
"will",
|
|
1174
|
+
"would",
|
|
1175
|
+
"could",
|
|
1176
|
+
"should",
|
|
1177
|
+
"may",
|
|
1178
|
+
"might",
|
|
1179
|
+
"can",
|
|
1180
|
+
"shall",
|
|
1181
|
+
"this",
|
|
1182
|
+
"that",
|
|
1183
|
+
"these",
|
|
1184
|
+
"those",
|
|
1185
|
+
"it",
|
|
1186
|
+
"its",
|
|
1187
|
+
"new",
|
|
1188
|
+
"session",
|
|
1189
|
+
"work",
|
|
1190
|
+
"done"
|
|
1191
|
+
]);
|
|
1192
|
+
const normalize = (text) => {
|
|
1193
|
+
const words = text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !stopWords.has(w));
|
|
1194
|
+
return new Set(words);
|
|
1195
|
+
};
|
|
1196
|
+
const wordsA = normalize(topicA);
|
|
1197
|
+
const wordsB = normalize(topicB);
|
|
1198
|
+
if (wordsA.size === 0 || wordsB.size === 0) return 0;
|
|
1199
|
+
let intersection = 0;
|
|
1200
|
+
for (const w of wordsA) if (wordsB.has(w)) intersection++;
|
|
1201
|
+
const union = new Set([...wordsA, ...wordsB]).size;
|
|
1202
|
+
return union > 0 ? intersection / union : 0;
|
|
1203
|
+
}
|
|
1204
|
+
/** Threshold: below this overlap ratio, we consider topics different. */
|
|
1205
|
+
const TOPIC_OVERLAP_THRESHOLD = .15;
|
|
1206
|
+
/**
|
|
1207
|
+
* Write (or update) the session note with the AI-generated summary.
|
|
1208
|
+
*
|
|
1209
|
+
* Strategy:
|
|
1210
|
+
* - Find the current month's latest note
|
|
1211
|
+
* - If it's from today, compare topics:
|
|
1212
|
+
* - Same topic (overlap >= 30%) → update existing note
|
|
1213
|
+
* - Different topic (overlap < 30%) → create a NEW note
|
|
1214
|
+
* - If it's from a different day, create a new note
|
|
1215
|
+
*/
|
|
1216
|
+
/**
|
|
1217
|
+
* Return true if the summarizer output has a meaningful body — i.e. content
|
|
1218
|
+
* beyond the TOPIC:/title/metadata/horizontal-rule scaffolding.
|
|
1219
|
+
*
|
|
1220
|
+
* A summary that is only headers (no Work Done items) must NOT create or update
|
|
1221
|
+
* a note: doing so births an empty-bodied scaffold that later rename/finalize
|
|
1222
|
+
* can strip to a footer-only stub. This is the born-stub failure mode.
|
|
1223
|
+
*/
|
|
1224
|
+
function summaryHasContent(summaryText) {
|
|
1225
|
+
return summaryText.replace(/^TOPIC:.*$/m, "").replace(/^# Session:.*$/m, "").replace(/^\*\*(Date|Status|Completed):\*\*.*$/gm, "").replace(/^#{1,6}\s.*$/gm, "").replace(/^---$/gm, "").replace(/<!--[\s\S]*?-->/g, "").trim().length > 0;
|
|
1226
|
+
}
|
|
1227
|
+
function writeSessionNote(cwd, summaryText, filesModified) {
|
|
1228
|
+
if (!summaryHasContent(summaryText)) {
|
|
1229
|
+
process.stderr.write(`[session-summary] Summary has no meaningful body — skipping note write.\n`);
|
|
1230
|
+
return null;
|
|
1231
|
+
}
|
|
1232
|
+
const notesInfo = findNotesDir(cwd);
|
|
1233
|
+
let notePath = getCurrentNotePath(notesInfo.path);
|
|
1234
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1235
|
+
const newTopic = extractTopic(summaryText);
|
|
1236
|
+
if (notePath) {
|
|
1237
|
+
const noteFilename = basename(notePath);
|
|
1238
|
+
const dateMatch = noteFilename.match(/(\d{4}-\d{2}-\d{2})/);
|
|
1239
|
+
if ((dateMatch ? dateMatch[1] : "") === today) {
|
|
1240
|
+
const existingTitle = extractExistingNoteTitle(notePath);
|
|
1241
|
+
let topicShifted = false;
|
|
1242
|
+
if (newTopic && existingTitle) {
|
|
1243
|
+
const overlap = computeTopicOverlap(newTopic, existingTitle);
|
|
1244
|
+
process.stderr.write(`[session-summary] Topic overlap: ${(overlap * 100).toFixed(1)}% (new="${newTopic}", existing="${existingTitle}")\n`);
|
|
1245
|
+
if (overlap < TOPIC_OVERLAP_THRESHOLD) {
|
|
1246
|
+
topicShifted = true;
|
|
1247
|
+
process.stderr.write(`[session-summary] Topic shift detected (word overlap) — creating new note.\n`);
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
if (!topicShifted) {
|
|
1251
|
+
const boundaryPath = join(notesInfo.path, "topic-boundary.json");
|
|
1252
|
+
if (existsSync(boundaryPath)) try {
|
|
1253
|
+
const boundary = JSON.parse(readFileSync(boundaryPath, "utf-8"));
|
|
1254
|
+
if (boundary.timestamp) {
|
|
1255
|
+
if (Date.now() - new Date(boundary.timestamp).getTime() < 1800 * 1e3) {
|
|
1256
|
+
topicShifted = true;
|
|
1257
|
+
process.stderr.write(`[session-summary] Topic shift detected (boundary marker) — ${boundary.previousProject} → ${boundary.suggestedProject}\n`);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
unlinkSync(boundaryPath);
|
|
1261
|
+
} catch {}
|
|
1262
|
+
}
|
|
1263
|
+
if (topicShifted) notePath = createNoteFromSummary(notesInfo.path, summaryText);
|
|
1264
|
+
else {
|
|
1265
|
+
updateNoteWithSummary(notePath, summaryText);
|
|
1266
|
+
process.stderr.write(`[session-summary] Updated existing note: ${noteFilename}\n`);
|
|
1267
|
+
}
|
|
1268
|
+
} else notePath = createNoteFromSummary(notesInfo.path, summaryText);
|
|
1269
|
+
} else notePath = createNoteFromSummary(notesInfo.path, summaryText);
|
|
1270
|
+
if (notePath) {
|
|
1271
|
+
const titleMatch = summaryText.match(/^# Session:\s*(.+)$/m);
|
|
1272
|
+
if (titleMatch) {
|
|
1273
|
+
const title = titleMatch[1].trim();
|
|
1274
|
+
if (title.length > 5 && title.length < 80) {
|
|
1275
|
+
const newPath = renameSessionNote(notePath, title);
|
|
1276
|
+
if (newPath !== notePath) notePath = newPath;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
return notePath;
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Update an existing session note's Work Done section with AI-generated content.
|
|
1284
|
+
*/
|
|
1285
|
+
function updateNoteWithSummary(notePath, summaryText) {
|
|
1286
|
+
if (!existsSync(notePath)) return;
|
|
1287
|
+
let content = readFileSync(notePath, "utf-8");
|
|
1288
|
+
const newTopic = extractTopic(summaryText);
|
|
1289
|
+
if (newTopic) if (content.includes("<!-- TOPIC:")) content = content.replace(/<!-- TOPIC:.*?-->/, `<!-- TOPIC: ${newTopic} -->`);
|
|
1290
|
+
else content = content.replace(/^(# Session .+)$/m, `$1\n<!-- TOPIC: ${newTopic} -->`);
|
|
1291
|
+
const workDoneMatch = summaryText.match(/## Work Done\n\n([\s\S]*?)(?=\n## Key Decisions|\n## Known Issues|\n\*\*Tags|\n$)/);
|
|
1292
|
+
if (workDoneMatch) {
|
|
1293
|
+
const aiWorkContent = workDoneMatch[1].trim();
|
|
1294
|
+
const sectionHeader = `\n### AI Summary (${(/* @__PURE__ */ new Date()).toISOString().split("T")[1].split(".")[0]})\n\n${aiWorkContent}\n`;
|
|
1295
|
+
const nextStepsIdx = content.indexOf("## Next Steps");
|
|
1296
|
+
const knownIssuesIdx = content.indexOf("## Known Issues");
|
|
1297
|
+
const insertBefore = knownIssuesIdx !== -1 ? knownIssuesIdx : nextStepsIdx !== -1 ? nextStepsIdx : content.length;
|
|
1298
|
+
content = content.slice(0, insertBefore) + sectionHeader + "\n" + content.slice(insertBefore);
|
|
1299
|
+
}
|
|
1300
|
+
const decisionsMatch = summaryText.match(/## Key Decisions\n\n([\s\S]*?)(?=\n## Known Issues|\n\*\*Tags|\n$)/);
|
|
1301
|
+
if (decisionsMatch) {
|
|
1302
|
+
const decisions = decisionsMatch[1].trim();
|
|
1303
|
+
if (decisions && !content.includes("## Key Decisions")) {
|
|
1304
|
+
const nextStepsIdx = content.indexOf("## Next Steps");
|
|
1305
|
+
const insertAt = nextStepsIdx !== -1 ? nextStepsIdx : content.length;
|
|
1306
|
+
content = content.slice(0, insertAt) + `## Key Decisions\n\n${decisions}\n\n` + content.slice(insertAt);
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
const issuesMatch = summaryText.match(/## Known Issues\n\n([\s\S]*?)(?=\n\*\*Tags|\n$)/);
|
|
1310
|
+
if (issuesMatch) {
|
|
1311
|
+
const issues = issuesMatch[1].trim();
|
|
1312
|
+
if (issues && !content.includes("## Known Issues")) {
|
|
1313
|
+
const nextStepsIdx = content.indexOf("## Next Steps");
|
|
1314
|
+
const insertAt = nextStepsIdx !== -1 ? nextStepsIdx : content.length;
|
|
1315
|
+
content = content.slice(0, insertAt) + `## Known Issues\n\n${issues}\n\n` + content.slice(insertAt);
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
writeFileSync(notePath, content, "utf-8");
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Create a brand new session note from the AI summary.
|
|
1322
|
+
*/
|
|
1323
|
+
function createNoteFromSummary(notesDir, summaryText) {
|
|
1324
|
+
try {
|
|
1325
|
+
const notePath = createSessionNote(notesDir, "New Session");
|
|
1326
|
+
const noteFilename = basename(notePath);
|
|
1327
|
+
const numberMatch = noteFilename.match(/^(\d+)/);
|
|
1328
|
+
const noteNumber = numberMatch ? numberMatch[1] : "0000";
|
|
1329
|
+
const titleMatch = summaryText.match(/^# Session:\s*(.+)$/m);
|
|
1330
|
+
const title = titleMatch ? titleMatch[1].trim() : "New Session";
|
|
1331
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1332
|
+
const topic = extractTopic(summaryText);
|
|
1333
|
+
const aiBody = summaryText.replace(/^TOPIC:.*$/m, "").replace(/^# Session:.*$/m, "").replace(/^\*\*Date:\*\*.*$/m, "").replace(/^\*\*Status:\*\*.*$/m, "").replace(/^---$/m, "").trim();
|
|
1334
|
+
writeFileSync(notePath, `# Session ${noteNumber}: ${title}
|
|
1335
|
+
${topic ? `<!-- TOPIC: ${topic} -->` : ""}
|
|
1336
|
+
|
|
1337
|
+
**Date:** ${date}
|
|
1338
|
+
**Status:** In Progress
|
|
1339
|
+
|
|
1340
|
+
---
|
|
1341
|
+
|
|
1342
|
+
${aiBody}
|
|
1343
|
+
|
|
1344
|
+
---
|
|
1345
|
+
|
|
1346
|
+
## Next Steps
|
|
1347
|
+
|
|
1348
|
+
<!-- To be filled at session end -->
|
|
1349
|
+
|
|
1350
|
+
---
|
|
1351
|
+
|
|
1352
|
+
**Tags:** #Session
|
|
1353
|
+
`, "utf-8");
|
|
1354
|
+
process.stderr.write(`[session-summary] Created AI-powered note: ${noteFilename}\n`);
|
|
1355
|
+
return notePath;
|
|
1356
|
+
} catch (e) {
|
|
1357
|
+
process.stderr.write(`[session-summary] Failed to create note: ${e}\n`);
|
|
1358
|
+
return null;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* Look up the integer project_id from the registry DB for a given slug.
|
|
1363
|
+
* Returns null if not found or registryDb is not yet initialized.
|
|
1364
|
+
*/
|
|
1365
|
+
function lookupProjectId(slug) {
|
|
1366
|
+
try {
|
|
1367
|
+
if (!registryDb) return null;
|
|
1368
|
+
return registryDb.prepare("SELECT id FROM projects WHERE slug = ? LIMIT 1").get(slug)?.id ?? null;
|
|
1369
|
+
} catch {
|
|
1370
|
+
return null;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* Extract structured KG triples from a session summary and store them.
|
|
1375
|
+
*
|
|
1376
|
+
* This is best-effort: any error is logged but never propagated.
|
|
1377
|
+
* Requires Postgres backend — silently no-ops on SQLite.
|
|
1378
|
+
*/
|
|
1379
|
+
async function extractAndStoreTriples(params) {
|
|
1380
|
+
try {
|
|
1381
|
+
if (!storageBackend || storageBackend.backendType !== "postgres") return;
|
|
1382
|
+
const pool = storageBackend.getPool?.();
|
|
1383
|
+
if (!pool) {
|
|
1384
|
+
process.stderr.write("[session-summary] Triple extraction: no pool available.\n");
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
const cfg = daemonConfig;
|
|
1388
|
+
if (cfg && cfg.kg_extraction_enabled === false) {
|
|
1389
|
+
process.stderr.write("[session-summary] Triple extraction disabled via kg_extraction_enabled=false.\n");
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
const federationDb = openFederation();
|
|
1393
|
+
let result;
|
|
1394
|
+
try {
|
|
1395
|
+
result = await extractAndStoreTriples$1(pool, {
|
|
1396
|
+
summaryText: params.summaryText,
|
|
1397
|
+
projectSlug: params.projectSlug,
|
|
1398
|
+
projectId: params.projectId,
|
|
1399
|
+
sessionId: params.sessionId,
|
|
1400
|
+
gitLog: params.gitLog,
|
|
1401
|
+
model: "sonnet",
|
|
1402
|
+
federationDb
|
|
1403
|
+
});
|
|
1404
|
+
} finally {
|
|
1405
|
+
federationDb.close();
|
|
1406
|
+
}
|
|
1407
|
+
process.stderr.write(`[session-summary] Triple extraction complete: ${result.extracted} extracted, ${result.added} added, ${result.superseded} superseded.\n`);
|
|
1408
|
+
} catch (err) {
|
|
1409
|
+
process.stderr.write(`[session-summary] Triple extraction failed: ${err}\n`);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Process a `session-summary` work item.
|
|
1414
|
+
*
|
|
1415
|
+
* This is the main function called by work-queue-worker.ts.
|
|
1416
|
+
* Throws on fatal errors (work queue will retry with backoff).
|
|
1417
|
+
*/
|
|
1418
|
+
async function handleSessionSummary(payload) {
|
|
1419
|
+
const { cwd, sessionId, projectSlug, transcriptPath, force } = payload;
|
|
1420
|
+
if (!cwd) throw new Error("session-summary payload missing cwd");
|
|
1421
|
+
process.stderr.write(`[session-summary] Starting for ${cwd}${sessionId ? ` (session=${sessionId})` : ""}${force ? " (force=true)" : ""}\n`);
|
|
1422
|
+
if (!force && isOnCooldown(cwd)) {
|
|
1423
|
+
process.stderr.write("[session-summary] Skipping — last summary was less than 30 minutes ago.\n");
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
let jsonlPath = transcriptPath || null;
|
|
1427
|
+
if (jsonlPath && !existsSync(jsonlPath)) {
|
|
1428
|
+
process.stderr.write(`[session-summary] Provided transcript path not found: ${jsonlPath}\n`);
|
|
1429
|
+
jsonlPath = null;
|
|
1430
|
+
}
|
|
1431
|
+
if (!jsonlPath) jsonlPath = findLatestJsonl(cwd);
|
|
1432
|
+
if (!jsonlPath) {
|
|
1433
|
+
process.stderr.write("[session-summary] No JSONL transcript found — skipping.\n");
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
process.stderr.write(`[session-summary] Using transcript: ${jsonlPath}\n`);
|
|
1437
|
+
const selectedModel = payload.model ?? (force ? "haiku" : "sonnet");
|
|
1438
|
+
const extracted = extractFromJsonl(jsonlPath, selectedModel);
|
|
1439
|
+
if (extracted.userMessages.length === 0) {
|
|
1440
|
+
process.stderr.write("[session-summary] No user messages found in transcript — skipping.\n");
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
1443
|
+
process.stderr.write(`[session-summary] Extracted ${extracted.userMessages.length} user messages, ${extracted.filesModified.length} modified files.\n`);
|
|
1444
|
+
const gitLog = await getGitContext(cwd, extracted.sessionStartTime);
|
|
1445
|
+
if (gitLog) process.stderr.write(`[session-summary] Got git context (${gitLog.split("\n").length} lines).\n`);
|
|
1446
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1447
|
+
const existingNotePath = getCurrentNotePath(findNotesDir(cwd).path);
|
|
1448
|
+
let existingNote;
|
|
1449
|
+
if (existingNotePath) {
|
|
1450
|
+
const dateMatch = basename(existingNotePath).match(/(\d{4}-\d{2}-\d{2})/);
|
|
1451
|
+
if (dateMatch && dateMatch[1] === today) try {
|
|
1452
|
+
existingNote = readFileSync(existingNotePath, "utf-8");
|
|
1453
|
+
} catch {}
|
|
1454
|
+
}
|
|
1455
|
+
const prompt = buildSessionSummaryPrompt({
|
|
1456
|
+
userMessages: extracted.userMessages,
|
|
1457
|
+
gitLog,
|
|
1458
|
+
cwd,
|
|
1459
|
+
date: today,
|
|
1460
|
+
filesModified: extracted.filesModified,
|
|
1461
|
+
existingNote
|
|
1462
|
+
});
|
|
1463
|
+
process.stderr.write(`[session-summary] Sending ${prompt.length} char prompt to ${selectedModel}...\n`);
|
|
1464
|
+
const summaryText = await spawnSummarizer(prompt, selectedModel);
|
|
1465
|
+
if (!summaryText) {
|
|
1466
|
+
process.stderr.write(`[session-summary] ${selectedModel} did not produce output — falling back to mechanical checkpoint.\n`);
|
|
1467
|
+
markCooldown(cwd);
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
process.stderr.write(`[session-summary] ${selectedModel} produced ${summaryText.length} char summary.\n`);
|
|
1471
|
+
const notePath = writeSessionNote(cwd, summaryText, extracted.filesModified);
|
|
1472
|
+
if (notePath) process.stderr.write(`[session-summary] Session note written: ${basename(notePath)}\n`);
|
|
1473
|
+
await extractAndStoreTriples({
|
|
1474
|
+
summaryText,
|
|
1475
|
+
projectSlug: projectSlug ?? basename(cwd),
|
|
1476
|
+
projectId: projectSlug ? lookupProjectId(projectSlug) : null,
|
|
1477
|
+
sessionId: sessionId ?? cwd,
|
|
1478
|
+
gitLog,
|
|
1479
|
+
model: selectedModel
|
|
1480
|
+
});
|
|
1481
|
+
markCooldown(cwd);
|
|
1482
|
+
process.stderr.write("[session-summary] Done.\n");
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
//#endregion
|
|
1486
|
+
//#region src/daemon/topic-detect-worker.ts
|
|
1487
|
+
/**
|
|
1488
|
+
* topic-detect-worker.ts — Topic shift detection for session note splitting
|
|
1489
|
+
*
|
|
1490
|
+
* Processes `topic-detect` work items by:
|
|
1491
|
+
* 1. Extracting recent user messages from the JSONL transcript
|
|
1492
|
+
* 2. Running the BM25-based topic shift detector against the PAI memory DB
|
|
1493
|
+
* 3. If a shift is detected, recording a topic boundary marker
|
|
1494
|
+
*
|
|
1495
|
+
* The actual note splitting is handled by session-summary-worker.ts when it
|
|
1496
|
+
* processes the next `session-summary` work item — it uses the TOPIC: line
|
|
1497
|
+
* from the summarizer to decide whether to create a new note.
|
|
1498
|
+
*
|
|
1499
|
+
* This worker provides an additional signal: project-level topic shift
|
|
1500
|
+
* (e.g., conversation moved from project A to project B). The session
|
|
1501
|
+
* summary worker handles intra-project topic shifts (e.g., from "dark mode"
|
|
1502
|
+
* to "keyboard IPC" within the same project).
|
|
1503
|
+
*/
|
|
1504
|
+
const MAX_CONTEXT_MESSAGES = 5;
|
|
1505
|
+
const MAX_CONTEXT_CHARS = 2e3;
|
|
1506
|
+
/**
|
|
1507
|
+
* Extract recent user messages from a JSONL transcript for topic detection.
|
|
1508
|
+
* Takes only the last few messages to represent the current topic.
|
|
1509
|
+
*/
|
|
1510
|
+
function extractRecentContext(jsonlPath) {
|
|
1511
|
+
try {
|
|
1512
|
+
const raw = readFileSync(jsonlPath, "utf-8");
|
|
1513
|
+
const lines = (raw.length > 5e4 ? raw.slice(-5e4) : raw).trim().split("\n");
|
|
1514
|
+
const messages = [];
|
|
1515
|
+
for (let i = lines.length - 1; i >= 0 && messages.length < MAX_CONTEXT_MESSAGES; i--) {
|
|
1516
|
+
const line = lines[i].trim();
|
|
1517
|
+
if (!line) continue;
|
|
1518
|
+
try {
|
|
1519
|
+
const entry = JSON.parse(line);
|
|
1520
|
+
if (entry.type === "user") {
|
|
1521
|
+
const msg = entry.message;
|
|
1522
|
+
if (msg?.content) {
|
|
1523
|
+
const text = contentToText$1(msg.content);
|
|
1524
|
+
if (text && text.length > 3) messages.unshift(text.slice(0, 500));
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
} catch {}
|
|
1528
|
+
}
|
|
1529
|
+
return messages.join("\n\n").slice(0, MAX_CONTEXT_CHARS);
|
|
1530
|
+
} catch {
|
|
1531
|
+
return "";
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
/** Convert Claude content (string or content block array) to plain text. */
|
|
1535
|
+
function contentToText$1(content) {
|
|
1536
|
+
if (typeof content === "string") return content;
|
|
1537
|
+
if (Array.isArray(content)) return content.map((c) => {
|
|
1538
|
+
if (typeof c === "string") return c;
|
|
1539
|
+
const block = c;
|
|
1540
|
+
if (block?.text) return String(block.text);
|
|
1541
|
+
if (block?.content) return String(block.content);
|
|
1542
|
+
return "";
|
|
1543
|
+
}).join(" ").trim();
|
|
1544
|
+
return "";
|
|
1545
|
+
}
|
|
1546
|
+
const TOPIC_BOUNDARY_FILE = "topic-boundary.json";
|
|
1547
|
+
/**
|
|
1548
|
+
* Write a topic boundary marker into the Notes directory.
|
|
1549
|
+
* The session-summary-worker checks for this file and uses it as an
|
|
1550
|
+
* additional signal that a new note should be created.
|
|
1551
|
+
*/
|
|
1552
|
+
function writeTopicBoundary(cwd, boundary) {
|
|
1553
|
+
try {
|
|
1554
|
+
const boundaryPath = join(findNotesDir(cwd).path, TOPIC_BOUNDARY_FILE);
|
|
1555
|
+
writeFileSync(boundaryPath, JSON.stringify(boundary, null, 2), "utf-8");
|
|
1556
|
+
process.stderr.write(`[topic-detect] Wrote topic boundary marker: ${boundaryPath}\n`);
|
|
1557
|
+
} catch (e) {
|
|
1558
|
+
process.stderr.write(`[topic-detect] Could not write boundary marker: ${e}\n`);
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* Process a `topic-detect` work item.
|
|
1563
|
+
*
|
|
1564
|
+
* Called by work-queue-worker.ts. Throws on fatal errors so the work queue
|
|
1565
|
+
* retry logic handles them.
|
|
1566
|
+
*/
|
|
1567
|
+
async function handleTopicDetect(payload) {
|
|
1568
|
+
const { cwd, currentProject, transcriptPath, sessionId } = payload;
|
|
1569
|
+
if (!cwd) throw new Error("topic-detect payload missing cwd");
|
|
1570
|
+
process.stderr.write(`[topic-detect] Starting for ${cwd}${currentProject ? ` (project=${currentProject})` : ""}${sessionId ? ` (session=${sessionId})` : ""}\n`);
|
|
1571
|
+
if (!registryDb || !storageBackend) {
|
|
1572
|
+
process.stderr.write("[topic-detect] Registry DB or storage backend not available — skipping.\n");
|
|
1573
|
+
return;
|
|
1574
|
+
}
|
|
1575
|
+
let context = payload.context || "";
|
|
1576
|
+
if (!context && transcriptPath && existsSync(transcriptPath)) context = extractRecentContext(transcriptPath);
|
|
1577
|
+
if (!context || context.trim().length < 10) {
|
|
1578
|
+
process.stderr.write("[topic-detect] Insufficient context for topic detection — skipping.\n");
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
process.stderr.write(`[topic-detect] Context: ${context.length} chars, checking against memory...\n`);
|
|
1582
|
+
const result = await detectTopicShift(registryDb, storageBackend, {
|
|
1583
|
+
context,
|
|
1584
|
+
currentProject,
|
|
1585
|
+
threshold: .6,
|
|
1586
|
+
candidates: 20
|
|
1587
|
+
});
|
|
1588
|
+
process.stderr.write(`[topic-detect] Result: shifted=${result.shifted}, suggested=${result.suggestedProject}, confidence=${result.confidence.toFixed(2)}, chunks=${result.chunkCount}\n`);
|
|
1589
|
+
if (result.topProjects.length > 0) process.stderr.write(`[topic-detect] Top projects: ${result.topProjects.map((p) => `${p.slug}(${(p.score * 100).toFixed(0)}%)`).join(", ")}\n`);
|
|
1590
|
+
if (result.shifted) {
|
|
1591
|
+
writeTopicBoundary(cwd, {
|
|
1592
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1593
|
+
previousProject: result.currentProject,
|
|
1594
|
+
suggestedProject: result.suggestedProject,
|
|
1595
|
+
confidence: result.confidence,
|
|
1596
|
+
context: context.slice(0, 200)
|
|
1597
|
+
});
|
|
1598
|
+
try {
|
|
1599
|
+
const notePath = getCurrentNotePath(findNotesDir(cwd).path);
|
|
1600
|
+
if (notePath) appendCheckpoint(notePath, `Topic shift detected: conversation moved from **${result.currentProject}** to **${result.suggestedProject}** (confidence: ${(result.confidence * 100).toFixed(0)}%). A new session note will be created for the new topic.`);
|
|
1601
|
+
} catch (e) {
|
|
1602
|
+
process.stderr.write(`[topic-detect] Could not append checkpoint: ${e}\n`);
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
process.stderr.write("[topic-detect] Done.\n");
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
//#endregion
|
|
1609
|
+
//#region src/daemon/work-queue-worker.ts
|
|
1610
|
+
/**
|
|
1611
|
+
* work-queue-worker.ts — Daemon worker loop for the persistent work queue
|
|
1612
|
+
*
|
|
1613
|
+
* Runs every 5 seconds to drain the queue.
|
|
1614
|
+
* Handles 'session-end' work items by reading the transcript, extracting
|
|
1615
|
+
* work summaries, updating the session note, and updating TODO.md.
|
|
1616
|
+
* Handles 'session-summary' items by spawning Haiku for AI-powered note generation.
|
|
1617
|
+
* Handles 'registry-scan' items by running performScan() against the registry DB.
|
|
1618
|
+
*
|
|
1619
|
+
* Handles 'topic-detect' items by running BM25-based topic shift detection.
|
|
1620
|
+
* Other item types (note-update, todo-update) are stubs — they log and
|
|
1621
|
+
* complete immediately, ready for future expansion.
|
|
1622
|
+
*/
|
|
1623
|
+
var work_queue_worker_exports = /* @__PURE__ */ __exportAll({
|
|
1624
|
+
enqueueRegistryScan: () => enqueueRegistryScan,
|
|
1625
|
+
notifyNewWork: () => notifyNewWork,
|
|
1626
|
+
startWorker: () => startWorker,
|
|
1627
|
+
stopWorker: () => stopWorker
|
|
1628
|
+
});
|
|
1629
|
+
const WORKER_INTERVAL_MS = 5e3;
|
|
1630
|
+
const HOUSEKEEPING_INTERVAL_MS = 600 * 1e3;
|
|
1631
|
+
let workerTimer = null;
|
|
1632
|
+
let housekeepingTimer = null;
|
|
1633
|
+
/** Start the background worker and housekeeping timers. */
|
|
1634
|
+
function startWorker() {
|
|
1635
|
+
process.stderr.write("[work-queue-worker] Starting worker loop.\n");
|
|
1636
|
+
workerTimer = setInterval(async () => {
|
|
1637
|
+
try {
|
|
1638
|
+
await processNextItem();
|
|
1639
|
+
} catch (e) {
|
|
1640
|
+
process.stderr.write(`[work-queue-worker] Uncaught error in worker loop: ${e}\n`);
|
|
1641
|
+
}
|
|
1642
|
+
}, WORKER_INTERVAL_MS);
|
|
1643
|
+
housekeepingTimer = setInterval(() => {
|
|
1644
|
+
try {
|
|
1645
|
+
cleanup();
|
|
1646
|
+
} catch (e) {
|
|
1647
|
+
process.stderr.write(`[work-queue-worker] Housekeeping error: ${e}\n`);
|
|
1648
|
+
}
|
|
1649
|
+
}, HOUSEKEEPING_INTERVAL_MS);
|
|
1650
|
+
process.stderr.write("[work-queue-worker] Worker started (interval=5s, housekeeping=10min).\n");
|
|
1651
|
+
}
|
|
1652
|
+
/** Stop the worker timers gracefully. */
|
|
1653
|
+
function stopWorker() {
|
|
1654
|
+
if (workerTimer !== null) {
|
|
1655
|
+
clearInterval(workerTimer);
|
|
1656
|
+
workerTimer = null;
|
|
1657
|
+
}
|
|
1658
|
+
if (housekeepingTimer !== null) {
|
|
1659
|
+
clearInterval(housekeepingTimer);
|
|
1660
|
+
housekeepingTimer = null;
|
|
1661
|
+
}
|
|
1662
|
+
process.stderr.write("[work-queue-worker] Worker stopped.\n");
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Signal that new work has been enqueued.
|
|
1666
|
+
* The worker will run on its next tick — we don't need to reset the timer
|
|
1667
|
+
* since 5 s is fast enough. The flag allows future optimisations.
|
|
1668
|
+
*/
|
|
1669
|
+
function notifyNewWork() {}
|
|
1670
|
+
async function processNextItem() {
|
|
1671
|
+
const item = dequeue();
|
|
1672
|
+
if (!item) return;
|
|
1673
|
+
process.stderr.write(`[work-queue-worker] Processing ${item.type} (id=${item.id}, attempt=${item.attempts}).\n`);
|
|
1674
|
+
try {
|
|
1675
|
+
switch (item.type) {
|
|
1676
|
+
case "session-end":
|
|
1677
|
+
await handleSessionEnd(item);
|
|
1678
|
+
break;
|
|
1679
|
+
case "session-summary":
|
|
1680
|
+
await handleSessionSummary(item.payload);
|
|
1681
|
+
break;
|
|
1682
|
+
case "topic-detect":
|
|
1683
|
+
await handleTopicDetect(item.payload);
|
|
1684
|
+
break;
|
|
1685
|
+
case "registry-scan":
|
|
1686
|
+
await handleRegistryScan();
|
|
1687
|
+
break;
|
|
1688
|
+
case "note-update":
|
|
1689
|
+
case "todo-update":
|
|
1690
|
+
process.stderr.write(`[work-queue-worker] Item type '${item.type}' is not yet implemented — completing as no-op.\n`);
|
|
1691
|
+
break;
|
|
1692
|
+
default: throw new Error(`Unknown work item type: ${item.type}`);
|
|
1693
|
+
}
|
|
1694
|
+
markCompleted(item.id);
|
|
1695
|
+
process.stderr.write(`[work-queue-worker] Completed ${item.type} (id=${item.id}).\n`);
|
|
1696
|
+
} catch (e) {
|
|
1697
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1698
|
+
markFailed(item.id, msg);
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Process a 'session-end' work item.
|
|
1703
|
+
*
|
|
1704
|
+
* Expected payload:
|
|
1705
|
+
* transcriptPath: string — absolute path to the .jsonl transcript
|
|
1706
|
+
* cwd: string — working directory of the session
|
|
1707
|
+
* message?: string — COMPLETED: line extracted by the hook (optional)
|
|
1708
|
+
*/
|
|
1709
|
+
async function handleSessionEnd(item) {
|
|
1710
|
+
const { transcriptPath, cwd, message: hookMessage } = item.payload;
|
|
1711
|
+
if (!transcriptPath) throw new Error("session-end payload missing transcriptPath");
|
|
1712
|
+
if (!cwd) throw new Error("session-end payload missing cwd");
|
|
1713
|
+
let transcript;
|
|
1714
|
+
try {
|
|
1715
|
+
transcript = readFileSync(transcriptPath, "utf-8");
|
|
1716
|
+
} catch (e) {
|
|
1717
|
+
throw new Error(`Could not read transcript at ${transcriptPath}: ${e}`);
|
|
1718
|
+
}
|
|
1719
|
+
const lines = transcript.trim().split("\n");
|
|
1720
|
+
const workItems = extractWorkFromTranscript(lines);
|
|
1721
|
+
let message = hookMessage ?? "";
|
|
1722
|
+
if (!message) {
|
|
1723
|
+
const lastEntry = tryParseJson(lines[lines.length - 1]);
|
|
1724
|
+
if (lastEntry?.type === "assistant" && lastEntry.message?.content) {
|
|
1725
|
+
const m = contentToText(lastEntry.message.content).match(/COMPLETED:\s*(.+?)(?:\n|$)/i);
|
|
1726
|
+
if (m) message = m[1].trim().replace(/\*+/g, "").replace(/\[.*?\]/g, "").trim();
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
const currentNotePath = getCurrentNotePath(findNotesDir(cwd).path);
|
|
1730
|
+
if (currentNotePath) {
|
|
1731
|
+
if (workItems.length > 0) {
|
|
1732
|
+
addWorkToSessionNote(currentNotePath, workItems);
|
|
1733
|
+
process.stderr.write(`[work-queue-worker] Added ${workItems.length} work item(s) to note.\n`);
|
|
1734
|
+
} else if (message) {
|
|
1735
|
+
addWorkToSessionNote(currentNotePath, [{
|
|
1736
|
+
title: message,
|
|
1737
|
+
completed: true
|
|
1738
|
+
}]);
|
|
1739
|
+
process.stderr.write("[work-queue-worker] Added completion message to note.\n");
|
|
1740
|
+
}
|
|
1741
|
+
finalizeSessionNote(currentNotePath, message || "Session completed.");
|
|
1742
|
+
process.stderr.write(`[work-queue-worker] Finalized session note: ${basename(currentNotePath)}.\n`);
|
|
1743
|
+
try {
|
|
1744
|
+
const stateLines = [];
|
|
1745
|
+
stateLines.push(`Working directory: ${cwd}`);
|
|
1746
|
+
if (workItems.length > 0) {
|
|
1747
|
+
stateLines.push("", "Work completed:");
|
|
1748
|
+
for (const wi of workItems.slice(0, 5)) stateLines.push(`- ${wi.title}`);
|
|
1749
|
+
}
|
|
1750
|
+
if (message) stateLines.push("", `Last completed: ${message}`);
|
|
1751
|
+
updateTodoContinue(cwd, basename(currentNotePath), stateLines.join("\n"), "session-end");
|
|
1752
|
+
} catch (todoError) {
|
|
1753
|
+
process.stderr.write(`[work-queue-worker] Could not update TODO.md: ${todoError}\n`);
|
|
1754
|
+
}
|
|
1755
|
+
} else process.stderr.write("[work-queue-worker] No current session note found — skipping note update.\n");
|
|
1756
|
+
try {
|
|
1757
|
+
const movedCount = moveSessionFilesToSessionsDir(dirname(transcriptPath));
|
|
1758
|
+
if (movedCount > 0) process.stderr.write(`[work-queue-worker] Moved ${movedCount} session file(s) to sessions/.\n`);
|
|
1759
|
+
} catch (moveError) {
|
|
1760
|
+
process.stderr.write(`[work-queue-worker] Could not move session files: ${moveError}\n`);
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
/**
|
|
1764
|
+
* Run performScan() against the registry DB.
|
|
1765
|
+
*
|
|
1766
|
+
* Debounce: if another registry-scan job is already pending in the queue,
|
|
1767
|
+
* we still run this one (dequeue already picked it), but enqueueRegistryScan()
|
|
1768
|
+
* checks before enqueuing so duplicates rarely reach here.
|
|
1769
|
+
*/
|
|
1770
|
+
async function handleRegistryScan() {
|
|
1771
|
+
if (!registryDb) throw new Error("registry-scan: registryDb not initialized yet");
|
|
1772
|
+
const t0 = Date.now();
|
|
1773
|
+
process.stderr.write("[work-queue-worker] Running registry scan...\n");
|
|
1774
|
+
const result = performScan(registryDb);
|
|
1775
|
+
const elapsed = Date.now() - t0;
|
|
1776
|
+
process.stderr.write(`[work-queue-worker] Registry scan complete: ${result.projectsScanned} projects (${result.projectsNew} new, ${result.projectsUpdated} updated), ${result.sessionsScanned} sessions (${result.sessionsNew} new) in ${elapsed}ms.\n`);
|
|
1777
|
+
if (result.skipped.length > 0) process.stderr.write(`[work-queue-worker] Registry scan: ${result.skipped.length} project(s) skipped (path not found).\n`);
|
|
1778
|
+
}
|
|
1779
|
+
/**
|
|
1780
|
+
* Enqueue a registry-scan work item — debounced.
|
|
1781
|
+
* If a registry-scan item is already pending or processing, skip enqueue.
|
|
1782
|
+
*/
|
|
1783
|
+
function enqueueRegistryScan() {
|
|
1784
|
+
if (hasPendingOrProcessingOfType("registry-scan")) {
|
|
1785
|
+
process.stderr.write("[work-queue-worker] Registry scan already pending/processing — skipping duplicate enqueue.\n");
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
enqueue({
|
|
1789
|
+
type: "registry-scan",
|
|
1790
|
+
priority: 5,
|
|
1791
|
+
payload: {}
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
function tryParseJson(line) {
|
|
1795
|
+
try {
|
|
1796
|
+
return JSON.parse(line);
|
|
1797
|
+
} catch {
|
|
1798
|
+
return null;
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
function contentToText(content) {
|
|
1802
|
+
if (typeof content === "string") return content;
|
|
1803
|
+
if (Array.isArray(content)) return content.map((c) => {
|
|
1804
|
+
if (typeof c === "string") return c;
|
|
1805
|
+
const block = c;
|
|
1806
|
+
if (block?.text) return String(block.text);
|
|
1807
|
+
if (block?.content) return String(block.content);
|
|
1808
|
+
return "";
|
|
1809
|
+
}).join(" ").trim();
|
|
1810
|
+
return "";
|
|
1811
|
+
}
|
|
1812
|
+
function extractWorkFromTranscript(lines) {
|
|
1813
|
+
const workItems = [];
|
|
1814
|
+
const seenSummaries = /* @__PURE__ */ new Set();
|
|
1815
|
+
for (const line of lines) {
|
|
1816
|
+
const entry = tryParseJson(line);
|
|
1817
|
+
if (!entry || entry.type !== "assistant") continue;
|
|
1818
|
+
const msg = entry.message;
|
|
1819
|
+
if (!msg?.content) continue;
|
|
1820
|
+
const content = contentToText(msg.content);
|
|
1821
|
+
const summaryMatch = content.match(/SUMMARY:\s*(.+?)(?:\n|$)/i);
|
|
1822
|
+
if (summaryMatch) {
|
|
1823
|
+
const summary = summaryMatch[1].trim();
|
|
1824
|
+
if (summary && !seenSummaries.has(summary) && summary.length > 5) {
|
|
1825
|
+
seenSummaries.add(summary);
|
|
1826
|
+
const details = [];
|
|
1827
|
+
const actionsMatch = content.match(/ACTIONS:\s*(.+?)(?=\n[A-Z]+:|$)/is);
|
|
1828
|
+
if (actionsMatch) {
|
|
1829
|
+
const actionLines = actionsMatch[1].split("\n").map((l) => l.replace(/^[-*•]\s*/, "").replace(/^\d+\.\s*/, "").trim()).filter((l) => l.length > 3 && l.length < 100);
|
|
1830
|
+
details.push(...actionLines.slice(0, 3));
|
|
1831
|
+
}
|
|
1832
|
+
workItems.push({
|
|
1833
|
+
title: summary,
|
|
1834
|
+
details: details.length > 0 ? details : void 0,
|
|
1835
|
+
completed: true
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
const completedMatch = content.match(/COMPLETED:\s*(.+?)(?:\n|$)/i);
|
|
1840
|
+
if (completedMatch && workItems.length === 0) {
|
|
1841
|
+
const completed = completedMatch[1].trim().replace(/\*+/g, "").replace(/\[.*?\]/g, "").trim();
|
|
1842
|
+
if (completed && !seenSummaries.has(completed) && completed.length > 5) {
|
|
1843
|
+
seenSummaries.add(completed);
|
|
1844
|
+
workItems.push({
|
|
1845
|
+
title: completed,
|
|
1846
|
+
completed: true
|
|
1847
|
+
});
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
return workItems;
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
//#endregion
|
|
1855
|
+
export { enqueue as a, work_queue_worker_exports as i, startWorker as n, getStats as o, stopWorker as r, loadQueue as s, notifyNewWork as t };
|
|
1856
|
+
//# sourceMappingURL=work-queue-worker-CEMpy89q.mjs.map
|