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/setup.js
CHANGED
|
@@ -12,7 +12,7 @@ var CAPTURE_JS = join(scriptDir, "capture.js");
|
|
|
12
12
|
var SESSION_START_JS = join(scriptDir, "session-start.js");
|
|
13
13
|
var CAPTURE_CONFIG = join(MEMORY_DIR, "config.json");
|
|
14
14
|
var ANTIGRAVITY_HOOK_NAME = "toon-memory";
|
|
15
|
-
var
|
|
15
|
+
var INSTRUCTION_CONTENT_BASE = `# toon-memory
|
|
16
16
|
|
|
17
17
|
Persistent memory for this project. Use it to avoid re-investigating things.
|
|
18
18
|
|
|
@@ -31,11 +31,22 @@ Persistent memory for this project. Use it to avoid re-investigating things.
|
|
|
31
31
|
## At the END of every session
|
|
32
32
|
- Save important decisions, bugs resolved, and patterns observed.
|
|
33
33
|
`;
|
|
34
|
-
var
|
|
35
|
-
|
|
36
|
-
Memory
|
|
37
|
-
|
|
34
|
+
var INSTRUCTION_MARKER = "<!-- toon-memory:instructions -->";
|
|
35
|
+
var ACTIVE_RULES = `
|
|
36
|
+
## Memory loop
|
|
37
|
+
- A compact brief is auto-injected at session start; when a task is known it is a context_compile packet with directives, constraints and retrieve/hydrate keys.
|
|
38
|
+
- Call memory_compile(task=...) at task start for a fresh packet; follow its Retrieval plan and hydrate only the keys you need.
|
|
39
|
+
- Use memory_recall BEFORE the first read/grep when the task may already be solved in memory.
|
|
40
|
+
- Before editing a file, check the warnings in the brief; run memory_recall(query=<path>) for file-specific traps.
|
|
41
|
+
- When a recalled entry was useful or wrong, call memory_feedback(key=..., signal=...) to train future ranking.
|
|
42
|
+
- When you learn a directive, decision or fix, save it with memory_remember \u2014 or let the ambient hooks capture it.
|
|
43
|
+
- When the user asks to see the memory graph, call memory_visualize().
|
|
38
44
|
`;
|
|
45
|
+
var OPENCODE_PASSIVE_INSTRUCTION = `${INSTRUCTION_MARKER}
|
|
46
|
+
# toon-memory
|
|
47
|
+
${ACTIVE_RULES}`;
|
|
48
|
+
var INSTRUCTION_CONTENT = `${INSTRUCTION_MARKER}
|
|
49
|
+
${INSTRUCTION_CONTENT_BASE}${ACTIVE_RULES}`;
|
|
39
50
|
|
|
40
51
|
// src/cli/capture-toggle.ts
|
|
41
52
|
function captureToggle(enable) {
|
|
@@ -62,7 +73,9 @@ function captureToggle(enable) {
|
|
|
62
73
|
// src/cli/commands.ts
|
|
63
74
|
import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync7, unlinkSync, rmSync } from "fs";
|
|
64
75
|
import { basename, join as join7 } from "path";
|
|
65
|
-
import
|
|
76
|
+
import checkbox from "@inquirer/checkbox";
|
|
77
|
+
import select from "@inquirer/select";
|
|
78
|
+
import confirm from "@inquirer/confirm";
|
|
66
79
|
|
|
67
80
|
// src/lib/vocab.ts
|
|
68
81
|
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
@@ -86,8 +99,8 @@ function extractProjectDeps(root) {
|
|
|
86
99
|
try {
|
|
87
100
|
const txt = readFileSync2(cargoPath, "utf-8");
|
|
88
101
|
const block = txt.match(/\[dependencies\][\s\S]*?(?:\n\[|$)/)?.[0] || "";
|
|
89
|
-
for (const
|
|
90
|
-
const m =
|
|
102
|
+
for (const line2 of block.split("\n")) {
|
|
103
|
+
const m = line2.match(/^\s*([A-Za-z0-9_-]+)\s*=/);
|
|
91
104
|
if (m) {
|
|
92
105
|
const tag = m[1].toLowerCase();
|
|
93
106
|
vocab[tag] = [tag];
|
|
@@ -351,7 +364,107 @@ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as rea
|
|
|
351
364
|
import { join as join4 } from "path";
|
|
352
365
|
|
|
353
366
|
// src/lib/utils.ts
|
|
354
|
-
var
|
|
367
|
+
var normalize = (s) => s.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
368
|
+
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
369
|
+
"a",
|
|
370
|
+
"de",
|
|
371
|
+
"del",
|
|
372
|
+
"la",
|
|
373
|
+
"el",
|
|
374
|
+
"los",
|
|
375
|
+
"las",
|
|
376
|
+
"un",
|
|
377
|
+
"una",
|
|
378
|
+
"unos",
|
|
379
|
+
"unas",
|
|
380
|
+
"y",
|
|
381
|
+
"o",
|
|
382
|
+
"en",
|
|
383
|
+
"al",
|
|
384
|
+
"por",
|
|
385
|
+
"para",
|
|
386
|
+
"con",
|
|
387
|
+
"sin",
|
|
388
|
+
"sobre",
|
|
389
|
+
"como",
|
|
390
|
+
"que",
|
|
391
|
+
"cual",
|
|
392
|
+
"cuando",
|
|
393
|
+
"donde",
|
|
394
|
+
"es",
|
|
395
|
+
"son",
|
|
396
|
+
"fue",
|
|
397
|
+
"era",
|
|
398
|
+
"se",
|
|
399
|
+
"su",
|
|
400
|
+
"sus",
|
|
401
|
+
"lo",
|
|
402
|
+
"le",
|
|
403
|
+
"les",
|
|
404
|
+
"me",
|
|
405
|
+
"te",
|
|
406
|
+
"nos",
|
|
407
|
+
"os",
|
|
408
|
+
"mi",
|
|
409
|
+
"tu",
|
|
410
|
+
"the",
|
|
411
|
+
"and",
|
|
412
|
+
"or",
|
|
413
|
+
"for",
|
|
414
|
+
"with",
|
|
415
|
+
"from",
|
|
416
|
+
"this",
|
|
417
|
+
"that",
|
|
418
|
+
"into",
|
|
419
|
+
"was",
|
|
420
|
+
"were",
|
|
421
|
+
"been",
|
|
422
|
+
"being"
|
|
423
|
+
]);
|
|
424
|
+
var isExpiredLocal = (ttl, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) => {
|
|
425
|
+
if (!ttl) return false;
|
|
426
|
+
return ttl <= today;
|
|
427
|
+
};
|
|
428
|
+
function importance(e, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
|
|
429
|
+
const days = (Date.parse(`${today}T00:00:00`) - Date.parse(`${e.date || today}T00:00:00`)) / 864e5;
|
|
430
|
+
const recency = Math.min(1, Math.max(0, 30 - days) / 30);
|
|
431
|
+
const freq = Math.min(1, e.accessed / 5);
|
|
432
|
+
return recency * 0.6 + freq * 0.4;
|
|
433
|
+
}
|
|
434
|
+
var IMPORTANCE_BOOST = {
|
|
435
|
+
critical: 0.3,
|
|
436
|
+
high: 0.15,
|
|
437
|
+
medium: 0,
|
|
438
|
+
low: -0.1
|
|
439
|
+
};
|
|
440
|
+
var importanceBoost = (level) => IMPORTANCE_BOOST[level] ?? 0;
|
|
441
|
+
var importanceRank = (level) => {
|
|
442
|
+
if (level === "critical") return 4;
|
|
443
|
+
if (level === "high") return 3;
|
|
444
|
+
if (level === "low") return 1;
|
|
445
|
+
return 2;
|
|
446
|
+
};
|
|
447
|
+
var tokenize = (s) => normalize(s.replace(/([a-z])([A-Z])/g, "$1 $2")).split(" ").filter((t) => t.length >= 2 && !STOPWORDS.has(t));
|
|
448
|
+
var estimateTokens = (s) => {
|
|
449
|
+
if (!s) return 0;
|
|
450
|
+
const chars = Math.ceil(s.length / 4);
|
|
451
|
+
const words = (s.match(/\S+/g) || []).length;
|
|
452
|
+
return Math.max(1, chars + words);
|
|
453
|
+
};
|
|
454
|
+
var escField = (s) => {
|
|
455
|
+
let out = "";
|
|
456
|
+
for (let i = 0; i < s.length; i++) {
|
|
457
|
+
const c = s[i];
|
|
458
|
+
if (c === "\\") out += "\\\\";
|
|
459
|
+
else if (c === "\n") out += "\\n";
|
|
460
|
+
else if (c === "\r") {
|
|
461
|
+
out += "\\n";
|
|
462
|
+
if (s[i + 1] === "\n") i++;
|
|
463
|
+
} else if (c === "|") out += "\\|";
|
|
464
|
+
else out += c;
|
|
465
|
+
}
|
|
466
|
+
return out;
|
|
467
|
+
};
|
|
355
468
|
var unescField = (s) => {
|
|
356
469
|
let out = "";
|
|
357
470
|
for (let i = 0; i < s.length; i++) {
|
|
@@ -372,11 +485,11 @@ var unescField = (s) => {
|
|
|
372
485
|
}
|
|
373
486
|
return out;
|
|
374
487
|
};
|
|
375
|
-
var parseToonLine = (
|
|
488
|
+
var parseToonLine = (line2) => {
|
|
376
489
|
const parts = [];
|
|
377
490
|
let cur = "";
|
|
378
491
|
let escaped = false;
|
|
379
|
-
for (const c of
|
|
492
|
+
for (const c of line2.trim()) {
|
|
380
493
|
if (escaped) {
|
|
381
494
|
cur += c;
|
|
382
495
|
escaped = false;
|
|
@@ -398,6 +511,8 @@ var parseToonLine = (line) => {
|
|
|
398
511
|
parts.push(unescField(cur));
|
|
399
512
|
return parts;
|
|
400
513
|
};
|
|
514
|
+
var toToonLine = (parts) => ` ${parts.map(escField).join("|")}`;
|
|
515
|
+
var isPrivate = (e) => e.tags.some((t) => t.toLowerCase() === "private");
|
|
401
516
|
|
|
402
517
|
// src/cli/memory.ts
|
|
403
518
|
function installMemoryDir() {
|
|
@@ -433,8 +548,8 @@ function dumpMemoryMarkdown() {
|
|
|
433
548
|
}
|
|
434
549
|
const data = readFileSync4(memoryFile, "utf-8");
|
|
435
550
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|"));
|
|
436
|
-
const entries = lines.map((
|
|
437
|
-
const parts = parseToonLine(
|
|
551
|
+
const entries = lines.map((line2) => {
|
|
552
|
+
const parts = parseToonLine(line2);
|
|
438
553
|
return {
|
|
439
554
|
id: parts[0] ?? "",
|
|
440
555
|
category: parts[1] ?? "",
|
|
@@ -711,7 +826,7 @@ function installInstructions(agent) {
|
|
|
711
826
|
const content = agent.name === "opencode" ? OPENCODE_PASSIVE_INSTRUCTION : INSTRUCTION_CONTENT;
|
|
712
827
|
if (existsSync6(filePath)) {
|
|
713
828
|
const existing = readFileSync6(filePath, "utf-8");
|
|
714
|
-
if (existing.includes(
|
|
829
|
+
if (existing.includes(INSTRUCTION_MARKER)) {
|
|
715
830
|
console.log(` Instructions already present in ${filePath}`);
|
|
716
831
|
return;
|
|
717
832
|
}
|
|
@@ -909,44 +1024,58 @@ function registerAntigravityHooks(agent) {
|
|
|
909
1024
|
import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "fs";
|
|
910
1025
|
import { join as join6 } from "path";
|
|
911
1026
|
function opencodePluginContent() {
|
|
912
|
-
return `import * as
|
|
913
|
-
import * as path from "path"
|
|
1027
|
+
return `import * as path from "path"
|
|
914
1028
|
|
|
915
1029
|
export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
916
1030
|
const root = worktree || directory
|
|
917
|
-
|
|
918
|
-
|
|
1031
|
+
let cachedBrief = ""
|
|
1032
|
+
let cachedTask = ""
|
|
1033
|
+
let cachedAt = 0
|
|
1034
|
+
let lastTask = ""
|
|
1035
|
+
let promoted = false
|
|
1036
|
+
let dynamic = []
|
|
919
1037
|
|
|
920
|
-
const
|
|
921
|
-
return await
|
|
1038
|
+
const run = async (cmd) => {
|
|
1039
|
+
try { return (await cmd.cwd(root).text()).trim() } catch { return "" }
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
const brief = async () => {
|
|
1043
|
+
const task = (lastTask || "").replace(/[\`$"]/g, " ").trim().slice(0, 200)
|
|
1044
|
+
const now = Date.now()
|
|
1045
|
+
if (cachedBrief && cachedTask === task && now - cachedAt < 5 * 60 * 1000) return cachedBrief
|
|
1046
|
+
cachedBrief = task
|
|
1047
|
+
? await run(\`TOON_MEMORY_TASK=\${JSON.stringify(task)} npx -y toon-memory brief\`)
|
|
1048
|
+
: await run(\`npx -y toon-memory brief\`)
|
|
1049
|
+
cachedTask = task
|
|
1050
|
+
cachedAt = now
|
|
1051
|
+
return cachedBrief
|
|
922
1052
|
}
|
|
923
1053
|
|
|
924
1054
|
const recall = async (query, opts = {}) => {
|
|
925
1055
|
try {
|
|
926
|
-
const args = { query, mode: "flat", budget:
|
|
1056
|
+
const args = { query, mode: "flat", budget: "tiny", limit: 3, path_scope: opts.path_scope || "" }
|
|
927
1057
|
if (opts.category) args.category = opts.category
|
|
928
|
-
const result = await $\`npx -y toon-memory mcp\`.
|
|
929
|
-
.
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
}))
|
|
935
|
-
.text()
|
|
1058
|
+
const result = await run($\`npx -y toon-memory mcp\`.stdin(JSON.stringify({
|
|
1059
|
+
jsonrpc: "2.0",
|
|
1060
|
+
id: 1,
|
|
1061
|
+
method: "tools/call",
|
|
1062
|
+
params: { name: "memory_recall", arguments: args }
|
|
1063
|
+
})))
|
|
936
1064
|
const parsed = JSON.parse(result)
|
|
937
1065
|
return parsed?.result?.content?.[0]?.text || ""
|
|
938
1066
|
} catch { return "" }
|
|
939
1067
|
}
|
|
940
1068
|
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
return await recall(filePath, { budget: "tiny", path_scope: filePath, category: "warning" })
|
|
1069
|
+
const record = async (type, summary, file, session) => {
|
|
1070
|
+
if (!summary) return
|
|
1071
|
+
await run($\`npx -y toon-memory signal --type \${type} --summary \${summary} --file \${file || ""} --session \${session || "opencode"}\`)
|
|
945
1072
|
}
|
|
946
1073
|
|
|
947
|
-
const
|
|
948
|
-
|
|
949
|
-
|
|
1074
|
+
const inject = (key, text) => {
|
|
1075
|
+
if (!text || text.includes("(empty)") || text.includes("No results")) return
|
|
1076
|
+
dynamic = dynamic.filter((d) => d.key !== key)
|
|
1077
|
+
dynamic.push({ key, text: text.slice(0, 400) })
|
|
1078
|
+
if (dynamic.length > 2) dynamic.shift()
|
|
950
1079
|
}
|
|
951
1080
|
|
|
952
1081
|
const pickPath = (args) => {
|
|
@@ -964,92 +1093,88 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
964
1093
|
return [basename, ...dirParts.slice(-2)].join(" ")
|
|
965
1094
|
}
|
|
966
1095
|
|
|
967
|
-
const
|
|
968
|
-
|
|
969
|
-
|
|
1096
|
+
const extractPath = (text) => {
|
|
1097
|
+
const match = text.match(/(?:file|path|source):\\s*([\\w/.\\-]+)/i)
|
|
1098
|
+
return match ? match[1] : ""
|
|
970
1099
|
}
|
|
971
1100
|
|
|
972
|
-
// Edit/write-ish tools are where known risks matter most.
|
|
973
1101
|
const isEditTool = (name) => {
|
|
974
1102
|
if (!name) return false
|
|
975
1103
|
return name === "edit" || name === "write" || name === "apply-patch" ||
|
|
976
1104
|
name.includes("edit") || name.includes("write") || name.includes("patch")
|
|
977
1105
|
}
|
|
978
1106
|
|
|
1107
|
+
const isDirective = (text) =>
|
|
1108
|
+
/recuerda|siempre|nunca|no hagas|importante|ten cuidado|decidimos|must not|always|never/i.test(text)
|
|
1109
|
+
|
|
979
1110
|
return {
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
1111
|
+
event: async ({ event }) => {
|
|
1112
|
+
const type = event?.type || ""
|
|
1113
|
+
if (type === "session.created" || type === "session.updated") {
|
|
1114
|
+
cachedBrief = ""
|
|
1115
|
+
cachedTask = ""
|
|
1116
|
+
cachedAt = 0
|
|
1117
|
+
lastTask = ""
|
|
1118
|
+
dynamic = []
|
|
1119
|
+
promoted = false
|
|
1120
|
+
}
|
|
1121
|
+
if (type === "session.idle" && !promoted) {
|
|
1122
|
+
promoted = true
|
|
1123
|
+
await run($\`npx -y toon-memory promote\`)
|
|
1124
|
+
}
|
|
985
1125
|
},
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
1126
|
+
|
|
1127
|
+
"experimental.chat.system.transform": async (input, output) => {
|
|
1128
|
+
const text = await brief()
|
|
1129
|
+
if (text) output.system.push(text)
|
|
1130
|
+
for (const d of dynamic) output.system.push(d.text)
|
|
1131
|
+
},
|
|
1132
|
+
|
|
1133
|
+
"experimental.session.compacting": async (input, output) => {
|
|
1134
|
+
const text = await brief()
|
|
1135
|
+
if (text && Array.isArray(output?.context)) output.context.push(text)
|
|
991
1136
|
},
|
|
1137
|
+
|
|
1138
|
+
"chat.message": async (input) => {
|
|
1139
|
+
const parts = input?.parts || input?.message?.parts || []
|
|
1140
|
+
const text = parts.map((p) => typeof p?.text === "string" ? p.text : "").join(" ")
|
|
1141
|
+
lastTask = text.replace(/s+/g, " ").trim().slice(0, 200)
|
|
1142
|
+
if (isDirective(text)) {
|
|
1143
|
+
await record("user_directive", text.replace(/\\s+/g, " ").slice(0, 280), "", input?.sessionID)
|
|
1144
|
+
}
|
|
1145
|
+
},
|
|
1146
|
+
|
|
992
1147
|
"tool.execute.before": async (input, output) => {
|
|
993
|
-
// Pre-edit risk surfacing: for edit/write tools, surface known
|
|
994
|
-
// warning entries for the target file BEFORE the tool runs.
|
|
995
1148
|
try {
|
|
996
1149
|
const toolName = input?.tool || ""
|
|
997
1150
|
if (!isEditTool(toolName)) return
|
|
998
|
-
const
|
|
999
|
-
const filePath = pickPath(args)
|
|
1151
|
+
const filePath = pickPath(output?.args || input?.args || {})
|
|
1000
1152
|
if (!filePath) return
|
|
1001
|
-
const text = await
|
|
1002
|
-
inject(
|
|
1153
|
+
const text = await recall(filePath, { category: "warning" })
|
|
1154
|
+
inject("risks:" + filePath, "\u26A0 KNOWN RISKS for " + filePath + ":\\n" + text)
|
|
1003
1155
|
} catch {}
|
|
1004
1156
|
},
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
// recall only memory relevant to that file, inject as context.
|
|
1008
|
-
// Also proactively recalls entries scoped to the matched paths.
|
|
1157
|
+
|
|
1158
|
+
"tool.execute.after": async (input, output) => {
|
|
1009
1159
|
try {
|
|
1010
1160
|
const toolName = input?.tool || ""
|
|
1011
|
-
const args = input?.args || {}
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
let filePath = pickPath(args)
|
|
1015
|
-
|
|
1016
|
-
// Also try to extract from tool output text
|
|
1017
|
-
if (!filePath && input?.output) {
|
|
1018
|
-
const outputText = typeof input.output === "string" ? input.output : ""
|
|
1019
|
-
const fileMatch = outputText.match(/(?:file|path|source):s*([\\w/.\\-]+)/i)
|
|
1020
|
-
if (fileMatch) filePath = fileMatch[1]
|
|
1021
|
-
}
|
|
1161
|
+
const args = output?.args || input?.args || {}
|
|
1162
|
+
const resultText = typeof output?.output === "string" ? output.output : ""
|
|
1163
|
+
const filePath = pickPath(args) || extractPath(resultText)
|
|
1022
1164
|
|
|
1023
1165
|
if (filePath) {
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
const text = await recall(query, { budget: "tiny", path_scope: filePath })
|
|
1027
|
-
inject(input, "toon-memory:" + filePath, text)
|
|
1028
|
-
|
|
1029
|
-
// Pre-edit risk block for edit/write tools (same key as the before
|
|
1030
|
-
// hook \u2014 setContext overwrites, so no duplication when both fire).
|
|
1166
|
+
const text = await recall(buildQuery(filePath), { path_scope: filePath })
|
|
1167
|
+
inject("memory:" + filePath, text)
|
|
1031
1168
|
if (isEditTool(toolName)) {
|
|
1032
|
-
|
|
1033
|
-
inject(input, "toon-memory:risks:" + filePath, "\u26A0 KNOWN RISKS for " + filePath + ":\\n" + riskText)
|
|
1169
|
+
await record("diff_pattern", "Edited " + filePath + " while implementing a change", filePath, input?.sessionID)
|
|
1034
1170
|
}
|
|
1035
1171
|
}
|
|
1036
1172
|
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
.replace(/^context_/, "")
|
|
1043
|
-
.replace(/^file_/, "")
|
|
1044
|
-
.replace(/^text_document_/, "")
|
|
1045
|
-
.split("_")
|
|
1046
|
-
.filter(Boolean)
|
|
1047
|
-
.join(" ")
|
|
1048
|
-
|
|
1049
|
-
if (toolKeywords.length > 3) {
|
|
1050
|
-
const text = await recall(toolKeywords, { budget: "tiny" })
|
|
1051
|
-
inject(input, "toon-memory:" + toolName, text)
|
|
1052
|
-
}
|
|
1173
|
+
if (/error|failed|exception|fatal/i.test(resultText)) {
|
|
1174
|
+
const line = resultText.split("\\n").find((l) => /error|failed|exception|fatal/i.test(l)) || ""
|
|
1175
|
+
const signature = line.replace(/\\s+/g, " ").slice(0, 180)
|
|
1176
|
+
inject("error:" + toolName, "\u26A0 Tool error: " + signature)
|
|
1177
|
+
await record("error_fix", "Tool " + toolName + " failed: " + signature, filePath, input?.sessionID)
|
|
1053
1178
|
}
|
|
1054
1179
|
} catch {}
|
|
1055
1180
|
},
|
|
@@ -1063,11 +1188,6 @@ function installOpenCodePlugin(agent) {
|
|
|
1063
1188
|
const dest = join6(pluginsDir, "toon-memory.ts");
|
|
1064
1189
|
writeFileSync6(dest, opencodePluginContent());
|
|
1065
1190
|
console.log(` Plugin created at ${dest}`);
|
|
1066
|
-
const instrDir = join6(projectRoot, ".opencode", "instructions");
|
|
1067
|
-
if (!existsSync8(instrDir)) mkdirSync6(instrDir, { recursive: true });
|
|
1068
|
-
const instrFile = join6(instrDir, "memory-autoload.md");
|
|
1069
|
-
writeFileSync6(instrFile, dumpMemoryMarkdown());
|
|
1070
|
-
console.log(` Seeded ${instrFile}`);
|
|
1071
1191
|
const configPath = agent.local || agent.global;
|
|
1072
1192
|
if (configPath && existsSync8(configPath)) {
|
|
1073
1193
|
try {
|
|
@@ -1378,8 +1498,8 @@ function stats() {
|
|
|
1378
1498
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|"));
|
|
1379
1499
|
const categories = {};
|
|
1380
1500
|
let latestDate = "";
|
|
1381
|
-
for (const
|
|
1382
|
-
const parts = parseToonLine(
|
|
1501
|
+
for (const line2 of lines) {
|
|
1502
|
+
const parts = parseToonLine(line2);
|
|
1383
1503
|
if (parts.length >= 7) {
|
|
1384
1504
|
const category = parts[1];
|
|
1385
1505
|
const date = parts[6];
|
|
@@ -1407,8 +1527,8 @@ function exportMemory() {
|
|
|
1407
1527
|
}
|
|
1408
1528
|
const data = readFileSync9(memoryFile, "utf-8");
|
|
1409
1529
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|"));
|
|
1410
|
-
const entries = lines.map((
|
|
1411
|
-
const parts = parseToonLine(
|
|
1530
|
+
const entries = lines.map((line2) => {
|
|
1531
|
+
const parts = parseToonLine(line2);
|
|
1412
1532
|
return {
|
|
1413
1533
|
id: parts[0],
|
|
1414
1534
|
category: parts[1],
|
|
@@ -1679,7 +1799,7 @@ function watch(args2) {
|
|
|
1679
1799
|
// src/viewer/index.ts
|
|
1680
1800
|
import { writeFileSync as writeFileSync11, mkdirSync as mkdirSync10 } from "fs";
|
|
1681
1801
|
import { join as join10 } from "path";
|
|
1682
|
-
import {
|
|
1802
|
+
import { spawn } from "child_process";
|
|
1683
1803
|
|
|
1684
1804
|
// src/lib/lock.ts
|
|
1685
1805
|
import { openSync, closeSync, writeFileSync as writeFileSync9, readFileSync as readFileSync11, unlinkSync as unlinkSync3, existsSync as existsSync11, statSync as statSync2, renameSync } from "fs";
|
|
@@ -1762,6 +1882,11 @@ function withLockSync(file, fn) {
|
|
|
1762
1882
|
}
|
|
1763
1883
|
}
|
|
1764
1884
|
}
|
|
1885
|
+
function atomicWrite(file, content) {
|
|
1886
|
+
const tmp = `${file}.tmp`;
|
|
1887
|
+
writeFileSync9(tmp, content);
|
|
1888
|
+
renameSync(tmp, file);
|
|
1889
|
+
}
|
|
1765
1890
|
function readUnderLock(file, encoding = "utf-8") {
|
|
1766
1891
|
let content = "";
|
|
1767
1892
|
withLockSync(file, () => {
|
|
@@ -1778,6 +1903,9 @@ var MEMORY_DIR3 = join9(process.cwd(), ".toon-memory", "memory");
|
|
|
1778
1903
|
var MEMORY_FILE = join9(MEMORY_DIR3, "data.toon");
|
|
1779
1904
|
var ARCHIVE_FILE = join9(MEMORY_DIR3, "archive.toon");
|
|
1780
1905
|
var OBSERVATIONS_FILE = join9(MEMORY_DIR3, "observations.toon");
|
|
1906
|
+
var FEEDBACK_FILE = join9(MEMORY_DIR3, "feedback.toon");
|
|
1907
|
+
var EDGES_FILE = join9(MEMORY_DIR3, "edges.toon");
|
|
1908
|
+
var VECTORS_FILE = join9(MEMORY_DIR3, "vectors.bin");
|
|
1781
1909
|
var SECRETS_FILE = join9(MEMORY_DIR3, "secrets.toon");
|
|
1782
1910
|
var GLOBAL_FILE = process.env.TOON_MEMORY_GLOBAL_FILE || join9(homedir(), ".toon-memory", "memory", "global.toon");
|
|
1783
1911
|
var CONFIG_FILE = join9(MEMORY_DIR3, "config.json");
|
|
@@ -1792,6 +1920,18 @@ function loadConfig() {
|
|
|
1792
1920
|
return { encrypted: false };
|
|
1793
1921
|
}
|
|
1794
1922
|
}
|
|
1923
|
+
function saveConfig(config) {
|
|
1924
|
+
ensureMemoryDir();
|
|
1925
|
+
let existing = {};
|
|
1926
|
+
if (existsSync12(CONFIG_FILE)) {
|
|
1927
|
+
try {
|
|
1928
|
+
existing = JSON.parse(readFileSync12(CONFIG_FILE, "utf-8"));
|
|
1929
|
+
} catch {
|
|
1930
|
+
existing = {};
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
writeFileSync10(CONFIG_FILE, JSON.stringify({ ...existing, ...config }, null, 2));
|
|
1934
|
+
}
|
|
1795
1935
|
function getKey() {
|
|
1796
1936
|
return process.env.TOON_MEMORY_KEY;
|
|
1797
1937
|
}
|
|
@@ -1807,6 +1947,15 @@ function ensureMemoryFile() {
|
|
|
1807
1947
|
|
|
1808
1948
|
// src/mcp/crypto.ts
|
|
1809
1949
|
import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
|
|
1950
|
+
function encrypt(text, key) {
|
|
1951
|
+
const keyBuffer = Buffer.from(key, "hex");
|
|
1952
|
+
const iv = randomBytes(16);
|
|
1953
|
+
const cipher = createCipheriv(ALGORITHM, keyBuffer, iv);
|
|
1954
|
+
let encrypted = cipher.update(text, "utf8", "hex");
|
|
1955
|
+
encrypted += cipher.final("hex");
|
|
1956
|
+
const authTag = cipher.getAuthTag();
|
|
1957
|
+
return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
|
|
1958
|
+
}
|
|
1810
1959
|
function decrypt(encryptedData, key) {
|
|
1811
1960
|
const keyBuffer = Buffer.from(key, "hex");
|
|
1812
1961
|
const parts = encryptedData.split(":");
|
|
@@ -1824,6 +1973,9 @@ function decrypt(encryptedData, key) {
|
|
|
1824
1973
|
}
|
|
1825
1974
|
|
|
1826
1975
|
// src/mcp/memory-io.ts
|
|
1976
|
+
function safeWrite(file, content) {
|
|
1977
|
+
withLockSync(file, () => atomicWrite(file, content));
|
|
1978
|
+
}
|
|
1827
1979
|
function readMemory() {
|
|
1828
1980
|
ensureMemoryFile();
|
|
1829
1981
|
const config = loadConfig();
|
|
@@ -1835,6 +1987,223 @@ function readMemory() {
|
|
|
1835
1987
|
}
|
|
1836
1988
|
return data;
|
|
1837
1989
|
}
|
|
1990
|
+
function writeMemory(content) {
|
|
1991
|
+
ensureMemoryFile();
|
|
1992
|
+
const config = loadConfig();
|
|
1993
|
+
if (config.encrypted) {
|
|
1994
|
+
const key = getKey();
|
|
1995
|
+
if (!key) throw new Error("Encryption enabled but TOON_MEMORY_KEY is not set. Run 'npx toon-memory init' or set the env var.");
|
|
1996
|
+
const encrypted = encrypt(content, key);
|
|
1997
|
+
safeWrite(MEMORY_FILE, encrypted);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
safeWrite(MEMORY_FILE, content);
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
// src/lib/synonyms.ts
|
|
2004
|
+
var SYNONYMS = {
|
|
2005
|
+
// Infrastructure / networking
|
|
2006
|
+
"conexi\xF3n": ["timeout", "red", "conectar", "disconnect", "connection", "conn"],
|
|
2007
|
+
"conectar": ["timeout", "red", "conexi\xF3n", "connect", "connection"],
|
|
2008
|
+
"ca\xEDda": ["down", "crash", "fail", "error", "dropped", "falla"],
|
|
2009
|
+
"down": ["ca\xEDda", "crash", "fail", "caer", "offline"],
|
|
2010
|
+
"crash": ["ca\xEDda", "down", "fail", "error", "colapso"],
|
|
2011
|
+
"timeout": ["conexi\xF3n", "red", "expirar", "deadline", "exceed"],
|
|
2012
|
+
"red": ["network", "conexi\xF3n", "ip", "dns", "proxy", "gateway"],
|
|
2013
|
+
"network": ["red", "conexi\xF3n", "ip", "dns", "proxy"],
|
|
2014
|
+
"server": ["servidor", "backend", "api", "host"],
|
|
2015
|
+
"servidor": ["server", "backend", "api", "host"],
|
|
2016
|
+
"client": ["cliente", "frontend", "browser", "user-agent"],
|
|
2017
|
+
"cliente": ["client", "frontend", "browser"],
|
|
2018
|
+
// Data / storage
|
|
2019
|
+
"cache": ["redis", "memcached", "cached", "cach\xE9"],
|
|
2020
|
+
"redis": ["cache", "memcached", "session", "pubsub"],
|
|
2021
|
+
"pool": ["pool", "connection pool", "pooling", "concurrencia"],
|
|
2022
|
+
"database": ["db", "postgres", "mysql", "mongo", "sql", "base de datos"],
|
|
2023
|
+
"db": ["database", "postgres", "mysql", "mongo", "sql"],
|
|
2024
|
+
"session": ["sesi\xF3n", "cookie", "token", "auth"],
|
|
2025
|
+
// Errors / debugging
|
|
2026
|
+
"error": ["bug", "exception", "fail", "fallo", "error", "err"],
|
|
2027
|
+
"bug": ["error", "defect", "issue", "fallo", "problema"],
|
|
2028
|
+
"exception": ["error", "throw", "catch", "error"],
|
|
2029
|
+
"fail": ["error", "falla", "fallo", "crash", "fail"],
|
|
2030
|
+
"falla": ["error", "fail", "fallo", "bug", "crash"],
|
|
2031
|
+
"debug": ["debugging", "log", "trace", "diagn\xF3stico"],
|
|
2032
|
+
"log": ["logging", "debug", "trace", "registro"],
|
|
2033
|
+
"warning": ["warn", "advertencia", "alerta"],
|
|
2034
|
+
// Architecture
|
|
2035
|
+
"auth": ["authentication", "autenticaci\xF3n", "login", "jwt", "token", "oauth"],
|
|
2036
|
+
"autenticaci\xF3n": ["auth", "authentication", "login", "jwt", "oauth"],
|
|
2037
|
+
"api": ["endpoint", "route", "rest", "graphql", "rpc"],
|
|
2038
|
+
"endpoint": ["api", "route", "url", "path"],
|
|
2039
|
+
"config": ["configuraci\xF3n", "settings", "env", "environment"],
|
|
2040
|
+
"configuraci\xF3n": ["config", "settings", "env", "environment"],
|
|
2041
|
+
"deploy": ["deployment", "despliegue", "release", "ship", "ci/cd"],
|
|
2042
|
+
"despliegue": ["deploy", "deployment", "release", "publish"],
|
|
2043
|
+
"migration": ["migraci\xF3n", "migrate", "upgrade", "schema change"],
|
|
2044
|
+
"migraci\xF3n": ["migration", "migrate", "upgrade"],
|
|
2045
|
+
// Code / patterns
|
|
2046
|
+
"refactor": ["refactoring", "reorganizar", "reestructurar", "clean"],
|
|
2047
|
+
"reestructurar": ["refactor", "refactoring", "reorganizar", "restructure"],
|
|
2048
|
+
"pattern": ["patr\xF3n", "pattern", "convention", "norma", "est\xE1ndar"],
|
|
2049
|
+
"patr\xF3n": ["pattern", "convention", "norma", "est\xE1ndar"],
|
|
2050
|
+
"decision": ["decisi\xF3n", "decision", "elecci\xF3n", "choice", "acuerdo"],
|
|
2051
|
+
"decisi\xF3n": ["decision", "elecci\xF3n", "choice", "acuerdo"],
|
|
2052
|
+
"knowledge": ["conocimiento", "knowledge", "info", "informaci\xF3n"],
|
|
2053
|
+
"conocimiento": ["knowledge", "info", "informaci\xF3n"],
|
|
2054
|
+
// Performance
|
|
2055
|
+
"performance": ["rendimiento", "perf", "latency", "throughput", "speed"],
|
|
2056
|
+
"rendimiento": ["performance", "perf", "latency", "speed"],
|
|
2057
|
+
"latency": ["latencia", "delay", "response time", "rt"],
|
|
2058
|
+
"latencia": ["latency", "delay", "response time"],
|
|
2059
|
+
"memory": ["memoria", "ram", "heap", "leak"],
|
|
2060
|
+
"memoria": ["memory", "ram", "heap", "leak"],
|
|
2061
|
+
"leak": ["fuga", "memory leak", "memoria"],
|
|
2062
|
+
// Testing
|
|
2063
|
+
"test": ["testing", "prueba", "tests", "spec"],
|
|
2064
|
+
"prueba": ["test", "testing", "spec"],
|
|
2065
|
+
"mock": ["mocking", "stub", "fake", "doble"],
|
|
2066
|
+
"coverage": ["cobertura", "coverage", "tests"],
|
|
2067
|
+
// Git / VCS
|
|
2068
|
+
"commit": ["commits", "\u63D0\u4EA4", "checkpoint", "save"],
|
|
2069
|
+
"branch": ["rama", "branch", "feature branch", "checkout"],
|
|
2070
|
+
"rama": ["branch", "feature branch", "checkout"],
|
|
2071
|
+
"merge": ["mergear", "merge", "combine", "unir"],
|
|
2072
|
+
"conflict": ["conflicto", "conflict", "merge conflict", "clash"],
|
|
2073
|
+
"conflicto": ["conflict", "merge conflict", "clash"],
|
|
2074
|
+
"revert": ["rollback", "deshacer", "undo", "restore"],
|
|
2075
|
+
// UI / frontend
|
|
2076
|
+
"ui": ["interfaz", "interface", "gui", "frontend", "vista"],
|
|
2077
|
+
"interfaz": ["ui", "interface", "gui", "frontend"],
|
|
2078
|
+
"component": ["componente", "widget", "module", "pieza"],
|
|
2079
|
+
"componente": ["component", "widget", "module"],
|
|
2080
|
+
"responsive": ["responsive", "mobile", "adaptativo", "layout"],
|
|
2081
|
+
"layout": ["dise\xF1o", "design", "layout", "estructura"],
|
|
2082
|
+
// DevOps
|
|
2083
|
+
"docker": ["container", "contenedor", "image", "imagen"],
|
|
2084
|
+
"contenedor": ["docker", "container", "image"],
|
|
2085
|
+
"kubernetes": ["k8s", "cluster", "pods", "deployment"],
|
|
2086
|
+
"ci/cd": ["pipeline", "deploy", "continuous integration", "continuous deployment"],
|
|
2087
|
+
"monitoring": ["monitoreo", "observability", "metrics", "alerts"],
|
|
2088
|
+
"monitoreo": ["monitoring", "observability", "metrics"]
|
|
2089
|
+
};
|
|
2090
|
+
function expandSynonyms(queryTokens) {
|
|
2091
|
+
const expanded = new Set(queryTokens);
|
|
2092
|
+
for (const token of queryTokens) {
|
|
2093
|
+
const synonyms = SYNONYMS[token];
|
|
2094
|
+
if (synonyms) {
|
|
2095
|
+
for (const s of synonyms) expanded.add(s);
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
return [...expanded];
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
// src/lib/fuzzy.ts
|
|
2102
|
+
function levenshtein(a, b) {
|
|
2103
|
+
const al = a.length;
|
|
2104
|
+
const bl = b.length;
|
|
2105
|
+
if (al === 0) return bl;
|
|
2106
|
+
if (bl === 0) return al;
|
|
2107
|
+
let prev = new Array(bl + 1);
|
|
2108
|
+
let curr = new Array(bl + 1);
|
|
2109
|
+
for (let j = 0; j <= bl; j++) prev[j] = j;
|
|
2110
|
+
for (let i = 1; i <= al; i++) {
|
|
2111
|
+
curr[0] = i;
|
|
2112
|
+
for (let j = 1; j <= bl; j++) {
|
|
2113
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
2114
|
+
curr[j] = Math.min(
|
|
2115
|
+
prev[j] + 1,
|
|
2116
|
+
// deletion
|
|
2117
|
+
curr[j - 1] + 1,
|
|
2118
|
+
// insertion
|
|
2119
|
+
prev[j - 1] + cost
|
|
2120
|
+
// substitution
|
|
2121
|
+
);
|
|
2122
|
+
}
|
|
2123
|
+
;
|
|
2124
|
+
[prev, curr] = [curr, prev];
|
|
2125
|
+
}
|
|
2126
|
+
return prev[bl];
|
|
2127
|
+
}
|
|
2128
|
+
function fuzzyMatch(queryTokens, docTokens, maxDistance = 2) {
|
|
2129
|
+
for (const qt of queryTokens) {
|
|
2130
|
+
if (qt.length <= 2) continue;
|
|
2131
|
+
for (const dt of docTokens) {
|
|
2132
|
+
if (Math.abs(qt.length - dt.length) > maxDistance) continue;
|
|
2133
|
+
if (levenshtein(qt, dt) <= maxDistance) return true;
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
return false;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
// src/lib/evidence.ts
|
|
2140
|
+
var EVIDENCE_BOOST = {
|
|
2141
|
+
conflict: 0.15,
|
|
2142
|
+
verified: 0.03,
|
|
2143
|
+
unverified: -0.02
|
|
2144
|
+
};
|
|
2145
|
+
var evidenceBoost = (evidence) => EVIDENCE_BOOST[evidence] ?? 0;
|
|
2146
|
+
|
|
2147
|
+
// src/lib/ngrams.ts
|
|
2148
|
+
function fnv1a32(s) {
|
|
2149
|
+
let h = 2166136261;
|
|
2150
|
+
for (let i = 0; i < s.length; i++) {
|
|
2151
|
+
h ^= s.charCodeAt(i);
|
|
2152
|
+
h = h * 16777619 >>> 0;
|
|
2153
|
+
}
|
|
2154
|
+
return h >>> 0;
|
|
2155
|
+
}
|
|
2156
|
+
function ngramHashes(text, n = 3) {
|
|
2157
|
+
const out = /* @__PURE__ */ new Set();
|
|
2158
|
+
const tokens = text.split(/\s+/);
|
|
2159
|
+
for (const token of tokens) {
|
|
2160
|
+
if (!token) continue;
|
|
2161
|
+
const padded = "^" + token + "$";
|
|
2162
|
+
for (let i = 0; i + n <= padded.length; i++) {
|
|
2163
|
+
out.add(fnv1a32(padded.slice(i, i + n)));
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
return out;
|
|
2167
|
+
}
|
|
2168
|
+
function ngramCosine(a, b) {
|
|
2169
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
2170
|
+
let inter = 0;
|
|
2171
|
+
const [small, large] = a.size <= b.size ? [a, b] : [b, a];
|
|
2172
|
+
for (const h of small) if (large.has(h)) inter++;
|
|
2173
|
+
return inter / Math.sqrt(a.size * b.size);
|
|
2174
|
+
}
|
|
2175
|
+
function ngramScores(entries, query) {
|
|
2176
|
+
const qHashes = ngramHashes(query);
|
|
2177
|
+
const out = /* @__PURE__ */ new Map();
|
|
2178
|
+
for (const e of entries) {
|
|
2179
|
+
const text = `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")} ${e.path_scope || ""}`;
|
|
2180
|
+
out.set(e.key, ngramCosine(qHashes, ngramHashes(text)));
|
|
2181
|
+
}
|
|
2182
|
+
return out;
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
// src/lib/activation.ts
|
|
2186
|
+
function activationScores(edges, seeds, depth = 1) {
|
|
2187
|
+
const out = /* @__PURE__ */ new Map();
|
|
2188
|
+
let frontier = [...new Set(seeds)];
|
|
2189
|
+
for (let d = 0; d < Math.max(0, depth); d++) {
|
|
2190
|
+
const next = [];
|
|
2191
|
+
for (const node of frontier) {
|
|
2192
|
+
for (const edge of edges) {
|
|
2193
|
+
let other = "";
|
|
2194
|
+
if (edge.from === node) other = edge.to;
|
|
2195
|
+
else if (edge.to === node) other = edge.from;
|
|
2196
|
+
if (!other || other === node || seeds.includes(other)) continue;
|
|
2197
|
+
const kind = edge.type === "supports" || edge.type === "used_in" ? 1 : edge.type === "contradicts" ? 0.6 : 0.8;
|
|
2198
|
+
const gain = edge.weight * kind * Math.pow(0.5, d);
|
|
2199
|
+
out.set(other, (out.get(other) || 0) + gain);
|
|
2200
|
+
next.push(other);
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
frontier = [...new Set(next)];
|
|
2204
|
+
}
|
|
2205
|
+
return out;
|
|
2206
|
+
}
|
|
1838
2207
|
|
|
1839
2208
|
// src/lib/graph.ts
|
|
1840
2209
|
var DEFAULT_EDGE_TYPE = "related";
|
|
@@ -1853,8 +2222,8 @@ var entryLines = (data) => data.split("\n").filter(
|
|
|
1853
2222
|
);
|
|
1854
2223
|
function parseEntries(data) {
|
|
1855
2224
|
const out = [];
|
|
1856
|
-
for (const
|
|
1857
|
-
const parts = parseToonLine(
|
|
2225
|
+
for (const line2 of entryLines(data)) {
|
|
2226
|
+
const parts = parseToonLine(line2);
|
|
1858
2227
|
if (parts.length < 3) continue;
|
|
1859
2228
|
const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] = parts;
|
|
1860
2229
|
out.push({
|
|
@@ -1993,6 +2362,265 @@ function connectedComponents(adjacency) {
|
|
|
1993
2362
|
}
|
|
1994
2363
|
return comps;
|
|
1995
2364
|
}
|
|
2365
|
+
function rrfFuse(rankers, k = 60) {
|
|
2366
|
+
const out = /* @__PURE__ */ new Map();
|
|
2367
|
+
for (const ranker of rankers) {
|
|
2368
|
+
for (const [key, rank] of ranker) {
|
|
2369
|
+
out.set(key, (out.get(key) || 0) + 1 / (k + rank));
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
2372
|
+
return out;
|
|
2373
|
+
}
|
|
2374
|
+
function rrfK(candidateCount) {
|
|
2375
|
+
return Math.max(3, Math.min(60, Math.round(Math.sqrt(candidateCount))));
|
|
2376
|
+
}
|
|
2377
|
+
function rankBy(score) {
|
|
2378
|
+
const out = /* @__PURE__ */ new Map();
|
|
2379
|
+
[...score.entries()].sort((a, b) => b[1] - a[1]).forEach(([key], i) => out.set(key, i));
|
|
2380
|
+
return out;
|
|
2381
|
+
}
|
|
2382
|
+
function bm25Scores(entries, query) {
|
|
2383
|
+
const N = entries.length;
|
|
2384
|
+
const scores = /* @__PURE__ */ new Map();
|
|
2385
|
+
if (N === 0) return scores;
|
|
2386
|
+
const docs = entries.map(
|
|
2387
|
+
(e) => tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")} ${e.path_scope}`)
|
|
2388
|
+
);
|
|
2389
|
+
const df = /* @__PURE__ */ new Map();
|
|
2390
|
+
for (const d of docs) {
|
|
2391
|
+
for (const t of new Set(d)) df.set(t, (df.get(t) || 0) + 1);
|
|
2392
|
+
}
|
|
2393
|
+
const avgdl = docs.reduce((a, b2) => a + b2.length, 0) / N;
|
|
2394
|
+
const k1 = 1.5;
|
|
2395
|
+
const b = 0.75;
|
|
2396
|
+
const qTokens = tokenize(query);
|
|
2397
|
+
entries.forEach((e, i) => {
|
|
2398
|
+
const d = docs[i];
|
|
2399
|
+
const dl = d.length || 1;
|
|
2400
|
+
let score = 0;
|
|
2401
|
+
for (const t of qTokens) {
|
|
2402
|
+
const dfT = df.get(t);
|
|
2403
|
+
if (!dfT) continue;
|
|
2404
|
+
const f = d.filter((x) => x === t).length;
|
|
2405
|
+
const idf = Math.log((N - dfT + 0.5) / (dfT + 0.5) + 1);
|
|
2406
|
+
score += idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avgdl));
|
|
2407
|
+
}
|
|
2408
|
+
scores.set(e.key, score);
|
|
2409
|
+
});
|
|
2410
|
+
return scores;
|
|
2411
|
+
}
|
|
2412
|
+
function centrality(adjacency) {
|
|
2413
|
+
let maxDeg = 1;
|
|
2414
|
+
const deg = /* @__PURE__ */ new Map();
|
|
2415
|
+
for (const [k, v] of adjacency) {
|
|
2416
|
+
deg.set(k, v.length);
|
|
2417
|
+
if (v.length > maxDeg) maxDeg = v.length;
|
|
2418
|
+
}
|
|
2419
|
+
const out = /* @__PURE__ */ new Map();
|
|
2420
|
+
for (const [k, d] of deg) out.set(k, d / maxDeg);
|
|
2421
|
+
return out;
|
|
2422
|
+
}
|
|
2423
|
+
function localCentrality(adjacency, keys) {
|
|
2424
|
+
let maxDeg = 1;
|
|
2425
|
+
const deg = /* @__PURE__ */ new Map();
|
|
2426
|
+
for (const k of keys) {
|
|
2427
|
+
const d = (adjacency.get(k) || []).length;
|
|
2428
|
+
deg.set(k, d);
|
|
2429
|
+
if (d > maxDeg) maxDeg = d;
|
|
2430
|
+
}
|
|
2431
|
+
const out = /* @__PURE__ */ new Map();
|
|
2432
|
+
for (const [k, d] of deg) out.set(k, d / maxDeg);
|
|
2433
|
+
return out;
|
|
2434
|
+
}
|
|
2435
|
+
function buildReason(e, bm25Score, bm25Max, impScore, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
|
|
2436
|
+
const parts = [];
|
|
2437
|
+
if (bm25Max > 0) {
|
|
2438
|
+
parts.push(`${Math.round(bm25Score / bm25Max * 100)}% relevance`);
|
|
2439
|
+
}
|
|
2440
|
+
if (e.accessed > 0) {
|
|
2441
|
+
parts.push(`used ${e.accessed}\xD7`);
|
|
2442
|
+
}
|
|
2443
|
+
if (e.lastAccessed) {
|
|
2444
|
+
const days = Math.floor((Date.parse(`${today}T00:00:00`) - Date.parse(e.lastAccessed)) / 864e5);
|
|
2445
|
+
parts.push(days <= 0 ? "used today" : days === 1 ? "used yesterday" : `used ${days}d ago`);
|
|
2446
|
+
} else if (e.accessed === 0) {
|
|
2447
|
+
parts.push("never used");
|
|
2448
|
+
}
|
|
2449
|
+
parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW");
|
|
2450
|
+
if (e.importance) parts.push(`explicit ${e.importance}`);
|
|
2451
|
+
if (e.evidence) parts.push(`evidence ${e.evidence}`);
|
|
2452
|
+
return parts.join(" \xB7 ");
|
|
2453
|
+
}
|
|
2454
|
+
var W_CENT = 0.4;
|
|
2455
|
+
var W_IMP = 0.25;
|
|
2456
|
+
var SEED_BONUS = 1;
|
|
2457
|
+
var DECAY = 0.5;
|
|
2458
|
+
var NGRAM_SEED_MIN = 0.45;
|
|
2459
|
+
function entryQuality(e, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
|
|
2460
|
+
let q = Math.min(0.3, e.tags.length * 0.1) + Math.min(0.2, e.links.length * 0.1);
|
|
2461
|
+
const len = e.content.length;
|
|
2462
|
+
if (len > 20) q += 0.1;
|
|
2463
|
+
if (len > 60) q += 0.1;
|
|
2464
|
+
if (len > 150) q += 0.1;
|
|
2465
|
+
q += importance(e, today) * 0.1;
|
|
2466
|
+
q += Math.min(0.15, e.accessed * 0.03);
|
|
2467
|
+
if (e.origin === "human") q += 0.1;
|
|
2468
|
+
else if (e.origin === "inferred") q -= 0.05;
|
|
2469
|
+
q += evidenceBoost(e.evidence);
|
|
2470
|
+
if (e.date) {
|
|
2471
|
+
const age = (Date.parse(`${today}T00:00:00`) - Date.parse(`${e.date}T00:00:00`)) / 864e5;
|
|
2472
|
+
if (age > 30) q -= Math.min(0.2, (age - 30) / 90 * 0.2);
|
|
2473
|
+
}
|
|
2474
|
+
return Math.max(0, Math.min(1, Number(q.toFixed(3))));
|
|
2475
|
+
}
|
|
2476
|
+
function graphRecallDetailed(data, query, opts = {}) {
|
|
2477
|
+
const entries = parseEntries(data);
|
|
2478
|
+
const { adjacency, byKey } = buildGraph(entries);
|
|
2479
|
+
const hops = Math.max(1, Math.min(2, opts.hops ?? 1));
|
|
2480
|
+
const category = opts.category || "";
|
|
2481
|
+
const tagsFilter = opts.tags ? opts.tags.split(";").map((t) => t.trim()).filter(Boolean) : [];
|
|
2482
|
+
const from_date = opts.from_date || "";
|
|
2483
|
+
const to_date = opts.to_date || "";
|
|
2484
|
+
const qTokens = tokenize(query);
|
|
2485
|
+
const expandedTokens = expandSynonyms(qTokens);
|
|
2486
|
+
const bm25 = bm25Scores(entries, query);
|
|
2487
|
+
const cent = centrality(adjacency);
|
|
2488
|
+
const ngram = ngramScores(entries, query);
|
|
2489
|
+
const seedKeys = /* @__PURE__ */ new Set();
|
|
2490
|
+
const asOf = opts.asOf || "";
|
|
2491
|
+
for (const e of entries) {
|
|
2492
|
+
if (e.status === "obsolete" || e.status === "draft") {
|
|
2493
|
+
if (!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)) continue;
|
|
2494
|
+
}
|
|
2495
|
+
if (asOf && e.date && e.date > asOf) continue;
|
|
2496
|
+
if (category && e.category !== category) continue;
|
|
2497
|
+
if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue;
|
|
2498
|
+
if (from_date && e.date < from_date) continue;
|
|
2499
|
+
if (to_date && e.date > to_date) continue;
|
|
2500
|
+
if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue;
|
|
2501
|
+
if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue;
|
|
2502
|
+
const text = normalize(
|
|
2503
|
+
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
2504
|
+
);
|
|
2505
|
+
const docTokens = text.split(" ");
|
|
2506
|
+
const exactMatch = expandedTokens.some((t) => text.includes(t));
|
|
2507
|
+
const fuzzy = !exactMatch && fuzzyMatch(qTokens, docTokens);
|
|
2508
|
+
const ngMatch = !exactMatch && !fuzzy && (ngram.get(e.key) || 0) >= NGRAM_SEED_MIN;
|
|
2509
|
+
if (qTokens.length > 0 && !exactMatch && !fuzzy && !ngMatch) continue;
|
|
2510
|
+
seedKeys.add(e.key);
|
|
2511
|
+
}
|
|
2512
|
+
let selected;
|
|
2513
|
+
const scored = [];
|
|
2514
|
+
const visibleEntries = entries.filter((e) => {
|
|
2515
|
+
if (e.status === "obsolete" || e.status === "draft") {
|
|
2516
|
+
return !!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf);
|
|
2517
|
+
}
|
|
2518
|
+
return !(asOf && e.date && e.date > asOf);
|
|
2519
|
+
});
|
|
2520
|
+
const isVisible = new Set(visibleEntries.map((e) => e.key));
|
|
2521
|
+
if (seedKeys.size === 0) {
|
|
2522
|
+
scored.push(
|
|
2523
|
+
...visibleEntries.sort((a, b) => {
|
|
2524
|
+
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
2525
|
+
const ia = importanceRank(a.importance);
|
|
2526
|
+
const ib = importanceRank(b.importance);
|
|
2527
|
+
if (ia !== ib) return ib - ia;
|
|
2528
|
+
return importance(b, opts.today) + entryQuality(b, opts.today) * 0.25 - (importance(a, opts.today) + entryQuality(a, opts.today) * 0.25);
|
|
2529
|
+
}).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) + entryQuality(e, opts.today) * 0.25 + importanceBoost(e.importance) }))
|
|
2530
|
+
);
|
|
2531
|
+
} else {
|
|
2532
|
+
const best = /* @__PURE__ */ new Map();
|
|
2533
|
+
const queue = [];
|
|
2534
|
+
for (const k of seedKeys) queue.push({ key: k, dist: 0 });
|
|
2535
|
+
while (queue.length) {
|
|
2536
|
+
const { key, dist } = queue.shift();
|
|
2537
|
+
if (best.has(key) && best.get(key) <= dist) continue;
|
|
2538
|
+
best.set(key, dist);
|
|
2539
|
+
if (dist >= hops) continue;
|
|
2540
|
+
for (const nb of adjacency.get(key) || []) {
|
|
2541
|
+
if (!isVisible.has(nb)) continue;
|
|
2542
|
+
queue.push({ key: nb, dist: dist + 1 });
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
const cand = new Set(best.keys());
|
|
2546
|
+
const sub = (m) => new Map([...m].filter(([k]) => cand.has(k)));
|
|
2547
|
+
const localCent = localCentrality(adjacency, cand);
|
|
2548
|
+
const bm25Rank = rankBy(sub(bm25));
|
|
2549
|
+
const ngRank = rankBy(sub(ngram));
|
|
2550
|
+
const centRank = rankBy(sub(localCent));
|
|
2551
|
+
const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, ngRank, centRank], rrfK(bm25Rank.size)) : null;
|
|
2552
|
+
const base = [...best.keys()].map((k) => {
|
|
2553
|
+
const e = byKey.get(k);
|
|
2554
|
+
const dist = best.get(k);
|
|
2555
|
+
const decay = Math.pow(DECAY, dist);
|
|
2556
|
+
let s = fused ? fused.get(k) || 0 : (bm25.get(k) || 0) + W_CENT * (cent.get(k) || 0) + W_IMP * importance(e, opts.today);
|
|
2557
|
+
if (!fused && seedKeys.has(k)) s += SEED_BONUS;
|
|
2558
|
+
if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
|
|
2559
|
+
const entryFile = e.file.split(":")[0];
|
|
2560
|
+
if (opts.sessionFiles.some((f) => f === entryFile)) {
|
|
2561
|
+
s *= 1.15;
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
if (e.category === "warning") s += 0.2;
|
|
2565
|
+
s += importanceBoost(e.importance);
|
|
2566
|
+
s += evidenceBoost(e.evidence);
|
|
2567
|
+
s += entryQuality(e, opts.today) * 0.08;
|
|
2568
|
+
if (opts.utility) s += (opts.utility.get(k) || 0) * 0.25;
|
|
2569
|
+
if (opts.dense) s += (opts.dense.get(k) || 0) * (opts.denseWeight ?? 0.25);
|
|
2570
|
+
s *= decay;
|
|
2571
|
+
return { e, s, priority: e.priority };
|
|
2572
|
+
});
|
|
2573
|
+
if (opts.activation && opts.edges && base.length > 0) {
|
|
2574
|
+
const seeds = [...base].sort((a, b) => b.s - a.s).slice(0, 5).map((x) => x.e.key);
|
|
2575
|
+
const activated = activationScores(opts.edges, seeds, opts.activationDepth ?? 1);
|
|
2576
|
+
for (const x of base) x.s += (activated.get(x.e.key) || 0) * 0.1;
|
|
2577
|
+
}
|
|
2578
|
+
scored.push(
|
|
2579
|
+
...base.sort((a, b) => {
|
|
2580
|
+
if (a.priority !== b.priority) return b.priority - a.priority;
|
|
2581
|
+
return b.s - a.s;
|
|
2582
|
+
}).slice(0, opts.limit ?? 6)
|
|
2583
|
+
);
|
|
2584
|
+
}
|
|
2585
|
+
selected = scored.map((x) => x.e);
|
|
2586
|
+
const pinnedKeys = new Set(visibleEntries.filter((e) => e.priority > 0).map((e) => e.key));
|
|
2587
|
+
const inResult = new Set(selected.map((e) => e.key));
|
|
2588
|
+
const toInject = [...pinnedKeys].filter((k) => !inResult.has(k) && byKey.has(k)).map((k) => byKey.get(k)).sort((a, b) => b.priority - a.priority);
|
|
2589
|
+
for (const e of toInject) {
|
|
2590
|
+
selected.unshift(e);
|
|
2591
|
+
scored.unshift({ e, s: 999 });
|
|
2592
|
+
}
|
|
2593
|
+
const subAdj = /* @__PURE__ */ new Map();
|
|
2594
|
+
for (const e of selected) {
|
|
2595
|
+
subAdj.set(
|
|
2596
|
+
e.key,
|
|
2597
|
+
(adjacency.get(e.key) || []).filter((k) => selected.some((s) => s.key === k))
|
|
2598
|
+
);
|
|
2599
|
+
}
|
|
2600
|
+
const scores = /* @__PURE__ */ new Map();
|
|
2601
|
+
selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key).s));
|
|
2602
|
+
let bm25Max = 0;
|
|
2603
|
+
for (const v of bm25.values()) if (v > bm25Max) bm25Max = v;
|
|
2604
|
+
const reasons = /* @__PURE__ */ new Map();
|
|
2605
|
+
for (const e of selected) {
|
|
2606
|
+
reasons.set(
|
|
2607
|
+
e.key,
|
|
2608
|
+
buildReason(e, bm25.get(e.key) || 0, bm25Max, importance(e, opts.today), opts.today)
|
|
2609
|
+
);
|
|
2610
|
+
}
|
|
2611
|
+
return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons };
|
|
2612
|
+
}
|
|
2613
|
+
function globMatch(pattern, target) {
|
|
2614
|
+
if (!pattern) return true;
|
|
2615
|
+
if (pattern.startsWith("/")) pattern = pattern.slice(1);
|
|
2616
|
+
if (target.startsWith("/")) target = target.slice(1);
|
|
2617
|
+
const reStr = "^" + pattern.replace(/\*\*/g, "___DOUBLESTAR___").replace(/\*/g, "[^/]*").replace(/___DOUBLESTAR___/g, ".*").replace(/\?/g, ".").replace(/\./g, "\\.").replace(/\\\.\*/g, ".*") + "$";
|
|
2618
|
+
try {
|
|
2619
|
+
return new RegExp(reStr).test(target);
|
|
2620
|
+
} catch {
|
|
2621
|
+
return false;
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
1996
2624
|
|
|
1997
2625
|
// src/viewer/data.ts
|
|
1998
2626
|
function buildViewerData() {
|
|
@@ -2039,19 +2667,6 @@ function buildViewerData() {
|
|
|
2039
2667
|
import { readFileSync as readFileSync13 } from "fs";
|
|
2040
2668
|
import { resolve, dirname as dirname8 } from "path";
|
|
2041
2669
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2042
|
-
var d3Src = (() => {
|
|
2043
|
-
try {
|
|
2044
|
-
const dir = dirname8(fileURLToPath2(import.meta.url));
|
|
2045
|
-
return readFileSync13(resolve(dir, "../src/viewer/d3.v7.min.js"), "utf-8");
|
|
2046
|
-
} catch {
|
|
2047
|
-
try {
|
|
2048
|
-
const dir = dirname8(fileURLToPath2(import.meta.url));
|
|
2049
|
-
return readFileSync13(resolve(dir, "d3.v7.min.js"), "utf-8");
|
|
2050
|
-
} catch {
|
|
2051
|
-
return null;
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
})();
|
|
2055
2670
|
function readViewerAsset(name) {
|
|
2056
2671
|
const dir = dirname8(fileURLToPath2(import.meta.url));
|
|
2057
2672
|
const candidates = [
|
|
@@ -2067,6 +2682,7 @@ function readViewerAsset(name) {
|
|
|
2067
2682
|
}
|
|
2068
2683
|
return "";
|
|
2069
2684
|
}
|
|
2685
|
+
var d3Src = readViewerAsset("d3.v7.min.js");
|
|
2070
2686
|
var logoSrc = readViewerAsset("logo.svg");
|
|
2071
2687
|
var isologoSrc = readViewerAsset("logo-isologo.svg");
|
|
2072
2688
|
function generateHtml(viewerData) {
|
|
@@ -2341,7 +2957,7 @@ const tooltip = document.getElementById('tooltip');
|
|
|
2341
2957
|
function showTooltip(e, d) {
|
|
2342
2958
|
const score = d.quality || 0;
|
|
2343
2959
|
tooltip.innerHTML =
|
|
2344
|
-
'<div class="tt-cat" style="color:' + (COLORS[d.category] || 'var(--muted)') + '">' + d.category + '</div>' +
|
|
2960
|
+
'<div class="tt-cat" style="color:' + (COLORS[d.category] || 'var(--muted)') + '">' + escHtml(d.category) + '</div>' +
|
|
2345
2961
|
'<div class="tt-key">' + escHtml(d.id) + '</div>' +
|
|
2346
2962
|
'<div class="tt-content">' + escHtml(d.content) + '</div>' +
|
|
2347
2963
|
'<div class="tt-score">Quality: ' + score.toFixed(2) + ' | Access: ' + (d.accessCount || 0) + '</div>';
|
|
@@ -2431,7 +3047,7 @@ function renderEntries() {
|
|
|
2431
3047
|
div.className = 'entry-item' + (selectedEntry && selectedEntry.id === e.id ? ' selected' : '') + (firstEntriesRender ? ' reveal' : '');
|
|
2432
3048
|
if (firstEntriesRender) div.style.animationDelay = Math.min(i * 0.03, 0.6) + 's';
|
|
2433
3049
|
div.innerHTML =
|
|
2434
|
-
'<div class="entry-cat ' + e.category + '">' + e.category + '</div>' +
|
|
3050
|
+
'<div class="entry-cat ' + escHtml(e.category) + '">' + escHtml(e.category) + '</div>' +
|
|
2435
3051
|
'<div class="entry-key">' + escHtml(e.id) + '</div>' +
|
|
2436
3052
|
'<div class="entry-preview">' + escHtml(e.content) + '</div>' +
|
|
2437
3053
|
(e.tags.length ? '<div class="entry-tags">' + e.tags.map(t => '<span class="entry-tag">' + escHtml(t) + '</span>').join('') + '</div>' : '');
|
|
@@ -2441,7 +3057,7 @@ function renderEntries() {
|
|
|
2441
3057
|
firstEntriesRender = false;
|
|
2442
3058
|
}
|
|
2443
3059
|
|
|
2444
|
-
function escHtml(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
|
3060
|
+
function escHtml(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'''); }
|
|
2445
3061
|
|
|
2446
3062
|
// --- Entry Selection ---
|
|
2447
3063
|
function selectEntry(entry) {
|
|
@@ -2460,17 +3076,17 @@ function showDetail(e) {
|
|
|
2460
3076
|
.map(ed => (typeof ed.source === 'object' ? ed.source.id : ed.source) === e.id ? (typeof ed.target === 'object' ? ed.target.id : ed.target) : (typeof ed.source === 'object' ? ed.source.id : ed.source));
|
|
2461
3077
|
|
|
2462
3078
|
panel.innerHTML =
|
|
2463
|
-
'<div class="detail-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + e.category + '</div>' +
|
|
3079
|
+
'<div class="detail-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + escHtml(e.category) + '</div>' +
|
|
2464
3080
|
'<h2>' + escHtml(e.id) + '</h2>' +
|
|
2465
3081
|
'<div class="detail-field"><label>Content</label><span class="value mono">' + escHtml(e.content) + '</span></div>' +
|
|
2466
3082
|
(e.file ? '<div class="detail-field"><label>File</label><span class="value mono"><a href="#" onclick="event.preventDefault()" style="color:var(--brand);text-decoration:none;cursor:pointer">' + escHtml(e.file) + '</a></span></div>' : '') +
|
|
2467
|
-
(e.date ? '<div class="detail-field"><label>Date</label><span class="value">' + e.date + '</span></div>' : '') +
|
|
3083
|
+
(e.date ? '<div class="detail-field"><label>Date</label><span class="value">' + escHtml(e.date) + '</span></div>' : '') +
|
|
2468
3084
|
'<div class="detail-field"><label>Quality Score</label><span class="value" style="color:var(--brand);font-weight:700;font-size:1.1rem">' + (e.quality || 0).toFixed(3) + '</span></div>' +
|
|
2469
3085
|
'<div class="detail-field"><label>Access Count</label><span class="value">' + (e.accessCount || 0) + '</span></div>' +
|
|
2470
|
-
(e.ttl ? '<div class="detail-field"><label>TTL</label><span class="value">' + e.ttl + '</span></div>' : '') +
|
|
2471
|
-
(e.lastAccessed ? '<div class="detail-field"><label>Last Accessed</label><span class="value">' + e.lastAccessed + '</span></div>' : '') +
|
|
3086
|
+
(e.ttl ? '<div class="detail-field"><label>TTL</label><span class="value">' + escHtml(e.ttl) + '</span></div>' : '') +
|
|
3087
|
+
(e.lastAccessed ? '<div class="detail-field"><label>Last Accessed</label><span class="value">' + escHtml(e.lastAccessed) + '</span></div>' : '') +
|
|
2472
3088
|
(e.tags.length ? '<div class="detail-field"><label>Tags</label><div class="entry-tags">' + e.tags.map(t => '<span class="entry-tag">' + escHtml(t) + '</span>').join('') + '</div></div>' : '') +
|
|
2473
|
-
(linkedNodes.length ? '<div class="detail-field"><label>Linked Entries (' + linkedNodes.length + ')</label><div class="detail-links">' + linkedNodes.map(k => '<span class="detail-link"
|
|
3089
|
+
(linkedNodes.length ? '<div class="detail-field"><label>Linked Entries (' + linkedNodes.length + ')</label><div class="detail-links">' + linkedNodes.map(k => '<span class="detail-link" data-id="' + escHtml(k) + '">' + escHtml(k) + '</span>').join('') + '</div></div>' : '');
|
|
2474
3090
|
}
|
|
2475
3091
|
|
|
2476
3092
|
window.selectEntryById = function(id) {
|
|
@@ -2478,6 +3094,16 @@ window.selectEntryById = function(id) {
|
|
|
2478
3094
|
if (e) selectEntry(e);
|
|
2479
3095
|
};
|
|
2480
3096
|
|
|
3097
|
+
// Delegated click handling for data-id elements (detail links, timeline) \u2014
|
|
3098
|
+
// avoids inline onclick handlers with interpolated entry data (XSS vector).
|
|
3099
|
+
document.addEventListener('click', function(ev) {
|
|
3100
|
+
const t = ev.target;
|
|
3101
|
+
const el = t && t.closest ? t.closest('[data-id]') : null;
|
|
3102
|
+
if (el && el.dataset.id) {
|
|
3103
|
+
window.selectEntryById(el.dataset.id);
|
|
3104
|
+
}
|
|
3105
|
+
});
|
|
3106
|
+
|
|
2481
3107
|
// --- Stats ---
|
|
2482
3108
|
function renderStats() {
|
|
2483
3109
|
const grid = document.getElementById('statsGrid');
|
|
@@ -2496,7 +3122,7 @@ function renderStats() {
|
|
|
2496
3122
|
card(3, '<h3>Max Access</h3><div class="stat-big">' + maxAccess + '</div>') +
|
|
2497
3123
|
card(4, '<h3>Categories</h3><div class="bar-chart">' +
|
|
2498
3124
|
catEntries.map(([cat, count]) =>
|
|
2499
|
-
'<div class="bar-row"><span class="bar-label">' + cat + '</span><div class="bar-track"><div class="bar-fill" data-w="' + (count/maxCat*100) + '" style="background:' + (COLORS[cat] || 'var(--brand)') + '"></div></div><span class="bar-value">' + count + '</span></div>'
|
|
3125
|
+
'<div class="bar-row"><span class="bar-label">' + escHtml(cat) + '</span><div class="bar-track"><div class="bar-fill" data-w="' + (count/maxCat*100) + '" style="background:' + (COLORS[cat] || 'var(--brand)') + '"></div></div><span class="bar-value">' + count + '</span></div>'
|
|
2500
3126
|
).join('') +
|
|
2501
3127
|
'</div>') +
|
|
2502
3128
|
card(5, '<h3>Top Tags</h3><div class="tag-cloud">' +
|
|
@@ -2526,9 +3152,9 @@ function renderTimeline() {
|
|
|
2526
3152
|
let idx = 0;
|
|
2527
3153
|
for (const [date, entries] of Object.entries(grouped)) {
|
|
2528
3154
|
for (const e of entries) {
|
|
2529
|
-
html += '<div class="timeline-entry reveal" style="border-left:3px solid ' + (COLORS[e.category] || 'var(--border)') + ';animation-delay:' + Math.min(idx * 0.02, 0.6) + 's"
|
|
3155
|
+
html += '<div class="timeline-entry reveal" style="border-left:3px solid ' + (COLORS[e.category] || 'var(--border)') + ';animation-delay:' + Math.min(idx * 0.02, 0.6) + 's" data-id="' + escHtml(e.id) + '">' +
|
|
2530
3156
|
'<div class="tl-date">' + escHtml(date) + '</div>' +
|
|
2531
|
-
'<div class="tl-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + e.category + '</div>' +
|
|
3157
|
+
'<div class="tl-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + escHtml(e.category) + '</div>' +
|
|
2532
3158
|
'<div class="tl-key">' + escHtml(e.id) + '</div>' +
|
|
2533
3159
|
'<div class="tl-content">' + escHtml(e.content.substring(0, 100)) + '</div>' +
|
|
2534
3160
|
'</div>';
|
|
@@ -3001,13 +3627,10 @@ if (window.parent !== window) {
|
|
|
3001
3627
|
import { createServer } from "http";
|
|
3002
3628
|
function openBrowser(url) {
|
|
3003
3629
|
const platform = process.platform;
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
} catch {
|
|
3009
|
-
console.log(`Open in browser: ${url}`);
|
|
3010
|
-
}
|
|
3630
|
+
const opts = { stdio: "ignore", detached: true };
|
|
3631
|
+
const child = platform === "darwin" ? spawn("open", [url], opts) : platform === "win32" ? spawn("cmd", ["/c", "start", "", url], opts) : spawn("xdg-open", [url], opts);
|
|
3632
|
+
child.unref();
|
|
3633
|
+
child.on("error", () => console.log(`Open in browser: ${url}`));
|
|
3011
3634
|
}
|
|
3012
3635
|
function resolvePort(portArg) {
|
|
3013
3636
|
const raw = portArg ?? process.env.PORT;
|
|
@@ -3080,8 +3703,1045 @@ function viewerExport() {
|
|
|
3080
3703
|
openBrowser(outFile);
|
|
3081
3704
|
}
|
|
3082
3705
|
|
|
3706
|
+
// src/cli/ambient.ts
|
|
3707
|
+
import { existsSync as existsSync14, readFileSync as readFileSync15 } from "fs";
|
|
3708
|
+
import { join as join12 } from "path";
|
|
3709
|
+
|
|
3710
|
+
// src/lib/handoff.ts
|
|
3711
|
+
import { basename as basename2 } from "path";
|
|
3712
|
+
function projectSlug(root) {
|
|
3713
|
+
return root.replace(/^[\\/]+/, "").replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase();
|
|
3714
|
+
}
|
|
3715
|
+
function entryAgeDays(date, today) {
|
|
3716
|
+
if (!date) return 0;
|
|
3717
|
+
const then = Date.parse(`${date}T00:00:00`);
|
|
3718
|
+
const now = Date.parse(`${today}T00:00:00`);
|
|
3719
|
+
if (!Number.isFinite(then) || !Number.isFinite(now)) return 0;
|
|
3720
|
+
return Math.max(0, Math.round((now - then) / 864e5));
|
|
3721
|
+
}
|
|
3722
|
+
function claim(e, maxChars = 130) {
|
|
3723
|
+
const text = e.content.replace(/\s+/g, " ").trim();
|
|
3724
|
+
if (!text) return e.key;
|
|
3725
|
+
const sentence = text.match(/^[^.!?]+[.!?]?/)?.[0] || text;
|
|
3726
|
+
if (sentence.length <= maxChars) return sentence.trim();
|
|
3727
|
+
const cut = sentence.slice(0, maxChars).replace(/\s+\S*$/, "");
|
|
3728
|
+
return `${cut} \xB7 ver ${e.key}`;
|
|
3729
|
+
}
|
|
3730
|
+
function matches(e, task) {
|
|
3731
|
+
const q = task.toLowerCase();
|
|
3732
|
+
if (!q) return false;
|
|
3733
|
+
const text = `${e.key} ${e.content} ${e.tags.join(" ")} ${e.file}`.toLowerCase();
|
|
3734
|
+
return q.split(/\s+/).filter((t) => t.length > 3).some((t) => text.includes(t));
|
|
3735
|
+
}
|
|
3736
|
+
function buildHandoffBrief(data, root, opts = {}) {
|
|
3737
|
+
const today = opts.today || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
3738
|
+
const maxTokens = opts.maxTokens ?? 420;
|
|
3739
|
+
const task = opts.task || "";
|
|
3740
|
+
const usable = parseEntries(data).filter(
|
|
3741
|
+
(e) => e.status !== "obsolete" && e.status !== "draft" && !isPrivate(e) && !(e.ttl && isExpiredLocal(e.ttl, today))
|
|
3742
|
+
);
|
|
3743
|
+
const newest = usable.reduce((acc, e) => e.date > acc ? e.date : acc, "");
|
|
3744
|
+
const age = entryAgeDays(newest, today);
|
|
3745
|
+
const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh";
|
|
3746
|
+
const head = [
|
|
3747
|
+
`<memory project="${basename2(root) || root}" as_of="${today}" freshness="${freshness}">`,
|
|
3748
|
+
`identity: mcp_project=${projectSlug(root)} | root=${root}`
|
|
3749
|
+
];
|
|
3750
|
+
const used = /* @__PURE__ */ new Set();
|
|
3751
|
+
const take = (list) => {
|
|
3752
|
+
const out2 = [];
|
|
3753
|
+
for (const e of list) {
|
|
3754
|
+
if (used.has(e.key)) continue;
|
|
3755
|
+
used.add(e.key);
|
|
3756
|
+
out2.push(e);
|
|
3757
|
+
}
|
|
3758
|
+
return out2;
|
|
3759
|
+
};
|
|
3760
|
+
const byDate = (a, b) => b.date.localeCompare(a.date);
|
|
3761
|
+
const line2 = (section, e) => {
|
|
3762
|
+
const stale = entryAgeDays(e.date, today) > 30 ? ` [stale ${entryAgeDays(e.date, today)}d]` : "";
|
|
3763
|
+
const file = e.file ? ` @ ${e.file}` : "";
|
|
3764
|
+
return `${section} [${e.category}] ${e.key}: ${claim(e)}${file}${stale}`;
|
|
3765
|
+
};
|
|
3766
|
+
const traps = take(
|
|
3767
|
+
usable.filter(
|
|
3768
|
+
(e) => e.category === "warning" || e.tags.some((t) => ["trap", "gotcha", "risk", "warning"].includes(t.toLowerCase()))
|
|
3769
|
+
).sort(byDate).slice(0, 2)
|
|
3770
|
+
);
|
|
3771
|
+
const directives = take(
|
|
3772
|
+
usable.filter((e) => e.origin === "human" || e.importance === "critical").sort((a, b) => b.priority - a.priority || byDate(a, b)).slice(0, 2)
|
|
3773
|
+
);
|
|
3774
|
+
const open = take(usable.filter((e) => e.category === "decision").sort(byDate).slice(0, 3));
|
|
3775
|
+
const recent = take(
|
|
3776
|
+
[...usable].sort((a, b) => {
|
|
3777
|
+
const tm = Number(matches(b, task)) - Number(matches(a, task));
|
|
3778
|
+
return tm || byDate(a, b);
|
|
3779
|
+
}).slice(0, 3)
|
|
3780
|
+
);
|
|
3781
|
+
const files = usable.filter((e) => e.file).sort(byDate).slice(0, 3);
|
|
3782
|
+
const sections = [];
|
|
3783
|
+
const push = (title, rows) => {
|
|
3784
|
+
if (rows.length > 0) sections.push(`${title}
|
|
3785
|
+
${rows.join("\n")}`);
|
|
3786
|
+
};
|
|
3787
|
+
push("directives:", directives.map((e) => line2("-", e)));
|
|
3788
|
+
push("traps:", traps.map((e) => line2("-", e)));
|
|
3789
|
+
push("open:", open.map((e) => line2("-", e)));
|
|
3790
|
+
push("recent:", recent.map((e) => line2("-", e)));
|
|
3791
|
+
if (files.length > 0) {
|
|
3792
|
+
push("files:", files.map((e) => `- ${e.file}${e.key ? ` \u2190 ${e.key}` : ""}`));
|
|
3793
|
+
}
|
|
3794
|
+
const out = [...head];
|
|
3795
|
+
for (const section of sections) {
|
|
3796
|
+
if (estimateTokens(out.join("\n") + "\n" + section) > maxTokens) break;
|
|
3797
|
+
out.push(section);
|
|
3798
|
+
}
|
|
3799
|
+
if (out.length === 2) out.push("(no stable memories yet)");
|
|
3800
|
+
out.push("</memory>");
|
|
3801
|
+
return out.join("\n");
|
|
3802
|
+
}
|
|
3803
|
+
|
|
3804
|
+
// src/lib/compiler.ts
|
|
3805
|
+
import { basename as basename3 } from "path";
|
|
3806
|
+
function claim2(e, maxChars = 120) {
|
|
3807
|
+
const text = e.content.replace(/\s+/g, " ").trim();
|
|
3808
|
+
if (!text) return e.key;
|
|
3809
|
+
const sentence = text.match(/^[^.!?]+[.!?]?/)?.[0] || text;
|
|
3810
|
+
if (sentence.length <= maxChars) return sentence.trim();
|
|
3811
|
+
return `${sentence.slice(0, maxChars).replace(/\s+\S*$/, "")} \xB7 ${e.key}`;
|
|
3812
|
+
}
|
|
3813
|
+
function line(e, today) {
|
|
3814
|
+
const age = entryAgeDays(e.date, today);
|
|
3815
|
+
const stale = age > 30 ? ` [stale ${age}d]` : "";
|
|
3816
|
+
const file = e.file ? ` @ ${e.file}` : "";
|
|
3817
|
+
return `- [${e.category}] ${e.key}: ${claim2(e)}${file}${stale}`;
|
|
3818
|
+
}
|
|
3819
|
+
function compileContext(data, task, opts = {}) {
|
|
3820
|
+
const today = opts.today || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
3821
|
+
const root = opts.root || process.cwd();
|
|
3822
|
+
const maxTokens = opts.maxTokens ?? 900;
|
|
3823
|
+
const usable = parseEntries(data).filter(
|
|
3824
|
+
(e) => e.status !== "obsolete" && e.status !== "draft" && !isPrivate(e) && !(e.ttl && isExpiredLocal(e.ttl, today))
|
|
3825
|
+
);
|
|
3826
|
+
const newest = usable.reduce((acc, e) => e.date > acc ? e.date : acc, "");
|
|
3827
|
+
const age = entryAgeDays(newest, today);
|
|
3828
|
+
const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh";
|
|
3829
|
+
const graphRanked = graphRecallDetailed(data, task, {
|
|
3830
|
+
limit: 12,
|
|
3831
|
+
utility: opts.utility,
|
|
3832
|
+
edges: opts.edges,
|
|
3833
|
+
activation: opts.activation,
|
|
3834
|
+
dense: opts.dense
|
|
3835
|
+
}).entries;
|
|
3836
|
+
const utilitySeeds = [...opts.utility?.entries() || []].filter(([, value]) => value > 0).sort((a, b) => b[1] - a[1]).map(([key]) => key);
|
|
3837
|
+
const utilityEntries = utilitySeeds.map((key) => usable.find((e) => e.key === key)).filter((e) => Boolean(e));
|
|
3838
|
+
const ranked = [...utilityEntries, ...graphRanked.filter((e) => !utilitySeeds.includes(e.key))];
|
|
3839
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3840
|
+
const take = (list) => {
|
|
3841
|
+
const out = [];
|
|
3842
|
+
for (const e of list) {
|
|
3843
|
+
if (seen.has(e.key)) continue;
|
|
3844
|
+
seen.add(e.key);
|
|
3845
|
+
out.push(e);
|
|
3846
|
+
}
|
|
3847
|
+
return out;
|
|
3848
|
+
};
|
|
3849
|
+
const byDate = (a, b) => b.date.localeCompare(a.date);
|
|
3850
|
+
const directives = take(
|
|
3851
|
+
usable.filter(
|
|
3852
|
+
(e) => (e.origin === "human" || e.importance === "critical" || e.priority > 0) && e.category !== "warning" && e.evidence !== "conflict"
|
|
3853
|
+
).sort((a, b) => b.priority - a.priority || byDate(a, b)).slice(0, 3)
|
|
3854
|
+
);
|
|
3855
|
+
const constraints = take(
|
|
3856
|
+
usable.filter(
|
|
3857
|
+
(e) => e.category === "warning" || e.evidence === "conflict" || e.tags.some((t) => ["trap", "gotcha", "risk", "warning", "outdated"].includes(t.toLowerCase()))
|
|
3858
|
+
).sort(byDate).slice(0, 2)
|
|
3859
|
+
);
|
|
3860
|
+
const memory = take(ranked.slice(0, 5));
|
|
3861
|
+
const decisions = take(ranked.filter((e) => e.category === "decision").slice(0, 2));
|
|
3862
|
+
const tokens = tokenize(task).slice(0, 4);
|
|
3863
|
+
const queries = [];
|
|
3864
|
+
if (task.trim()) queries.push(task.trim().slice(0, 140));
|
|
3865
|
+
if (tokens.length >= 2) queries.push(`${tokens[0]} ${tokens[1]}`);
|
|
3866
|
+
if (memory.length > 0 && tokens.length > 0) queries.push(`${memory[0].key} ${tokens[0]}`);
|
|
3867
|
+
const queriesOut = [...new Set(queries)].slice(0, 3);
|
|
3868
|
+
const hydrate = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.key))].slice(0, 8);
|
|
3869
|
+
const files = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.file).filter(Boolean))].slice(0, 4);
|
|
3870
|
+
const sessionLines = (opts.sessions || []).slice(0, 2).map((s) => `- ${s}`);
|
|
3871
|
+
const sections = [
|
|
3872
|
+
{ title: "Directives", lines: directives.map((e) => line(e, today)) },
|
|
3873
|
+
{ title: "Constraints", lines: constraints.map((e) => line(e, today)) },
|
|
3874
|
+
{ title: "Memory", lines: memory.map((e) => line(e, today)) },
|
|
3875
|
+
{ title: "Decisions", lines: decisions.map((e) => line(e, today)) },
|
|
3876
|
+
{ title: "Retrieval", lines: queriesOut.map((q) => `- query: ${q}`) },
|
|
3877
|
+
{ title: "Hydrate", lines: hydrate.length ? hydrate.map((k) => `- ${k}`) : ["- (none)"] },
|
|
3878
|
+
{ title: "Files", lines: files.map((f) => `- ${f}`) },
|
|
3879
|
+
{ title: "Sessions", lines: sessionLines.length ? sessionLines : ["- (none)"] }
|
|
3880
|
+
].filter((s) => s.lines.length > 0);
|
|
3881
|
+
const pkg = {
|
|
3882
|
+
task,
|
|
3883
|
+
asOf: today,
|
|
3884
|
+
freshness,
|
|
3885
|
+
project: basename3(root) || root,
|
|
3886
|
+
slug: projectSlug(root),
|
|
3887
|
+
root,
|
|
3888
|
+
sections: [],
|
|
3889
|
+
queries: queriesOut,
|
|
3890
|
+
hydrate,
|
|
3891
|
+
usedTokens: 0
|
|
3892
|
+
};
|
|
3893
|
+
let used = estimateTokens(
|
|
3894
|
+
`<memory project="${pkg.project}" as_of="${today}" freshness="${freshness}">
|
|
3895
|
+
identity: mcp_project=${pkg.slug} | root=${root}
|
|
3896
|
+
</memory>`
|
|
3897
|
+
);
|
|
3898
|
+
for (const section of sections) {
|
|
3899
|
+
const block = `${section.title}
|
|
3900
|
+
${section.lines.join("\n")}`;
|
|
3901
|
+
const cost = estimateTokens(`
|
|
3902
|
+
${block}`);
|
|
3903
|
+
if (used + cost > maxTokens) continue;
|
|
3904
|
+
used += cost;
|
|
3905
|
+
pkg.sections.push(section);
|
|
3906
|
+
}
|
|
3907
|
+
pkg.usedTokens = used;
|
|
3908
|
+
return pkg;
|
|
3909
|
+
}
|
|
3910
|
+
function renderContextPackage(pkg) {
|
|
3911
|
+
const task = pkg.task.replace(/"/g, """).slice(0, 140);
|
|
3912
|
+
const out = [
|
|
3913
|
+
`<memory project="${pkg.project}" as_of="${pkg.asOf}" freshness="${pkg.freshness}" task="${task}">`,
|
|
3914
|
+
`identity: mcp_project=${pkg.slug} | root=${pkg.root}`
|
|
3915
|
+
];
|
|
3916
|
+
for (const section of pkg.sections) out.push(`${section.title}
|
|
3917
|
+
${section.lines.join("\n")}`);
|
|
3918
|
+
if (pkg.sections.length === 0) out.push("(no stable memories yet)");
|
|
3919
|
+
out.push("</memory>");
|
|
3920
|
+
return out.join("\n");
|
|
3921
|
+
}
|
|
3922
|
+
|
|
3923
|
+
// src/lib/promoter.ts
|
|
3924
|
+
var PROMOTE_THRESHOLD = 0.75;
|
|
3925
|
+
var DIRECTIVE = /recuerda|siempre|nunca|no hagas|importante|ten cuidado|decidimos|must not|always|never/i;
|
|
3926
|
+
var FIX = /fix|fixed|error|fallo|bug|verified|pas(o|ó|ed)|green/i;
|
|
3927
|
+
var DECISION = /decidimos|elegimos|optamos|rechazamos|commit|merge|pr\b/i;
|
|
3928
|
+
function slug(text) {
|
|
3929
|
+
return text.toLowerCase().replace(/[^a-z0-9áéíóúñü]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "signal";
|
|
3930
|
+
}
|
|
3931
|
+
function scoreSignal(signal) {
|
|
3932
|
+
const text = `${signal.summary} ${signal.file}`;
|
|
3933
|
+
const type = signal.type.replace(/:$/, "");
|
|
3934
|
+
const hasFile = Boolean(signal.file);
|
|
3935
|
+
const lengthOk = signal.summary.length >= 40 && signal.summary.length <= 300;
|
|
3936
|
+
let score = 0.2;
|
|
3937
|
+
let category = "knowledge";
|
|
3938
|
+
let tags = "auto-captured";
|
|
3939
|
+
let origin = "inferred";
|
|
3940
|
+
let importance2 = "";
|
|
3941
|
+
let evidence = "unverified";
|
|
3942
|
+
if (type === "user_directive" || DIRECTIVE.test(text)) {
|
|
3943
|
+
category = "warning";
|
|
3944
|
+
origin = "human";
|
|
3945
|
+
importance2 = "high";
|
|
3946
|
+
tags = "auto-captured;directive";
|
|
3947
|
+
score = 0.85;
|
|
3948
|
+
} else if (type === "error_fix" || FIX.test(text)) {
|
|
3949
|
+
category = "bug";
|
|
3950
|
+
tags = "auto-captured;error-fix";
|
|
3951
|
+
score = 0.6;
|
|
3952
|
+
if (hasFile && FIX.test(text)) evidence = "verified";
|
|
3953
|
+
} else if (type === "decision" || DECISION.test(text)) {
|
|
3954
|
+
category = "decision";
|
|
3955
|
+
tags = "auto-captured;decision";
|
|
3956
|
+
score = 0.58;
|
|
3957
|
+
} else if (type === "diff_pattern") {
|
|
3958
|
+
category = "pattern";
|
|
3959
|
+
tags = "auto-captured;pattern";
|
|
3960
|
+
score = 0.45;
|
|
3961
|
+
} else if (type === "checkpoint") {
|
|
3962
|
+
tags = "auto-captured;checkpoint";
|
|
3963
|
+
score = 0.4;
|
|
3964
|
+
}
|
|
3965
|
+
if (lengthOk) score += 0.08;
|
|
3966
|
+
if (hasFile) score += 0.04;
|
|
3967
|
+
if (origin === "human") score += 0.04;
|
|
3968
|
+
if (evidence === "verified") score += 0.06;
|
|
3969
|
+
return { signal, score: Math.min(1, Number(score.toFixed(2))), category, tags, origin, importance: importance2, evidence };
|
|
3970
|
+
}
|
|
3971
|
+
function promoteSignals(data, signals, opts = {}) {
|
|
3972
|
+
const threshold = opts.threshold ?? PROMOTE_THRESHOLD;
|
|
3973
|
+
const today = opts.today || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
3974
|
+
const lines = data.split("\n");
|
|
3975
|
+
let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
3976
|
+
if (headerIdx === -1) {
|
|
3977
|
+
lines.push("[0|]");
|
|
3978
|
+
headerIdx = lines.length - 1;
|
|
3979
|
+
}
|
|
3980
|
+
const known = new Set(parseEntries(data).map((e) => e.key));
|
|
3981
|
+
const promoted = [];
|
|
3982
|
+
let kept = 0;
|
|
3983
|
+
for (const raw of signals) {
|
|
3984
|
+
const signal = { ...raw, summary: (raw.summary || "").replace(/\s+/g, " ").trim() };
|
|
3985
|
+
const scored = scoreSignal(signal);
|
|
3986
|
+
if (scored.score < threshold || !signal.summary) {
|
|
3987
|
+
kept++;
|
|
3988
|
+
continue;
|
|
3989
|
+
}
|
|
3990
|
+
const key = `${scored.category}-${slug(signal.summary)}`;
|
|
3991
|
+
if (known.has(key)) {
|
|
3992
|
+
kept++;
|
|
3993
|
+
continue;
|
|
3994
|
+
}
|
|
3995
|
+
known.add(key);
|
|
3996
|
+
const id = `sig-${Date.now().toString(36)}-${promoted.length.toString(36)}`;
|
|
3997
|
+
const line2 = toToonLine([
|
|
3998
|
+
id,
|
|
3999
|
+
scored.category,
|
|
4000
|
+
key,
|
|
4001
|
+
escField(signal.summary),
|
|
4002
|
+
escField(signal.file || ""),
|
|
4003
|
+
scored.tags,
|
|
4004
|
+
today,
|
|
4005
|
+
"",
|
|
4006
|
+
"0",
|
|
4007
|
+
"",
|
|
4008
|
+
"0.85",
|
|
4009
|
+
"1.0",
|
|
4010
|
+
today,
|
|
4011
|
+
"0",
|
|
4012
|
+
"",
|
|
4013
|
+
scored.origin,
|
|
4014
|
+
"active",
|
|
4015
|
+
"",
|
|
4016
|
+
scored.importance,
|
|
4017
|
+
scored.evidence
|
|
4018
|
+
]);
|
|
4019
|
+
lines.splice(headerIdx + 1, 0, line2);
|
|
4020
|
+
promoted.push({ key, category: scored.category, score: scored.score });
|
|
4021
|
+
}
|
|
4022
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/);
|
|
4023
|
+
const count = match ? parseInt(match[1]) : 0;
|
|
4024
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + promoted.length}|`);
|
|
4025
|
+
return { data: lines.join("\n"), promoted, kept };
|
|
4026
|
+
}
|
|
4027
|
+
|
|
4028
|
+
// src/mcp/session-store.ts
|
|
4029
|
+
import { readFileSync as readFileSync14, existsSync as existsSync13 } from "fs";
|
|
4030
|
+
import { join as join11 } from "path";
|
|
4031
|
+
var MAX_SESSION_ENTRIES = 500;
|
|
4032
|
+
function readSessionEntries(sessionId) {
|
|
4033
|
+
const filePath = getSessionFile();
|
|
4034
|
+
if (!existsSync13(filePath)) return [];
|
|
4035
|
+
const entries = readFileSync14(filePath, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
|
|
4036
|
+
const p = parseToonLine(l);
|
|
4037
|
+
return {
|
|
4038
|
+
ts: p[0] || "",
|
|
4039
|
+
session: p[1] || "",
|
|
4040
|
+
agent: p[2] || "",
|
|
4041
|
+
branch: p[3] || "",
|
|
4042
|
+
tool: p[4] || "",
|
|
4043
|
+
file: p[6] || "",
|
|
4044
|
+
summary: p[7] || "",
|
|
4045
|
+
accessed: p.length > 8 ? parseInt(p[8]) || 0 : 0,
|
|
4046
|
+
lastAccessed: p.length > 9 ? p[9] || "" : ""
|
|
4047
|
+
};
|
|
4048
|
+
});
|
|
4049
|
+
if (sessionId) {
|
|
4050
|
+
return entries.filter((e) => e.session === sessionId);
|
|
4051
|
+
}
|
|
4052
|
+
return entries;
|
|
4053
|
+
}
|
|
4054
|
+
function writeSessionEntry(entry) {
|
|
4055
|
+
const filePath = getSessionFile();
|
|
4056
|
+
ensureSessionFile();
|
|
4057
|
+
const data = readUnderLock(filePath);
|
|
4058
|
+
const lines = data.split("\n");
|
|
4059
|
+
let headerIdx = lines.findIndex((l) => l.startsWith("session[") || l.startsWith("observations["));
|
|
4060
|
+
if (headerIdx === -1) {
|
|
4061
|
+
lines.push("session[0|]");
|
|
4062
|
+
headerIdx = lines.length - 1;
|
|
4063
|
+
}
|
|
4064
|
+
const entryLine = toToonLine([entry.ts, entry.session, entry.agent, entry.branch, entry.tool, "", entry.file, entry.summary, "0", ""]);
|
|
4065
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/);
|
|
4066
|
+
const count = match ? parseInt(match[1]) : 0;
|
|
4067
|
+
lines.splice(headerIdx + 1, 0, entryLine);
|
|
4068
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
|
|
4069
|
+
atomicWrite(filePath, lines.join("\n"));
|
|
4070
|
+
pruneSessionEntries();
|
|
4071
|
+
}
|
|
4072
|
+
function getSessionFile() {
|
|
4073
|
+
const sessionFile = join11(MEMORY_DIR3, "session.toon");
|
|
4074
|
+
if (existsSync13(sessionFile)) return sessionFile;
|
|
4075
|
+
if (existsSync13(OBSERVATIONS_FILE)) {
|
|
4076
|
+
migrateObservationsToSession();
|
|
4077
|
+
return sessionFile;
|
|
4078
|
+
}
|
|
4079
|
+
return sessionFile;
|
|
4080
|
+
}
|
|
4081
|
+
function migrateObservationsToSession() {
|
|
4082
|
+
const data = readFileSync14(OBSERVATIONS_FILE, "utf-8");
|
|
4083
|
+
const lines = data.split("\n");
|
|
4084
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("observations["));
|
|
4085
|
+
if (headerIdx === -1) return;
|
|
4086
|
+
const newLines = [`session[0|]{ts|session|agent|branch|tool||file|summary|accessed|lastAccessed}:`];
|
|
4087
|
+
for (const line2 of lines.slice(headerIdx + 1)) {
|
|
4088
|
+
if (!line2.startsWith(" ") || !line2.includes("|")) continue;
|
|
4089
|
+
const parts = parseToonLine(line2);
|
|
4090
|
+
while (parts.length < 8) parts.push("");
|
|
4091
|
+
parts.push("0", "");
|
|
4092
|
+
newLines.push(toToonLine(parts));
|
|
4093
|
+
}
|
|
4094
|
+
const sessionFile = join11(MEMORY_DIR3, "session.toon");
|
|
4095
|
+
atomicWrite(sessionFile, newLines.join("\n"));
|
|
4096
|
+
}
|
|
4097
|
+
function ensureSessionFile() {
|
|
4098
|
+
const filePath = getSessionFile();
|
|
4099
|
+
if (!existsSync13(filePath)) {
|
|
4100
|
+
atomicWrite(filePath, "session[0|]{ts|session|agent|branch|tool||file|summary|accessed|lastAccessed}:\n");
|
|
4101
|
+
}
|
|
4102
|
+
}
|
|
4103
|
+
function pruneSessionEntries() {
|
|
4104
|
+
const filePath = getSessionFile();
|
|
4105
|
+
if (!existsSync13(filePath)) return;
|
|
4106
|
+
const data = readUnderLock(filePath);
|
|
4107
|
+
const lines = data.split("\n");
|
|
4108
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("session[") || l.startsWith("observations["));
|
|
4109
|
+
if (headerIdx === -1) return;
|
|
4110
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
|
|
4111
|
+
if (entryLines2.length <= MAX_SESSION_ENTRIES) return;
|
|
4112
|
+
const toRemove = entryLines2.length - MAX_SESSION_ENTRIES;
|
|
4113
|
+
const kept = entryLines2.slice(toRemove);
|
|
4114
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`);
|
|
4115
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...kept.map((l) => ` ${l.trim()}`));
|
|
4116
|
+
atomicWrite(filePath, lines.join("\n"));
|
|
4117
|
+
}
|
|
4118
|
+
|
|
4119
|
+
// src/cli/ambient.ts
|
|
4120
|
+
function flag(args2, name) {
|
|
4121
|
+
const i = args2.indexOf(`--${name}`);
|
|
4122
|
+
return i !== -1 && args2[i + 1] && !args2[i + 1].startsWith("--") ? args2[i + 1] : "";
|
|
4123
|
+
}
|
|
4124
|
+
function printBrief(task = "") {
|
|
4125
|
+
const data = readMemory();
|
|
4126
|
+
const root = process.cwd();
|
|
4127
|
+
if (task.trim()) {
|
|
4128
|
+
const sessions = readSessionEntries().slice(-2).map((e) => `${e.session || "cli"}: ${e.summary.slice(0, 80)}`);
|
|
4129
|
+
process.stdout.write(renderContextPackage(compileContext(data, task, { root, sessions })));
|
|
4130
|
+
return;
|
|
4131
|
+
}
|
|
4132
|
+
process.stdout.write(buildHandoffBrief(data, root, { task }));
|
|
4133
|
+
}
|
|
4134
|
+
function recordSignal(args2) {
|
|
4135
|
+
const type = flag(args2, "type") || "observation";
|
|
4136
|
+
const summary = flag(args2, "summary");
|
|
4137
|
+
if (!summary) {
|
|
4138
|
+
console.error("signal: --summary is required");
|
|
4139
|
+
process.exitCode = 1;
|
|
4140
|
+
return;
|
|
4141
|
+
}
|
|
4142
|
+
writeSessionEntry({
|
|
4143
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4144
|
+
session: flag(args2, "session") || process.env.TOON_MEMORY_SESSION || "cli",
|
|
4145
|
+
agent: flag(args2, "agent") || "opencode",
|
|
4146
|
+
branch: flag(args2, "branch") || "",
|
|
4147
|
+
tool: `${type}:${flag(args2, "tool") || "hook"}`,
|
|
4148
|
+
file: flag(args2, "file") || "",
|
|
4149
|
+
summary
|
|
4150
|
+
});
|
|
4151
|
+
}
|
|
4152
|
+
function runPromotion(args2) {
|
|
4153
|
+
const thresholdArg = Number(flag(args2, "threshold"));
|
|
4154
|
+
const threshold = Number.isFinite(thresholdArg) && thresholdArg > 0 ? thresholdArg : PROMOTE_THRESHOLD;
|
|
4155
|
+
const entries = readSessionEntries(flag(args2, "session") || void 0);
|
|
4156
|
+
const signals = entries.map((e) => ({
|
|
4157
|
+
type: e.tool,
|
|
4158
|
+
summary: e.summary,
|
|
4159
|
+
file: e.file,
|
|
4160
|
+
session: e.session,
|
|
4161
|
+
ts: e.ts
|
|
4162
|
+
}));
|
|
4163
|
+
const result = promoteSignals(readMemory(), signals, { threshold });
|
|
4164
|
+
if (result.promoted.length > 0) writeMemory(result.data);
|
|
4165
|
+
console.log(`Promoted ${result.promoted.length} signal(s); ${result.kept} kept in log.`);
|
|
4166
|
+
for (const p of result.promoted) console.log(` + ${p.category}/${p.key} (${p.score})`);
|
|
4167
|
+
}
|
|
4168
|
+
function printDoctor() {
|
|
4169
|
+
const root = process.cwd();
|
|
4170
|
+
const lines = [
|
|
4171
|
+
`toon-memory doctor \u2014 ${root}`,
|
|
4172
|
+
`mcp_project: ${projectSlug(root)}`
|
|
4173
|
+
];
|
|
4174
|
+
if (!existsSync14(MEMORY_FILE)) {
|
|
4175
|
+
lines.push(`memory: MISSING (${MEMORY_FILE}) \u2014 run 'toon-memory init'`);
|
|
4176
|
+
} else {
|
|
4177
|
+
const entries = parseEntries(readFileSync15(MEMORY_FILE, "utf-8"));
|
|
4178
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
4179
|
+
const newest = entries.reduce((a, e) => e.date > a ? e.date : a, "");
|
|
4180
|
+
const age = newest ? entryAgeDays(newest, today) : 0;
|
|
4181
|
+
const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh";
|
|
4182
|
+
const stale = entries.filter((e) => e.date && entryAgeDays(e.date, today) > 30 && e.status !== "obsolete").length;
|
|
4183
|
+
const traps = entries.filter(
|
|
4184
|
+
(e) => e.category === "warning" || e.tags.some((t) => ["trap", "gotcha", "risk"].includes(t.toLowerCase()))
|
|
4185
|
+
).length;
|
|
4186
|
+
lines.push(`memory: ${entries.length} entries | newest: ${newest || "none"} | freshness: ${freshness}`);
|
|
4187
|
+
lines.push(`hygiene: ${stale} stale | ${traps} traps`);
|
|
4188
|
+
}
|
|
4189
|
+
const sessionFile = join12(MEMORY_DIR3, "session.toon");
|
|
4190
|
+
lines.push(`signals: ${existsSync14(sessionFile) ? readSessionEntries().length : 0} in session.toon`);
|
|
4191
|
+
lines.push(`config: ${existsSync14(CONFIG_FILE) ? "present" : "default"}`);
|
|
4192
|
+
lines.push(`global: ${existsSync14(GLOBAL_FILE) ? "present" : "absent"}`);
|
|
4193
|
+
const plugin = join12(root, ".opencode", "plugins", "toon-memory.ts");
|
|
4194
|
+
if (existsSync14(plugin)) {
|
|
4195
|
+
const src = readFileSync15(plugin, "utf-8");
|
|
4196
|
+
const hasSystem = src.includes("experimental.chat.system.transform");
|
|
4197
|
+
lines.push(`opencode plugin: installed | system injection: ${hasSystem ? "OK" : "STALE \u2014 re-run init"}`);
|
|
4198
|
+
} else {
|
|
4199
|
+
lines.push("opencode plugin: absent");
|
|
4200
|
+
}
|
|
4201
|
+
lines.push(`injection: brief via 'toon-memory brief' (system.transform) | auto-write via 'signal' + 'promote'`);
|
|
4202
|
+
lines.push(`catalog: ${process.env.TOON_MEMORY_EXPERT_TOOLS === "1" ? "expert" : "core"} (set TOON_MEMORY_EXPERT_TOOLS=1 for advanced tools)`);
|
|
4203
|
+
console.log(lines.join("\n"));
|
|
4204
|
+
}
|
|
4205
|
+
|
|
4206
|
+
// src/mcp/observations.ts
|
|
4207
|
+
import { readFileSync as readFileSync16, existsSync as existsSync15, writeFileSync as writeFileSync13 } from "fs";
|
|
4208
|
+
var MAX_OBSERVATIONS = 500;
|
|
4209
|
+
function readObservations() {
|
|
4210
|
+
if (!existsSync15(OBSERVATIONS_FILE)) return [];
|
|
4211
|
+
return readFileSync16(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
|
|
4212
|
+
const p = parseToonLine(l);
|
|
4213
|
+
return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" };
|
|
4214
|
+
});
|
|
4215
|
+
}
|
|
4216
|
+
function pruneObservations() {
|
|
4217
|
+
if (!existsSync15(OBSERVATIONS_FILE)) return 0;
|
|
4218
|
+
const data = readFileSync16(OBSERVATIONS_FILE, "utf-8");
|
|
4219
|
+
const lines = data.split("\n");
|
|
4220
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("observations["));
|
|
4221
|
+
if (headerIdx === -1) return 0;
|
|
4222
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
|
|
4223
|
+
if (entryLines2.length <= MAX_OBSERVATIONS) return 0;
|
|
4224
|
+
const toRemove = entryLines2.length - MAX_OBSERVATIONS;
|
|
4225
|
+
const pruned = entryLines2.slice(toRemove);
|
|
4226
|
+
const kept = entryLines2.slice(0, MAX_OBSERVATIONS);
|
|
4227
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`);
|
|
4228
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...kept.map((l) => ` ${l.trim()}`));
|
|
4229
|
+
writeFileSync13(OBSERVATIONS_FILE, lines.join("\n"));
|
|
4230
|
+
return toRemove;
|
|
4231
|
+
}
|
|
4232
|
+
|
|
4233
|
+
// src/mcp/feedback.ts
|
|
4234
|
+
import { existsSync as existsSync16, mkdirSync as mkdirSync11, readFileSync as readFileSync17 } from "fs";
|
|
4235
|
+
var SIGNAL_WEIGHT = {
|
|
4236
|
+
useful: 1,
|
|
4237
|
+
irrelevant: -1,
|
|
4238
|
+
outdated: -1.5,
|
|
4239
|
+
wrong: -2
|
|
4240
|
+
};
|
|
4241
|
+
function readFeedback() {
|
|
4242
|
+
if (!existsSync16(FEEDBACK_FILE)) return [];
|
|
4243
|
+
let data = "";
|
|
4244
|
+
try {
|
|
4245
|
+
data = readFileSync17(FEEDBACK_FILE, "utf-8");
|
|
4246
|
+
} catch {
|
|
4247
|
+
return [];
|
|
4248
|
+
}
|
|
4249
|
+
const lines = data.split("\n");
|
|
4250
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("feedback[") || /^\[\d+\|]/.test(l));
|
|
4251
|
+
if (headerIdx === -1) return [];
|
|
4252
|
+
const out = [];
|
|
4253
|
+
for (const line2 of lines.slice(headerIdx + 1)) {
|
|
4254
|
+
if (!line2.startsWith(" ") || !line2.includes("|")) continue;
|
|
4255
|
+
const p = parseToonLine(line2.trim());
|
|
4256
|
+
if (p.length < 5) continue;
|
|
4257
|
+
const signal = p[2];
|
|
4258
|
+
if (!(signal in SIGNAL_WEIGHT)) continue;
|
|
4259
|
+
out.push({
|
|
4260
|
+
id: p[0],
|
|
4261
|
+
key: p[1],
|
|
4262
|
+
signal,
|
|
4263
|
+
source: p[3] === "implicit" ? "implicit" : "explicit",
|
|
4264
|
+
ts: p[4],
|
|
4265
|
+
session: p[5] || "",
|
|
4266
|
+
task: p[6] || ""
|
|
4267
|
+
});
|
|
4268
|
+
}
|
|
4269
|
+
return out;
|
|
4270
|
+
}
|
|
4271
|
+
|
|
4272
|
+
// src/mcp/edges.ts
|
|
4273
|
+
import { existsSync as existsSync17, mkdirSync as mkdirSync12, readFileSync as readFileSync18 } from "fs";
|
|
4274
|
+
import { dirname as dirname9 } from "path";
|
|
4275
|
+
var EDGE_TYPES = ["related", "supports", "contradicts", "supersedes", "depends_on", "derived_from", "used_in"];
|
|
4276
|
+
var MAX_EDGES = 2e3;
|
|
4277
|
+
function normalizeType(type) {
|
|
4278
|
+
const t = type.toLowerCase();
|
|
4279
|
+
return EDGE_TYPES.includes(t) ? t : "related";
|
|
4280
|
+
}
|
|
4281
|
+
function writeEdges(edges) {
|
|
4282
|
+
const dir = dirname9(EDGES_FILE);
|
|
4283
|
+
if (!existsSync17(dir)) mkdirSync12(dir, { recursive: true });
|
|
4284
|
+
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);
|
|
4285
|
+
const header = `version: 1
|
|
4286
|
+
edges[${sorted.length}|]{from|to|type|weight|ts}:`;
|
|
4287
|
+
const lines = [header, ...sorted.map((e) => toToonLine([e.from, e.to, e.type, String(e.weight), e.ts]))];
|
|
4288
|
+
withLockSync(EDGES_FILE, () => atomicWrite(EDGES_FILE, lines.join("\n")));
|
|
4289
|
+
}
|
|
4290
|
+
function deriveEdges(data, feedback = []) {
|
|
4291
|
+
const entries = parseEntries(data);
|
|
4292
|
+
const keys = new Set(entries.map((e) => e.key));
|
|
4293
|
+
const map = /* @__PURE__ */ new Map();
|
|
4294
|
+
const add = (from, to, type, weight, ts) => {
|
|
4295
|
+
if (!keys.has(from) || !keys.has(to) || from === to) return;
|
|
4296
|
+
const id = `${from}|${to}|${type}`;
|
|
4297
|
+
const prev = map.get(id);
|
|
4298
|
+
if (prev) prev.weight = Math.max(prev.weight, weight);
|
|
4299
|
+
else map.set(id, { from, to, type, weight, ts });
|
|
4300
|
+
};
|
|
4301
|
+
for (const e of entries) {
|
|
4302
|
+
for (const link of e.links) {
|
|
4303
|
+
const { type, key } = parseLinkToken(link);
|
|
4304
|
+
add(e.key, key, normalizeType(type), 1, e.date);
|
|
4305
|
+
}
|
|
4306
|
+
}
|
|
4307
|
+
for (const event of feedback) {
|
|
4308
|
+
if (!event.task) continue;
|
|
4309
|
+
const haystack = event.task.toLowerCase();
|
|
4310
|
+
const type = event.signal === "wrong" || event.signal === "outdated" ? "contradicts" : "used_in";
|
|
4311
|
+
const weight = event.signal === "useful" ? 1 : 0.5;
|
|
4312
|
+
for (const key of keys) {
|
|
4313
|
+
if (key === event.key) continue;
|
|
4314
|
+
if (!haystack.includes(key.toLowerCase())) continue;
|
|
4315
|
+
add(event.key, key, type, weight, event.ts.slice(0, 10));
|
|
4316
|
+
}
|
|
4317
|
+
}
|
|
4318
|
+
return [...map.values()];
|
|
4319
|
+
}
|
|
4320
|
+
function rebuildEdges(data, feedback = []) {
|
|
4321
|
+
const edges = deriveEdges(data, feedback);
|
|
4322
|
+
writeEdges(edges);
|
|
4323
|
+
return edges.length;
|
|
4324
|
+
}
|
|
4325
|
+
|
|
4326
|
+
// src/mcp/archive.ts
|
|
4327
|
+
import { readFileSync as readFileSync19, existsSync as existsSync18 } from "fs";
|
|
4328
|
+
|
|
4329
|
+
// src/mcp/entries.ts
|
|
4330
|
+
function parseTTL(ttl) {
|
|
4331
|
+
if (!ttl || !ttl.trim()) return "";
|
|
4332
|
+
const trimmed = ttl.trim();
|
|
4333
|
+
const dayMatch = trimmed.match(/^(\d+)d$/);
|
|
4334
|
+
if (dayMatch) {
|
|
4335
|
+
const days = parseInt(dayMatch[1]);
|
|
4336
|
+
const d = /* @__PURE__ */ new Date();
|
|
4337
|
+
d.setDate(d.getDate() + days);
|
|
4338
|
+
return d.toISOString().split("T")[0];
|
|
4339
|
+
}
|
|
4340
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
|
|
4341
|
+
return "";
|
|
4342
|
+
}
|
|
4343
|
+
function isExpired(ttl) {
|
|
4344
|
+
if (!ttl) return false;
|
|
4345
|
+
const ttlDate = parseTTL(ttl) || ttl;
|
|
4346
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
4347
|
+
return ttlDate <= today;
|
|
4348
|
+
}
|
|
4349
|
+
|
|
4350
|
+
// src/mcp/archive.ts
|
|
4351
|
+
function findHeaderIdx(lines) {
|
|
4352
|
+
return lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
4353
|
+
}
|
|
4354
|
+
function bumpHeaderCount(line2, count) {
|
|
4355
|
+
return line2.replace(/^([a-z]+)?\[(\d+)\|/, (_m, pre) => `${pre || ""}[${count}|`);
|
|
4356
|
+
}
|
|
4357
|
+
function pruneExpiredEntries() {
|
|
4358
|
+
ensureMemoryFile();
|
|
4359
|
+
if (!existsSync18(MEMORY_FILE)) return 0;
|
|
4360
|
+
let pruned = 0;
|
|
4361
|
+
withLockSync(MEMORY_FILE, () => {
|
|
4362
|
+
const data = readMemory();
|
|
4363
|
+
const lines = data.split("\n");
|
|
4364
|
+
const headerIdx = findHeaderIdx(lines);
|
|
4365
|
+
if (headerIdx === -1) return;
|
|
4366
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
|
|
4367
|
+
const kept = entryLines2.filter((l) => {
|
|
4368
|
+
const parts = parseToonLine(l);
|
|
4369
|
+
if (parts.length < 8) return true;
|
|
4370
|
+
const ttl = parts[7] || "";
|
|
4371
|
+
if (ttl && isExpired(ttl)) {
|
|
4372
|
+
pruned++;
|
|
4373
|
+
return false;
|
|
4374
|
+
}
|
|
4375
|
+
return true;
|
|
4376
|
+
});
|
|
4377
|
+
if (pruned === 0) return;
|
|
4378
|
+
lines[headerIdx] = bumpHeaderCount(lines[headerIdx], kept.length);
|
|
4379
|
+
const keepSet = new Set(kept.map((l) => l.trim()));
|
|
4380
|
+
const allEntryLines = lines.slice(headerIdx + 1);
|
|
4381
|
+
const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()));
|
|
4382
|
+
lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => l.trim().length ? ` ${l.trim()}` : l));
|
|
4383
|
+
writeMemory(lines.join("\n"));
|
|
4384
|
+
});
|
|
4385
|
+
return pruned;
|
|
4386
|
+
}
|
|
4387
|
+
|
|
4388
|
+
// src/lib/quality.ts
|
|
4389
|
+
function qualityScore(tags, links, content, date, accessed = 0, lastAccessed = "", origin = "") {
|
|
4390
|
+
let score = 0;
|
|
4391
|
+
if (tags) {
|
|
4392
|
+
const count = tags.split(";").filter(Boolean).length;
|
|
4393
|
+
score += Math.min(0.3, count * 0.1);
|
|
4394
|
+
}
|
|
4395
|
+
if (links) {
|
|
4396
|
+
const count = links.split(/[\s;]+/).filter(Boolean).length;
|
|
4397
|
+
score += Math.min(0.2, count * 0.1);
|
|
4398
|
+
}
|
|
4399
|
+
const len = content.length;
|
|
4400
|
+
if (len > 20) score += 0.1;
|
|
4401
|
+
if (len > 60) score += 0.1;
|
|
4402
|
+
if (len > 150) score += 0.1;
|
|
4403
|
+
if (date) {
|
|
4404
|
+
const days = (Date.now() - (/* @__PURE__ */ new Date(`${date}T00:00:00`)).getTime()) / 864e5;
|
|
4405
|
+
if (days < 7) score += 0.1;
|
|
4406
|
+
else if (days < 30) score += 0.05;
|
|
4407
|
+
}
|
|
4408
|
+
const words = content.toLowerCase().split(/\s+/).filter(Boolean);
|
|
4409
|
+
const unique = new Set(words);
|
|
4410
|
+
const specificity = words.length > 0 ? unique.size / words.length : 0;
|
|
4411
|
+
score += specificity * 0.1;
|
|
4412
|
+
if (accessed > 0) {
|
|
4413
|
+
score += Math.min(0.15, accessed * 0.03);
|
|
4414
|
+
}
|
|
4415
|
+
if (lastAccessed) {
|
|
4416
|
+
const daysSinceAccess = (Date.now() - new Date(lastAccessed).getTime()) / 864e5;
|
|
4417
|
+
if (daysSinceAccess < 1) score += 0.1;
|
|
4418
|
+
else if (daysSinceAccess < 7) score += 0.07;
|
|
4419
|
+
else if (daysSinceAccess < 30) score += 0.03;
|
|
4420
|
+
}
|
|
4421
|
+
if (origin === "human") score += 0.1;
|
|
4422
|
+
else if (origin === "inferred") score -= 0.05;
|
|
4423
|
+
if (date) {
|
|
4424
|
+
const daysSinceCreation = (Date.now() - (/* @__PURE__ */ new Date(`${date}T00:00:00`)).getTime()) / 864e5;
|
|
4425
|
+
const daysSinceLastAccess = lastAccessed ? (Date.now() - new Date(lastAccessed).getTime()) / 864e5 : daysSinceCreation;
|
|
4426
|
+
if (daysSinceCreation > 30 && daysSinceLastAccess > 30) {
|
|
4427
|
+
const staleness = Math.min(1, (daysSinceLastAccess - 30) / 90);
|
|
4428
|
+
score -= staleness * 0.2;
|
|
4429
|
+
}
|
|
4430
|
+
}
|
|
4431
|
+
return Math.max(0, Math.min(1, score));
|
|
4432
|
+
}
|
|
4433
|
+
function mergeEntries(existingLine, newLine) {
|
|
4434
|
+
const ep = parseToonLine(existingLine);
|
|
4435
|
+
const np = parseToonLine(newLine);
|
|
4436
|
+
if (ep.length < 7 || np.length < 7) return newLine;
|
|
4437
|
+
const id = ep[0];
|
|
4438
|
+
const category = np[1] || ep[1];
|
|
4439
|
+
const key = ep[2];
|
|
4440
|
+
const content = np[3] || ep[3];
|
|
4441
|
+
const file = np[4] || ep[4];
|
|
4442
|
+
const existingTags = (ep[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
|
|
4443
|
+
const newTags = (np[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
|
|
4444
|
+
const mergedTags = [.../* @__PURE__ */ new Set([...existingTags, ...newTags])].join(";");
|
|
4445
|
+
const existingDate = ep[6] || "";
|
|
4446
|
+
const newDate = np[6] || "";
|
|
4447
|
+
const date = newDate > existingDate ? newDate : existingDate;
|
|
4448
|
+
const existingTtl = ep[7] || "";
|
|
4449
|
+
const newTtl = np[7] || "";
|
|
4450
|
+
const ttl = newTtl || existingTtl;
|
|
4451
|
+
const existingAccessed = ep.length > 8 ? parseInt(ep[8]) || 0 : 0;
|
|
4452
|
+
const newAccessed = np.length > 8 ? parseInt(np[8]) || 0 : 0;
|
|
4453
|
+
const accessed = Math.max(existingAccessed, newAccessed);
|
|
4454
|
+
const existingLinks = (ep[9] || "").split(/[\s;]+/).filter(Boolean);
|
|
4455
|
+
const newLinks = (np[9] || "").split(/[\s;]+/).filter(Boolean);
|
|
4456
|
+
const mergedLinks = [.../* @__PURE__ */ new Set([...existingLinks, ...newLinks])].join(" ");
|
|
4457
|
+
const existingConf = ep.length > 11 ? parseFloat(ep[11]) || 0 : 0;
|
|
4458
|
+
const newConf = np.length > 11 ? parseFloat(np[11]) || 0 : 0;
|
|
4459
|
+
const confidence = Math.max(existingConf, newConf);
|
|
4460
|
+
const existingLastAccessed = ep.length > 12 ? ep[12] || "" : "";
|
|
4461
|
+
const newLastAccessed = np.length > 12 ? np[12] || "" : "";
|
|
4462
|
+
const lastAccessed = newLastAccessed > existingLastAccessed ? newLastAccessed : existingLastAccessed;
|
|
4463
|
+
const existingPriority = ep.length > 13 ? parseInt(ep[13]) || 0 : 0;
|
|
4464
|
+
const newPriority = np.length > 13 ? parseInt(np[13]) || 0 : 0;
|
|
4465
|
+
const priority = Math.max(existingPriority, newPriority);
|
|
4466
|
+
const quality = qualityScore(mergedTags, mergedLinks, content, date, accessed, lastAccessed);
|
|
4467
|
+
const existingScope = ep.length > 14 ? ep[14] || "" : "";
|
|
4468
|
+
const newScope = np.length > 14 ? np[14] || "" : "";
|
|
4469
|
+
const path_scope = newScope || existingScope;
|
|
4470
|
+
const existingOrigin = ep.length > 15 ? ep[15] || "" : "";
|
|
4471
|
+
const newOrigin = np.length > 15 ? np[15] || "" : "";
|
|
4472
|
+
const originRank = { human: 3, agent: 2, inferred: 1 };
|
|
4473
|
+
const origin = (originRank[newOrigin] || 0) >= (originRank[existingOrigin] || 0) ? newOrigin : existingOrigin;
|
|
4474
|
+
const existingStatus = ep.length > 16 ? ep[16] || "" : "";
|
|
4475
|
+
const newStatus = np.length > 16 ? np[16] || "" : "";
|
|
4476
|
+
const status2 = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active";
|
|
4477
|
+
const existingSupersededOn = ep.length > 17 ? ep[17] || "" : "";
|
|
4478
|
+
const existingImportance = ep.length > 18 ? ep[18] || "" : "";
|
|
4479
|
+
const newImportance = np.length > 18 ? np[18] || "" : "";
|
|
4480
|
+
const importance2 = importanceRank(newImportance) >= importanceRank(existingImportance) ? newImportance : existingImportance;
|
|
4481
|
+
const existingEvidence = ep.length > 19 ? ep[19] || "" : "";
|
|
4482
|
+
const newEvidence = np.length > 19 ? np[19] || "" : "";
|
|
4483
|
+
const evidence = existingEvidence === "conflict" || newEvidence === "conflict" ? "conflict" : newEvidence || existingEvidence;
|
|
4484
|
+
return toToonLine([id, category, key, content, file, mergedTags, date, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status2, existingSupersededOn, importance2, evidence]);
|
|
4485
|
+
}
|
|
4486
|
+
|
|
4487
|
+
// src/mcp/consolidation.ts
|
|
4488
|
+
function contentSimilarity(a, b) {
|
|
4489
|
+
const wordsA = new Set(a.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
|
|
4490
|
+
const wordsB = new Set(b.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
|
|
4491
|
+
if (wordsA.size === 0 && wordsB.size === 0) return 1;
|
|
4492
|
+
if (wordsA.size === 0 || wordsB.size === 0) return 0;
|
|
4493
|
+
let intersection = 0;
|
|
4494
|
+
for (const w of wordsA) {
|
|
4495
|
+
if (wordsB.has(w)) intersection++;
|
|
4496
|
+
}
|
|
4497
|
+
const union = wordsA.size + wordsB.size - intersection;
|
|
4498
|
+
return union > 0 ? intersection / union : 0;
|
|
4499
|
+
}
|
|
4500
|
+
var NEAR_DUP_THRESHOLD = 0.7;
|
|
4501
|
+
function consolidateEntries() {
|
|
4502
|
+
const data = readMemory();
|
|
4503
|
+
const lines = data.split("\n");
|
|
4504
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
4505
|
+
if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
|
|
4506
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
|
|
4507
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
4508
|
+
const keyOrder = [];
|
|
4509
|
+
const mergedAway = [];
|
|
4510
|
+
for (let i = 0; i < entryLines2.length; i++) {
|
|
4511
|
+
const line2 = entryLines2[i].trim();
|
|
4512
|
+
const parts = parseToonLine(line2);
|
|
4513
|
+
if (parts.length < 3) continue;
|
|
4514
|
+
const key = parts[2];
|
|
4515
|
+
const existingIdx = keyOrder.findIndex((idx) => {
|
|
4516
|
+
const ep = parseToonLine(entryLines2[idx]);
|
|
4517
|
+
return ep[2] === key;
|
|
4518
|
+
});
|
|
4519
|
+
if (existingIdx !== -1) {
|
|
4520
|
+
const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx]), line2);
|
|
4521
|
+
byKey.set(keyOrder[existingIdx], mergedLine);
|
|
4522
|
+
mergedAway.push(i);
|
|
4523
|
+
} else {
|
|
4524
|
+
byKey.set(i, line2);
|
|
4525
|
+
keyOrder.push(i);
|
|
4526
|
+
}
|
|
4527
|
+
}
|
|
4528
|
+
const contentSeen = /* @__PURE__ */ new Map();
|
|
4529
|
+
const order = [];
|
|
4530
|
+
const duplicates = [];
|
|
4531
|
+
for (const idx of keyOrder) {
|
|
4532
|
+
const line2 = byKey.get(idx);
|
|
4533
|
+
const parts = parseToonLine(line2);
|
|
4534
|
+
if (parts.length < 3) {
|
|
4535
|
+
order.push(line2);
|
|
4536
|
+
continue;
|
|
4537
|
+
}
|
|
4538
|
+
const content = parts[3] || "";
|
|
4539
|
+
const normalized = content.toLowerCase().replace(/\s+/g, " ").trim();
|
|
4540
|
+
if (contentSeen.has(normalized)) {
|
|
4541
|
+
duplicates.push(parts[2]);
|
|
4542
|
+
continue;
|
|
4543
|
+
}
|
|
4544
|
+
let merged = false;
|
|
4545
|
+
for (const [seenNorm, existing] of contentSeen) {
|
|
4546
|
+
const existingParts = parseToonLine(existing.line);
|
|
4547
|
+
if (existingParts[1] !== parts[1]) continue;
|
|
4548
|
+
const sim = contentSimilarity(content, existingParts[3] || "");
|
|
4549
|
+
if (sim >= NEAR_DUP_THRESHOLD) {
|
|
4550
|
+
const mergedLine = mergeEntries(existing.line, line2);
|
|
4551
|
+
contentSeen.set(seenNorm, { line: mergedLine, idx: existing.idx });
|
|
4552
|
+
const orderIdx = order.findIndex((l) => l === existing.line);
|
|
4553
|
+
if (orderIdx !== -1) order[orderIdx] = mergedLine;
|
|
4554
|
+
duplicates.push(parts[2]);
|
|
4555
|
+
merged = true;
|
|
4556
|
+
break;
|
|
4557
|
+
}
|
|
4558
|
+
}
|
|
4559
|
+
if (!merged) {
|
|
4560
|
+
contentSeen.set(normalized, { line: line2, idx: order.length });
|
|
4561
|
+
order.push(line2);
|
|
4562
|
+
}
|
|
4563
|
+
}
|
|
4564
|
+
const totalRemoved = mergedAway.length + duplicates.length;
|
|
4565
|
+
if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] };
|
|
4566
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`);
|
|
4567
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`));
|
|
4568
|
+
writeMemory(lines.join("\n"));
|
|
4569
|
+
return { removed: totalRemoved, kept: order.length, duplicates };
|
|
4570
|
+
}
|
|
4571
|
+
|
|
4572
|
+
// src/cli/sleep.ts
|
|
4573
|
+
function runSleep() {
|
|
4574
|
+
const config = loadConfig();
|
|
4575
|
+
if (!config.sleep?.enabled && process.env.TOON_MEMORY_SLEEP !== "1") {
|
|
4576
|
+
return { ran: false, promoted: 0, edges: 0, pruned: 0, duplicates: 0 };
|
|
4577
|
+
}
|
|
4578
|
+
const signals = readObservations().map((o) => ({
|
|
4579
|
+
type: o.tool,
|
|
4580
|
+
summary: o.summary,
|
|
4581
|
+
file: o.file,
|
|
4582
|
+
session: o.session,
|
|
4583
|
+
ts: o.ts
|
|
4584
|
+
}));
|
|
4585
|
+
const promotedResult = promoteSignals(readMemory(), signals, {});
|
|
4586
|
+
if (promotedResult.promoted.length > 0) writeMemory(promotedResult.data);
|
|
4587
|
+
const edges = rebuildEdges(readMemory(), readFeedback());
|
|
4588
|
+
const pruned = pruneExpiredEntries() + pruneObservations();
|
|
4589
|
+
const duplicates = consolidateEntries().removed;
|
|
4590
|
+
return {
|
|
4591
|
+
ran: true,
|
|
4592
|
+
promoted: promotedResult.promoted.length,
|
|
4593
|
+
edges,
|
|
4594
|
+
pruned,
|
|
4595
|
+
duplicates
|
|
4596
|
+
};
|
|
4597
|
+
}
|
|
4598
|
+
|
|
4599
|
+
// src/cli/dense.ts
|
|
4600
|
+
import { existsSync as existsSync20 } from "fs";
|
|
4601
|
+
|
|
4602
|
+
// src/lib/dense.ts
|
|
4603
|
+
import { existsSync as existsSync19, mkdirSync as mkdirSync13, readFileSync as readFileSync20, writeFileSync as writeFileSync14 } from "fs";
|
|
4604
|
+
import { dirname as dirname10 } from "path";
|
|
4605
|
+
async function loadDenseModule() {
|
|
4606
|
+
const spec = process.env.TOON_MEMORY_DENSE_MODULE || "toon-memory-dense";
|
|
4607
|
+
try {
|
|
4608
|
+
const mod = await import(spec);
|
|
4609
|
+
const embed = mod?.embed || mod?.default?.embed || mod?.default;
|
|
4610
|
+
return typeof embed === "function" ? { embed } : null;
|
|
4611
|
+
} catch {
|
|
4612
|
+
return null;
|
|
4613
|
+
}
|
|
4614
|
+
}
|
|
4615
|
+
function readVectors() {
|
|
4616
|
+
const empty = { dim: 0, vectors: /* @__PURE__ */ new Map() };
|
|
4617
|
+
if (!existsSync19(VECTORS_FILE)) return empty;
|
|
4618
|
+
try {
|
|
4619
|
+
const buf = readFileSync20(VECTORS_FILE);
|
|
4620
|
+
const newline = buf.indexOf(10);
|
|
4621
|
+
if (newline === -1) return empty;
|
|
4622
|
+
const match = buf.subarray(0, newline).toString("utf-8").match(/^TMVEC1 (\d+)$/);
|
|
4623
|
+
if (!match) return empty;
|
|
4624
|
+
const dim = Number(match[1]);
|
|
4625
|
+
if (!Number.isFinite(dim) || dim <= 0) return empty;
|
|
4626
|
+
let offset = newline + 1;
|
|
4627
|
+
const vectors = /* @__PURE__ */ new Map();
|
|
4628
|
+
while (offset + 2 <= buf.length) {
|
|
4629
|
+
const len = buf.readUInt16BE(offset);
|
|
4630
|
+
offset += 2;
|
|
4631
|
+
if (offset + len + dim * 4 > buf.length) break;
|
|
4632
|
+
const key = buf.subarray(offset, offset + len).toString("utf-8");
|
|
4633
|
+
offset += len;
|
|
4634
|
+
const vec = [];
|
|
4635
|
+
for (let i = 0; i < dim; i++) vec.push(buf.readFloatLE(offset + i * 4));
|
|
4636
|
+
offset += dim * 4;
|
|
4637
|
+
vectors.set(key, vec);
|
|
4638
|
+
}
|
|
4639
|
+
return { dim, vectors };
|
|
4640
|
+
} catch {
|
|
4641
|
+
return empty;
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
function writeVectors(vectors, dim) {
|
|
4645
|
+
const dir = dirname10(VECTORS_FILE);
|
|
4646
|
+
if (!existsSync19(dir)) mkdirSync13(dir, { recursive: true });
|
|
4647
|
+
const chunks = [Buffer.from(`TMVEC1 ${dim}
|
|
4648
|
+
`, "utf-8")];
|
|
4649
|
+
let written = 0;
|
|
4650
|
+
for (const [key, vec] of vectors) {
|
|
4651
|
+
if (vec.length !== dim) continue;
|
|
4652
|
+
const keyBuf = Buffer.from(key, "utf-8");
|
|
4653
|
+
const lenBuf = Buffer.alloc(2);
|
|
4654
|
+
lenBuf.writeUInt16BE(keyBuf.length);
|
|
4655
|
+
const vecBuf = Buffer.alloc(dim * 4);
|
|
4656
|
+
for (let i = 0; i < dim; i++) vecBuf.writeFloatLE(vec[i], i * 4);
|
|
4657
|
+
chunks.push(lenBuf, keyBuf, vecBuf);
|
|
4658
|
+
written++;
|
|
4659
|
+
}
|
|
4660
|
+
const out = Buffer.concat(chunks);
|
|
4661
|
+
withLockSync(VECTORS_FILE, () => writeFileSync14(VECTORS_FILE, out));
|
|
4662
|
+
return written;
|
|
4663
|
+
}
|
|
4664
|
+
async function buildVectors(data, module, model) {
|
|
4665
|
+
const entries = parseEntries(data).filter((e) => e.status !== "obsolete" && e.status !== "draft");
|
|
4666
|
+
if (entries.length === 0) return 0;
|
|
4667
|
+
const embedded = await module.embed(entries.map((e) => `${e.key} ${e.content}`), model);
|
|
4668
|
+
const dim = embedded[0]?.length || loadConfig().dense?.dim || 0;
|
|
4669
|
+
if (!dim) return 0;
|
|
4670
|
+
const vectors = /* @__PURE__ */ new Map();
|
|
4671
|
+
entries.forEach((e, i) => {
|
|
4672
|
+
if (embedded[i]?.length === dim) vectors.set(e.key, embedded[i]);
|
|
4673
|
+
});
|
|
4674
|
+
return writeVectors(vectors, dim);
|
|
4675
|
+
}
|
|
4676
|
+
|
|
4677
|
+
// src/cli/dense.ts
|
|
4678
|
+
var DEFAULT_DENSE_MODEL = "multilingual-e5-small";
|
|
4679
|
+
async function runDense(args2) {
|
|
4680
|
+
const action = args2[0] || "status";
|
|
4681
|
+
const config = loadConfig();
|
|
4682
|
+
const dense = config.dense || {};
|
|
4683
|
+
if (action === "enable") {
|
|
4684
|
+
saveConfig({ ...config, dense: { ...dense, enabled: true, model: args2[1] || dense.model || DEFAULT_DENSE_MODEL } });
|
|
4685
|
+
console.log(`Dense retrieval enabled (model: ${args2[1] || dense.model || DEFAULT_DENSE_MODEL}). Run 'toon-memory dense build' once.`);
|
|
4686
|
+
return;
|
|
4687
|
+
}
|
|
4688
|
+
if (action === "disable") {
|
|
4689
|
+
saveConfig({ ...config, dense: { ...dense, enabled: false } });
|
|
4690
|
+
console.log("Dense retrieval disabled. BM25 recall remains active.");
|
|
4691
|
+
return;
|
|
4692
|
+
}
|
|
4693
|
+
if (action === "install") {
|
|
4694
|
+
console.log("Install the optional embedder: npm install toon-memory-dense");
|
|
4695
|
+
console.log("Then point to it with TOON_MEMORY_DENSE_MODULE=/absolute/path/to/module.js if it is not on the default resolution path.");
|
|
4696
|
+
return;
|
|
4697
|
+
}
|
|
4698
|
+
if (action === "build") {
|
|
4699
|
+
const module = await loadDenseModule();
|
|
4700
|
+
if (!module) {
|
|
4701
|
+
console.error("Dense embedder not found. Run 'toon-memory dense install' first.");
|
|
4702
|
+
process.exitCode = 1;
|
|
4703
|
+
return;
|
|
4704
|
+
}
|
|
4705
|
+
const count = await buildVectors(readMemory(), module, dense.model || DEFAULT_DENSE_MODEL);
|
|
4706
|
+
console.log(`Built vectors for ${count} entries in ${VECTORS_FILE}.`);
|
|
4707
|
+
return;
|
|
4708
|
+
}
|
|
4709
|
+
const stored = readVectors();
|
|
4710
|
+
console.log([
|
|
4711
|
+
`dense: ${dense.enabled ? "enabled" : "disabled"}`,
|
|
4712
|
+
`model: ${dense.model || DEFAULT_DENSE_MODEL}`,
|
|
4713
|
+
`module: ${process.env.TOON_MEMORY_DENSE_MODULE || "toon-memory-dense"}`,
|
|
4714
|
+
`vectors: ${existsSync20(VECTORS_FILE) ? `${stored.vectors.size} entries, dim ${stored.dim}` : "not built"}`
|
|
4715
|
+
].join("\n"));
|
|
4716
|
+
}
|
|
4717
|
+
|
|
3083
4718
|
// src/cli/setup.ts
|
|
3084
4719
|
var args = process.argv.slice(2);
|
|
4720
|
+
if (args[0] === "brief") {
|
|
4721
|
+
printBrief(args.slice(1).join(" ") || process.env.TOON_MEMORY_TASK || "");
|
|
4722
|
+
process.exit(0);
|
|
4723
|
+
}
|
|
4724
|
+
if (args[0] === "doctor") {
|
|
4725
|
+
printDoctor();
|
|
4726
|
+
process.exit(0);
|
|
4727
|
+
}
|
|
4728
|
+
if (args[0] === "signal") {
|
|
4729
|
+
recordSignal(args.slice(1));
|
|
4730
|
+
process.exit(0);
|
|
4731
|
+
}
|
|
4732
|
+
if (args[0] === "promote") {
|
|
4733
|
+
runPromotion(args.slice(1));
|
|
4734
|
+
process.exit(0);
|
|
4735
|
+
}
|
|
4736
|
+
if (args[0] === "sleep") {
|
|
4737
|
+
const result = runSleep();
|
|
4738
|
+
console.log(result.ran ? `Sleep complete: ${result.promoted} promoted, ${result.edges} edges, ${result.pruned} pruned, ${result.duplicates} duplicates.` : "Sleep is disabled (config.sleep.enabled or TOON_MEMORY_SLEEP=1).");
|
|
4739
|
+
process.exit(0);
|
|
4740
|
+
}
|
|
4741
|
+
if (args[0] === "dense") {
|
|
4742
|
+
await runDense(args.slice(1));
|
|
4743
|
+
process.exit(0);
|
|
4744
|
+
}
|
|
3085
4745
|
if (args[0] === "capture") {
|
|
3086
4746
|
captureToggle(args[1] === "on");
|
|
3087
4747
|
process.exit(0);
|
|
@@ -3097,17 +4757,21 @@ if (args[0] === "init") {
|
|
|
3097
4757
|
}
|
|
3098
4758
|
const rest = args.slice(1);
|
|
3099
4759
|
const agentNames = [];
|
|
4760
|
+
const scopes = /* @__PURE__ */ new Set(["local", "global"]);
|
|
4761
|
+
const addAgents = (value) => value.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean).forEach((a) => agentNames.push(a));
|
|
3100
4762
|
let scope;
|
|
3101
4763
|
let i = 0;
|
|
3102
4764
|
while (i < rest.length) {
|
|
3103
4765
|
if (rest[i] === "--agent" && rest[i + 1]) {
|
|
3104
|
-
|
|
4766
|
+
addAgents(rest[i + 1]);
|
|
3105
4767
|
i += 2;
|
|
3106
4768
|
} else if (rest[i] === "--scope" && rest[i + 1]) {
|
|
3107
4769
|
scope = rest[i + 1];
|
|
3108
4770
|
i += 2;
|
|
3109
4771
|
} else if (rest[i] !== "--agent" && rest[i] !== "--scope") {
|
|
3110
|
-
|
|
4772
|
+
const token = rest[i].toLowerCase();
|
|
4773
|
+
if (scopes.has(token) && !scope) scope = token;
|
|
4774
|
+
else addAgents(token);
|
|
3111
4775
|
i++;
|
|
3112
4776
|
} else {
|
|
3113
4777
|
i++;
|
|
@@ -3182,9 +4846,15 @@ Press 'r' in the terminal while serving to reload the graph.`);
|
|
|
3182
4846
|
}
|
|
3183
4847
|
function printUsage() {
|
|
3184
4848
|
console.log(`Usage: toon-memory <command> [options]
|
|
3185
|
-
Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, mcp
|
|
4849
|
+
Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, brief, doctor, signal, promote, sleep, dense, mcp
|
|
4850
|
+
brief [task] \u2014 Print the compact handoff brief injected at session start
|
|
4851
|
+
doctor \u2014 Check memory path, signals and injection channel
|
|
4852
|
+
signal --type <t> --summary <s> [--file <f>] \u2014 Append one deterministic signal
|
|
4853
|
+
promote [--threshold <0-1>] \u2014 Promote high-confidence signals into memory
|
|
4854
|
+
sleep \u2014 Deterministic consolidation (opt-in: config.sleep.enabled)
|
|
4855
|
+
dense <status|enable|disable|build|install> \u2014 Optional local embeddings with BM25 fallback
|
|
3186
4856
|
viewer [--export] [--port <n>] \u2014 Start an HTTP server with the graph viewer (press 'r' to reload). --export saves static HTML.
|
|
3187
|
-
Init: toon-memory init [
|
|
4857
|
+
Init: toon-memory init [local|global] [agent...] | --agent <name>[,<name>...] [--scope local|global]
|
|
3188
4858
|
Without --agent: interactive agent and scope selector.
|
|
3189
4859
|
With --agent: non-interactive installation (default: scope local).
|
|
3190
4860
|
Options: -v/--version, -h/--help
|