toon-memory 2.7.0 → 2.8.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.md +4 -3
- package/mcp/server.js +65 -83
- package/package.json +1 -5
- package/src/lib/context.ts +6 -27
- package/src/lib/git.ts +10 -11
- package/src/lib/graph.ts +2 -20
- package/src/lib/quality.ts +1 -20
- package/src/lib/utils.ts +25 -0
- package/src/mcp/entries.ts +1 -1
- package/src/mcp/tools.ts +21 -12
package/README.md
CHANGED
|
@@ -452,13 +452,14 @@ The System Primer is an auto-generated knowledge map exposed as an MCP resource.
|
|
|
452
452
|
#### Enable encryption
|
|
453
453
|
|
|
454
454
|
```typescript
|
|
455
|
+
// First, set TOON_MEMORY_KEY in your environment (or .env file):
|
|
456
|
+
// export TOON_MEMORY_KEY="your-secret-key-here"
|
|
457
|
+
|
|
455
458
|
memory_encrypt()
|
|
456
459
|
// 🔐 Encriptación habilitada
|
|
457
|
-
// ⚠️ Guarda esta clave (no se puede recuperar):
|
|
458
|
-
// a1b2c3d4...
|
|
459
460
|
```
|
|
460
461
|
|
|
461
|
-
> **Warning:**
|
|
462
|
+
> **Warning:** The encryption key must be set via `TOON_MEMORY_KEY` env var before encrypting. Save it somewhere safe — if you lose it, your memory data is gone forever. Quality scores and confidence are preserved through encryption.
|
|
462
463
|
|
|
463
464
|
---
|
|
464
465
|
|
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 = "",
|
|
16510
|
-
if (
|
|
16509
|
+
function getFullPath(resolver, id = "", normalize2) {
|
|
16510
|
+
if (normalize2 !== 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
|
|
17605
|
+
function normalize2(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:
|
|
17783
|
+
normalize: normalize2,
|
|
17784
17784
|
resolve,
|
|
17785
17785
|
resolveComponent,
|
|
17786
17786
|
equal,
|
|
@@ -27639,7 +27639,7 @@ var StdioServerTransport = class {
|
|
|
27639
27639
|
};
|
|
27640
27640
|
|
|
27641
27641
|
// src/mcp/tools.ts
|
|
27642
|
-
import {
|
|
27642
|
+
import { writeFileSync as writeFileSync4, existsSync as existsSync10 } from "fs";
|
|
27643
27643
|
|
|
27644
27644
|
// src/lib/lock.ts
|
|
27645
27645
|
import { openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, renameSync } from "fs";
|
|
@@ -27842,6 +27842,24 @@ function writeMemory(content) {
|
|
|
27842
27842
|
|
|
27843
27843
|
// src/mcp/entries.ts
|
|
27844
27844
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
27845
|
+
|
|
27846
|
+
// src/lib/utils.ts
|
|
27847
|
+
var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
27848
|
+
var isExpiredLocal = (ttl) => {
|
|
27849
|
+
if (!ttl) return false;
|
|
27850
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
27851
|
+
return ttl <= today;
|
|
27852
|
+
};
|
|
27853
|
+
function importance(e) {
|
|
27854
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
27855
|
+
const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
|
|
27856
|
+
const recency = Math.max(0, 30 - days) / 30;
|
|
27857
|
+
const freq = Math.min(1, e.accessed / 5);
|
|
27858
|
+
return recency * 0.6 + freq * 0.4;
|
|
27859
|
+
}
|
|
27860
|
+
var tokenize = (s) => normalize(s).split(" ").filter(Boolean);
|
|
27861
|
+
|
|
27862
|
+
// src/mcp/entries.ts
|
|
27845
27863
|
function generateId() {
|
|
27846
27864
|
return randomBytes2(4).toString("hex");
|
|
27847
27865
|
}
|
|
@@ -27921,7 +27939,6 @@ function parseRelativeDate(since) {
|
|
|
27921
27939
|
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
27922
27940
|
return today;
|
|
27923
27941
|
}
|
|
27924
|
-
var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
27925
27942
|
|
|
27926
27943
|
// src/mcp/scoring.ts
|
|
27927
27944
|
function entryScore(dateStr, accessed) {
|
|
@@ -28082,12 +28099,6 @@ function pruneExpiredEntries() {
|
|
|
28082
28099
|
}
|
|
28083
28100
|
|
|
28084
28101
|
// src/lib/graph.ts
|
|
28085
|
-
var isExpiredLocal = (ttl) => {
|
|
28086
|
-
if (!ttl) return false;
|
|
28087
|
-
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
28088
|
-
return ttl <= today;
|
|
28089
|
-
};
|
|
28090
|
-
var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
28091
28102
|
var entryLines = (data) => data.split("\n").filter(
|
|
28092
28103
|
(l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
|
|
28093
28104
|
);
|
|
@@ -28135,14 +28146,6 @@ function buildGraph(entries) {
|
|
|
28135
28146
|
for (const [k, v] of adj) adjacency.set(k, [...v]);
|
|
28136
28147
|
return { adjacency, byKey };
|
|
28137
28148
|
}
|
|
28138
|
-
var importance = (e) => {
|
|
28139
|
-
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
28140
|
-
const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
|
|
28141
|
-
const recency = Math.max(0, 30 - days) / 30;
|
|
28142
|
-
const freq = Math.min(1, e.accessed / 5);
|
|
28143
|
-
return recency * 0.6 + freq * 0.4;
|
|
28144
|
-
};
|
|
28145
|
-
var tokenize = (s) => normalize2(s).split(" ").filter(Boolean);
|
|
28146
28149
|
function bm25Scores(entries, query) {
|
|
28147
28150
|
const N = entries.length;
|
|
28148
28151
|
const scores = /* @__PURE__ */ new Map();
|
|
@@ -28204,7 +28207,7 @@ function graphRecallDetailed(data, query, opts = {}) {
|
|
|
28204
28207
|
if (from_date && e.date < from_date) continue;
|
|
28205
28208
|
if (to_date && e.date > to_date) continue;
|
|
28206
28209
|
if (e.ttl && isExpiredLocal(e.ttl)) continue;
|
|
28207
|
-
const text =
|
|
28210
|
+
const text = normalize(
|
|
28208
28211
|
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
28209
28212
|
);
|
|
28210
28213
|
if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue;
|
|
@@ -28276,20 +28279,6 @@ function renderCompact(entries, opts = {}) {
|
|
|
28276
28279
|
}
|
|
28277
28280
|
|
|
28278
28281
|
// src/lib/quality.ts
|
|
28279
|
-
var normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
28280
|
-
var tokenize2 = (s) => normalize3(s).split(" ").filter(Boolean);
|
|
28281
|
-
var isExpiredLocal2 = (ttl) => {
|
|
28282
|
-
if (!ttl) return false;
|
|
28283
|
-
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
28284
|
-
return ttl <= today;
|
|
28285
|
-
};
|
|
28286
|
-
var importance2 = (e) => {
|
|
28287
|
-
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
28288
|
-
const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
|
|
28289
|
-
const recency = Math.max(0, 30 - days) / 30;
|
|
28290
|
-
const freq = Math.min(1, e.accessed / 5);
|
|
28291
|
-
return recency * 0.6 + freq * 0.4;
|
|
28292
|
-
};
|
|
28293
28282
|
function qualityScore(tags, links, content, date5) {
|
|
28294
28283
|
let score = 0;
|
|
28295
28284
|
if (tags) {
|
|
@@ -28350,24 +28339,24 @@ function generateSmartRecall(data, intent, opts = {}) {
|
|
|
28350
28339
|
const cent = centrality(adjacency);
|
|
28351
28340
|
const limit = opts.limit ?? 8;
|
|
28352
28341
|
const category = opts.category || "";
|
|
28353
|
-
const qTokens =
|
|
28342
|
+
const qTokens = tokenize(intent);
|
|
28354
28343
|
const scored = entries.filter((e) => {
|
|
28355
28344
|
if (category && e.category !== category) return false;
|
|
28356
|
-
if (e.ttl &&
|
|
28345
|
+
if (e.ttl && isExpiredLocal(e.ttl)) return false;
|
|
28357
28346
|
return true;
|
|
28358
28347
|
}).map((e) => {
|
|
28359
|
-
const text =
|
|
28348
|
+
const text = normalize(
|
|
28360
28349
|
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
28361
28350
|
);
|
|
28362
28351
|
const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t));
|
|
28363
28352
|
const bm25Score = bm25.get(e.key) || 0;
|
|
28364
28353
|
const centScore = cent.get(e.key) || 0;
|
|
28365
|
-
const impScore =
|
|
28354
|
+
const impScore = importance(e);
|
|
28366
28355
|
const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0);
|
|
28367
28356
|
return { entry: e, score: combined, matchesQuery };
|
|
28368
28357
|
}).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b) => b.score - a.score).slice(0, limit);
|
|
28369
28358
|
if (scored.length === 0) {
|
|
28370
|
-
const top = entries.filter((e) => !category || e.category === category).sort((a, b) =>
|
|
28359
|
+
const top = entries.filter((e) => !category || e.category === category).sort((a, b) => importance(b) - importance(a)).slice(0, limit);
|
|
28371
28360
|
if (top.length === 0) return "No hay entradas en memoria.";
|
|
28372
28361
|
return renderCompact(top);
|
|
28373
28362
|
}
|
|
@@ -28387,7 +28376,7 @@ function generateSystemPrimer(data) {
|
|
|
28387
28376
|
`Entradas: ${entries.length}`,
|
|
28388
28377
|
""
|
|
28389
28378
|
];
|
|
28390
|
-
const top = [...entries].sort((a, b) =>
|
|
28379
|
+
const top = [...entries].sort((a, b) => importance(b) - importance(a)).slice(0, 5);
|
|
28391
28380
|
lines.push("Top memorias:");
|
|
28392
28381
|
for (const e of top) {
|
|
28393
28382
|
const quality = qualityScore(
|
|
@@ -28645,8 +28634,12 @@ function parseIndex(dir) {
|
|
|
28645
28634
|
const size = buf.readUInt32BE(offset + 28);
|
|
28646
28635
|
const sha = buf.slice(offset + 32, offset + 52).toString("hex");
|
|
28647
28636
|
const flags = buf.readUInt16BE(offset + 52);
|
|
28637
|
+
let nameOffset = 62;
|
|
28638
|
+
if (version2 >= 3) {
|
|
28639
|
+
nameOffset += 4;
|
|
28640
|
+
}
|
|
28648
28641
|
const nameLen = flags & 4095;
|
|
28649
|
-
const nameStart = entryStart +
|
|
28642
|
+
const nameStart = entryStart + nameOffset;
|
|
28650
28643
|
let name;
|
|
28651
28644
|
if (nameLen > 0 && nameStart + nameLen <= buf.length) {
|
|
28652
28645
|
name = buf.toString("utf-8", nameStart, nameStart + nameLen);
|
|
@@ -28654,9 +28647,7 @@ function parseIndex(dir) {
|
|
|
28654
28647
|
const end = buf.indexOf(0, nameStart);
|
|
28655
28648
|
name = end >= 0 ? buf.toString("utf-8", nameStart, end) : buf.toString("utf-8", nameStart);
|
|
28656
28649
|
}
|
|
28657
|
-
|
|
28658
|
-
}
|
|
28659
|
-
const rawLen = 62 + name.length;
|
|
28650
|
+
const rawLen = nameOffset + name.length;
|
|
28660
28651
|
const paddedLen = Math.ceil(rawLen / 8) * 8;
|
|
28661
28652
|
offset = entryStart + paddedLen;
|
|
28662
28653
|
entries.push({ mtimeSec, mtimeNsec, dev, ino, mode, uid, gid, size, sha, flags, name });
|
|
@@ -29024,20 +29015,6 @@ function findCallers(root, symbol2) {
|
|
|
29024
29015
|
}
|
|
29025
29016
|
|
|
29026
29017
|
// src/lib/context.ts
|
|
29027
|
-
var normalize4 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
29028
|
-
var tokenize3 = (s) => normalize4(s).split(" ").filter(Boolean);
|
|
29029
|
-
var isExpiredLocal3 = (ttl) => {
|
|
29030
|
-
if (!ttl) return false;
|
|
29031
|
-
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
29032
|
-
return ttl <= today;
|
|
29033
|
-
};
|
|
29034
|
-
var importance3 = (e) => {
|
|
29035
|
-
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
29036
|
-
const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
|
|
29037
|
-
const recency = Math.max(0, 30 - days) / 30;
|
|
29038
|
-
const freq = Math.min(1, e.accessed / 5);
|
|
29039
|
-
return recency * 0.6 + freq * 0.4;
|
|
29040
|
-
};
|
|
29041
29018
|
function formatOverview(data) {
|
|
29042
29019
|
const entries = parseEntries(data);
|
|
29043
29020
|
if (entries.length === 0) return "Memoria: vac\xEDa";
|
|
@@ -29045,7 +29022,7 @@ function formatOverview(data) {
|
|
|
29045
29022
|
let expired = 0;
|
|
29046
29023
|
for (const e of entries) {
|
|
29047
29024
|
byCategory[e.category] = (byCategory[e.category] || 0) + 1;
|
|
29048
|
-
if (e.ttl &&
|
|
29025
|
+
if (e.ttl && isExpiredLocal(e.ttl)) expired++;
|
|
29049
29026
|
}
|
|
29050
29027
|
const cats = Object.entries(byCategory).map(([k, v]) => `${k}:${v}`).join(" ");
|
|
29051
29028
|
const ttlNote = expired > 0 ? ` | ${expired} expiradas` : "";
|
|
@@ -29058,15 +29035,15 @@ function formatRelevantEntries(data, task, limit = 6) {
|
|
|
29058
29035
|
const { adjacency, byKey } = buildGraph(entries);
|
|
29059
29036
|
const bm25 = bm25Scores(entries, task);
|
|
29060
29037
|
const cent = centrality(adjacency);
|
|
29061
|
-
const qTokens =
|
|
29062
|
-
const scored = entries.filter((e) => !(e.ttl &&
|
|
29063
|
-
const text =
|
|
29038
|
+
const qTokens = tokenize(task);
|
|
29039
|
+
const scored = entries.filter((e) => !(e.ttl && isExpiredLocal(e.ttl))).map((e) => {
|
|
29040
|
+
const text = normalize(
|
|
29064
29041
|
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
29065
29042
|
);
|
|
29066
29043
|
const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t));
|
|
29067
29044
|
const bm25Score = bm25.get(e.key) || 0;
|
|
29068
29045
|
const centScore = cent.get(e.key) || 0;
|
|
29069
|
-
const impScore =
|
|
29046
|
+
const impScore = importance(e);
|
|
29070
29047
|
const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0);
|
|
29071
29048
|
return { entry: e, score: combined, matchesQuery };
|
|
29072
29049
|
}).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b) => b.score - a.score).slice(0, limit);
|
|
@@ -29087,7 +29064,7 @@ ${rendered}`;
|
|
|
29087
29064
|
}
|
|
29088
29065
|
function formatPatterns(data) {
|
|
29089
29066
|
const entries = parseEntries(data);
|
|
29090
|
-
const patterns = entries.filter((e) => e.category === "pattern").sort((a, b) =>
|
|
29067
|
+
const patterns = entries.filter((e) => e.category === "pattern").sort((a, b) => importance(b) - importance(a)).slice(0, 5);
|
|
29091
29068
|
if (patterns.length === 0) return "";
|
|
29092
29069
|
const lines = patterns.map(
|
|
29093
29070
|
(e) => `- **${e.key}**: ${e.content.slice(0, 120)}`
|
|
@@ -29121,7 +29098,7 @@ Rama: ${branch} | Sin otras sesiones activas`;
|
|
|
29121
29098
|
function formatHealth(data) {
|
|
29122
29099
|
const entries = parseEntries(data);
|
|
29123
29100
|
const warnings = [];
|
|
29124
|
-
const expired = entries.filter((e) => e.ttl &&
|
|
29101
|
+
const expired = entries.filter((e) => e.ttl && isExpiredLocal(e.ttl));
|
|
29125
29102
|
if (expired.length > 0) {
|
|
29126
29103
|
warnings.push(`${expired.length} entradas con TTL expirado (ejecutar memory_archive)`);
|
|
29127
29104
|
}
|
|
@@ -29164,7 +29141,7 @@ function generateContextBrief(data, opts = {}) {
|
|
|
29164
29141
|
function formatTopEntries(data, limit) {
|
|
29165
29142
|
const entries = parseEntries(data);
|
|
29166
29143
|
if (entries.length === 0) return "";
|
|
29167
|
-
const top = [...entries].filter((e) => !(e.ttl &&
|
|
29144
|
+
const top = [...entries].filter((e) => !(e.ttl && isExpiredLocal(e.ttl))).sort((a, b) => importance(b) - importance(a)).slice(0, limit);
|
|
29168
29145
|
if (top.length === 0) return "";
|
|
29169
29146
|
const rendered = renderCompact(top);
|
|
29170
29147
|
return `## Top memorias
|
|
@@ -29325,14 +29302,13 @@ function generateContextHealth(data, root) {
|
|
|
29325
29302
|
warnings.push(`${duplicates.length} entradas duplicadas: ${duplicates.slice(0, 3).join("; ")}`);
|
|
29326
29303
|
score -= 5;
|
|
29327
29304
|
}
|
|
29328
|
-
const
|
|
29329
|
-
|
|
29330
|
-
|
|
29331
|
-
|
|
29332
|
-
info.push(`${missingQuality.length} entradas sin quality score`);
|
|
29305
|
+
const weekAgo = new Date(Date.now() - 7 * 864e5).toISOString().split("T")[0];
|
|
29306
|
+
const staleNeverAccessed = entries.filter((e) => e.accessed === 0 && e.date < weekAgo);
|
|
29307
|
+
if (staleNeverAccessed.length > 0) {
|
|
29308
|
+
info.push(`${staleNeverAccessed.length} entradas antiguas nunca recuperadas (posiblemente obsoletas)`);
|
|
29333
29309
|
score -= 2;
|
|
29334
29310
|
}
|
|
29335
|
-
const expired = entries.filter((e) => e.ttl &&
|
|
29311
|
+
const expired = entries.filter((e) => e.ttl && isExpiredLocal(e.ttl));
|
|
29336
29312
|
if (expired.length > 0) {
|
|
29337
29313
|
info.push(`${expired.length} entradas con TTL expirado (auto-prune en pr\xF3ximo inicio)`);
|
|
29338
29314
|
score -= 3;
|
|
@@ -29442,7 +29418,6 @@ _${e.date}${tags}${file2}${links}_`);
|
|
|
29442
29418
|
}
|
|
29443
29419
|
|
|
29444
29420
|
// src/mcp/tools.ts
|
|
29445
|
-
var normalize5 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
29446
29421
|
function registerTools(server2) {
|
|
29447
29422
|
server2.registerTool(
|
|
29448
29423
|
"memory_remember",
|
|
@@ -29553,7 +29528,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
|
|
|
29553
29528
|
async ({ query, category, from_date, to_date, mode, hops, compact }) => {
|
|
29554
29529
|
const data = readMemory();
|
|
29555
29530
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
|
|
29556
|
-
const queryTokens =
|
|
29531
|
+
const queryTokens = normalize(query).split(" ").filter(Boolean);
|
|
29557
29532
|
const results = lines.map((line) => {
|
|
29558
29533
|
const trimmed = line.trim();
|
|
29559
29534
|
const parts = trimmed.split("|");
|
|
@@ -29565,7 +29540,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
|
|
|
29565
29540
|
if (from_date && date5 < from_date) return null;
|
|
29566
29541
|
if (to_date && date5 > to_date) return null;
|
|
29567
29542
|
if (ttl && isExpired(ttl)) return null;
|
|
29568
|
-
const searchStr =
|
|
29543
|
+
const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file2} ${tags} ${qualityRaw} ${confidenceRaw}`);
|
|
29569
29544
|
if (!queryTokens.every((token) => searchStr.includes(token))) return null;
|
|
29570
29545
|
const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
|
|
29571
29546
|
return { id, cat, key, content, file: file2, tags, date: date5, accessed, qualityRaw, confidenceRaw };
|
|
@@ -29596,10 +29571,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
|
|
|
29596
29571
|
}).join("\n\n");
|
|
29597
29572
|
return { content: [{ type: "text", text: formatted2 }] };
|
|
29598
29573
|
}
|
|
29574
|
+
const bm25 = bm25Scores(parseEntries(data), query);
|
|
29599
29575
|
const ranked = results.map((r) => {
|
|
29600
29576
|
const quality = r.qualityRaw ? parseFloat(r.qualityRaw) || 0 : 0;
|
|
29601
29577
|
const qualityBoost = quality * 0.15;
|
|
29602
|
-
|
|
29578
|
+
const bm25Score = bm25.get(r.key) || 0;
|
|
29579
|
+
return { ...r, score: bm25Score + entryScore(r.date, r.accessed) + qualityBoost };
|
|
29603
29580
|
}).sort((a, b) => b.score - a.score);
|
|
29604
29581
|
bumpAccessed(ranked.map((r) => r.id));
|
|
29605
29582
|
if (compact) {
|
|
@@ -29651,6 +29628,11 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
|
|
|
29651
29628
|
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
|
|
29652
29629
|
lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
|
|
29653
29630
|
writeMemory(lines.join("\n"));
|
|
29631
|
+
if (removed === 0) {
|
|
29632
|
+
return {
|
|
29633
|
+
content: [{ type: "text", text: `No se encontr\xF3 "${key}" en memoria.` }]
|
|
29634
|
+
};
|
|
29635
|
+
}
|
|
29654
29636
|
return {
|
|
29655
29637
|
content: [{ type: "text", text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }]
|
|
29656
29638
|
};
|
|
@@ -29861,7 +29843,7 @@ ${formatted}` }] };
|
|
|
29861
29843
|
"memory_encrypt",
|
|
29862
29844
|
{
|
|
29863
29845
|
title: "Enable Encryption",
|
|
29864
|
-
description: "Habilita encriptaci\xF3n AES-256-GCM para la memoria.
|
|
29846
|
+
description: "Habilita encriptaci\xF3n AES-256-GCM para la memoria. Requiere TOON_MEMORY_KEY en el entorno.",
|
|
29865
29847
|
inputSchema: {}
|
|
29866
29848
|
},
|
|
29867
29849
|
async () => {
|
|
@@ -29873,9 +29855,9 @@ ${formatted}` }] };
|
|
|
29873
29855
|
if (!key) {
|
|
29874
29856
|
return { content: [{ type: "text", text: "\u274C Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] };
|
|
29875
29857
|
}
|
|
29876
|
-
const data =
|
|
29858
|
+
const data = readUnderLock(MEMORY_FILE);
|
|
29877
29859
|
const encrypted = encrypt(data, key);
|
|
29878
|
-
|
|
29860
|
+
safeWrite(MEMORY_FILE, encrypted);
|
|
29879
29861
|
saveConfig({ encrypted: true });
|
|
29880
29862
|
return {
|
|
29881
29863
|
content: [{ type: "text", text: "\u{1F510} Encriptaci\xF3n habilitada" }]
|
|
@@ -29901,9 +29883,9 @@ ${formatted}` }] };
|
|
|
29901
29883
|
return { content: [{ type: "text", text: "\u274C No hay clave. P\xE1sala como argumento o la del archivo .env" }] };
|
|
29902
29884
|
}
|
|
29903
29885
|
try {
|
|
29904
|
-
const data =
|
|
29886
|
+
const data = readUnderLock(MEMORY_FILE);
|
|
29905
29887
|
const decrypted = decrypt(data, resolvedKey);
|
|
29906
|
-
|
|
29888
|
+
safeWrite(MEMORY_FILE, decrypted);
|
|
29907
29889
|
saveConfig({ encrypted: false });
|
|
29908
29890
|
return {
|
|
29909
29891
|
content: [{ type: "text", text: "\u{1F513} Encriptaci\xF3n deshabilitada" }]
|
|
@@ -30185,7 +30167,7 @@ function registerResources(server2) {
|
|
|
30185
30167
|
|
|
30186
30168
|
// src/mcp/server.ts
|
|
30187
30169
|
var server = new McpServer(
|
|
30188
|
-
{ name: "toon-memory", version: "2.
|
|
30170
|
+
{ name: "toon-memory", version: "2.8.0" },
|
|
30189
30171
|
{ capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
|
|
30190
30172
|
);
|
|
30191
30173
|
registerResources(server);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.8.0",
|
|
4
4
|
"description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 20 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -31,13 +31,9 @@
|
|
|
31
31
|
"prepublishOnly": "npm run build && npm test"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@ffmpeg-installer/ffmpeg": "^1.1.0",
|
|
35
34
|
"@inquirer/prompts": "^8.5.2",
|
|
36
35
|
"@modelcontextprotocol/server": "^2.0.0-beta.3",
|
|
37
36
|
"@toon-format/toon": "^2.3.0",
|
|
38
|
-
"ffmpeg-static": "^5.3.0",
|
|
39
|
-
"hyperframes": "^0.7.59",
|
|
40
|
-
"yauzl": "^3.4.0",
|
|
41
37
|
"zod": "^4.4.3"
|
|
42
38
|
},
|
|
43
39
|
"devDependencies": {
|
package/src/lib/context.ts
CHANGED
|
@@ -17,31 +17,12 @@ import { existsSync, readFileSync } from "fs"
|
|
|
17
17
|
import { join } from "path"
|
|
18
18
|
import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
|
|
19
19
|
import { qualityScore } from "./quality"
|
|
20
|
+
import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
|
|
20
21
|
import { coordinationView, currentBranch, pruneSessions, listSessions } from "./sessions"
|
|
21
22
|
import { readRecentCommits, gitStatusSummary, readGitIndex } from "./git"
|
|
22
23
|
import { scanProjectStructure, readManifest, readEnvExample } from "./project-scan"
|
|
23
24
|
import { findFilesByPattern, searchCode, findCallers } from "./code-search"
|
|
24
25
|
|
|
25
|
-
const normalize = (s: string): string =>
|
|
26
|
-
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
27
|
-
|
|
28
|
-
const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
|
29
|
-
|
|
30
|
-
const isExpiredLocal = (ttl: string): boolean => {
|
|
31
|
-
if (!ttl) return false
|
|
32
|
-
const today = new Date().toISOString().split("T")[0]
|
|
33
|
-
return ttl <= today
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const importance = (e: GraphEntry): number => {
|
|
37
|
-
const today = new Date().toISOString().split("T")[0]
|
|
38
|
-
const days =
|
|
39
|
-
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
40
|
-
const recency = Math.max(0, 30 - days) / 30
|
|
41
|
-
const freq = Math.min(1, e.accessed / 5)
|
|
42
|
-
return recency * 0.6 + freq * 0.4
|
|
43
|
-
}
|
|
44
|
-
|
|
45
26
|
// ── Section builders ────────────────────────────────────────────────
|
|
46
27
|
|
|
47
28
|
/**
|
|
@@ -507,13 +488,11 @@ export function generateContextHealth(data: string, root: string): { report: Hea
|
|
|
507
488
|
score -= 5
|
|
508
489
|
}
|
|
509
490
|
|
|
510
|
-
// 3.
|
|
511
|
-
const
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
if (missingQuality.length > 0) {
|
|
516
|
-
info.push(`${missingQuality.length} entradas sin quality score`)
|
|
491
|
+
// 3. Never-accessed old entries (created >7d ago but never recalled = possibly stale)
|
|
492
|
+
const weekAgo = new Date(Date.now() - 7 * 86400000).toISOString().split("T")[0]
|
|
493
|
+
const staleNeverAccessed = entries.filter((e) => e.accessed === 0 && e.date < weekAgo)
|
|
494
|
+
if (staleNeverAccessed.length > 0) {
|
|
495
|
+
info.push(`${staleNeverAccessed.length} entradas antiguas nunca recuperadas (posiblemente obsoletas)`)
|
|
517
496
|
score -= 2
|
|
518
497
|
}
|
|
519
498
|
|
package/src/lib/git.ts
CHANGED
|
@@ -89,26 +89,25 @@ function parseIndex(dir: string): IndexEntry[] {
|
|
|
89
89
|
const sha = buf.slice(offset + 32, offset + 52).toString("hex")
|
|
90
90
|
const flags = buf.readUInt16BE(offset + 52)
|
|
91
91
|
|
|
92
|
-
//
|
|
92
|
+
// v3/v4 entries have an extra 4-byte extended entry field after the standard 62 bytes
|
|
93
|
+
let nameOffset = 62
|
|
94
|
+
if (version >= 3) {
|
|
95
|
+
nameOffset += 4
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Name starts at entryStart + nameOffset, null-terminated, padded to 8-byte alignment
|
|
93
99
|
const nameLen = flags & 0x0fff
|
|
94
|
-
const nameStart = entryStart +
|
|
100
|
+
const nameStart = entryStart + nameOffset
|
|
95
101
|
let name: string
|
|
96
102
|
if (nameLen > 0 && nameStart + nameLen <= buf.length) {
|
|
97
103
|
name = buf.toString("utf-8", nameStart, nameStart + nameLen)
|
|
98
104
|
} else {
|
|
99
|
-
// Read until null byte
|
|
100
105
|
const end = buf.indexOf(0, nameStart)
|
|
101
106
|
name = end >= 0 ? buf.toString("utf-8", nameStart, end) : buf.toString("utf-8", nameStart)
|
|
102
107
|
}
|
|
103
108
|
|
|
104
|
-
//
|
|
105
|
-
|
|
106
|
-
// In v3, there's an extra 4-byte field (padding/extended)
|
|
107
|
-
// The name starts at entryStart + 62 regardless in v2-v4
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// Compute total entry size: 62 bytes + name length, padded to 8-byte boundary
|
|
111
|
-
const rawLen = 62 + name.length
|
|
109
|
+
// Compute total entry size: base bytes + name length, padded to 8-byte boundary
|
|
110
|
+
const rawLen = nameOffset + name.length
|
|
112
111
|
const paddedLen = Math.ceil(rawLen / 8) * 8
|
|
113
112
|
offset = entryStart + paddedLen
|
|
114
113
|
|
package/src/lib/graph.ts
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
* without mutating the stored `.toon` file.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
|
|
18
|
+
|
|
17
19
|
export interface GraphEntry {
|
|
18
20
|
id: string
|
|
19
21
|
category: string
|
|
@@ -35,15 +37,6 @@ export interface MemoryGraph {
|
|
|
35
37
|
byKey: Map<string, GraphEntry>
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
const isExpiredLocal = (ttl: string): boolean => {
|
|
39
|
-
if (!ttl) return false
|
|
40
|
-
const today = new Date().toISOString().split("T")[0]
|
|
41
|
-
return ttl <= today
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const normalize = (s: string): string =>
|
|
45
|
-
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
46
|
-
|
|
47
40
|
const entryLines = (data: string): string[] =>
|
|
48
41
|
data
|
|
49
42
|
.split("\n")
|
|
@@ -125,17 +118,6 @@ export interface GraphRecallOpts {
|
|
|
125
118
|
limit?: number
|
|
126
119
|
}
|
|
127
120
|
|
|
128
|
-
const importance = (e: GraphEntry): number => {
|
|
129
|
-
const today = new Date().toISOString().split("T")[0]
|
|
130
|
-
const days =
|
|
131
|
-
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
132
|
-
const recency = Math.max(0, 30 - days) / 30
|
|
133
|
-
const freq = Math.min(1, e.accessed / 5)
|
|
134
|
-
return recency * 0.6 + freq * 0.4
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
|
138
|
-
|
|
139
121
|
/**
|
|
140
122
|
* BM25 relevance of each entry for the query. Deterministic and offline.
|
|
141
123
|
* Returns a map key -> score (0 when the entry shares no query token).
|
package/src/lib/quality.ts
CHANGED
|
@@ -8,26 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
|
|
11
|
-
|
|
12
|
-
const normalize = (s: string): string =>
|
|
13
|
-
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
14
|
-
|
|
15
|
-
const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
|
16
|
-
|
|
17
|
-
const isExpiredLocal = (ttl: string): boolean => {
|
|
18
|
-
if (!ttl) return false
|
|
19
|
-
const today = new Date().toISOString().split("T")[0]
|
|
20
|
-
return ttl <= today
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const importance = (e: GraphEntry): number => {
|
|
24
|
-
const today = new Date().toISOString().split("T")[0]
|
|
25
|
-
const days =
|
|
26
|
-
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
27
|
-
const recency = Math.max(0, 30 - days) / 30
|
|
28
|
-
const freq = Math.min(1, e.accessed / 5)
|
|
29
|
-
return recency * 0.6 + freq * 0.4
|
|
30
|
-
}
|
|
11
|
+
import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
|
|
31
12
|
|
|
32
13
|
/**
|
|
33
14
|
* Quality score for an entry (0..1). Pure heuristics, no LLM.
|
package/src/lib/utils.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helper functions used across lib/ modules.
|
|
3
|
+
* Eliminates copy-paste duplication of normalize, isExpiredLocal, importance, tokenize.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const normalize = (s: string): string =>
|
|
7
|
+
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
8
|
+
|
|
9
|
+
export const isExpiredLocal = (ttl: string): boolean => {
|
|
10
|
+
if (!ttl) return false
|
|
11
|
+
const today = new Date().toISOString().split("T")[0]
|
|
12
|
+
return ttl <= today
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Lightweight importance score: recency (60%) + frequency (40%). */
|
|
16
|
+
export function importance(e: { date: string; accessed: number }): number {
|
|
17
|
+
const today = new Date().toISOString().split("T")[0]
|
|
18
|
+
const days =
|
|
19
|
+
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
20
|
+
const recency = Math.max(0, 30 - days) / 30
|
|
21
|
+
const freq = Math.min(1, e.accessed / 5)
|
|
22
|
+
return recency * 0.6 + freq * 0.4
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
package/src/mcp/entries.ts
CHANGED
package/src/mcp/tools.ts
CHANGED
|
@@ -1,23 +1,22 @@
|
|
|
1
1
|
import type { McpServer } from "@modelcontextprotocol/server"
|
|
2
2
|
import { z } from "zod"
|
|
3
3
|
import { readFileSync, writeFileSync, existsSync } from "fs"
|
|
4
|
-
import { readMemory, writeMemory } from "./memory-io"
|
|
4
|
+
import { readMemory, writeMemory, safeWrite } from "./memory-io"
|
|
5
5
|
import { loadConfig, saveConfig, getKey, MEMORY_FILE, OBSERVATIONS_FILE, MAX_ENTRIES } from "./config"
|
|
6
|
-
import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate } from "./entries"
|
|
6
|
+
import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate, normalize } from "./entries"
|
|
7
7
|
import { entryScore, findRelatedEntries, bumpAccessed } from "./scoring"
|
|
8
8
|
import { readObservations } from "./observations"
|
|
9
9
|
import { archiveOldEntries } from "./archive"
|
|
10
10
|
import { consolidateEntries } from "./consolidation"
|
|
11
|
+
import { readUnderLock } from "../lib/lock"
|
|
11
12
|
import { encrypt, decrypt } from "./crypto"
|
|
12
|
-
import { graphRecallDetailed, renderCompact } from "../lib/graph"
|
|
13
|
+
import { graphRecallDetailed, renderCompact, bm25Scores, parseEntries } from "../lib/graph"
|
|
13
14
|
import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
|
|
14
15
|
import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
|
|
15
16
|
import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
|
|
16
17
|
|
|
17
|
-
const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
18
|
-
|
|
19
18
|
/**
|
|
20
|
-
* Register all
|
|
19
|
+
* Register all 20 memory tools.
|
|
21
20
|
*/
|
|
22
21
|
export function registerTools(server: McpServer): void {
|
|
23
22
|
|
|
@@ -188,11 +187,14 @@ server.registerTool(
|
|
|
188
187
|
return { content: [{ type: "text" as const, text: formatted }] }
|
|
189
188
|
}
|
|
190
189
|
|
|
190
|
+
const bm25 = bm25Scores(parseEntries(data), query)
|
|
191
|
+
|
|
191
192
|
const ranked = results
|
|
192
193
|
.map((r) => {
|
|
193
194
|
const quality = r.qualityRaw ? parseFloat(r.qualityRaw) || 0 : 0
|
|
194
195
|
const qualityBoost = quality * 0.15
|
|
195
|
-
|
|
196
|
+
const bm25Score = bm25.get(r.key) || 0
|
|
197
|
+
return { ...r, score: bm25Score + entryScore(r.date, r.accessed) + qualityBoost }
|
|
196
198
|
})
|
|
197
199
|
.sort((a, b) => b.score - a.score)
|
|
198
200
|
|
|
@@ -256,6 +258,13 @@ server.registerTool(
|
|
|
256
258
|
lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
|
|
257
259
|
|
|
258
260
|
writeMemory(lines.join("\n"))
|
|
261
|
+
|
|
262
|
+
if (removed === 0) {
|
|
263
|
+
return {
|
|
264
|
+
content: [{ type: "text" as const, text: `No se encontró "${key}" en memoria.` }],
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
259
268
|
return {
|
|
260
269
|
content: [{ type: "text" as const, text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }],
|
|
261
270
|
}
|
|
@@ -511,7 +520,7 @@ server.registerTool(
|
|
|
511
520
|
"memory_encrypt",
|
|
512
521
|
{
|
|
513
522
|
title: "Enable Encryption",
|
|
514
|
-
description: "Habilita encriptación AES-256-GCM para la memoria.
|
|
523
|
+
description: "Habilita encriptación AES-256-GCM para la memoria. Requiere TOON_MEMORY_KEY en el entorno.",
|
|
515
524
|
inputSchema: {},
|
|
516
525
|
},
|
|
517
526
|
async () => {
|
|
@@ -526,9 +535,9 @@ server.registerTool(
|
|
|
526
535
|
return { content: [{ type: "text" as const, text: "❌ Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] }
|
|
527
536
|
}
|
|
528
537
|
|
|
529
|
-
const data =
|
|
538
|
+
const data = readUnderLock(MEMORY_FILE)
|
|
530
539
|
const encrypted = encrypt(data, key)
|
|
531
|
-
|
|
540
|
+
safeWrite(MEMORY_FILE, encrypted)
|
|
532
541
|
|
|
533
542
|
saveConfig({ encrypted: true })
|
|
534
543
|
|
|
@@ -562,10 +571,10 @@ server.registerTool(
|
|
|
562
571
|
}
|
|
563
572
|
|
|
564
573
|
try {
|
|
565
|
-
const data =
|
|
574
|
+
const data = readUnderLock(MEMORY_FILE)
|
|
566
575
|
const decrypted = decrypt(data, resolvedKey)
|
|
567
576
|
|
|
568
|
-
|
|
577
|
+
safeWrite(MEMORY_FILE, decrypted)
|
|
569
578
|
saveConfig({ encrypted: false })
|
|
570
579
|
|
|
571
580
|
return {
|