toon-memory 4.3.4 → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.de.md +2 -2
- package/README.es.md +2 -2
- package/README.fr.md +2 -2
- package/README.ja.md +2 -2
- package/README.ko.md +2 -2
- package/README.md +59 -13
- package/README.pt-br.md +2 -2
- package/README.zh.md +2 -2
- package/bin/toon-memory.js +4 -0
- package/dist/cli/capture.js +658 -26
- package/dist/cli/setup.js +1813 -143
- package/mcp/server.js +1391 -380
- package/package.json +6 -3
- package/src/bin/toon-memory.ts +4 -0
- package/src/cli/ambient.ts +117 -0
- package/src/cli/capture.ts +5 -2
- package/src/cli/commands.ts +3 -1
- package/src/cli/constants.ts +19 -11
- package/src/cli/dense.ts +50 -0
- package/src/cli/instructions.ts +2 -2
- package/src/cli/opencode-plugin.ts +100 -95
- package/src/cli/setup.ts +51 -4
- package/src/cli/sleep.ts +45 -0
- package/src/lib/activation.ts +32 -0
- package/src/lib/compiler.ts +178 -0
- package/src/lib/dense.ts +123 -0
- package/src/lib/graph.ts +123 -36
- package/src/lib/handoff.ts +144 -0
- package/src/lib/ngrams.ts +68 -0
- package/src/lib/promoter.ts +140 -0
- package/src/lib/quality.ts +25 -10
- package/src/lib/utils.ts +17 -7
- package/src/mcp/args.ts +46 -0
- package/src/mcp/config.ts +20 -0
- package/src/mcp/edges.ts +99 -0
- package/src/mcp/entries.ts +34 -9
- package/src/mcp/feedback.ts +130 -0
- package/src/mcp/resources.ts +12 -9
- package/src/mcp/server.ts +13 -1
- package/src/mcp/tools.ts +271 -102
- package/src/viewer/html.ts +23 -25
- package/src/viewer/index.ts +8 -8
package/dist/cli/capture.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/cli/capture.ts
|
|
2
|
-
import { readFileSync as
|
|
2
|
+
import { readFileSync as readFileSync8, existsSync as existsSync8, mkdirSync as mkdirSync5 } from "fs";
|
|
3
3
|
import { join as join3 } from "path";
|
|
4
4
|
import { createHash } from "crypto";
|
|
5
5
|
|
|
@@ -89,6 +89,13 @@ function atomicWrite(file, content) {
|
|
|
89
89
|
writeFileSync(tmp, content);
|
|
90
90
|
renameSync(tmp, file);
|
|
91
91
|
}
|
|
92
|
+
function readUnderLock(file, encoding = "utf-8") {
|
|
93
|
+
let content = "";
|
|
94
|
+
withLockSync(file, () => {
|
|
95
|
+
content = readFileSync(file, encoding);
|
|
96
|
+
});
|
|
97
|
+
return content;
|
|
98
|
+
}
|
|
92
99
|
|
|
93
100
|
// src/lib/sessions.ts
|
|
94
101
|
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, readdirSync, unlinkSync as unlinkSync2, statSync as statSync2 } from "fs";
|
|
@@ -172,20 +179,67 @@ function endSession(agent, sessionId) {
|
|
|
172
179
|
}
|
|
173
180
|
|
|
174
181
|
// src/mcp/observations.ts
|
|
175
|
-
import { readFileSync as
|
|
182
|
+
import { readFileSync as readFileSync4, existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
|
|
176
183
|
|
|
177
184
|
// src/mcp/config.ts
|
|
185
|
+
import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
|
|
178
186
|
import { join as join2 } from "path";
|
|
179
187
|
import { homedir } from "os";
|
|
180
188
|
var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
|
|
181
189
|
var MEMORY_FILE = join2(MEMORY_DIR, "data.toon");
|
|
182
190
|
var ARCHIVE_FILE = join2(MEMORY_DIR, "archive.toon");
|
|
183
191
|
var OBSERVATIONS_FILE = join2(MEMORY_DIR, "observations.toon");
|
|
192
|
+
var FEEDBACK_FILE = join2(MEMORY_DIR, "feedback.toon");
|
|
193
|
+
var EDGES_FILE = join2(MEMORY_DIR, "edges.toon");
|
|
194
|
+
var VECTORS_FILE = join2(MEMORY_DIR, "vectors.bin");
|
|
184
195
|
var SECRETS_FILE = join2(MEMORY_DIR, "secrets.toon");
|
|
185
196
|
var GLOBAL_FILE = process.env.TOON_MEMORY_GLOBAL_FILE || join2(homedir(), ".toon-memory", "memory", "global.toon");
|
|
186
197
|
var CONFIG_FILE = join2(MEMORY_DIR, "config.json");
|
|
198
|
+
var ALGORITHM = "aes-256-gcm";
|
|
199
|
+
function loadConfig() {
|
|
200
|
+
if (!existsSync3(CONFIG_FILE)) {
|
|
201
|
+
return { encrypted: false };
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
return JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
|
|
205
|
+
} catch {
|
|
206
|
+
return { encrypted: false };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function getKey() {
|
|
210
|
+
return process.env.TOON_MEMORY_KEY;
|
|
211
|
+
}
|
|
212
|
+
function ensureMemoryDir() {
|
|
213
|
+
if (!existsSync3(MEMORY_DIR)) mkdirSync2(MEMORY_DIR, { recursive: true });
|
|
214
|
+
}
|
|
215
|
+
function ensureMemoryFile() {
|
|
216
|
+
ensureMemoryDir();
|
|
217
|
+
if (!existsSync3(MEMORY_FILE)) {
|
|
218
|
+
writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence|lastAccessed|pinned}:\n");
|
|
219
|
+
}
|
|
220
|
+
}
|
|
187
221
|
|
|
188
222
|
// src/lib/utils.ts
|
|
223
|
+
var importanceRank = (level) => {
|
|
224
|
+
if (level === "critical") return 4;
|
|
225
|
+
if (level === "high") return 3;
|
|
226
|
+
if (level === "low") return 1;
|
|
227
|
+
return 2;
|
|
228
|
+
};
|
|
229
|
+
var escField = (s) => {
|
|
230
|
+
let out = "";
|
|
231
|
+
for (let i = 0; i < s.length; i++) {
|
|
232
|
+
const c = s[i];
|
|
233
|
+
if (c === "\\") out += "\\\\";
|
|
234
|
+
else if (c === "\n") out += "\\n";
|
|
235
|
+
else if (c === "\r") {
|
|
236
|
+
out += "\\n";
|
|
237
|
+
if (s[i + 1] === "\n") i++;
|
|
238
|
+
} else if (c === "|") out += "\\|";
|
|
239
|
+
else out += c;
|
|
240
|
+
}
|
|
241
|
+
return out;
|
|
242
|
+
};
|
|
189
243
|
var unescField = (s) => {
|
|
190
244
|
let out = "";
|
|
191
245
|
for (let i = 0; i < s.length; i++) {
|
|
@@ -232,35 +286,611 @@ var parseToonLine = (line) => {
|
|
|
232
286
|
parts.push(unescField(cur));
|
|
233
287
|
return parts;
|
|
234
288
|
};
|
|
289
|
+
var toToonLine = (parts) => ` ${parts.map(escField).join("|")}`;
|
|
235
290
|
|
|
236
291
|
// src/mcp/observations.ts
|
|
237
292
|
var MAX_OBSERVATIONS = 500;
|
|
293
|
+
function readObservations() {
|
|
294
|
+
if (!existsSync4(OBSERVATIONS_FILE)) return [];
|
|
295
|
+
return readFileSync4(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
|
|
296
|
+
const p = parseToonLine(l);
|
|
297
|
+
return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" };
|
|
298
|
+
});
|
|
299
|
+
}
|
|
238
300
|
function pruneObservations() {
|
|
239
|
-
if (!
|
|
240
|
-
const data =
|
|
301
|
+
if (!existsSync4(OBSERVATIONS_FILE)) return 0;
|
|
302
|
+
const data = readFileSync4(OBSERVATIONS_FILE, "utf-8");
|
|
241
303
|
const lines = data.split("\n");
|
|
242
304
|
const headerIdx = lines.findIndex((l) => l.startsWith("observations["));
|
|
243
305
|
if (headerIdx === -1) return 0;
|
|
244
|
-
const
|
|
245
|
-
if (
|
|
246
|
-
const toRemove =
|
|
247
|
-
const pruned =
|
|
248
|
-
const kept =
|
|
306
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
|
|
307
|
+
if (entryLines2.length <= MAX_OBSERVATIONS) return 0;
|
|
308
|
+
const toRemove = entryLines2.length - MAX_OBSERVATIONS;
|
|
309
|
+
const pruned = entryLines2.slice(toRemove);
|
|
310
|
+
const kept = entryLines2.slice(0, MAX_OBSERVATIONS);
|
|
249
311
|
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`);
|
|
250
312
|
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...kept.map((l) => ` ${l.trim()}`));
|
|
251
|
-
|
|
313
|
+
writeFileSync4(OBSERVATIONS_FILE, lines.join("\n"));
|
|
252
314
|
return toRemove;
|
|
253
315
|
}
|
|
254
316
|
|
|
317
|
+
// src/mcp/crypto.ts
|
|
318
|
+
import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
|
|
319
|
+
function encrypt(text, key) {
|
|
320
|
+
const keyBuffer = Buffer.from(key, "hex");
|
|
321
|
+
const iv = randomBytes(16);
|
|
322
|
+
const cipher = createCipheriv(ALGORITHM, keyBuffer, iv);
|
|
323
|
+
let encrypted = cipher.update(text, "utf8", "hex");
|
|
324
|
+
encrypted += cipher.final("hex");
|
|
325
|
+
const authTag = cipher.getAuthTag();
|
|
326
|
+
return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
|
|
327
|
+
}
|
|
328
|
+
function decrypt(encryptedData, key) {
|
|
329
|
+
const keyBuffer = Buffer.from(key, "hex");
|
|
330
|
+
const parts = encryptedData.split(":");
|
|
331
|
+
if (parts.length !== 3) {
|
|
332
|
+
throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext");
|
|
333
|
+
}
|
|
334
|
+
const [ivHex, authTagHex, encrypted] = parts;
|
|
335
|
+
const iv = Buffer.from(ivHex, "hex");
|
|
336
|
+
const authTag = Buffer.from(authTagHex, "hex");
|
|
337
|
+
const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv);
|
|
338
|
+
decipher.setAuthTag(authTag);
|
|
339
|
+
let decrypted = decipher.update(encrypted, "hex", "utf8");
|
|
340
|
+
decrypted += decipher.final("utf8");
|
|
341
|
+
return decrypted;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/mcp/memory-io.ts
|
|
345
|
+
function safeWrite(file, content) {
|
|
346
|
+
withLockSync(file, () => atomicWrite(file, content));
|
|
347
|
+
}
|
|
348
|
+
function readMemory() {
|
|
349
|
+
ensureMemoryFile();
|
|
350
|
+
const config = loadConfig();
|
|
351
|
+
const data = readUnderLock(MEMORY_FILE);
|
|
352
|
+
if (config.encrypted) {
|
|
353
|
+
const key = getKey();
|
|
354
|
+
if (!key) throw new Error("Encryption enabled but TOON_MEMORY_KEY is not set. Run 'npx toon-memory init' or set the env var.");
|
|
355
|
+
return decrypt(data, key);
|
|
356
|
+
}
|
|
357
|
+
return data;
|
|
358
|
+
}
|
|
359
|
+
function writeMemory(content) {
|
|
360
|
+
ensureMemoryFile();
|
|
361
|
+
const config = loadConfig();
|
|
362
|
+
if (config.encrypted) {
|
|
363
|
+
const key = getKey();
|
|
364
|
+
if (!key) throw new Error("Encryption enabled but TOON_MEMORY_KEY is not set. Run 'npx toon-memory init' or set the env var.");
|
|
365
|
+
const encrypted = encrypt(content, key);
|
|
366
|
+
safeWrite(MEMORY_FILE, encrypted);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
safeWrite(MEMORY_FILE, content);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/lib/graph.ts
|
|
373
|
+
var DEFAULT_EDGE_TYPE = "related";
|
|
374
|
+
function parseLinkToken(token) {
|
|
375
|
+
const idx = token.lastIndexOf(":");
|
|
376
|
+
if (idx === -1) return { type: DEFAULT_EDGE_TYPE, key: token };
|
|
377
|
+
const type = token.slice(0, idx);
|
|
378
|
+
const key = token.slice(idx + 1);
|
|
379
|
+
return { type: type || DEFAULT_EDGE_TYPE, key: key || token };
|
|
380
|
+
}
|
|
381
|
+
var entryLines = (data) => data.split("\n").filter(
|
|
382
|
+
(l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
|
|
383
|
+
);
|
|
384
|
+
function parseEntries(data) {
|
|
385
|
+
const out = [];
|
|
386
|
+
for (const line of entryLines(data)) {
|
|
387
|
+
const parts = parseToonLine(line);
|
|
388
|
+
if (parts.length < 3) continue;
|
|
389
|
+
const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] = parts;
|
|
390
|
+
out.push({
|
|
391
|
+
id,
|
|
392
|
+
category,
|
|
393
|
+
key,
|
|
394
|
+
content,
|
|
395
|
+
file: file || "",
|
|
396
|
+
tags: (tags || "").split(";").map((t) => t.trim()).filter(Boolean),
|
|
397
|
+
date: date || "",
|
|
398
|
+
ttl: ttl || "",
|
|
399
|
+
accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
|
|
400
|
+
links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean),
|
|
401
|
+
lastAccessed: parts.length > 12 ? parts[12] || "" : "",
|
|
402
|
+
priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
|
|
403
|
+
path_scope: parts.length > 14 ? parts[14] || "" : "",
|
|
404
|
+
origin: parts.length > 15 && parts[15] ? parts[15] : "agent",
|
|
405
|
+
status: parts.length > 16 && parts[16] ? parts[16] : "active",
|
|
406
|
+
supersededOn: parts.length > 17 ? parts[17] || "" : "",
|
|
407
|
+
importance: parts.length > 18 ? parts[18] || "" : "",
|
|
408
|
+
evidence: parts.length > 19 ? parts[19] || "" : ""
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
return out;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// src/lib/promoter.ts
|
|
415
|
+
var PROMOTE_THRESHOLD = 0.75;
|
|
416
|
+
var DIRECTIVE = /recuerda|siempre|nunca|no hagas|importante|ten cuidado|decidimos|must not|always|never/i;
|
|
417
|
+
var FIX = /fix|fixed|error|fallo|bug|verified|pas(o|ó|ed)|green/i;
|
|
418
|
+
var DECISION = /decidimos|elegimos|optamos|rechazamos|commit|merge|pr\b/i;
|
|
419
|
+
function slug(text) {
|
|
420
|
+
return text.toLowerCase().replace(/[^a-z0-9áéíóúñü]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "signal";
|
|
421
|
+
}
|
|
422
|
+
function scoreSignal(signal) {
|
|
423
|
+
const text = `${signal.summary} ${signal.file}`;
|
|
424
|
+
const type = signal.type.replace(/:$/, "");
|
|
425
|
+
const hasFile = Boolean(signal.file);
|
|
426
|
+
const lengthOk = signal.summary.length >= 40 && signal.summary.length <= 300;
|
|
427
|
+
let score = 0.2;
|
|
428
|
+
let category = "knowledge";
|
|
429
|
+
let tags = "auto-captured";
|
|
430
|
+
let origin = "inferred";
|
|
431
|
+
let importance2 = "";
|
|
432
|
+
let evidence = "unverified";
|
|
433
|
+
if (type === "user_directive" || DIRECTIVE.test(text)) {
|
|
434
|
+
category = "warning";
|
|
435
|
+
origin = "human";
|
|
436
|
+
importance2 = "high";
|
|
437
|
+
tags = "auto-captured;directive";
|
|
438
|
+
score = 0.85;
|
|
439
|
+
} else if (type === "error_fix" || FIX.test(text)) {
|
|
440
|
+
category = "bug";
|
|
441
|
+
tags = "auto-captured;error-fix";
|
|
442
|
+
score = 0.6;
|
|
443
|
+
if (hasFile && FIX.test(text)) evidence = "verified";
|
|
444
|
+
} else if (type === "decision" || DECISION.test(text)) {
|
|
445
|
+
category = "decision";
|
|
446
|
+
tags = "auto-captured;decision";
|
|
447
|
+
score = 0.58;
|
|
448
|
+
} else if (type === "diff_pattern") {
|
|
449
|
+
category = "pattern";
|
|
450
|
+
tags = "auto-captured;pattern";
|
|
451
|
+
score = 0.45;
|
|
452
|
+
} else if (type === "checkpoint") {
|
|
453
|
+
tags = "auto-captured;checkpoint";
|
|
454
|
+
score = 0.4;
|
|
455
|
+
}
|
|
456
|
+
if (lengthOk) score += 0.08;
|
|
457
|
+
if (hasFile) score += 0.04;
|
|
458
|
+
if (origin === "human") score += 0.04;
|
|
459
|
+
if (evidence === "verified") score += 0.06;
|
|
460
|
+
return { signal, score: Math.min(1, Number(score.toFixed(2))), category, tags, origin, importance: importance2, evidence };
|
|
461
|
+
}
|
|
462
|
+
function promoteSignals(data, signals, opts = {}) {
|
|
463
|
+
const threshold = opts.threshold ?? PROMOTE_THRESHOLD;
|
|
464
|
+
const today = opts.today || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
465
|
+
const lines = data.split("\n");
|
|
466
|
+
let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
467
|
+
if (headerIdx === -1) {
|
|
468
|
+
lines.push("[0|]");
|
|
469
|
+
headerIdx = lines.length - 1;
|
|
470
|
+
}
|
|
471
|
+
const known = new Set(parseEntries(data).map((e) => e.key));
|
|
472
|
+
const promoted = [];
|
|
473
|
+
let kept = 0;
|
|
474
|
+
for (const raw of signals) {
|
|
475
|
+
const signal = { ...raw, summary: (raw.summary || "").replace(/\s+/g, " ").trim() };
|
|
476
|
+
const scored = scoreSignal(signal);
|
|
477
|
+
if (scored.score < threshold || !signal.summary) {
|
|
478
|
+
kept++;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
const key = `${scored.category}-${slug(signal.summary)}`;
|
|
482
|
+
if (known.has(key)) {
|
|
483
|
+
kept++;
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
known.add(key);
|
|
487
|
+
const id = `sig-${Date.now().toString(36)}-${promoted.length.toString(36)}`;
|
|
488
|
+
const line = toToonLine([
|
|
489
|
+
id,
|
|
490
|
+
scored.category,
|
|
491
|
+
key,
|
|
492
|
+
escField(signal.summary),
|
|
493
|
+
escField(signal.file || ""),
|
|
494
|
+
scored.tags,
|
|
495
|
+
today,
|
|
496
|
+
"",
|
|
497
|
+
"0",
|
|
498
|
+
"",
|
|
499
|
+
"0.85",
|
|
500
|
+
"1.0",
|
|
501
|
+
today,
|
|
502
|
+
"0",
|
|
503
|
+
"",
|
|
504
|
+
scored.origin,
|
|
505
|
+
"active",
|
|
506
|
+
"",
|
|
507
|
+
scored.importance,
|
|
508
|
+
scored.evidence
|
|
509
|
+
]);
|
|
510
|
+
lines.splice(headerIdx + 1, 0, line);
|
|
511
|
+
promoted.push({ key, category: scored.category, score: scored.score });
|
|
512
|
+
}
|
|
513
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/);
|
|
514
|
+
const count = match ? parseInt(match[1]) : 0;
|
|
515
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + promoted.length}|`);
|
|
516
|
+
return { data: lines.join("\n"), promoted, kept };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// src/mcp/feedback.ts
|
|
520
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync5 } from "fs";
|
|
521
|
+
var SIGNAL_WEIGHT = {
|
|
522
|
+
useful: 1,
|
|
523
|
+
irrelevant: -1,
|
|
524
|
+
outdated: -1.5,
|
|
525
|
+
wrong: -2
|
|
526
|
+
};
|
|
527
|
+
function readFeedback() {
|
|
528
|
+
if (!existsSync5(FEEDBACK_FILE)) return [];
|
|
529
|
+
let data = "";
|
|
530
|
+
try {
|
|
531
|
+
data = readFileSync5(FEEDBACK_FILE, "utf-8");
|
|
532
|
+
} catch {
|
|
533
|
+
return [];
|
|
534
|
+
}
|
|
535
|
+
const lines = data.split("\n");
|
|
536
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("feedback[") || /^\[\d+\|]/.test(l));
|
|
537
|
+
if (headerIdx === -1) return [];
|
|
538
|
+
const out = [];
|
|
539
|
+
for (const line of lines.slice(headerIdx + 1)) {
|
|
540
|
+
if (!line.startsWith(" ") || !line.includes("|")) continue;
|
|
541
|
+
const p = parseToonLine(line.trim());
|
|
542
|
+
if (p.length < 5) continue;
|
|
543
|
+
const signal = p[2];
|
|
544
|
+
if (!(signal in SIGNAL_WEIGHT)) continue;
|
|
545
|
+
out.push({
|
|
546
|
+
id: p[0],
|
|
547
|
+
key: p[1],
|
|
548
|
+
signal,
|
|
549
|
+
source: p[3] === "implicit" ? "implicit" : "explicit",
|
|
550
|
+
ts: p[4],
|
|
551
|
+
session: p[5] || "",
|
|
552
|
+
task: p[6] || ""
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// src/mcp/edges.ts
|
|
559
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "fs";
|
|
560
|
+
import { dirname } from "path";
|
|
561
|
+
var EDGE_TYPES = ["related", "supports", "contradicts", "supersedes", "depends_on", "derived_from", "used_in"];
|
|
562
|
+
var MAX_EDGES = 2e3;
|
|
563
|
+
function normalizeType(type) {
|
|
564
|
+
const t = type.toLowerCase();
|
|
565
|
+
return EDGE_TYPES.includes(t) ? t : "related";
|
|
566
|
+
}
|
|
567
|
+
function writeEdges(edges) {
|
|
568
|
+
const dir = dirname(EDGES_FILE);
|
|
569
|
+
if (!existsSync6(dir)) mkdirSync4(dir, { recursive: true });
|
|
570
|
+
const sorted = [...edges].filter((e) => e.from && e.to && e.from !== e.to).sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || a.type.localeCompare(b.type)).slice(0, MAX_EDGES);
|
|
571
|
+
const header = `version: 1
|
|
572
|
+
edges[${sorted.length}|]{from|to|type|weight|ts}:`;
|
|
573
|
+
const lines = [header, ...sorted.map((e) => toToonLine([e.from, e.to, e.type, String(e.weight), e.ts]))];
|
|
574
|
+
withLockSync(EDGES_FILE, () => atomicWrite(EDGES_FILE, lines.join("\n")));
|
|
575
|
+
}
|
|
576
|
+
function deriveEdges(data, feedback = []) {
|
|
577
|
+
const entries = parseEntries(data);
|
|
578
|
+
const keys = new Set(entries.map((e) => e.key));
|
|
579
|
+
const map = /* @__PURE__ */ new Map();
|
|
580
|
+
const add = (from, to, type, weight, ts) => {
|
|
581
|
+
if (!keys.has(from) || !keys.has(to) || from === to) return;
|
|
582
|
+
const id = `${from}|${to}|${type}`;
|
|
583
|
+
const prev = map.get(id);
|
|
584
|
+
if (prev) prev.weight = Math.max(prev.weight, weight);
|
|
585
|
+
else map.set(id, { from, to, type, weight, ts });
|
|
586
|
+
};
|
|
587
|
+
for (const e of entries) {
|
|
588
|
+
for (const link of e.links) {
|
|
589
|
+
const { type, key } = parseLinkToken(link);
|
|
590
|
+
add(e.key, key, normalizeType(type), 1, e.date);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
for (const event of feedback) {
|
|
594
|
+
if (!event.task) continue;
|
|
595
|
+
const haystack = event.task.toLowerCase();
|
|
596
|
+
const type = event.signal === "wrong" || event.signal === "outdated" ? "contradicts" : "used_in";
|
|
597
|
+
const weight = event.signal === "useful" ? 1 : 0.5;
|
|
598
|
+
for (const key of keys) {
|
|
599
|
+
if (key === event.key) continue;
|
|
600
|
+
if (!haystack.includes(key.toLowerCase())) continue;
|
|
601
|
+
add(event.key, key, type, weight, event.ts.slice(0, 10));
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return [...map.values()];
|
|
605
|
+
}
|
|
606
|
+
function rebuildEdges(data, feedback = []) {
|
|
607
|
+
const edges = deriveEdges(data, feedback);
|
|
608
|
+
writeEdges(edges);
|
|
609
|
+
return edges.length;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// src/mcp/archive.ts
|
|
613
|
+
import { readFileSync as readFileSync7, existsSync as existsSync7 } from "fs";
|
|
614
|
+
|
|
615
|
+
// src/mcp/entries.ts
|
|
616
|
+
function parseTTL(ttl) {
|
|
617
|
+
if (!ttl || !ttl.trim()) return "";
|
|
618
|
+
const trimmed = ttl.trim();
|
|
619
|
+
const dayMatch = trimmed.match(/^(\d+)d$/);
|
|
620
|
+
if (dayMatch) {
|
|
621
|
+
const days = parseInt(dayMatch[1]);
|
|
622
|
+
const d = /* @__PURE__ */ new Date();
|
|
623
|
+
d.setDate(d.getDate() + days);
|
|
624
|
+
return d.toISOString().split("T")[0];
|
|
625
|
+
}
|
|
626
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
|
|
627
|
+
return "";
|
|
628
|
+
}
|
|
629
|
+
function isExpired(ttl) {
|
|
630
|
+
if (!ttl) return false;
|
|
631
|
+
const ttlDate = parseTTL(ttl) || ttl;
|
|
632
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
633
|
+
return ttlDate <= today;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// src/mcp/archive.ts
|
|
637
|
+
function findHeaderIdx(lines) {
|
|
638
|
+
return lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
639
|
+
}
|
|
640
|
+
function bumpHeaderCount(line, count) {
|
|
641
|
+
return line.replace(/^([a-z]+)?\[(\d+)\|/, (_m, pre) => `${pre || ""}[${count}|`);
|
|
642
|
+
}
|
|
643
|
+
function pruneExpiredEntries() {
|
|
644
|
+
ensureMemoryFile();
|
|
645
|
+
if (!existsSync7(MEMORY_FILE)) return 0;
|
|
646
|
+
let pruned = 0;
|
|
647
|
+
withLockSync(MEMORY_FILE, () => {
|
|
648
|
+
const data = readMemory();
|
|
649
|
+
const lines = data.split("\n");
|
|
650
|
+
const headerIdx = findHeaderIdx(lines);
|
|
651
|
+
if (headerIdx === -1) return;
|
|
652
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
|
|
653
|
+
const kept = entryLines2.filter((l) => {
|
|
654
|
+
const parts = parseToonLine(l);
|
|
655
|
+
if (parts.length < 8) return true;
|
|
656
|
+
const ttl = parts[7] || "";
|
|
657
|
+
if (ttl && isExpired(ttl)) {
|
|
658
|
+
pruned++;
|
|
659
|
+
return false;
|
|
660
|
+
}
|
|
661
|
+
return true;
|
|
662
|
+
});
|
|
663
|
+
if (pruned === 0) return;
|
|
664
|
+
lines[headerIdx] = bumpHeaderCount(lines[headerIdx], kept.length);
|
|
665
|
+
const keepSet = new Set(kept.map((l) => l.trim()));
|
|
666
|
+
const allEntryLines = lines.slice(headerIdx + 1);
|
|
667
|
+
const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()));
|
|
668
|
+
lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => l.trim().length ? ` ${l.trim()}` : l));
|
|
669
|
+
writeMemory(lines.join("\n"));
|
|
670
|
+
});
|
|
671
|
+
return pruned;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// src/lib/quality.ts
|
|
675
|
+
function qualityScore(tags, links, content, date, accessed = 0, lastAccessed = "", origin = "") {
|
|
676
|
+
let score = 0;
|
|
677
|
+
if (tags) {
|
|
678
|
+
const count = tags.split(";").filter(Boolean).length;
|
|
679
|
+
score += Math.min(0.3, count * 0.1);
|
|
680
|
+
}
|
|
681
|
+
if (links) {
|
|
682
|
+
const count = links.split(/[\s;]+/).filter(Boolean).length;
|
|
683
|
+
score += Math.min(0.2, count * 0.1);
|
|
684
|
+
}
|
|
685
|
+
const len = content.length;
|
|
686
|
+
if (len > 20) score += 0.1;
|
|
687
|
+
if (len > 60) score += 0.1;
|
|
688
|
+
if (len > 150) score += 0.1;
|
|
689
|
+
if (date) {
|
|
690
|
+
const days = (Date.now() - (/* @__PURE__ */ new Date(`${date}T00:00:00`)).getTime()) / 864e5;
|
|
691
|
+
if (days < 7) score += 0.1;
|
|
692
|
+
else if (days < 30) score += 0.05;
|
|
693
|
+
}
|
|
694
|
+
const words = content.toLowerCase().split(/\s+/).filter(Boolean);
|
|
695
|
+
const unique = new Set(words);
|
|
696
|
+
const specificity = words.length > 0 ? unique.size / words.length : 0;
|
|
697
|
+
score += specificity * 0.1;
|
|
698
|
+
if (accessed > 0) {
|
|
699
|
+
score += Math.min(0.15, accessed * 0.03);
|
|
700
|
+
}
|
|
701
|
+
if (lastAccessed) {
|
|
702
|
+
const daysSinceAccess = (Date.now() - new Date(lastAccessed).getTime()) / 864e5;
|
|
703
|
+
if (daysSinceAccess < 1) score += 0.1;
|
|
704
|
+
else if (daysSinceAccess < 7) score += 0.07;
|
|
705
|
+
else if (daysSinceAccess < 30) score += 0.03;
|
|
706
|
+
}
|
|
707
|
+
if (origin === "human") score += 0.1;
|
|
708
|
+
else if (origin === "inferred") score -= 0.05;
|
|
709
|
+
if (date) {
|
|
710
|
+
const daysSinceCreation = (Date.now() - (/* @__PURE__ */ new Date(`${date}T00:00:00`)).getTime()) / 864e5;
|
|
711
|
+
const daysSinceLastAccess = lastAccessed ? (Date.now() - new Date(lastAccessed).getTime()) / 864e5 : daysSinceCreation;
|
|
712
|
+
if (daysSinceCreation > 30 && daysSinceLastAccess > 30) {
|
|
713
|
+
const staleness = Math.min(1, (daysSinceLastAccess - 30) / 90);
|
|
714
|
+
score -= staleness * 0.2;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
return Math.max(0, Math.min(1, score));
|
|
718
|
+
}
|
|
719
|
+
function mergeEntries(existingLine, newLine) {
|
|
720
|
+
const ep = parseToonLine(existingLine);
|
|
721
|
+
const np = parseToonLine(newLine);
|
|
722
|
+
if (ep.length < 7 || np.length < 7) return newLine;
|
|
723
|
+
const id = ep[0];
|
|
724
|
+
const category = np[1] || ep[1];
|
|
725
|
+
const key = ep[2];
|
|
726
|
+
const content = np[3] || ep[3];
|
|
727
|
+
const file = np[4] || ep[4];
|
|
728
|
+
const existingTags = (ep[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
|
|
729
|
+
const newTags = (np[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
|
|
730
|
+
const mergedTags = [.../* @__PURE__ */ new Set([...existingTags, ...newTags])].join(";");
|
|
731
|
+
const existingDate = ep[6] || "";
|
|
732
|
+
const newDate = np[6] || "";
|
|
733
|
+
const date = newDate > existingDate ? newDate : existingDate;
|
|
734
|
+
const existingTtl = ep[7] || "";
|
|
735
|
+
const newTtl = np[7] || "";
|
|
736
|
+
const ttl = newTtl || existingTtl;
|
|
737
|
+
const existingAccessed = ep.length > 8 ? parseInt(ep[8]) || 0 : 0;
|
|
738
|
+
const newAccessed = np.length > 8 ? parseInt(np[8]) || 0 : 0;
|
|
739
|
+
const accessed = Math.max(existingAccessed, newAccessed);
|
|
740
|
+
const existingLinks = (ep[9] || "").split(/[\s;]+/).filter(Boolean);
|
|
741
|
+
const newLinks = (np[9] || "").split(/[\s;]+/).filter(Boolean);
|
|
742
|
+
const mergedLinks = [.../* @__PURE__ */ new Set([...existingLinks, ...newLinks])].join(" ");
|
|
743
|
+
const existingConf = ep.length > 11 ? parseFloat(ep[11]) || 0 : 0;
|
|
744
|
+
const newConf = np.length > 11 ? parseFloat(np[11]) || 0 : 0;
|
|
745
|
+
const confidence = Math.max(existingConf, newConf);
|
|
746
|
+
const existingLastAccessed = ep.length > 12 ? ep[12] || "" : "";
|
|
747
|
+
const newLastAccessed = np.length > 12 ? np[12] || "" : "";
|
|
748
|
+
const lastAccessed = newLastAccessed > existingLastAccessed ? newLastAccessed : existingLastAccessed;
|
|
749
|
+
const existingPriority = ep.length > 13 ? parseInt(ep[13]) || 0 : 0;
|
|
750
|
+
const newPriority = np.length > 13 ? parseInt(np[13]) || 0 : 0;
|
|
751
|
+
const priority = Math.max(existingPriority, newPriority);
|
|
752
|
+
const quality = qualityScore(mergedTags, mergedLinks, content, date, accessed, lastAccessed);
|
|
753
|
+
const existingScope = ep.length > 14 ? ep[14] || "" : "";
|
|
754
|
+
const newScope = np.length > 14 ? np[14] || "" : "";
|
|
755
|
+
const path_scope = newScope || existingScope;
|
|
756
|
+
const existingOrigin = ep.length > 15 ? ep[15] || "" : "";
|
|
757
|
+
const newOrigin = np.length > 15 ? np[15] || "" : "";
|
|
758
|
+
const originRank = { human: 3, agent: 2, inferred: 1 };
|
|
759
|
+
const origin = (originRank[newOrigin] || 0) >= (originRank[existingOrigin] || 0) ? newOrigin : existingOrigin;
|
|
760
|
+
const existingStatus = ep.length > 16 ? ep[16] || "" : "";
|
|
761
|
+
const newStatus = np.length > 16 ? np[16] || "" : "";
|
|
762
|
+
const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active";
|
|
763
|
+
const existingSupersededOn = ep.length > 17 ? ep[17] || "" : "";
|
|
764
|
+
const existingImportance = ep.length > 18 ? ep[18] || "" : "";
|
|
765
|
+
const newImportance = np.length > 18 ? np[18] || "" : "";
|
|
766
|
+
const importance2 = importanceRank(newImportance) >= importanceRank(existingImportance) ? newImportance : existingImportance;
|
|
767
|
+
const existingEvidence = ep.length > 19 ? ep[19] || "" : "";
|
|
768
|
+
const newEvidence = np.length > 19 ? np[19] || "" : "";
|
|
769
|
+
const evidence = existingEvidence === "conflict" || newEvidence === "conflict" ? "conflict" : newEvidence || existingEvidence;
|
|
770
|
+
return toToonLine([id, category, key, content, file, mergedTags, date, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn, importance2, evidence]);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// src/mcp/consolidation.ts
|
|
774
|
+
function contentSimilarity(a, b) {
|
|
775
|
+
const wordsA = new Set(a.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
|
|
776
|
+
const wordsB = new Set(b.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
|
|
777
|
+
if (wordsA.size === 0 && wordsB.size === 0) return 1;
|
|
778
|
+
if (wordsA.size === 0 || wordsB.size === 0) return 0;
|
|
779
|
+
let intersection = 0;
|
|
780
|
+
for (const w of wordsA) {
|
|
781
|
+
if (wordsB.has(w)) intersection++;
|
|
782
|
+
}
|
|
783
|
+
const union = wordsA.size + wordsB.size - intersection;
|
|
784
|
+
return union > 0 ? intersection / union : 0;
|
|
785
|
+
}
|
|
786
|
+
var NEAR_DUP_THRESHOLD = 0.7;
|
|
787
|
+
function consolidateEntries() {
|
|
788
|
+
const data = readMemory();
|
|
789
|
+
const lines = data.split("\n");
|
|
790
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
791
|
+
if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
|
|
792
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
|
|
793
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
794
|
+
const keyOrder = [];
|
|
795
|
+
const mergedAway = [];
|
|
796
|
+
for (let i = 0; i < entryLines2.length; i++) {
|
|
797
|
+
const line = entryLines2[i].trim();
|
|
798
|
+
const parts = parseToonLine(line);
|
|
799
|
+
if (parts.length < 3) continue;
|
|
800
|
+
const key = parts[2];
|
|
801
|
+
const existingIdx = keyOrder.findIndex((idx) => {
|
|
802
|
+
const ep = parseToonLine(entryLines2[idx]);
|
|
803
|
+
return ep[2] === key;
|
|
804
|
+
});
|
|
805
|
+
if (existingIdx !== -1) {
|
|
806
|
+
const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx]), line);
|
|
807
|
+
byKey.set(keyOrder[existingIdx], mergedLine);
|
|
808
|
+
mergedAway.push(i);
|
|
809
|
+
} else {
|
|
810
|
+
byKey.set(i, line);
|
|
811
|
+
keyOrder.push(i);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
const contentSeen = /* @__PURE__ */ new Map();
|
|
815
|
+
const order = [];
|
|
816
|
+
const duplicates = [];
|
|
817
|
+
for (const idx of keyOrder) {
|
|
818
|
+
const line = byKey.get(idx);
|
|
819
|
+
const parts = parseToonLine(line);
|
|
820
|
+
if (parts.length < 3) {
|
|
821
|
+
order.push(line);
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
const content = parts[3] || "";
|
|
825
|
+
const normalized = content.toLowerCase().replace(/\s+/g, " ").trim();
|
|
826
|
+
if (contentSeen.has(normalized)) {
|
|
827
|
+
duplicates.push(parts[2]);
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
let merged = false;
|
|
831
|
+
for (const [seenNorm, existing] of contentSeen) {
|
|
832
|
+
const existingParts = parseToonLine(existing.line);
|
|
833
|
+
if (existingParts[1] !== parts[1]) continue;
|
|
834
|
+
const sim = contentSimilarity(content, existingParts[3] || "");
|
|
835
|
+
if (sim >= NEAR_DUP_THRESHOLD) {
|
|
836
|
+
const mergedLine = mergeEntries(existing.line, line);
|
|
837
|
+
contentSeen.set(seenNorm, { line: mergedLine, idx: existing.idx });
|
|
838
|
+
const orderIdx = order.findIndex((l) => l === existing.line);
|
|
839
|
+
if (orderIdx !== -1) order[orderIdx] = mergedLine;
|
|
840
|
+
duplicates.push(parts[2]);
|
|
841
|
+
merged = true;
|
|
842
|
+
break;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if (!merged) {
|
|
846
|
+
contentSeen.set(normalized, { line, idx: order.length });
|
|
847
|
+
order.push(line);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const totalRemoved = mergedAway.length + duplicates.length;
|
|
851
|
+
if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] };
|
|
852
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`);
|
|
853
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`));
|
|
854
|
+
writeMemory(lines.join("\n"));
|
|
855
|
+
return { removed: totalRemoved, kept: order.length, duplicates };
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// src/cli/sleep.ts
|
|
859
|
+
function runSleep() {
|
|
860
|
+
const config = loadConfig();
|
|
861
|
+
if (!config.sleep?.enabled && process.env.TOON_MEMORY_SLEEP !== "1") {
|
|
862
|
+
return { ran: false, promoted: 0, edges: 0, pruned: 0, duplicates: 0 };
|
|
863
|
+
}
|
|
864
|
+
const signals = readObservations().map((o) => ({
|
|
865
|
+
type: o.tool,
|
|
866
|
+
summary: o.summary,
|
|
867
|
+
file: o.file,
|
|
868
|
+
session: o.session,
|
|
869
|
+
ts: o.ts
|
|
870
|
+
}));
|
|
871
|
+
const promotedResult = promoteSignals(readMemory(), signals, {});
|
|
872
|
+
if (promotedResult.promoted.length > 0) writeMemory(promotedResult.data);
|
|
873
|
+
const edges = rebuildEdges(readMemory(), readFeedback());
|
|
874
|
+
const pruned = pruneExpiredEntries() + pruneObservations();
|
|
875
|
+
const duplicates = consolidateEntries().removed;
|
|
876
|
+
return {
|
|
877
|
+
ran: true,
|
|
878
|
+
promoted: promotedResult.promoted.length,
|
|
879
|
+
edges,
|
|
880
|
+
pruned,
|
|
881
|
+
duplicates
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
255
885
|
// src/cli/capture.ts
|
|
256
|
-
var
|
|
257
|
-
var OBSERVATIONS_FILE2 = join3(
|
|
258
|
-
var CONFIG_FILE2 = join3(
|
|
886
|
+
var MEMORY_DIR3 = join3(process.cwd(), ".toon-memory", "memory");
|
|
887
|
+
var OBSERVATIONS_FILE2 = join3(MEMORY_DIR3, "observations.toon");
|
|
888
|
+
var CONFIG_FILE2 = join3(MEMORY_DIR3, "config.json");
|
|
259
889
|
var DEDUP_WINDOW_MS = 5 * 60 * 1e3;
|
|
260
890
|
function captureEnabled() {
|
|
261
891
|
if (process.env.TOON_MEMORY_CAPTURE) return true;
|
|
262
892
|
try {
|
|
263
|
-
const cfg = JSON.parse(
|
|
893
|
+
const cfg = JSON.parse(readFileSync8(CONFIG_FILE2, "utf-8"));
|
|
264
894
|
if (cfg && cfg.capture) return true;
|
|
265
895
|
} catch {
|
|
266
896
|
}
|
|
@@ -298,31 +928,31 @@ function derive(tool, input) {
|
|
|
298
928
|
summary = stripSecrets(String(summary || "")).replace(/\s+/g, " ").trim().slice(0, 200);
|
|
299
929
|
return { file: String(file || "").trim(), summary };
|
|
300
930
|
}
|
|
301
|
-
function
|
|
302
|
-
if (!
|
|
931
|
+
function ensureMemoryDir2() {
|
|
932
|
+
if (!existsSync8(MEMORY_DIR3)) mkdirSync5(MEMORY_DIR3, { recursive: true });
|
|
303
933
|
}
|
|
304
934
|
function appendObservation(row) {
|
|
305
|
-
|
|
306
|
-
let data =
|
|
935
|
+
ensureMemoryDir2();
|
|
936
|
+
let data = existsSync8(OBSERVATIONS_FILE2) ? readFileSync8(OBSERVATIONS_FILE2, "utf-8") : "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n";
|
|
307
937
|
const lines = data.split("\n");
|
|
308
938
|
let headerIdx = lines.findIndex((l) => l.startsWith("observations["));
|
|
309
939
|
if (headerIdx === -1) {
|
|
310
940
|
lines.push("observations[0|]{ts|session|agent|branch|tool|hash|file|summary}:");
|
|
311
941
|
headerIdx = lines.length - 1;
|
|
312
942
|
}
|
|
313
|
-
const
|
|
314
|
-
|
|
943
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0).map((l) => l.trim());
|
|
944
|
+
entryLines2.unshift(row);
|
|
315
945
|
const match = lines[headerIdx].match(/\[(\d+)\|/);
|
|
316
946
|
const count = match ? parseInt(match[1]) : 0;
|
|
317
947
|
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
|
|
318
|
-
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...
|
|
948
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...entryLines2.map((l) => ` ${l}`));
|
|
319
949
|
withLockSync(OBSERVATIONS_FILE2, () => atomicWrite(OBSERVATIONS_FILE2, lines.join("\n")));
|
|
320
950
|
}
|
|
321
951
|
function main() {
|
|
322
952
|
const agent = process.argv[2] || "agent";
|
|
323
953
|
let raw = "";
|
|
324
954
|
try {
|
|
325
|
-
raw =
|
|
955
|
+
raw = readFileSync8(0, "utf-8");
|
|
326
956
|
} catch {
|
|
327
957
|
process.exit(0);
|
|
328
958
|
}
|
|
@@ -339,8 +969,10 @@ function main() {
|
|
|
339
969
|
if (sessionEnabled()) {
|
|
340
970
|
const input2 = payload.tool_input ?? payload.input ?? {};
|
|
341
971
|
const { file: file2 } = derive(effectiveTool, input2);
|
|
342
|
-
if (isStop)
|
|
343
|
-
|
|
972
|
+
if (isStop) {
|
|
973
|
+
endSession(agent, sessionId);
|
|
974
|
+
runSleep();
|
|
975
|
+
} else heartbeat(agent, sessionId, { file: file2 });
|
|
344
976
|
}
|
|
345
977
|
if (!captureEnabled()) process.exit(0);
|
|
346
978
|
const input = payload.tool_input ?? payload.input ?? {};
|
|
@@ -349,8 +981,8 @@ function main() {
|
|
|
349
981
|
const hash = createHash("sha256").update(`${effectiveTool}|${normalized}`).digest("hex").slice(0, 16);
|
|
350
982
|
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
351
983
|
const branch = currentBranch();
|
|
352
|
-
if (
|
|
353
|
-
const data =
|
|
984
|
+
if (existsSync8(OBSERVATIONS_FILE2)) {
|
|
985
|
+
const data = readFileSync8(OBSERVATIONS_FILE2, "utf-8");
|
|
354
986
|
for (const line of data.split("\n")) {
|
|
355
987
|
if (!line.startsWith(" ")) continue;
|
|
356
988
|
const p = parseToonLine(line);
|