toon-memory 2.0.0 → 2.2.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 +219 -21
- package/dist/cli/capture.js +276 -0
- package/dist/cli/session-start.js +192 -0
- package/dist/cli/setup.js +123 -21
- package/dist/cli/toon-memory.js +3 -2
- package/mcp/server.js +647 -72
- package/package.json +5 -3
- package/skills/toon-memory.md +44 -10
- package/src/cli/capture.ts +187 -0
- package/src/cli/session-start.ts +70 -0
- package/src/cli/setup.ts +148 -15
- package/src/lib/graph.ts +200 -0
- package/src/lib/lock.ts +120 -0
- package/src/lib/sessions.ts +225 -0
- package/src/mcp/server.ts +411 -63
- package/src/memory.ts +1 -1
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 = "", normalize3) {
|
|
16510
|
+
if (normalize3 !== 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 normalize3(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: normalize3,
|
|
17784
17784
|
resolve,
|
|
17785
17785
|
resolveComponent,
|
|
17786
17786
|
equal,
|
|
@@ -27639,42 +27639,357 @@ var StdioServerTransport = class {
|
|
|
27639
27639
|
};
|
|
27640
27640
|
|
|
27641
27641
|
// src/mcp/server.ts
|
|
27642
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
|
|
27643
|
-
import { dirname, join } from "path";
|
|
27642
|
+
import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
|
|
27643
|
+
import { dirname, join as join2 } from "path";
|
|
27644
27644
|
import { fileURLToPath } from "url";
|
|
27645
27645
|
import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
|
|
27646
|
+
|
|
27647
|
+
// src/lib/lock.ts
|
|
27648
|
+
import { openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, renameSync } from "fs";
|
|
27649
|
+
var STALE_MS = 15e3;
|
|
27650
|
+
var LOCK_TIMEOUT_MS = 1e4;
|
|
27651
|
+
function isAlive(pid) {
|
|
27652
|
+
if (!pid || pid <= 0) return false;
|
|
27653
|
+
try {
|
|
27654
|
+
process.kill(pid, 0);
|
|
27655
|
+
return true;
|
|
27656
|
+
} catch {
|
|
27657
|
+
return false;
|
|
27658
|
+
}
|
|
27659
|
+
}
|
|
27660
|
+
function tryAcquire(lockFile) {
|
|
27661
|
+
if (existsSync(lockFile)) {
|
|
27662
|
+
const age = Date.now() - statSync(lockFile).mtimeMs;
|
|
27663
|
+
let stale = age > STALE_MS;
|
|
27664
|
+
if (!stale) {
|
|
27665
|
+
try {
|
|
27666
|
+
const pid = parseInt(readFileSync(lockFile, "utf-8").trim(), 10);
|
|
27667
|
+
if (!isAlive(pid)) stale = true;
|
|
27668
|
+
} catch {
|
|
27669
|
+
stale = true;
|
|
27670
|
+
}
|
|
27671
|
+
}
|
|
27672
|
+
if (stale) {
|
|
27673
|
+
try {
|
|
27674
|
+
unlinkSync(lockFile);
|
|
27675
|
+
} catch {
|
|
27676
|
+
}
|
|
27677
|
+
} else {
|
|
27678
|
+
return false;
|
|
27679
|
+
}
|
|
27680
|
+
}
|
|
27681
|
+
try {
|
|
27682
|
+
const fd = openSync(lockFile, "wx");
|
|
27683
|
+
writeFileSync(fd, String(process.pid));
|
|
27684
|
+
closeSync(fd);
|
|
27685
|
+
return true;
|
|
27686
|
+
} catch {
|
|
27687
|
+
return false;
|
|
27688
|
+
}
|
|
27689
|
+
}
|
|
27690
|
+
var held = /* @__PURE__ */ new Map();
|
|
27691
|
+
function withLockSync(file2, fn) {
|
|
27692
|
+
const lockFile = `${file2}.lock`;
|
|
27693
|
+
const depth = held.get(lockFile) ?? 0;
|
|
27694
|
+
if (depth > 0) {
|
|
27695
|
+
held.set(lockFile, depth + 1);
|
|
27696
|
+
try {
|
|
27697
|
+
fn();
|
|
27698
|
+
} finally {
|
|
27699
|
+
const d = (held.get(lockFile) ?? 0) - 1;
|
|
27700
|
+
if (d <= 0) held.delete(lockFile);
|
|
27701
|
+
else held.set(lockFile, d);
|
|
27702
|
+
}
|
|
27703
|
+
return;
|
|
27704
|
+
}
|
|
27705
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
27706
|
+
while (!tryAcquire(lockFile)) {
|
|
27707
|
+
if (Date.now() > deadline) throw new Error(`toon-memory lock timeout: ${file2}`);
|
|
27708
|
+
const t = Date.now() + 10;
|
|
27709
|
+
while (Date.now() < t) {
|
|
27710
|
+
}
|
|
27711
|
+
}
|
|
27712
|
+
held.set(lockFile, 1);
|
|
27713
|
+
try {
|
|
27714
|
+
fn();
|
|
27715
|
+
} finally {
|
|
27716
|
+
const d = (held.get(lockFile) ?? 0) - 1;
|
|
27717
|
+
if (d <= 0) {
|
|
27718
|
+
held.delete(lockFile);
|
|
27719
|
+
try {
|
|
27720
|
+
unlinkSync(lockFile);
|
|
27721
|
+
} catch {
|
|
27722
|
+
}
|
|
27723
|
+
} else {
|
|
27724
|
+
held.set(lockFile, d);
|
|
27725
|
+
}
|
|
27726
|
+
}
|
|
27727
|
+
}
|
|
27728
|
+
function atomicWrite(file2, content) {
|
|
27729
|
+
const tmp = `${file2}.tmp`;
|
|
27730
|
+
writeFileSync(tmp, content);
|
|
27731
|
+
renameSync(tmp, file2);
|
|
27732
|
+
}
|
|
27733
|
+
function readUnderLock(file2, encoding = "utf-8") {
|
|
27734
|
+
let content = "";
|
|
27735
|
+
withLockSync(file2, () => {
|
|
27736
|
+
content = readFileSync(file2, encoding);
|
|
27737
|
+
});
|
|
27738
|
+
return content;
|
|
27739
|
+
}
|
|
27740
|
+
|
|
27741
|
+
// src/lib/sessions.ts
|
|
27742
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, readdirSync, unlinkSync as unlinkSync2 } from "fs";
|
|
27743
|
+
import { join } from "path";
|
|
27744
|
+
import { execSync } from "child_process";
|
|
27745
|
+
var SESSION_TTL_MS = 10 * 60 * 1e3;
|
|
27746
|
+
var PRUNE_STALE_MS = 10 * 60 * 1e3;
|
|
27747
|
+
function isAlive2(pid) {
|
|
27748
|
+
if (!pid || pid <= 0) return false;
|
|
27749
|
+
try {
|
|
27750
|
+
process.kill(pid, 0);
|
|
27751
|
+
return true;
|
|
27752
|
+
} catch {
|
|
27753
|
+
return false;
|
|
27754
|
+
}
|
|
27755
|
+
}
|
|
27756
|
+
function sessionDir() {
|
|
27757
|
+
return join(process.cwd(), ".toon-memory", "memory", "sessions");
|
|
27758
|
+
}
|
|
27759
|
+
function resolveSessionId(payload = {}) {
|
|
27760
|
+
const fromPayload = payload.session_id || payload.sessionId || payload.session_id_untruncated;
|
|
27761
|
+
if (fromPayload && fromPayload.trim()) return fromPayload.trim();
|
|
27762
|
+
if (process.env.TOON_MEMORY_SESSION_ID && process.env.TOON_MEMORY_SESSION_ID.trim()) {
|
|
27763
|
+
return process.env.TOON_MEMORY_SESSION_ID.trim();
|
|
27764
|
+
}
|
|
27765
|
+
return `proc-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
|
|
27766
|
+
}
|
|
27767
|
+
function currentBranch() {
|
|
27768
|
+
if (process.env.TOON_MEMORY_BRANCH && process.env.TOON_MEMORY_BRANCH.trim()) {
|
|
27769
|
+
return process.env.TOON_MEMORY_BRANCH.trim();
|
|
27770
|
+
}
|
|
27771
|
+
try {
|
|
27772
|
+
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
|
|
27773
|
+
encoding: "utf-8",
|
|
27774
|
+
timeout: 2e3,
|
|
27775
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
27776
|
+
}).trim();
|
|
27777
|
+
return branch || "unknown";
|
|
27778
|
+
} catch {
|
|
27779
|
+
return "unknown";
|
|
27780
|
+
}
|
|
27781
|
+
}
|
|
27782
|
+
function recentIso(iso) {
|
|
27783
|
+
const t = new Date(iso).getTime();
|
|
27784
|
+
return !isNaN(t) && Date.now() - t <= SESSION_TTL_MS;
|
|
27785
|
+
}
|
|
27786
|
+
function listSessions() {
|
|
27787
|
+
const dir = sessionDir();
|
|
27788
|
+
if (!existsSync2(dir)) return [];
|
|
27789
|
+
return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => {
|
|
27790
|
+
try {
|
|
27791
|
+
return JSON.parse(readFileSync2(join(dir, f), "utf-8"));
|
|
27792
|
+
} catch {
|
|
27793
|
+
return null;
|
|
27794
|
+
}
|
|
27795
|
+
}).filter(Boolean).map((r) => {
|
|
27796
|
+
const rec = r;
|
|
27797
|
+
const active = recentIso(rec.lastSeen);
|
|
27798
|
+
return { ...rec, active, ageMs: Date.now() - new Date(rec.lastSeen).getTime() };
|
|
27799
|
+
}).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
|
|
27800
|
+
}
|
|
27801
|
+
function pruneSessions() {
|
|
27802
|
+
const pruned = [];
|
|
27803
|
+
const dir = sessionDir();
|
|
27804
|
+
if (!existsSync2(dir)) return pruned;
|
|
27805
|
+
for (const f of readdirSync(dir).filter((x) => x.endsWith(".json"))) {
|
|
27806
|
+
const p = join(dir, f);
|
|
27807
|
+
let rec = null;
|
|
27808
|
+
try {
|
|
27809
|
+
rec = JSON.parse(readFileSync2(p, "utf-8"));
|
|
27810
|
+
} catch {
|
|
27811
|
+
continue;
|
|
27812
|
+
}
|
|
27813
|
+
if (!rec) continue;
|
|
27814
|
+
const stale = Date.now() - new Date(rec.lastSeen).getTime() > PRUNE_STALE_MS;
|
|
27815
|
+
if (stale && !isAlive2(rec.pid)) {
|
|
27816
|
+
try {
|
|
27817
|
+
unlinkSync2(p);
|
|
27818
|
+
pruned.push(rec.id);
|
|
27819
|
+
} catch {
|
|
27820
|
+
}
|
|
27821
|
+
}
|
|
27822
|
+
}
|
|
27823
|
+
return pruned;
|
|
27824
|
+
}
|
|
27825
|
+
function detectConflicts(active = listSessions().filter((s) => s.active)) {
|
|
27826
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
27827
|
+
for (const s of active) {
|
|
27828
|
+
if (s.ended) continue;
|
|
27829
|
+
for (const file2 of Object.keys(s.files)) {
|
|
27830
|
+
if (!byFile.has(file2)) byFile.set(file2, []);
|
|
27831
|
+
byFile.get(file2).push({ id: s.id, agent: s.agent, branch: s.branch });
|
|
27832
|
+
}
|
|
27833
|
+
}
|
|
27834
|
+
const conflicts = [];
|
|
27835
|
+
for (const [file2, sessions] of byFile) {
|
|
27836
|
+
if (sessions.length >= 2) conflicts.push({ file: file2, sessions });
|
|
27837
|
+
}
|
|
27838
|
+
return conflicts;
|
|
27839
|
+
}
|
|
27840
|
+
function coordinationView(selfId) {
|
|
27841
|
+
const all = listSessions();
|
|
27842
|
+
const active = all.filter((s) => s.active);
|
|
27843
|
+
const conflicts = detectConflicts(active);
|
|
27844
|
+
const self = selfId ? all.find((s) => s.id === selfId) : void 0;
|
|
27845
|
+
pruneSessions();
|
|
27846
|
+
return { active, conflicts, self };
|
|
27847
|
+
}
|
|
27848
|
+
|
|
27849
|
+
// src/lib/graph.ts
|
|
27850
|
+
var isExpiredLocal = (ttl) => {
|
|
27851
|
+
if (!ttl) return false;
|
|
27852
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
27853
|
+
return ttl <= today;
|
|
27854
|
+
};
|
|
27855
|
+
var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
27856
|
+
var entryLines = (data) => data.split("\n").filter(
|
|
27857
|
+
(l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
|
|
27858
|
+
);
|
|
27859
|
+
function parseEntries(data) {
|
|
27860
|
+
const out = [];
|
|
27861
|
+
for (const line of entryLines(data)) {
|
|
27862
|
+
const parts = line.trim().split("|");
|
|
27863
|
+
if (parts.length < 7) continue;
|
|
27864
|
+
const [id, category, key, content, file2, tags, date5, ttl, accessedRaw, linksRaw] = parts;
|
|
27865
|
+
out.push({
|
|
27866
|
+
id,
|
|
27867
|
+
category,
|
|
27868
|
+
key,
|
|
27869
|
+
content,
|
|
27870
|
+
file: file2 || "",
|
|
27871
|
+
tags: (tags || "").split(";").map((t) => t.trim()).filter(Boolean),
|
|
27872
|
+
date: date5 || "",
|
|
27873
|
+
ttl: ttl || "",
|
|
27874
|
+
accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
|
|
27875
|
+
links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean)
|
|
27876
|
+
});
|
|
27877
|
+
}
|
|
27878
|
+
return out;
|
|
27879
|
+
}
|
|
27880
|
+
function buildGraph(entries) {
|
|
27881
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
27882
|
+
for (const e of entries) {
|
|
27883
|
+
if (!byKey.has(e.key)) byKey.set(e.key, e);
|
|
27884
|
+
}
|
|
27885
|
+
const adj = /* @__PURE__ */ new Map();
|
|
27886
|
+
const link = (a, b) => {
|
|
27887
|
+
if (a === b) return;
|
|
27888
|
+
if (!byKey.has(a) || !byKey.has(b)) return;
|
|
27889
|
+
if (!adj.has(a)) adj.set(a, /* @__PURE__ */ new Set());
|
|
27890
|
+
adj.get(a).add(b);
|
|
27891
|
+
if (!adj.has(b)) adj.set(b, /* @__PURE__ */ new Set());
|
|
27892
|
+
adj.get(b).add(a);
|
|
27893
|
+
};
|
|
27894
|
+
for (const e of entries) {
|
|
27895
|
+
for (const l of e.links) link(e.key, l);
|
|
27896
|
+
const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || [];
|
|
27897
|
+
for (const r of refs) link(e.key, r.slice(2, -2));
|
|
27898
|
+
}
|
|
27899
|
+
const adjacency = /* @__PURE__ */ new Map();
|
|
27900
|
+
for (const [k, v] of adj) adjacency.set(k, [...v]);
|
|
27901
|
+
return { adjacency, byKey };
|
|
27902
|
+
}
|
|
27903
|
+
var importance = (e) => {
|
|
27904
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
27905
|
+
const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
|
|
27906
|
+
const recency = Math.max(0, 30 - days) / 30;
|
|
27907
|
+
const freq = Math.min(1, e.accessed / 5);
|
|
27908
|
+
return recency * 0.6 + freq * 0.4;
|
|
27909
|
+
};
|
|
27910
|
+
function graphRecall(data, query, opts = {}) {
|
|
27911
|
+
const entries = parseEntries(data);
|
|
27912
|
+
const { adjacency, byKey } = buildGraph(entries);
|
|
27913
|
+
const hops = Math.max(1, Math.min(2, opts.hops ?? 1));
|
|
27914
|
+
const category = opts.category || "";
|
|
27915
|
+
const from_date = opts.from_date || "";
|
|
27916
|
+
const to_date = opts.to_date || "";
|
|
27917
|
+
const queryTokens = normalize(query).split(" ").filter(Boolean);
|
|
27918
|
+
const seedScore = /* @__PURE__ */ new Map();
|
|
27919
|
+
for (const e of entries) {
|
|
27920
|
+
if (category && e.category !== category) continue;
|
|
27921
|
+
if (from_date && e.date < from_date) continue;
|
|
27922
|
+
if (to_date && e.date > to_date) continue;
|
|
27923
|
+
if (e.ttl && isExpiredLocal(e.ttl)) continue;
|
|
27924
|
+
const searchStr = normalize(
|
|
27925
|
+
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
27926
|
+
);
|
|
27927
|
+
if (queryTokens.length > 0 && !queryTokens.every((t) => searchStr.includes(t)))
|
|
27928
|
+
continue;
|
|
27929
|
+
seedScore.set(e.key, importance(e) + 1);
|
|
27930
|
+
}
|
|
27931
|
+
if (seedScore.size === 0) {
|
|
27932
|
+
return [...entries].sort((a, b) => importance(b) - importance(a)).slice(0, opts.limit ?? 6);
|
|
27933
|
+
}
|
|
27934
|
+
const best = /* @__PURE__ */ new Map();
|
|
27935
|
+
const queue = [];
|
|
27936
|
+
for (const k of seedScore.keys()) queue.push({ key: k, dist: 0 });
|
|
27937
|
+
while (queue.length) {
|
|
27938
|
+
const { key, dist } = queue.shift();
|
|
27939
|
+
if (best.has(key) && best.get(key) <= dist) continue;
|
|
27940
|
+
best.set(key, dist);
|
|
27941
|
+
if (dist >= hops) continue;
|
|
27942
|
+
for (const nb of adjacency.get(key) || []) {
|
|
27943
|
+
queue.push({ key: nb, dist: dist + 1 });
|
|
27944
|
+
}
|
|
27945
|
+
}
|
|
27946
|
+
const scored = [...best.keys()].map((k) => {
|
|
27947
|
+
const e = byKey.get(k);
|
|
27948
|
+
let s = importance(e);
|
|
27949
|
+
if (seedScore.has(k)) s += 1;
|
|
27950
|
+
else s += 0.6 / best.get(k);
|
|
27951
|
+
return { e, s };
|
|
27952
|
+
}).sort((a, b) => b.s - a.s);
|
|
27953
|
+
return scored.slice(0, opts.limit ?? 6).map((x) => x.e);
|
|
27954
|
+
}
|
|
27955
|
+
|
|
27956
|
+
// src/mcp/server.ts
|
|
27646
27957
|
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
27647
|
-
var MEMORY_DIR =
|
|
27648
|
-
var MEMORY_FILE =
|
|
27649
|
-
var ARCHIVE_FILE =
|
|
27650
|
-
var
|
|
27958
|
+
var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
|
|
27959
|
+
var MEMORY_FILE = join2(MEMORY_DIR, "data.toon");
|
|
27960
|
+
var ARCHIVE_FILE = join2(MEMORY_DIR, "archive.toon");
|
|
27961
|
+
var OBSERVATIONS_FILE = join2(MEMORY_DIR, "observations.toon");
|
|
27962
|
+
var CONFIG_FILE = join2(MEMORY_DIR, "config.json");
|
|
27651
27963
|
var MAX_ENTRIES = 100;
|
|
27652
27964
|
var ARCHIVE_DAYS = 30;
|
|
27965
|
+
function safeWrite(file2, content) {
|
|
27966
|
+
withLockSync(file2, () => atomicWrite(file2, content));
|
|
27967
|
+
}
|
|
27653
27968
|
var ALGORITHM = "aes-256-gcm";
|
|
27654
27969
|
function loadConfig() {
|
|
27655
|
-
if (!
|
|
27970
|
+
if (!existsSync3(CONFIG_FILE)) {
|
|
27656
27971
|
return { encrypted: false };
|
|
27657
27972
|
}
|
|
27658
27973
|
try {
|
|
27659
|
-
return JSON.parse(
|
|
27974
|
+
return JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
|
|
27660
27975
|
} catch {
|
|
27661
27976
|
return { encrypted: false };
|
|
27662
27977
|
}
|
|
27663
27978
|
}
|
|
27664
27979
|
function saveConfig(config2) {
|
|
27665
27980
|
ensureMemoryDir();
|
|
27666
|
-
|
|
27981
|
+
writeFileSync3(CONFIG_FILE, JSON.stringify(config2, null, 2));
|
|
27667
27982
|
}
|
|
27668
27983
|
function getKey() {
|
|
27669
27984
|
return process.env.TOON_MEMORY_KEY;
|
|
27670
27985
|
}
|
|
27671
27986
|
function ensureMemoryDir() {
|
|
27672
|
-
if (!
|
|
27987
|
+
if (!existsSync3(MEMORY_DIR)) mkdirSync2(MEMORY_DIR, { recursive: true });
|
|
27673
27988
|
}
|
|
27674
27989
|
function ensureMemoryFile() {
|
|
27675
27990
|
ensureMemoryDir();
|
|
27676
|
-
if (!
|
|
27677
|
-
|
|
27991
|
+
if (!existsSync3(MEMORY_FILE)) {
|
|
27992
|
+
writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n");
|
|
27678
27993
|
}
|
|
27679
27994
|
}
|
|
27680
27995
|
function encrypt(text, key) {
|
|
@@ -27688,7 +28003,11 @@ function encrypt(text, key) {
|
|
|
27688
28003
|
}
|
|
27689
28004
|
function decrypt(encryptedData, key) {
|
|
27690
28005
|
const keyBuffer = Buffer.from(key, "hex");
|
|
27691
|
-
const
|
|
28006
|
+
const parts = encryptedData.split(":");
|
|
28007
|
+
if (parts.length !== 3) {
|
|
28008
|
+
throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext");
|
|
28009
|
+
}
|
|
28010
|
+
const [ivHex, authTagHex, encrypted] = parts;
|
|
27692
28011
|
const iv = Buffer.from(ivHex, "hex");
|
|
27693
28012
|
const authTag = Buffer.from(authTagHex, "hex");
|
|
27694
28013
|
const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv);
|
|
@@ -27700,7 +28019,7 @@ function decrypt(encryptedData, key) {
|
|
|
27700
28019
|
function readMemory() {
|
|
27701
28020
|
ensureMemoryFile();
|
|
27702
28021
|
const config2 = loadConfig();
|
|
27703
|
-
const data =
|
|
28022
|
+
const data = readUnderLock(MEMORY_FILE);
|
|
27704
28023
|
if (config2.encrypted) {
|
|
27705
28024
|
const key = getKey();
|
|
27706
28025
|
if (!key) return "";
|
|
@@ -27719,10 +28038,10 @@ function writeMemory(content) {
|
|
|
27719
28038
|
const key = getKey();
|
|
27720
28039
|
if (!key) return;
|
|
27721
28040
|
const encrypted = encrypt(content, key);
|
|
27722
|
-
|
|
28041
|
+
safeWrite(MEMORY_FILE, encrypted);
|
|
27723
28042
|
return;
|
|
27724
28043
|
}
|
|
27725
|
-
|
|
28044
|
+
safeWrite(MEMORY_FILE, content);
|
|
27726
28045
|
}
|
|
27727
28046
|
function generateId() {
|
|
27728
28047
|
return randomBytes(4).toString("hex");
|
|
@@ -27796,18 +28115,18 @@ function parseRelativeDate(since) {
|
|
|
27796
28115
|
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
27797
28116
|
return today;
|
|
27798
28117
|
}
|
|
27799
|
-
var
|
|
28118
|
+
var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
27800
28119
|
function findRelatedEntries(text, excludeKey = "", limit = 3) {
|
|
27801
28120
|
const data = readMemory();
|
|
27802
28121
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
|
|
27803
|
-
const queryTokens =
|
|
28122
|
+
const queryTokens = normalize2(text).split(" ").filter(Boolean);
|
|
27804
28123
|
const scored = lines.map((line) => {
|
|
27805
28124
|
const trimmed = line.trim();
|
|
27806
28125
|
const parts = trimmed.split("|");
|
|
27807
28126
|
if (parts.length < 7) return null;
|
|
27808
28127
|
const [id, cat, key, content, file2, tags, date5] = parts;
|
|
27809
28128
|
if (key === excludeKey) return null;
|
|
27810
|
-
const searchStr =
|
|
28129
|
+
const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
|
|
27811
28130
|
let score = 0;
|
|
27812
28131
|
for (const token of queryTokens) {
|
|
27813
28132
|
if (searchStr.includes(token)) score++;
|
|
@@ -27817,7 +28136,46 @@ function findRelatedEntries(text, excludeKey = "", limit = 3) {
|
|
|
27817
28136
|
}).filter(Boolean).sort((a, b) => b.score - a.score).slice(0, limit);
|
|
27818
28137
|
return scored;
|
|
27819
28138
|
}
|
|
27820
|
-
function
|
|
28139
|
+
function entryScore(dateStr, accessed) {
|
|
28140
|
+
const days = (Date.now() - (/* @__PURE__ */ new Date(`${dateStr}T00:00:00`)).getTime()) / 864e5;
|
|
28141
|
+
const recency = Math.max(0, 30 - days) / 30;
|
|
28142
|
+
const freq = Math.min(1, accessed / 5);
|
|
28143
|
+
return recency * 0.6 + freq * 0.4;
|
|
28144
|
+
}
|
|
28145
|
+
function entryScoreForLine(line) {
|
|
28146
|
+
const parts = line.trim().split("|");
|
|
28147
|
+
const date5 = parts[6] || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
28148
|
+
const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0;
|
|
28149
|
+
return entryScore(date5, accessed);
|
|
28150
|
+
}
|
|
28151
|
+
function bumpAccessed(ids) {
|
|
28152
|
+
if (ids.length === 0) return;
|
|
28153
|
+
const idSet = new Set(ids);
|
|
28154
|
+
const data = readMemory();
|
|
28155
|
+
const lines = data.split("\n");
|
|
28156
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
28157
|
+
if (headerIdx === -1) return;
|
|
28158
|
+
for (let i = headerIdx + 1; i < lines.length; i++) {
|
|
28159
|
+
const line = lines[i];
|
|
28160
|
+
if (!line.startsWith(" ") || !line.includes("|")) continue;
|
|
28161
|
+
if (line.startsWith(" summaries:")) break;
|
|
28162
|
+
const parts = line.trim().split("|");
|
|
28163
|
+
if (idSet.has(parts[0])) {
|
|
28164
|
+
const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1;
|
|
28165
|
+
parts[8] = String(accessed);
|
|
28166
|
+
lines[i] = ` ${parts.join("|")}`;
|
|
28167
|
+
}
|
|
28168
|
+
}
|
|
28169
|
+
writeMemory(lines.join("\n"));
|
|
28170
|
+
}
|
|
28171
|
+
function readObservations() {
|
|
28172
|
+
if (!existsSync3(OBSERVATIONS_FILE)) return [];
|
|
28173
|
+
return readFileSync3(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
|
|
28174
|
+
const p = l.trim().split("|");
|
|
28175
|
+
return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" };
|
|
28176
|
+
});
|
|
28177
|
+
}
|
|
28178
|
+
function archiveOldEntries(opts = {}) {
|
|
27821
28179
|
const data = readMemory();
|
|
27822
28180
|
const lines = data.split("\n");
|
|
27823
28181
|
const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
|
|
@@ -27826,29 +28184,29 @@ function archiveOldEntries() {
|
|
|
27826
28184
|
const cutoff = new Date(today);
|
|
27827
28185
|
cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS);
|
|
27828
28186
|
const cutoffStr = cutoff.toISOString().split("T")[0];
|
|
27829
|
-
const
|
|
27830
|
-
const toArchive =
|
|
27831
|
-
|
|
27832
|
-
for (const line of entryLines) {
|
|
28187
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
|
|
28188
|
+
const toArchive = /* @__PURE__ */ new Set();
|
|
28189
|
+
entryLines2.forEach((line, idx) => {
|
|
27833
28190
|
const parts = line.trim().split("|");
|
|
27834
|
-
if (parts.length
|
|
27835
|
-
|
|
27836
|
-
|
|
27837
|
-
|
|
27838
|
-
|
|
27839
|
-
|
|
27840
|
-
|
|
27841
|
-
|
|
27842
|
-
|
|
27843
|
-
}
|
|
27844
|
-
|
|
27845
|
-
toKeep.push(line.trim());
|
|
28191
|
+
if (parts.length < 7) return;
|
|
28192
|
+
const date5 = parts[6];
|
|
28193
|
+
const ttl = parts[7] || "";
|
|
28194
|
+
if (date5 < cutoffStr || ttl && isExpired(ttl)) toArchive.add(idx);
|
|
28195
|
+
});
|
|
28196
|
+
if (opts.trimToMax) {
|
|
28197
|
+
const remaining = entryLines2.length - toArchive.size;
|
|
28198
|
+
if (remaining > MAX_ENTRIES) {
|
|
28199
|
+
const need = remaining - MAX_ENTRIES;
|
|
28200
|
+
const candidates = entryLines2.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c) => !toArchive.has(c.idx)).sort((a, b) => a.score - b.score);
|
|
28201
|
+
for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx);
|
|
27846
28202
|
}
|
|
27847
28203
|
}
|
|
27848
|
-
if (toArchive.
|
|
28204
|
+
if (toArchive.size === 0) return { archived: 0, kept: entryLines2.length };
|
|
28205
|
+
const toArchiveLines = entryLines2.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim());
|
|
28206
|
+
const toKeepLines = entryLines2.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim());
|
|
27849
28207
|
let archiveContent = "";
|
|
27850
|
-
if (
|
|
27851
|
-
archiveContent =
|
|
28208
|
+
if (existsSync3(ARCHIVE_FILE)) {
|
|
28209
|
+
archiveContent = readFileSync3(ARCHIVE_FILE, "utf-8");
|
|
27852
28210
|
} else {
|
|
27853
28211
|
archiveContent = `version: 1
|
|
27854
28212
|
archived:
|
|
@@ -27862,18 +28220,83 @@ archived:
|
|
|
27862
28220
|
}
|
|
27863
28221
|
const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/);
|
|
27864
28222
|
const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0;
|
|
27865
|
-
for (const entry of
|
|
28223
|
+
for (const entry of toArchiveLines) {
|
|
27866
28224
|
archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`);
|
|
27867
28225
|
}
|
|
27868
|
-
archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount +
|
|
27869
|
-
|
|
27870
|
-
lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${
|
|
27871
|
-
|
|
28226
|
+
archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`);
|
|
28227
|
+
safeWrite(ARCHIVE_FILE, archiveLines.join("\n"));
|
|
28228
|
+
lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`);
|
|
28229
|
+
const keepSet = new Set(toKeepLines);
|
|
28230
|
+
const allEntryLines = lines.slice(headerIdx + 1);
|
|
28231
|
+
const newEntryLines = allEntryLines.filter((l) => {
|
|
28232
|
+
if (l.trim().length === 0) return false;
|
|
28233
|
+
return keepSet.has(l.trim());
|
|
28234
|
+
});
|
|
28235
|
+
lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`));
|
|
28236
|
+
writeMemory(lines.join("\n"));
|
|
28237
|
+
return { archived: toArchiveLines.length, kept: toKeepLines.length };
|
|
28238
|
+
}
|
|
28239
|
+
function pruneExpiredEntries() {
|
|
28240
|
+
ensureMemoryFile();
|
|
28241
|
+
if (!existsSync3(MEMORY_FILE)) return 0;
|
|
28242
|
+
let pruned = 0;
|
|
28243
|
+
withLockSync(MEMORY_FILE, () => {
|
|
28244
|
+
const data = readMemory();
|
|
28245
|
+
const lines = data.split("\n");
|
|
28246
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
|
|
28247
|
+
if (headerIdx === -1) return;
|
|
28248
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
|
|
28249
|
+
const kept = entryLines2.filter((l) => {
|
|
28250
|
+
const parts = l.trim().split("|");
|
|
28251
|
+
if (parts.length < 8) return true;
|
|
28252
|
+
const ttl = parts[7] || "";
|
|
28253
|
+
if (ttl && isExpired(ttl)) {
|
|
28254
|
+
pruned++;
|
|
28255
|
+
return false;
|
|
28256
|
+
}
|
|
28257
|
+
return true;
|
|
28258
|
+
});
|
|
28259
|
+
if (pruned === 0) return;
|
|
28260
|
+
lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`);
|
|
28261
|
+
const keepSet = new Set(kept.map((l) => l.trim()));
|
|
28262
|
+
const allEntryLines = lines.slice(headerIdx + 1);
|
|
28263
|
+
const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()));
|
|
28264
|
+
lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => l.trim().length ? ` ${l.trim()}` : l));
|
|
28265
|
+
writeMemory(lines.join("\n"));
|
|
28266
|
+
});
|
|
28267
|
+
return pruned;
|
|
28268
|
+
}
|
|
28269
|
+
function consolidateEntries() {
|
|
28270
|
+
const data = readMemory();
|
|
28271
|
+
const lines = data.split("\n");
|
|
28272
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
|
|
28273
|
+
if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
|
|
28274
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
|
|
28275
|
+
const seen = /* @__PURE__ */ new Map();
|
|
28276
|
+
const order = [];
|
|
28277
|
+
const duplicates = [];
|
|
28278
|
+
for (const line of entryLines2) {
|
|
28279
|
+
const parts = line.trim().split("|");
|
|
28280
|
+
if (parts.length < 3) {
|
|
28281
|
+
order.push(line.trim());
|
|
28282
|
+
continue;
|
|
28283
|
+
}
|
|
28284
|
+
const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
28285
|
+
if (seen.has(content)) {
|
|
28286
|
+
duplicates.push(parts[2]);
|
|
28287
|
+
continue;
|
|
28288
|
+
}
|
|
28289
|
+
seen.set(content, line.trim());
|
|
28290
|
+
order.push(line.trim());
|
|
28291
|
+
}
|
|
28292
|
+
if (duplicates.length === 0) return { removed: 0, kept: order.length, duplicates: [] };
|
|
28293
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`);
|
|
28294
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`));
|
|
27872
28295
|
writeMemory(lines.join("\n"));
|
|
27873
|
-
return {
|
|
28296
|
+
return { removed: duplicates.length, kept: order.length, duplicates };
|
|
27874
28297
|
}
|
|
27875
28298
|
var server = new McpServer(
|
|
27876
|
-
{ name: "toon-memory", version: "2.
|
|
28299
|
+
{ name: "toon-memory", version: "2.2.0" },
|
|
27877
28300
|
{ capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
|
|
27878
28301
|
);
|
|
27879
28302
|
server.registerResource(
|
|
@@ -27937,10 +28360,11 @@ server.registerTool(
|
|
|
27937
28360
|
content: external_exports.string().describe("Contenido detallado del hecho"),
|
|
27938
28361
|
file: external_exports.string().optional().default("").describe("Archivo o l\xEDnea relacionada (ej: spec.md:145)"),
|
|
27939
28362
|
tags: external_exports.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
|
|
27940
|
-
ttl: external_exports.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vac\xEDo = sin expiraci\xF3n")
|
|
28363
|
+
ttl: external_exports.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vac\xEDo = sin expiraci\xF3n"),
|
|
28364
|
+
links: external_exports.string().optional().default("").describe("Entradas relacionadas por key, separadas por espacio o ';' (ej: risk-spec engine-arch). Construye aristas del grafo de memoria.")
|
|
27941
28365
|
}
|
|
27942
28366
|
},
|
|
27943
|
-
async ({ category, key, content, file: file2, tags, ttl }) => {
|
|
28367
|
+
async ({ category, key, content, file: file2, tags, ttl, links }) => {
|
|
27944
28368
|
const data = readMemory();
|
|
27945
28369
|
const newId = generateId();
|
|
27946
28370
|
const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
@@ -27966,7 +28390,9 @@ server.registerTool(
|
|
|
27966
28390
|
const entryId = existingIdx !== -1 ? existingId : newId;
|
|
27967
28391
|
const resolvedTtl = parseTTL(ttl);
|
|
27968
28392
|
const resolvedTags = tags ? tags : inferTags(content, key);
|
|
27969
|
-
const
|
|
28393
|
+
const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
|
|
28394
|
+
const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
|
|
28395
|
+
const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
|
|
27970
28396
|
let action = "Guardado";
|
|
27971
28397
|
const tagsInferred = !tags && resolvedTags ? true : false;
|
|
27972
28398
|
if (existingIdx !== -1) {
|
|
@@ -27983,10 +28409,10 @@ server.registerTool(
|
|
|
27983
28409
|
const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0;
|
|
27984
28410
|
let archiveMsg = "";
|
|
27985
28411
|
if (entryCount > MAX_ENTRIES) {
|
|
27986
|
-
const result = archiveOldEntries();
|
|
28412
|
+
const result = archiveOldEntries({ trimToMax: true });
|
|
27987
28413
|
if (result.archived > 0) {
|
|
27988
28414
|
archiveMsg = `
|
|
27989
|
-
\u{1F4E6} Auto-archived ${result.archived}
|
|
28415
|
+
\u{1F4E6} Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`;
|
|
27990
28416
|
}
|
|
27991
28417
|
}
|
|
27992
28418
|
const ttlMsg = resolvedTtl ? `
|
|
@@ -28017,31 +28443,51 @@ server.registerTool(
|
|
|
28017
28443
|
query: external_exports.string().describe("Texto a buscar"),
|
|
28018
28444
|
category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)"),
|
|
28019
28445
|
from_date: external_exports.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
|
|
28020
|
-
to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)")
|
|
28446
|
+
to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
|
|
28447
|
+
mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = b\xFAsqueda por palabra clave (default). 'graph' = recall basado en grafo: expande el subgrafo de entradas relacionadas desde las coincidencias (m\xE1s preciso, menos tokens)."),
|
|
28448
|
+
hops: external_exports.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1.")
|
|
28021
28449
|
}
|
|
28022
28450
|
},
|
|
28023
|
-
async ({ query, category, from_date, to_date }) => {
|
|
28451
|
+
async ({ query, category, from_date, to_date, mode, hops }) => {
|
|
28024
28452
|
const data = readMemory();
|
|
28025
|
-
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith("summaries:"));
|
|
28026
|
-
const
|
|
28027
|
-
const queryTokens =
|
|
28453
|
+
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
|
|
28454
|
+
const normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
|
|
28455
|
+
const queryTokens = normalize3(query).split(" ").filter(Boolean);
|
|
28028
28456
|
const results = lines.map((line) => {
|
|
28029
28457
|
const trimmed = line.trim();
|
|
28030
28458
|
const parts = trimmed.split("|");
|
|
28031
28459
|
if (parts.length < 7) return null;
|
|
28032
|
-
const [id, cat, key, content, file2, tags, date5, ttl] = parts;
|
|
28460
|
+
const [id, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
|
|
28033
28461
|
if (category && cat !== category) return null;
|
|
28034
28462
|
if (from_date && date5 < from_date) return null;
|
|
28035
28463
|
if (to_date && date5 > to_date) return null;
|
|
28036
28464
|
if (ttl && isExpired(ttl)) return null;
|
|
28037
|
-
const searchStr =
|
|
28465
|
+
const searchStr = normalize3(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
|
|
28038
28466
|
if (!queryTokens.every((token) => searchStr.includes(token))) return null;
|
|
28039
|
-
|
|
28467
|
+
const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
|
|
28468
|
+
return { id, cat, key, content, file: file2, tags, date: date5, accessed };
|
|
28040
28469
|
}).filter(Boolean);
|
|
28041
28470
|
if (results.length === 0) {
|
|
28042
28471
|
return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
|
|
28043
28472
|
}
|
|
28044
|
-
|
|
28473
|
+
if (mode === "graph") {
|
|
28474
|
+
const subgraph = graphRecall(data, query, { category, from_date, to_date, hops });
|
|
28475
|
+
if (subgraph.length === 0) {
|
|
28476
|
+
return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
|
|
28477
|
+
}
|
|
28478
|
+
bumpAccessed(subgraph.map((e) => e.id));
|
|
28479
|
+
const formatted2 = subgraph.map((r) => {
|
|
28480
|
+
const links = r.links.length ? `
|
|
28481
|
+
links: ${r.links.join(", ")}` : "";
|
|
28482
|
+
return `[${r.category}] ${r.key} (${r.id})
|
|
28483
|
+
${r.content}
|
|
28484
|
+
File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`;
|
|
28485
|
+
}).join("\n\n");
|
|
28486
|
+
return { content: [{ type: "text", text: formatted2 }] };
|
|
28487
|
+
}
|
|
28488
|
+
const ranked = results.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) })).sort((a, b) => b.score - a.score);
|
|
28489
|
+
bumpAccessed(ranked.map((r) => r.id));
|
|
28490
|
+
const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
|
|
28045
28491
|
${r.content}
|
|
28046
28492
|
File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
|
|
28047
28493
|
return { content: [{ type: "text", text: formatted }] };
|
|
@@ -28063,16 +28509,16 @@ server.registerTool(
|
|
|
28063
28509
|
if (headerIdx === -1) {
|
|
28064
28510
|
return { content: [{ type: "text", text: "No hay entradas en memoria" }] };
|
|
28065
28511
|
}
|
|
28066
|
-
const
|
|
28067
|
-
const filtered =
|
|
28512
|
+
const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
|
|
28513
|
+
const filtered = entryLines2.filter((l) => {
|
|
28068
28514
|
const parts = l.trim().split("|");
|
|
28069
28515
|
return parts[0] !== key && parts[2] !== key;
|
|
28070
28516
|
});
|
|
28071
|
-
const removed =
|
|
28517
|
+
const removed = entryLines2.length - filtered.length;
|
|
28072
28518
|
const match = lines[headerIdx].match(/\[(\d+)\|/);
|
|
28073
28519
|
const count = match ? parseInt(match[1]) : 0;
|
|
28074
28520
|
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
|
|
28075
|
-
lines.splice(headerIdx + 1,
|
|
28521
|
+
lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
|
|
28076
28522
|
writeMemory(lines.join("\n"));
|
|
28077
28523
|
return {
|
|
28078
28524
|
content: [{ type: "text", text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }]
|
|
@@ -28275,9 +28721,9 @@ server.registerTool(
|
|
|
28275
28721
|
if (!key) {
|
|
28276
28722
|
return { content: [{ type: "text", text: "\u274C Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] };
|
|
28277
28723
|
}
|
|
28278
|
-
const data =
|
|
28724
|
+
const data = readFileSync3(MEMORY_FILE, "utf-8");
|
|
28279
28725
|
const encrypted = encrypt(data, key);
|
|
28280
|
-
|
|
28726
|
+
writeFileSync3(MEMORY_FILE, encrypted);
|
|
28281
28727
|
saveConfig({ encrypted: true });
|
|
28282
28728
|
return {
|
|
28283
28729
|
content: [{ type: "text", text: "\u{1F510} Encriptaci\xF3n habilitada" }]
|
|
@@ -28303,9 +28749,9 @@ server.registerTool(
|
|
|
28303
28749
|
return { content: [{ type: "text", text: "\u274C No hay clave. P\xE1sala como argumento o la del archivo .env" }] };
|
|
28304
28750
|
}
|
|
28305
28751
|
try {
|
|
28306
|
-
const data =
|
|
28752
|
+
const data = readFileSync3(MEMORY_FILE, "utf-8");
|
|
28307
28753
|
const decrypted = decrypt(data, resolvedKey);
|
|
28308
|
-
|
|
28754
|
+
writeFileSync3(MEMORY_FILE, decrypted);
|
|
28309
28755
|
saveConfig({ encrypted: false });
|
|
28310
28756
|
return {
|
|
28311
28757
|
content: [{ type: "text", text: "\u{1F513} Encriptaci\xF3n deshabilitada" }]
|
|
@@ -28315,6 +28761,135 @@ server.registerTool(
|
|
|
28315
28761
|
}
|
|
28316
28762
|
}
|
|
28317
28763
|
);
|
|
28764
|
+
server.registerTool(
|
|
28765
|
+
"memory_captured",
|
|
28766
|
+
{
|
|
28767
|
+
title: "List Captured Activity",
|
|
28768
|
+
description: "Muestra el log de actividad capturado autom\xE1ticamente por los hooks (solo si la captura est\xE1 habilitada). \xDAtil para promover observaciones a memoria con memory_remember.",
|
|
28769
|
+
inputSchema: {
|
|
28770
|
+
limit: external_exports.number().optional().default(20).describe("M\xE1ximo de observaciones a mostrar"),
|
|
28771
|
+
tool: external_exports.string().optional().default("").describe("Filtrar por nombre de herramienta"),
|
|
28772
|
+
file: external_exports.string().optional().default("").describe("Filtrar por archivo"),
|
|
28773
|
+
clear: external_exports.boolean().optional().default(false).describe("Si true, limpia el log de captura")
|
|
28774
|
+
}
|
|
28775
|
+
},
|
|
28776
|
+
async ({ limit, tool, file: file2, clear }) => {
|
|
28777
|
+
if (clear) {
|
|
28778
|
+
if (existsSync3(OBSERVATIONS_FILE)) {
|
|
28779
|
+
writeFileSync3(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n");
|
|
28780
|
+
}
|
|
28781
|
+
return { content: [{ type: "text", text: "\u{1F9F9} Log de captura limpiado" }] };
|
|
28782
|
+
}
|
|
28783
|
+
let obs = readObservations();
|
|
28784
|
+
if (tool) obs = obs.filter((o) => o.tool.toLowerCase().includes(tool.toLowerCase()));
|
|
28785
|
+
if (file2) obs = obs.filter((o) => o.file.toLowerCase().includes(file2.toLowerCase()));
|
|
28786
|
+
obs = obs.slice(-limit).reverse();
|
|
28787
|
+
if (obs.length === 0) {
|
|
28788
|
+
return {
|
|
28789
|
+
content: [{
|
|
28790
|
+
type: "text",
|
|
28791
|
+
text: "No hay actividad capturada. La captura est\xE1 desactivada por defecto; act\xEDvala con `toon-memory capture on`."
|
|
28792
|
+
}]
|
|
28793
|
+
};
|
|
28794
|
+
}
|
|
28795
|
+
const formatted = obs.map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}
|
|
28796
|
+
${o.summary}`).join("\n\n");
|
|
28797
|
+
return { content: [{ type: "text", text: `\u{1F50D} Actividad capturada (${obs.length}):
|
|
28798
|
+
|
|
28799
|
+
${formatted}` }] };
|
|
28800
|
+
}
|
|
28801
|
+
);
|
|
28802
|
+
server.registerTool(
|
|
28803
|
+
"memory_consolidate",
|
|
28804
|
+
{
|
|
28805
|
+
title: "Consolidate Memory",
|
|
28806
|
+
description: "Consolida la memoria eliminando entradas con contenido id\xE9ntico (mantiene la primera). Determinista, sin LLM.",
|
|
28807
|
+
inputSchema: {}
|
|
28808
|
+
},
|
|
28809
|
+
async () => {
|
|
28810
|
+
const result = consolidateEntries();
|
|
28811
|
+
if (result.removed === 0) {
|
|
28812
|
+
return { content: [{ type: "text", text: `\u2705 Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] };
|
|
28813
|
+
}
|
|
28814
|
+
return {
|
|
28815
|
+
content: [{
|
|
28816
|
+
type: "text",
|
|
28817
|
+
text: `\u{1F9F9} Consolidadas ${result.removed} entradas duplicadas.
|
|
28818
|
+
Quedan ${result.kept} activas.
|
|
28819
|
+
Duplicados: ${result.duplicates.join(", ")}`
|
|
28820
|
+
}]
|
|
28821
|
+
};
|
|
28822
|
+
}
|
|
28823
|
+
);
|
|
28824
|
+
server.registerTool(
|
|
28825
|
+
"memory_sessions",
|
|
28826
|
+
{
|
|
28827
|
+
title: "Active Sessions & Conflicts",
|
|
28828
|
+
description: "Muestra las sesiones de agente activas en este proyecto (rama git, archivos tocados, last-seen) y detecta conflictos suaves (archivos tocados por 2+ sesiones). \xDAsalo al iniciar para no pisar el trabajo de otras sesiones paralelas.",
|
|
28829
|
+
inputSchema: {
|
|
28830
|
+
conflictsOnly: external_exports.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves")
|
|
28831
|
+
}
|
|
28832
|
+
},
|
|
28833
|
+
async ({ conflictsOnly }) => {
|
|
28834
|
+
const selfId = resolveSessionId();
|
|
28835
|
+
const { active, conflicts } = coordinationView(selfId);
|
|
28836
|
+
if (conflictsOnly) {
|
|
28837
|
+
if (conflicts.length === 0) {
|
|
28838
|
+
return { content: [{ type: "text", text: "\u2705 No hay conflictos suaves entre sesiones activas." }] };
|
|
28839
|
+
}
|
|
28840
|
+
const lines = conflicts.map((c) => {
|
|
28841
|
+
const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ");
|
|
28842
|
+
return `\u26A0\uFE0F ${c.file}
|
|
28843
|
+
\u2194 ${who}`;
|
|
28844
|
+
});
|
|
28845
|
+
return {
|
|
28846
|
+
content: [{ type: "text", text: `\u{1F525} Conflictos suaves (${conflicts.length}):
|
|
28847
|
+
|
|
28848
|
+
${lines.join("\n\n")}` }]
|
|
28849
|
+
};
|
|
28850
|
+
}
|
|
28851
|
+
if (active.length === 0) {
|
|
28852
|
+
return {
|
|
28853
|
+
content: [{
|
|
28854
|
+
type: "text",
|
|
28855
|
+
text: "\u{1F7E2} No hay otras sesiones activas en este proyecto.\n(Esta sesi\xF3n: " + selfId + " @ " + currentBranch() + ")"
|
|
28856
|
+
}]
|
|
28857
|
+
};
|
|
28858
|
+
}
|
|
28859
|
+
const ttlMin = Math.round(SESSION_TTL_MS / 6e4);
|
|
28860
|
+
const section = (s) => {
|
|
28861
|
+
const mins = Math.max(0, Math.round(s.ageMs / 6e4));
|
|
28862
|
+
const tag = s.id === selfId ? " (t\xFA)" : "";
|
|
28863
|
+
const ended = s.ended ? " \u{1F3C1}" : "";
|
|
28864
|
+
const files = Object.keys(s.files).slice(0, 8).map((f) => ` \u2022 ${f}`).join("\n");
|
|
28865
|
+
const fileBlock = files ? `
|
|
28866
|
+
Archivos:
|
|
28867
|
+
${files}` : "";
|
|
28868
|
+
return `\u2022 ${s.agent} @ ${s.branch}${tag}${ended}
|
|
28869
|
+
id: ${s.id}
|
|
28870
|
+
hace ${mins} min${fileBlock}`;
|
|
28871
|
+
};
|
|
28872
|
+
const parts = [
|
|
28873
|
+
`\u{1F9ED} Sesiones activas (${active.length}) \u2014 ventana ${ttlMin} min:`,
|
|
28874
|
+
"",
|
|
28875
|
+
...active.map(section)
|
|
28876
|
+
];
|
|
28877
|
+
if (conflicts.length > 0) {
|
|
28878
|
+
parts.push("", `\u{1F525} Conflictos suaves (${conflicts.length}):`);
|
|
28879
|
+
for (const c of conflicts) {
|
|
28880
|
+
const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ");
|
|
28881
|
+
parts.push(` \u26A0\uFE0F ${c.file} \u2194 ${who}`);
|
|
28882
|
+
}
|
|
28883
|
+
} else {
|
|
28884
|
+
parts.push("", "\u2705 Sin conflictos suaves detectados.");
|
|
28885
|
+
}
|
|
28886
|
+
return { content: [{ type: "text", text: parts.join("\n") }] };
|
|
28887
|
+
}
|
|
28888
|
+
);
|
|
28889
|
+
try {
|
|
28890
|
+
pruneExpiredEntries();
|
|
28891
|
+
} catch {
|
|
28892
|
+
}
|
|
28318
28893
|
var transport = new StdioServerTransport();
|
|
28319
28894
|
await server.connect(transport);
|
|
28320
28895
|
/*! Bundled license information:
|