toon-memory 2.4.5 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/setup.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync, unlinkSync, readdirSync, statSync, chmodSync, rmSync } from "fs";
3
3
  import { basename, dirname, join as join2 } from "path";
4
4
  import { fileURLToPath } from "url";
5
- import { createInterface, emitKeypressEvents } from "readline";
5
+ import { checkbox, select, confirm } from "@inquirer/prompts";
6
6
  import { gzipSync } from "zlib";
7
7
 
8
8
  // src/lib/vocab.ts
@@ -624,7 +624,17 @@ function updateMemoryConfig(patch) {
624
624
  Object.assign(cfg, patch);
625
625
  writeFileSync(CAPTURE_CONFIG, JSON.stringify(cfg, null, 2));
626
626
  }
627
- function init(scope = "local") {
627
+ async function promptAgentSelection(agents) {
628
+ return checkbox({
629
+ message: "\xBFQu\xE9 agentes quieres configurar?",
630
+ choices: agents.map((a) => ({
631
+ name: `${a.name} (${a.format === "none" ? "instrucciones" : a.global ? "local/global" : "solo local"})`,
632
+ value: a,
633
+ checked: true
634
+ }))
635
+ });
636
+ }
637
+ async function init(scope, agentFilter) {
628
638
  console.log("\n\u{1F9E0} toon-memory init\n");
629
639
  installMemoryDir();
630
640
  const deps = extractProjectDeps(projectRoot);
@@ -634,8 +644,42 @@ function init(scope = "local") {
634
644
  console.log(` Detected ${depCount} dependencies \u2192 auto-tag vocabulary written to config.json`);
635
645
  }
636
646
  const agents = detectAgents();
637
- for (const agent of agents) {
638
- installForAgent(agent, scope);
647
+ let selected;
648
+ let finalScope = scope || "local";
649
+ if (agentFilter && agentFilter.length > 0) {
650
+ selected = agents.filter((a) => agentFilter.includes(a.name.toLowerCase()));
651
+ if (selected.length === 0) {
652
+ console.log(`Agentes no encontrados: ${agentFilter.join(", ")}`);
653
+ console.log(`Disponibles: ${agents.map((a) => a.name).join(", ")}`);
654
+ process.exit(1);
655
+ }
656
+ } else if (process.stdin.isTTY) {
657
+ selected = await promptAgentSelection(agents);
658
+ if (selected.length === 0) {
659
+ console.log("\nNo se seleccionaron agentes. Nada instalado.\n");
660
+ return;
661
+ }
662
+ finalScope = await select({
663
+ message: "Alcance:",
664
+ choices: [
665
+ { name: "Local (proyecto)", value: "local" },
666
+ { name: "Global (~home)", value: "global" }
667
+ ],
668
+ default: finalScope
669
+ });
670
+ const ok = await confirm({ message: "\xBFProceder?", default: true });
671
+ if (!ok) {
672
+ console.log("\nInstalaci\xF3n cancelada.\n");
673
+ return;
674
+ }
675
+ } else {
676
+ selected = agents;
677
+ }
678
+ console.log(`
679
+ Instalando (${finalScope}) \u2014 ${selected.map((a) => a.name).join(", ")}...
680
+ `);
681
+ for (const agent of selected) {
682
+ installForAgent(agent, finalScope);
639
683
  console.log("");
640
684
  }
641
685
  ensureGitignore();
@@ -1147,7 +1191,25 @@ if (args[0] === "uninstall") {
1147
1191
  process.exit(0);
1148
1192
  }
1149
1193
  if (args[0] === "init") {
1150
- init(args[1] || "local");
1194
+ const rest = args.slice(1);
1195
+ const agentNames = [];
1196
+ let scope;
1197
+ let i = 0;
1198
+ while (i < rest.length) {
1199
+ if (rest[i] === "--agent" && rest[i + 1]) {
1200
+ agentNames.push(rest[i + 1].toLowerCase());
1201
+ i += 2;
1202
+ } else if (rest[i] === "--scope" && rest[i + 1]) {
1203
+ scope = rest[i + 1];
1204
+ i += 2;
1205
+ } else if (rest[i] !== "--agent" && rest[i] !== "--scope") {
1206
+ scope = rest[i];
1207
+ i++;
1208
+ } else {
1209
+ i++;
1210
+ }
1211
+ }
1212
+ await init(scope, agentNames.length > 0 ? agentNames : void 0);
1151
1213
  process.exit(0);
1152
1214
  }
1153
1215
  if (args[0] === "status") {
@@ -1187,66 +1249,40 @@ console.log(`Comando desconocido: '${args[0]}'
1187
1249
  printUsage();
1188
1250
  process.exit(1);
1189
1251
  function printUsage() {
1190
- console.log(`Uso: toon-memory <comando> [alcance]
1252
+ console.log(`Uso: toon-memory <comando> [opciones]
1191
1253
  Comandos: init, status, stats, export, import, watch, uninstall, capture, upgrade, mcp
1254
+ Init: toon-memory init [--agent <nombre> --agent <nombre>...] [--scope local|global]
1255
+ Sin --agent: selector interactivo de agentes y scope.
1256
+ Con --agent: instalaci\xF3n no interactiva (default: scope local).
1192
1257
  Opciones: -v/--version, -h/--help
1193
1258
  Sin argumentos inicia el instalador interactivo.`);
1194
1259
  }
1195
- function ask(rl, prompt) {
1196
- return new Promise((resolve) => rl.question(prompt, resolve));
1197
- }
1198
1260
  async function interactiveInstall() {
1199
1261
  if (!process.stdin.isTTY) {
1200
1262
  console.log("\n\u{1F9E0} toon-memory \u2014 la instalaci\xF3n interactiva requiere una terminal.");
1201
- console.log("Ejecuta 'toon-memory init [local|global]' para instalaci\xF3n no interactiva.\n");
1263
+ console.log("Ejecuta 'toon-memory init [--agent <nombre>]' para instalaci\xF3n no interactiva.\n");
1202
1264
  return;
1203
1265
  }
1204
1266
  const agents = detectAgents();
1205
- const selected = await runAgentChecklist(agents);
1206
- if (selected === null) {
1207
- console.log("\nInstalaci\xF3n cancelada.\n");
1208
- return;
1209
- }
1267
+ const selected = await promptAgentSelection(agents);
1210
1268
  if (selected.length === 0) {
1211
1269
  console.log("\nNo se seleccionaron agentes. Nada instalado.\n");
1212
1270
  return;
1213
1271
  }
1214
- console.log(`
1215
- Seleccionados: ${selected.map((a) => a.name).join(", ")}
1216
- `);
1217
- const rl = createInterface({ input: process.stdin, output: process.stdout });
1218
- let scope = "local";
1219
- while (true) {
1220
- const scopeAnswer = (await ask(rl, "Alcance \u2014 (1) Local (proyecto) o (2) Global (~home)? [1/2]: ")).trim();
1221
- if (scopeAnswer === "" || scopeAnswer === "1") {
1222
- scope = "local";
1223
- break;
1224
- }
1225
- if (scopeAnswer === "2") {
1226
- scope = "global";
1227
- break;
1228
- }
1229
- console.log("Escribe 1 (local) o 2 (global).\n");
1230
- }
1231
- console.log("\nSe instalar\xE1:");
1232
- for (const a of selected) {
1233
- const resolved = scope === "global" && a.global ? "global" : "local";
1234
- const parts = [];
1235
- if (a.format !== "none") parts.push("MCP");
1236
- if (a.needsPlugin) parts.push("plugin");
1237
- else if (a.needsHooks) parts.push("hooks");
1238
- if (a.needsInstructions) parts.push("instrucciones");
1239
- const target = resolved === "global" && a.global ? a.global : a.local || "(instrucciones)";
1240
- console.log(` \u2022 ${a.name} [${resolved}] \u2192 ${target}${parts.length ? ` (${parts.join(", ")})` : ""}`);
1241
- }
1242
- const confirm = (await ask(rl, "\n\xBFProceder? [Y/n]: ")).trim().toLowerCase();
1243
- if (confirm === "n" || confirm === "no") {
1272
+ const scope = await select({
1273
+ message: "Alcance:",
1274
+ choices: [
1275
+ { name: "Local (proyecto)", value: "local" },
1276
+ { name: "Global (~home)", value: "global" }
1277
+ ]
1278
+ });
1279
+ const ok = await confirm({ message: "\xBFProceder?", default: true });
1280
+ if (!ok) {
1244
1281
  console.log("\nInstalaci\xF3n cancelada.\n");
1245
- rl.close();
1246
1282
  return;
1247
1283
  }
1248
1284
  console.log(`
1249
- Instalando (${scope})...
1285
+ Instalando (${scope}) \u2014 ${selected.map((a) => a.name).join(", ")}...
1250
1286
  `);
1251
1287
  installMemoryDir();
1252
1288
  const deps = extractProjectDeps(projectRoot);
@@ -1261,82 +1297,4 @@ Instalando (${scope})...
1261
1297
  ensureGitignore();
1262
1298
  console.log("Done! Restart your agent to use memory tools.");
1263
1299
  console.log("Run 'npx toon-memory uninstall' to remove.\n");
1264
- rl.close();
1265
- }
1266
- async function runAgentChecklist(agents) {
1267
- const n = agents.length;
1268
- let cursor = 0;
1269
- const selected = /* @__PURE__ */ new Set();
1270
- let prevLines = 0;
1271
- const render = () => {
1272
- let out = "";
1273
- if (prevLines > 0) out += `\x1B[${prevLines}A\x1B[J`;
1274
- const lines = [];
1275
- lines.push("\n\u{1F9E0} toon-memory installer");
1276
- lines.push("");
1277
- lines.push("Agentes detectados:");
1278
- agents.forEach((a, i) => {
1279
- const isCursor = i === cursor;
1280
- const isSel = selected.has(i);
1281
- const box = isSel ? "[x]" : "[ ]";
1282
- const cur = isCursor ? ">" : " ";
1283
- const hasConfig = a.format !== "none" && (a.local && existsSync2(a.local) || a.global && existsSync2(a.global));
1284
- const indicator = hasConfig ? "\u2713" : "\xB7";
1285
- const scopeNote = a.format === "none" ? "(instrucciones)" : a.global ? "(local/global)" : "(solo local)";
1286
- lines.push(` ${cur} ${box} ${indicator} ${i + 1}. ${a.name} ${scopeNote}`);
1287
- });
1288
- lines.push("");
1289
- lines.push(" \u2191/\u2193 mover \xB7 espacio marcar \xB7 'a' todos \xB7 Enter confirmar \xB7 'q' salir");
1290
- process.stdout.write(out + lines.join("\n") + "\n");
1291
- prevLines = lines.length;
1292
- };
1293
- return new Promise((resolve) => {
1294
- emitKeypressEvents(process.stdin);
1295
- process.stdin.setRawMode(true);
1296
- process.stdin.resume();
1297
- const finish = (result) => {
1298
- process.stdin.setRawMode(false);
1299
- process.stdin.removeListener("keypress", onKey);
1300
- process.stdout.write("\n");
1301
- resolve(result);
1302
- };
1303
- const onKey = (_str, key) => {
1304
- if (!key) return;
1305
- if (key.ctrl && key.name === "c") {
1306
- finish(null);
1307
- return;
1308
- }
1309
- switch (key.name) {
1310
- case "up":
1311
- case "k":
1312
- cursor = (cursor - 1 + n) % n;
1313
- break;
1314
- case "down":
1315
- case "j":
1316
- cursor = (cursor + 1) % n;
1317
- break;
1318
- case "space":
1319
- if (selected.has(cursor)) selected.delete(cursor);
1320
- else selected.add(cursor);
1321
- break;
1322
- case "a":
1323
- if (selected.size === n) selected.clear();
1324
- else for (let i = 0; i < n; i++) selected.add(i);
1325
- break;
1326
- case "return":
1327
- finish(agents.filter((_, i) => selected.has(i)));
1328
- return;
1329
- case "q":
1330
- case "c":
1331
- finish(null);
1332
- return;
1333
- default:
1334
- render();
1335
- return;
1336
- }
1337
- render();
1338
- };
1339
- process.stdin.on("keypress", onKey);
1340
- render();
1341
- });
1342
1300
  }
package/mcp/server.js CHANGED
@@ -16506,8 +16506,8 @@ var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
16506
16506
  }
16507
16507
  return count;
16508
16508
  }
16509
- function getFullPath(resolver, id = "", normalize3) {
16510
- if (normalize3 !== false) id = normalizeId(id);
16509
+ function getFullPath(resolver, id = "", normalize4) {
16510
+ if (normalize4 !== false) id = normalizeId(id);
16511
16511
  return _getFullPath(resolver, resolver.parse(id));
16512
16512
  }
16513
16513
  exports.getFullPath = getFullPath;
@@ -17602,7 +17602,7 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17602
17602
  var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17603
17603
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
17604
17604
  const { SCHEMES, getSchemeHandler } = require_schemes();
17605
- function normalize3(uri, options) {
17605
+ function normalize4(uri, options) {
17606
17606
  if (typeof uri === "string") uri = serialize(parse3(uri, options), options);
17607
17607
  else if (typeof uri === "object") uri = parse3(serialize(uri, options), options);
17608
17608
  return uri;
@@ -17780,7 +17780,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17780
17780
  }
17781
17781
  const fastUri = {
17782
17782
  SCHEMES,
17783
- normalize: normalize3,
17783
+ normalize: normalize4,
17784
17784
  resolve,
17785
17785
  resolveComponent,
17786
17786
  equal,
@@ -28050,6 +28050,148 @@ function renderCompact(entries, opts = {}) {
28050
28050
  }).join("\n\n");
28051
28051
  }
28052
28052
 
28053
+ // src/lib/quality.ts
28054
+ var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28055
+ var tokenize2 = (s) => normalize2(s).split(" ").filter(Boolean);
28056
+ var isExpiredLocal2 = (ttl) => {
28057
+ if (!ttl) return false;
28058
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28059
+ return ttl <= today;
28060
+ };
28061
+ var importance2 = (e) => {
28062
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28063
+ const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
28064
+ const recency = Math.max(0, 30 - days) / 30;
28065
+ const freq = Math.min(1, e.accessed / 5);
28066
+ return recency * 0.6 + freq * 0.4;
28067
+ };
28068
+ function qualityScore(tags, links, content, date5) {
28069
+ let score = 0;
28070
+ if (tags) {
28071
+ const count = tags.split(";").filter(Boolean).length;
28072
+ score += Math.min(0.3, count * 0.1);
28073
+ }
28074
+ if (links) {
28075
+ const count = links.split(/[\s;]+/).filter(Boolean).length;
28076
+ score += Math.min(0.2, count * 0.1);
28077
+ }
28078
+ const len = content.length;
28079
+ if (len > 20) score += 0.1;
28080
+ if (len > 60) score += 0.1;
28081
+ if (len > 150) score += 0.1;
28082
+ if (date5) {
28083
+ const days = (Date.now() - (/* @__PURE__ */ new Date(`${date5}T00:00:00`)).getTime()) / 864e5;
28084
+ if (days < 7) score += 0.1;
28085
+ else if (days < 30) score += 0.05;
28086
+ }
28087
+ const words = content.toLowerCase().split(/\s+/).filter(Boolean);
28088
+ const unique = new Set(words);
28089
+ const specificity = words.length > 0 ? unique.size / words.length : 0;
28090
+ score += specificity * 0.1;
28091
+ return Math.min(1, score);
28092
+ }
28093
+ function mergeEntries(existingLine, newLine) {
28094
+ const ep = existingLine.trim().split("|");
28095
+ const np = newLine.trim().split("|");
28096
+ if (ep.length < 7 || np.length < 7) return newLine;
28097
+ const id = ep[0];
28098
+ const category = np[1] || ep[1];
28099
+ const key = ep[2];
28100
+ const content = np[3] || ep[3];
28101
+ const file2 = np[4] || ep[4];
28102
+ const existingTags = (ep[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
28103
+ const newTags = (np[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
28104
+ const mergedTags = [.../* @__PURE__ */ new Set([...existingTags, ...newTags])].join(";");
28105
+ const existingDate = ep[6] || "";
28106
+ const newDate = np[6] || "";
28107
+ const date5 = newDate > existingDate ? newDate : existingDate;
28108
+ const existingTtl = ep[7] || "";
28109
+ const newTtl = np[7] || "";
28110
+ const ttl = newTtl || existingTtl;
28111
+ const existingConf = ep.length > 11 ? parseFloat(ep[11]) || 0 : 0;
28112
+ const newConf = np.length > 11 ? parseFloat(np[11]) || 0 : 0;
28113
+ const confidence = Math.max(existingConf, newConf);
28114
+ const existingLinks = (ep[9] || "").split(/[\s;]+/).filter(Boolean);
28115
+ const newLinks = (np[9] || "").split(/[\s;]+/).filter(Boolean);
28116
+ const mergedLinks = [.../* @__PURE__ */ new Set([...existingLinks, ...newLinks])].join(" ");
28117
+ const quality = qualityScore(mergedTags, mergedLinks, content, date5);
28118
+ return `${id}|${category}|${key}|${content}|${file2}|${mergedTags}|${date5}|${ttl}|0|${mergedLinks}|${quality.toFixed(2)}|${confidence}`;
28119
+ }
28120
+ function generateSmartRecall(data, intent, opts = {}) {
28121
+ const entries = parseEntries(data);
28122
+ if (entries.length === 0) return "Memoria vac\xEDa.";
28123
+ const { adjacency } = buildGraph(entries);
28124
+ const bm25 = bm25Scores(entries, intent);
28125
+ const cent = centrality(adjacency);
28126
+ const limit = opts.limit ?? 8;
28127
+ const category = opts.category || "";
28128
+ const qTokens = tokenize2(intent);
28129
+ const scored = entries.filter((e) => {
28130
+ if (category && e.category !== category) return false;
28131
+ if (e.ttl && isExpiredLocal2(e.ttl)) return false;
28132
+ return true;
28133
+ }).map((e) => {
28134
+ const text = normalize2(
28135
+ `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
28136
+ );
28137
+ const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t));
28138
+ const bm25Score = bm25.get(e.key) || 0;
28139
+ const centScore = cent.get(e.key) || 0;
28140
+ const impScore = importance2(e);
28141
+ const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0);
28142
+ return { entry: e, score: combined, matchesQuery };
28143
+ }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b) => b.score - a.score).slice(0, limit);
28144
+ if (scored.length === 0) {
28145
+ const top = entries.filter((e) => !category || e.category === category).sort((a, b) => importance2(b) - importance2(a)).slice(0, limit);
28146
+ if (top.length === 0) return "No hay entradas en memoria.";
28147
+ return renderCompact(top);
28148
+ }
28149
+ if (opts.bumpAccess) opts.bumpAccess(scored.map((x) => x.entry.id));
28150
+ return renderCompact(scored.map((x) => x.entry));
28151
+ }
28152
+ function generateSystemPrimer(data) {
28153
+ const entries = parseEntries(data);
28154
+ if (entries.length === 0) return "Memoria vac\xEDa. No hay entradas guardadas.";
28155
+ const byCategory = {};
28156
+ for (const e of entries) {
28157
+ if (!byCategory[e.category]) byCategory[e.category] = [];
28158
+ byCategory[e.category].push(e);
28159
+ }
28160
+ const lines = [
28161
+ "=== System Primer ===",
28162
+ `Entradas: ${entries.length}`,
28163
+ ""
28164
+ ];
28165
+ const top = [...entries].sort((a, b) => importance2(b) - importance2(a)).slice(0, 5);
28166
+ lines.push("Top memorias:");
28167
+ for (const e of top) {
28168
+ const quality = qualityScore(
28169
+ e.tags.join(";"),
28170
+ e.links.join(" "),
28171
+ e.content,
28172
+ e.date
28173
+ );
28174
+ const conf = quality >= 0.5 ? "alta" : quality >= 0.3 ? "media" : "baja";
28175
+ lines.push(
28176
+ ` [${e.category}] ${e.key} \u2014 ${e.content.slice(0, 80)} (calidad: ${conf})`
28177
+ );
28178
+ }
28179
+ lines.push("");
28180
+ lines.push("Categor\xEDas:");
28181
+ for (const [cat, items] of Object.entries(byCategory)) {
28182
+ lines.push(` ${cat}: ${items.length}`);
28183
+ }
28184
+ lines.push("");
28185
+ const patterns = entries.filter((e) => e.category === "pattern");
28186
+ if (patterns.length > 0) {
28187
+ lines.push("Patrones establecidos:");
28188
+ for (const p of patterns.slice(0, 5)) {
28189
+ lines.push(` \u2022 ${p.key}: ${p.content.slice(0, 100)}`);
28190
+ }
28191
+ }
28192
+ return lines.join("\n");
28193
+ }
28194
+
28053
28195
  // src/mcp/server.ts
28054
28196
  var __dirname = dirname(fileURLToPath(import.meta.url));
28055
28197
  var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
@@ -28094,7 +28236,7 @@ function ensureMemoryDir() {
28094
28236
  function ensureMemoryFile() {
28095
28237
  ensureMemoryDir();
28096
28238
  if (!existsSync3(MEMORY_FILE)) {
28097
- writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n");
28239
+ writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n");
28098
28240
  }
28099
28241
  }
28100
28242
  function encrypt(text, key) {
@@ -28227,18 +28369,18 @@ function parseRelativeDate(since) {
28227
28369
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28228
28370
  return today;
28229
28371
  }
28230
- var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28372
+ var normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28231
28373
  function findRelatedEntries(text, excludeKey = "", limit = 3) {
28232
28374
  const data = readMemory();
28233
28375
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28234
- const queryTokens = normalize2(text).split(" ").filter(Boolean);
28376
+ const queryTokens = normalize3(text).split(" ").filter(Boolean);
28235
28377
  const scored = lines.map((line) => {
28236
28378
  const trimmed = line.trim();
28237
28379
  const parts = trimmed.split("|");
28238
28380
  if (parts.length < 7) return null;
28239
28381
  const [id, cat, key, content, file2, tags, date5] = parts;
28240
28382
  if (key === excludeKey) return null;
28241
- const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28383
+ const searchStr = normalize3(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28242
28384
  let score = 0;
28243
28385
  for (const token of queryTokens) {
28244
28386
  if (searchStr.includes(token)) score++;
@@ -28384,28 +28526,51 @@ function consolidateEntries() {
28384
28526
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28385
28527
  if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
28386
28528
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28387
- const seen = /* @__PURE__ */ new Map();
28529
+ const byKey = /* @__PURE__ */ new Map();
28530
+ const keyOrder = [];
28531
+ const mergedAway = [];
28532
+ for (let i = 0; i < entryLines2.length; i++) {
28533
+ const line = entryLines2[i].trim();
28534
+ const parts = line.split("|");
28535
+ if (parts.length < 3) continue;
28536
+ const key = parts[2];
28537
+ const existingIdx = keyOrder.findIndex((idx) => {
28538
+ const ep = entryLines2[idx].trim().split("|");
28539
+ return ep[2] === key;
28540
+ });
28541
+ if (existingIdx !== -1) {
28542
+ const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx]), line);
28543
+ byKey.set(keyOrder[existingIdx], mergedLine);
28544
+ mergedAway.push(i);
28545
+ } else {
28546
+ byKey.set(i, line);
28547
+ keyOrder.push(i);
28548
+ }
28549
+ }
28550
+ const contentSeen = /* @__PURE__ */ new Map();
28388
28551
  const order = [];
28389
28552
  const duplicates = [];
28390
- for (const line of entryLines2) {
28391
- const parts = line.trim().split("|");
28553
+ for (const idx of keyOrder) {
28554
+ const line = byKey.get(idx);
28555
+ const parts = line.split("|");
28392
28556
  if (parts.length < 3) {
28393
- order.push(line.trim());
28557
+ order.push(line);
28394
28558
  continue;
28395
28559
  }
28396
28560
  const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim();
28397
- if (seen.has(content)) {
28561
+ if (contentSeen.has(content)) {
28398
28562
  duplicates.push(parts[2]);
28399
28563
  continue;
28400
28564
  }
28401
- seen.set(content, line.trim());
28402
- order.push(line.trim());
28565
+ contentSeen.set(content, line);
28566
+ order.push(line);
28403
28567
  }
28404
- if (duplicates.length === 0) return { removed: 0, kept: order.length, duplicates: [] };
28568
+ const totalRemoved = mergedAway.length + duplicates.length;
28569
+ if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] };
28405
28570
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`);
28406
28571
  lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`));
28407
28572
  writeMemory(lines.join("\n"));
28408
- return { removed: duplicates.length, kept: order.length, duplicates };
28573
+ return { removed: totalRemoved, kept: order.length, duplicates };
28409
28574
  }
28410
28575
  var server = new McpServer(
28411
28576
  { name: "toon-memory", version: "2.4.3" },
@@ -28452,13 +28617,8 @@ server.registerResource(
28452
28617
  { title: "Memory Summaries", mimeType: "text/plain" },
28453
28618
  async (uri) => {
28454
28619
  const data = readMemory();
28455
- const lines = data.split("\n");
28456
- const summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"));
28457
- if (summaryIdx === -1) {
28458
- return { contents: [{ uri: uri.href, text: "No hay res\xFAmenes guardados" }] };
28459
- }
28460
- const summaryText = lines.slice(summaryIdx + 1).filter((l) => l.includes(":")).join("\n");
28461
- return { contents: [{ uri: uri.href, text: summaryText || "No hay res\xFAmenes guardados" }] };
28620
+ const primer = generateSystemPrimer(data);
28621
+ return { contents: [{ uri: uri.href, text: primer }] };
28462
28622
  }
28463
28623
  );
28464
28624
  server.registerTool(
@@ -28504,13 +28664,19 @@ server.registerTool(
28504
28664
  const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab);
28505
28665
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
28506
28666
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
28507
- const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
28667
+ let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
28508
28668
  let action = "Guardado";
28669
+ let mergeInfo = "";
28509
28670
  const tagsInferred = !tags && resolvedTags ? true : false;
28510
28671
  if (existingIdx !== -1) {
28672
+ newEntry = mergeEntries(lines[existingIdx].trim(), newEntry);
28511
28673
  lines[existingIdx] = ` ${newEntry}`;
28512
28674
  action = "Actualizado";
28675
+ mergeInfo = "\n\u{1F517} Merge: tags combinados, fecha y links actualizados";
28513
28676
  } else {
28677
+ const quality = qualityScore(resolvedTags, resolvedLinks, content, date5);
28678
+ const confidence = 1;
28679
+ newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}|${quality.toFixed(2)}|${confidence}`;
28514
28680
  const match = lines[headerIdx].match(/\[(\d+)\|/);
28515
28681
  const count = match ? parseInt(match[1]) : 0;
28516
28682
  lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
@@ -28542,7 +28708,7 @@ ${items}`;
28542
28708
  }
28543
28709
  return {
28544
28710
  content: [{ type: "text", text: `\u{1F9E0} ${action}: ${category}/${key} (${entryId})
28545
- ${content}${ttlMsg}${inferredMsg}${archiveMsg}${relatedMsg}` }]
28711
+ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
28546
28712
  };
28547
28713
  }
28548
28714
  );
@@ -28564,21 +28730,23 @@ server.registerTool(
28564
28730
  async ({ query, category, from_date, to_date, mode, hops, compact }) => {
28565
28731
  const data = readMemory();
28566
28732
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28567
- const normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28568
- const queryTokens = normalize3(query).split(" ").filter(Boolean);
28733
+ const normalize4 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28734
+ const queryTokens = normalize4(query).split(" ").filter(Boolean);
28569
28735
  const results = lines.map((line) => {
28570
28736
  const trimmed = line.trim();
28571
28737
  const parts = trimmed.split("|");
28572
28738
  if (parts.length < 7) return null;
28573
28739
  const [id, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
28740
+ const qualityRaw = parts[10] || "";
28741
+ const confidenceRaw = parts[11] || "";
28574
28742
  if (category && cat !== category) return null;
28575
28743
  if (from_date && date5 < from_date) return null;
28576
28744
  if (to_date && date5 > to_date) return null;
28577
28745
  if (ttl && isExpired(ttl)) return null;
28578
- const searchStr = normalize3(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28746
+ const searchStr = normalize4(`${id} ${cat} ${key} ${content} ${file2} ${tags} ${qualityRaw} ${confidenceRaw}`);
28579
28747
  if (!queryTokens.every((token) => searchStr.includes(token))) return null;
28580
28748
  const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
28581
- return { id, cat, key, content, file: file2, tags, date: date5, accessed };
28749
+ return { id, cat, key, content, file: file2, tags, date: date5, accessed, qualityRaw, confidenceRaw };
28582
28750
  }).filter(Boolean);
28583
28751
  if (results.length === 0) {
28584
28752
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
@@ -28606,7 +28774,11 @@ server.registerTool(
28606
28774
  }).join("\n\n");
28607
28775
  return { content: [{ type: "text", text: formatted2 }] };
28608
28776
  }
28609
- const ranked = results.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) })).sort((a, b) => b.score - a.score);
28777
+ const ranked = results.map((r) => {
28778
+ const quality = r.qualityRaw ? parseFloat(r.qualityRaw) || 0 : 0;
28779
+ const qualityBoost = quality * 0.15;
28780
+ return { ...r, score: entryScore(r.date, r.accessed) + qualityBoost };
28781
+ }).sort((a, b) => b.score - a.score);
28610
28782
  bumpAccessed(ranked.map((r) => r.id));
28611
28783
  if (compact) {
28612
28784
  const entries = ranked.map((r) => ({
@@ -28674,7 +28846,7 @@ server.registerTool(
28674
28846
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28675
28847
  const entries = lines.map((l) => {
28676
28848
  const parts = l.trim().split("|");
28677
- return { category: parts[1] || "unknown", ttl: parts[7] || "" };
28849
+ return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" };
28678
28850
  });
28679
28851
  const byCategory = {};
28680
28852
  for (const e of entries) {
@@ -28682,6 +28854,8 @@ server.registerTool(
28682
28854
  }
28683
28855
  const withTtl = entries.filter((e) => e.ttl).length;
28684
28856
  const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length;
28857
+ const withQuality = entries.filter((e) => e.quality).length;
28858
+ const avgQuality = withQuality > 0 ? (entries.reduce((sum, e) => sum + (e.quality ? parseFloat(e.quality) : 0), 0) / withQuality).toFixed(2) : "N/A";
28685
28859
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l));
28686
28860
  const stats = [
28687
28861
  `Entradas totales: ${entries.length}`,
@@ -28691,12 +28865,14 @@ server.registerTool(
28691
28865
  ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
28692
28866
  "",
28693
28867
  `TTL: ${withTtl} con expiraci\xF3n, ${expired} expiradas`,
28868
+ `Calidad promedio: ${avgQuality} (${withQuality} con score)`,
28694
28869
  "",
28695
28870
  `\xDAltimas 5 entradas:`,
28696
28871
  ...lines.slice(-5).map((l) => {
28697
28872
  const parts = l.trim().split("|");
28698
28873
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : "";
28699
- return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}`;
28874
+ const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : "";
28875
+ return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}`;
28700
28876
  })
28701
28877
  ];
28702
28878
  return { content: [{ type: "text", text: stats.join("\n") }] };
@@ -28774,6 +28950,23 @@ server.registerTool(
28774
28950
  ${formatted}` }] };
28775
28951
  }
28776
28952
  );
28953
+ server.registerTool(
28954
+ "memory_smart_recall",
28955
+ {
28956
+ title: "Smart Recall (Unified)",
28957
+ description: "Recuperaci\xF3n unificada: combina BM25 + grafo + decay + calidad en una sola llamada. Usar al INICIO de cada tarea para obtener todo el contexto relevante de memoria.",
28958
+ inputSchema: {
28959
+ intent: external_exports.string().describe("Describe qu\xE9 necesitas saber (ej: 'dise\xF1o de base de datos para backend')"),
28960
+ limit: external_exports.number().optional().default(8).describe("M\xE1ximo de entradas a devolver"),
28961
+ category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)")
28962
+ }
28963
+ },
28964
+ async ({ intent, limit, category }) => {
28965
+ const data = readMemory();
28966
+ const result = generateSmartRecall(data, intent, { limit, category });
28967
+ return { content: [{ type: "text", text: result }] };
28968
+ }
28969
+ );
28777
28970
  server.registerTool(
28778
28971
  "memory_summary",
28779
28972
  {