toon-memory 1.8.0 → 2.1.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/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 = "", normalize) {
16510
- if (normalize !== false) id = normalizeId(id);
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 normalize(uri, options) {
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,42 +27639,250 @@ 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/mcp/server.ts
27646
27850
  var __dirname = dirname(fileURLToPath(import.meta.url));
27647
- var MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory");
27648
- var MEMORY_FILE = join(MEMORY_DIR, "data.toon");
27649
- var ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon");
27650
- var CONFIG_FILE = join(MEMORY_DIR, "config.json");
27851
+ var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
27852
+ var MEMORY_FILE = join2(MEMORY_DIR, "data.toon");
27853
+ var ARCHIVE_FILE = join2(MEMORY_DIR, "archive.toon");
27854
+ var OBSERVATIONS_FILE = join2(MEMORY_DIR, "observations.toon");
27855
+ var CONFIG_FILE = join2(MEMORY_DIR, "config.json");
27651
27856
  var MAX_ENTRIES = 100;
27652
27857
  var ARCHIVE_DAYS = 30;
27858
+ function safeWrite(file2, content) {
27859
+ withLockSync(file2, () => atomicWrite(file2, content));
27860
+ }
27653
27861
  var ALGORITHM = "aes-256-gcm";
27654
27862
  function loadConfig() {
27655
- if (!existsSync(CONFIG_FILE)) {
27863
+ if (!existsSync3(CONFIG_FILE)) {
27656
27864
  return { encrypted: false };
27657
27865
  }
27658
27866
  try {
27659
- return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
27867
+ return JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
27660
27868
  } catch {
27661
27869
  return { encrypted: false };
27662
27870
  }
27663
27871
  }
27664
27872
  function saveConfig(config2) {
27665
27873
  ensureMemoryDir();
27666
- writeFileSync(CONFIG_FILE, JSON.stringify(config2, null, 2));
27874
+ writeFileSync3(CONFIG_FILE, JSON.stringify(config2, null, 2));
27667
27875
  }
27668
27876
  function getKey() {
27669
27877
  return process.env.TOON_MEMORY_KEY;
27670
27878
  }
27671
27879
  function ensureMemoryDir() {
27672
- if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true });
27880
+ if (!existsSync3(MEMORY_DIR)) mkdirSync2(MEMORY_DIR, { recursive: true });
27673
27881
  }
27674
27882
  function ensureMemoryFile() {
27675
27883
  ensureMemoryDir();
27676
- if (!existsSync(MEMORY_FILE)) {
27677
- writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl}:\n");
27884
+ if (!existsSync3(MEMORY_FILE)) {
27885
+ writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed}:\n");
27678
27886
  }
27679
27887
  }
27680
27888
  function encrypt(text, key) {
@@ -27688,7 +27896,11 @@ function encrypt(text, key) {
27688
27896
  }
27689
27897
  function decrypt(encryptedData, key) {
27690
27898
  const keyBuffer = Buffer.from(key, "hex");
27691
- const [ivHex, authTagHex, encrypted] = encryptedData.split(":");
27899
+ const parts = encryptedData.split(":");
27900
+ if (parts.length !== 3) {
27901
+ throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext");
27902
+ }
27903
+ const [ivHex, authTagHex, encrypted] = parts;
27692
27904
  const iv = Buffer.from(ivHex, "hex");
27693
27905
  const authTag = Buffer.from(authTagHex, "hex");
27694
27906
  const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv);
@@ -27700,7 +27912,7 @@ function decrypt(encryptedData, key) {
27700
27912
  function readMemory() {
27701
27913
  ensureMemoryFile();
27702
27914
  const config2 = loadConfig();
27703
- const data = readFileSync(MEMORY_FILE, "utf-8");
27915
+ const data = readUnderLock(MEMORY_FILE);
27704
27916
  if (config2.encrypted) {
27705
27917
  const key = getKey();
27706
27918
  if (!key) return "";
@@ -27719,10 +27931,10 @@ function writeMemory(content) {
27719
27931
  const key = getKey();
27720
27932
  if (!key) return;
27721
27933
  const encrypted = encrypt(content, key);
27722
- writeFileSync(MEMORY_FILE, encrypted);
27934
+ safeWrite(MEMORY_FILE, encrypted);
27723
27935
  return;
27724
27936
  }
27725
- writeFileSync(MEMORY_FILE, content);
27937
+ safeWrite(MEMORY_FILE, content);
27726
27938
  }
27727
27939
  function generateId() {
27728
27940
  return randomBytes(4).toString("hex");
@@ -27796,7 +28008,67 @@ function parseRelativeDate(since) {
27796
28008
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
27797
28009
  return today;
27798
28010
  }
27799
- function archiveOldEntries() {
28011
+ var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28012
+ function findRelatedEntries(text, excludeKey = "", limit = 3) {
28013
+ const data = readMemory();
28014
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28015
+ const queryTokens = normalize(text).split(" ").filter(Boolean);
28016
+ const scored = lines.map((line) => {
28017
+ const trimmed = line.trim();
28018
+ const parts = trimmed.split("|");
28019
+ if (parts.length < 7) return null;
28020
+ const [id, cat, key, content, file2, tags, date5] = parts;
28021
+ if (key === excludeKey) return null;
28022
+ const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28023
+ let score = 0;
28024
+ for (const token of queryTokens) {
28025
+ if (searchStr.includes(token)) score++;
28026
+ }
28027
+ if (score === 0) return null;
28028
+ return { id, cat, key, content, file: file2, tags, date: date5, score };
28029
+ }).filter(Boolean).sort((a, b) => b.score - a.score).slice(0, limit);
28030
+ return scored;
28031
+ }
28032
+ function entryScore(dateStr, accessed) {
28033
+ const days = (Date.now() - (/* @__PURE__ */ new Date(`${dateStr}T00:00:00`)).getTime()) / 864e5;
28034
+ const recency = Math.max(0, 30 - days) / 30;
28035
+ const freq = Math.min(1, accessed / 5);
28036
+ return recency * 0.6 + freq * 0.4;
28037
+ }
28038
+ function entryScoreForLine(line) {
28039
+ const parts = line.trim().split("|");
28040
+ const date5 = parts[6] || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28041
+ const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0;
28042
+ return entryScore(date5, accessed);
28043
+ }
28044
+ function bumpAccessed(ids) {
28045
+ if (ids.length === 0) return;
28046
+ const idSet = new Set(ids);
28047
+ const data = readMemory();
28048
+ const lines = data.split("\n");
28049
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28050
+ if (headerIdx === -1) return;
28051
+ for (let i = headerIdx + 1; i < lines.length; i++) {
28052
+ const line = lines[i];
28053
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
28054
+ if (line.startsWith(" summaries:")) break;
28055
+ const parts = line.trim().split("|");
28056
+ if (idSet.has(parts[0])) {
28057
+ const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1;
28058
+ parts[8] = String(accessed);
28059
+ lines[i] = ` ${parts.join("|")}`;
28060
+ }
28061
+ }
28062
+ writeMemory(lines.join("\n"));
28063
+ }
28064
+ function readObservations() {
28065
+ if (!existsSync3(OBSERVATIONS_FILE)) return [];
28066
+ return readFileSync3(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
28067
+ const p = l.trim().split("|");
28068
+ return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" };
28069
+ });
28070
+ }
28071
+ function archiveOldEntries(opts = {}) {
27800
28072
  const data = readMemory();
27801
28073
  const lines = data.split("\n");
27802
28074
  const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
@@ -27806,28 +28078,28 @@ function archiveOldEntries() {
27806
28078
  cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS);
27807
28079
  const cutoffStr = cutoff.toISOString().split("T")[0];
27808
28080
  const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
27809
- const toArchive = [];
27810
- const toKeep = [];
27811
- for (const line of entryLines) {
28081
+ const toArchive = /* @__PURE__ */ new Set();
28082
+ entryLines.forEach((line, idx) => {
27812
28083
  const parts = line.trim().split("|");
27813
- if (parts.length >= 7) {
27814
- const date5 = parts[6];
27815
- const ttl = parts[7] || "";
27816
- const isOld = date5 < cutoffStr;
27817
- const isTtlExpired = ttl && isExpired(ttl);
27818
- if (isOld || isTtlExpired) {
27819
- toArchive.push(line.trim());
27820
- } else {
27821
- toKeep.push(line.trim());
27822
- }
27823
- } else {
27824
- toKeep.push(line.trim());
28084
+ if (parts.length < 7) return;
28085
+ const date5 = parts[6];
28086
+ const ttl = parts[7] || "";
28087
+ if (date5 < cutoffStr || ttl && isExpired(ttl)) toArchive.add(idx);
28088
+ });
28089
+ if (opts.trimToMax) {
28090
+ const remaining = entryLines.length - toArchive.size;
28091
+ if (remaining > MAX_ENTRIES) {
28092
+ const need = remaining - MAX_ENTRIES;
28093
+ const candidates = entryLines.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c) => !toArchive.has(c.idx)).sort((a, b) => a.score - b.score);
28094
+ for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx);
27825
28095
  }
27826
28096
  }
27827
- if (toArchive.length === 0) return { archived: 0, kept: toKeep.length };
28097
+ if (toArchive.size === 0) return { archived: 0, kept: entryLines.length };
28098
+ const toArchiveLines = entryLines.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim());
28099
+ const toKeepLines = entryLines.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim());
27828
28100
  let archiveContent = "";
27829
- if (existsSync(ARCHIVE_FILE)) {
27830
- archiveContent = readFileSync(ARCHIVE_FILE, "utf-8");
28101
+ if (existsSync3(ARCHIVE_FILE)) {
28102
+ archiveContent = readFileSync3(ARCHIVE_FILE, "utf-8");
27831
28103
  } else {
27832
28104
  archiveContent = `version: 1
27833
28105
  archived:
@@ -27841,19 +28113,134 @@ archived:
27841
28113
  }
27842
28114
  const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/);
27843
28115
  const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0;
27844
- for (const entry of toArchive) {
28116
+ for (const entry of toArchiveLines) {
27845
28117
  archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`);
27846
28118
  }
27847
- archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchive.length}|`);
27848
- writeFileSync(ARCHIVE_FILE, archiveLines.join("\n"));
27849
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeep.length}|`);
27850
- lines.splice(headerIdx + 1, entryLines.length, ...toKeep.map((l) => ` ${l}`));
28119
+ archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`);
28120
+ safeWrite(ARCHIVE_FILE, archiveLines.join("\n"));
28121
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`);
28122
+ const keepSet = new Set(toKeepLines);
28123
+ const allEntryLines = lines.slice(headerIdx + 1);
28124
+ const newEntryLines = allEntryLines.filter((l) => {
28125
+ if (l.trim().length === 0) return false;
28126
+ return keepSet.has(l.trim());
28127
+ });
28128
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`));
28129
+ writeMemory(lines.join("\n"));
28130
+ return { archived: toArchiveLines.length, kept: toKeepLines.length };
28131
+ }
28132
+ function pruneExpiredEntries() {
28133
+ ensureMemoryFile();
28134
+ if (!existsSync3(MEMORY_FILE)) return 0;
28135
+ let pruned = 0;
28136
+ withLockSync(MEMORY_FILE, () => {
28137
+ const data = readMemory();
28138
+ const lines = data.split("\n");
28139
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
28140
+ if (headerIdx === -1) return;
28141
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28142
+ const kept = entryLines.filter((l) => {
28143
+ const parts = l.trim().split("|");
28144
+ if (parts.length < 8) return true;
28145
+ const ttl = parts[7] || "";
28146
+ if (ttl && isExpired(ttl)) {
28147
+ pruned++;
28148
+ return false;
28149
+ }
28150
+ return true;
28151
+ });
28152
+ if (pruned === 0) return;
28153
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`);
28154
+ const keepSet = new Set(kept.map((l) => l.trim()));
28155
+ const allEntryLines = lines.slice(headerIdx + 1);
28156
+ const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()));
28157
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => l.trim().length ? ` ${l.trim()}` : l));
28158
+ writeMemory(lines.join("\n"));
28159
+ });
28160
+ return pruned;
28161
+ }
28162
+ function consolidateEntries() {
28163
+ const data = readMemory();
28164
+ const lines = data.split("\n");
28165
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28166
+ if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
28167
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28168
+ const seen = /* @__PURE__ */ new Map();
28169
+ const order = [];
28170
+ const duplicates = [];
28171
+ for (const line of entryLines) {
28172
+ const parts = line.trim().split("|");
28173
+ if (parts.length < 3) {
28174
+ order.push(line.trim());
28175
+ continue;
28176
+ }
28177
+ const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim();
28178
+ if (seen.has(content)) {
28179
+ duplicates.push(parts[2]);
28180
+ continue;
28181
+ }
28182
+ seen.set(content, line.trim());
28183
+ order.push(line.trim());
28184
+ }
28185
+ if (duplicates.length === 0) return { removed: 0, kept: order.length, duplicates: [] };
28186
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`);
28187
+ lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`));
27851
28188
  writeMemory(lines.join("\n"));
27852
- return { archived: toArchive.length, kept: toKeep.length };
28189
+ return { removed: duplicates.length, kept: order.length, duplicates };
27853
28190
  }
27854
28191
  var server = new McpServer(
27855
- { name: "toon-memory", version: "1.1.0" },
27856
- { capabilities: { tools: { listChanged: true } } }
28192
+ { name: "toon-memory", version: "2.1.0" },
28193
+ { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
28194
+ );
28195
+ server.registerResource(
28196
+ "memory-entries",
28197
+ "toon://memory/entries",
28198
+ { title: "Memory Entries", mimeType: "text/plain" },
28199
+ async (uri) => {
28200
+ const data = readMemory();
28201
+ return { contents: [{ uri: uri.href, text: data }] };
28202
+ }
28203
+ );
28204
+ server.registerResource(
28205
+ "memory-stats",
28206
+ "toon://memory/stats",
28207
+ { title: "Memory Stats", mimeType: "text/plain" },
28208
+ async (uri) => {
28209
+ const data = readMemory();
28210
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28211
+ const entries = lines.map((l) => {
28212
+ const parts = l.trim().split("|");
28213
+ return { category: parts[1] || "unknown", ttl: parts[7] || "" };
28214
+ });
28215
+ const byCategory = {};
28216
+ for (const e of entries) {
28217
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1;
28218
+ }
28219
+ const withTtl = entries.filter((e) => e.ttl).length;
28220
+ const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length;
28221
+ const text = [
28222
+ `Entradas totales: ${entries.length}`,
28223
+ `TTL: ${withTtl} con expiraci\xF3n, ${expired} expiradas`,
28224
+ "Por categor\xEDa:",
28225
+ ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`)
28226
+ ].join("\n");
28227
+ return { contents: [{ uri: uri.href, text }] };
28228
+ }
28229
+ );
28230
+ server.registerResource(
28231
+ "memory-summaries",
28232
+ "toon://memory/summaries",
28233
+ { title: "Memory Summaries", mimeType: "text/plain" },
28234
+ async (uri) => {
28235
+ const data = readMemory();
28236
+ const lines = data.split("\n");
28237
+ const summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"));
28238
+ if (summaryIdx === -1) {
28239
+ return { contents: [{ uri: uri.href, text: "No hay res\xFAmenes guardados" }] };
28240
+ }
28241
+ const summaryText = lines.slice(summaryIdx + 1).filter((l) => l.includes(":")).join("\n");
28242
+ return { contents: [{ uri: uri.href, text: summaryText || "No hay res\xFAmenes guardados" }] };
28243
+ }
27857
28244
  );
27858
28245
  server.registerTool(
27859
28246
  "memory_remember",
@@ -27895,7 +28282,7 @@ server.registerTool(
27895
28282
  const entryId = existingIdx !== -1 ? existingId : newId;
27896
28283
  const resolvedTtl = parseTTL(ttl);
27897
28284
  const resolvedTags = tags ? tags : inferTags(content, key);
27898
- const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}`;
28285
+ const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0`;
27899
28286
  let action = "Guardado";
27900
28287
  const tagsInferred = !tags && resolvedTags ? true : false;
27901
28288
  if (existingIdx !== -1) {
@@ -27912,19 +28299,28 @@ server.registerTool(
27912
28299
  const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0;
27913
28300
  let archiveMsg = "";
27914
28301
  if (entryCount > MAX_ENTRIES) {
27915
- const result = archiveOldEntries();
28302
+ const result = archiveOldEntries({ trimToMax: true });
27916
28303
  if (result.archived > 0) {
27917
28304
  archiveMsg = `
27918
- \u{1F4E6} Auto-archived ${result.archived} old entries (${result.kept} kept)`;
28305
+ \u{1F4E6} Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`;
27919
28306
  }
27920
28307
  }
27921
28308
  const ttlMsg = resolvedTtl ? `
27922
28309
  \u23F0 TTL: ${resolvedTtl}` : "";
27923
28310
  const inferredMsg = tagsInferred ? `
27924
28311
  \u{1F3F7}\uFE0F Tags inferidos: ${resolvedTags}` : "";
28312
+ const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3);
28313
+ let relatedMsg = "";
28314
+ if (related.length > 0) {
28315
+ const items = related.map((r) => ` [${r.cat}] ${r.key} \u2014 ${r.content.slice(0, 80)}`).join("\n");
28316
+ relatedMsg = `
28317
+
28318
+ \u{1F517} Entradas relacionadas:
28319
+ ${items}`;
28320
+ }
27925
28321
  return {
27926
28322
  content: [{ type: "text", text: `\u{1F9E0} ${action}: ${category}/${key} (${entryId})
27927
- ${content}${ttlMsg}${inferredMsg}${archiveMsg}` }]
28323
+ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${relatedMsg}` }]
27928
28324
  };
27929
28325
  }
27930
28326
  );
@@ -27942,26 +28338,29 @@ server.registerTool(
27942
28338
  },
27943
28339
  async ({ query, category, from_date, to_date }) => {
27944
28340
  const data = readMemory();
27945
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith("summaries:"));
27946
- const normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
27947
- const queryTokens = normalize(query).split(" ").filter(Boolean);
28341
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28342
+ const normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28343
+ const queryTokens = normalize2(query).split(" ").filter(Boolean);
27948
28344
  const results = lines.map((line) => {
27949
28345
  const trimmed = line.trim();
27950
28346
  const parts = trimmed.split("|");
27951
28347
  if (parts.length < 7) return null;
27952
- const [id, cat, key, content, file2, tags, date5, ttl] = parts;
28348
+ const [id, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
27953
28349
  if (category && cat !== category) return null;
27954
28350
  if (from_date && date5 < from_date) return null;
27955
28351
  if (to_date && date5 > to_date) return null;
27956
28352
  if (ttl && isExpired(ttl)) return null;
27957
- const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28353
+ const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
27958
28354
  if (!queryTokens.every((token) => searchStr.includes(token))) return null;
27959
- return { id, cat, key, content, file: file2, tags, date: date5 };
28355
+ const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
28356
+ return { id, cat, key, content, file: file2, tags, date: date5, accessed };
27960
28357
  }).filter(Boolean);
27961
28358
  if (results.length === 0) {
27962
28359
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
27963
28360
  }
27964
- const formatted = results.map((r) => `[${r.cat}] ${r.key} (${r.id})
28361
+ const ranked = results.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) })).sort((a, b) => b.score - a.score);
28362
+ bumpAccessed(ranked.map((r) => r.id));
28363
+ const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
27965
28364
  ${r.content}
27966
28365
  File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
27967
28366
  return { content: [{ type: "text", text: formatted }] };
@@ -27983,7 +28382,7 @@ server.registerTool(
27983
28382
  if (headerIdx === -1) {
27984
28383
  return { content: [{ type: "text", text: "No hay entradas en memoria" }] };
27985
28384
  }
27986
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith("summaries:"));
28385
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
27987
28386
  const filtered = entryLines.filter((l) => {
27988
28387
  const parts = l.trim().split("|");
27989
28388
  return parts[0] !== key && parts[2] !== key;
@@ -28088,6 +28487,29 @@ server.registerTool(
28088
28487
  return { content: [{ type: "text", text: sections.join("\n") }] };
28089
28488
  }
28090
28489
  );
28490
+ server.registerTool(
28491
+ "memory_suggest",
28492
+ {
28493
+ title: "Suggest Related Memories",
28494
+ description: "Sugiere entradas de memoria relacionadas con un contexto dado. \xDAtil para obtener contexto antes de una tarea.",
28495
+ inputSchema: {
28496
+ context: external_exports.string().describe("Texto o contexto para buscar sugerencias"),
28497
+ limit: external_exports.number().optional().default(5).describe("M\xE1ximo de sugerencias")
28498
+ }
28499
+ },
28500
+ async ({ context, limit }) => {
28501
+ const related = findRelatedEntries(context, "", limit);
28502
+ if (related.length === 0) {
28503
+ return { content: [{ type: "text", text: `No se encontraron entradas relacionadas con "${context}"` }] };
28504
+ }
28505
+ const formatted = related.map((r) => `[${r.cat}] ${r.key} (${r.id})
28506
+ ${r.content}
28507
+ File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
28508
+ return { content: [{ type: "text", text: `\u{1F50D} Sugerencias para "${context}":
28509
+
28510
+ ${formatted}` }] };
28511
+ }
28512
+ );
28091
28513
  server.registerTool(
28092
28514
  "memory_summary",
28093
28515
  {
@@ -28172,9 +28594,9 @@ server.registerTool(
28172
28594
  if (!key) {
28173
28595
  return { content: [{ type: "text", text: "\u274C Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] };
28174
28596
  }
28175
- const data = readFileSync(MEMORY_FILE, "utf-8");
28597
+ const data = readFileSync3(MEMORY_FILE, "utf-8");
28176
28598
  const encrypted = encrypt(data, key);
28177
- writeFileSync(MEMORY_FILE, encrypted);
28599
+ writeFileSync3(MEMORY_FILE, encrypted);
28178
28600
  saveConfig({ encrypted: true });
28179
28601
  return {
28180
28602
  content: [{ type: "text", text: "\u{1F510} Encriptaci\xF3n habilitada" }]
@@ -28200,9 +28622,9 @@ server.registerTool(
28200
28622
  return { content: [{ type: "text", text: "\u274C No hay clave. P\xE1sala como argumento o la del archivo .env" }] };
28201
28623
  }
28202
28624
  try {
28203
- const data = readFileSync(MEMORY_FILE, "utf-8");
28625
+ const data = readFileSync3(MEMORY_FILE, "utf-8");
28204
28626
  const decrypted = decrypt(data, resolvedKey);
28205
- writeFileSync(MEMORY_FILE, decrypted);
28627
+ writeFileSync3(MEMORY_FILE, decrypted);
28206
28628
  saveConfig({ encrypted: false });
28207
28629
  return {
28208
28630
  content: [{ type: "text", text: "\u{1F513} Encriptaci\xF3n deshabilitada" }]
@@ -28212,6 +28634,135 @@ server.registerTool(
28212
28634
  }
28213
28635
  }
28214
28636
  );
28637
+ server.registerTool(
28638
+ "memory_captured",
28639
+ {
28640
+ title: "List Captured Activity",
28641
+ 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.",
28642
+ inputSchema: {
28643
+ limit: external_exports.number().optional().default(20).describe("M\xE1ximo de observaciones a mostrar"),
28644
+ tool: external_exports.string().optional().default("").describe("Filtrar por nombre de herramienta"),
28645
+ file: external_exports.string().optional().default("").describe("Filtrar por archivo"),
28646
+ clear: external_exports.boolean().optional().default(false).describe("Si true, limpia el log de captura")
28647
+ }
28648
+ },
28649
+ async ({ limit, tool, file: file2, clear }) => {
28650
+ if (clear) {
28651
+ if (existsSync3(OBSERVATIONS_FILE)) {
28652
+ writeFileSync3(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n");
28653
+ }
28654
+ return { content: [{ type: "text", text: "\u{1F9F9} Log de captura limpiado" }] };
28655
+ }
28656
+ let obs = readObservations();
28657
+ if (tool) obs = obs.filter((o) => o.tool.toLowerCase().includes(tool.toLowerCase()));
28658
+ if (file2) obs = obs.filter((o) => o.file.toLowerCase().includes(file2.toLowerCase()));
28659
+ obs = obs.slice(-limit).reverse();
28660
+ if (obs.length === 0) {
28661
+ return {
28662
+ content: [{
28663
+ type: "text",
28664
+ text: "No hay actividad capturada. La captura est\xE1 desactivada por defecto; act\xEDvala con `toon-memory capture on`."
28665
+ }]
28666
+ };
28667
+ }
28668
+ const formatted = obs.map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}
28669
+ ${o.summary}`).join("\n\n");
28670
+ return { content: [{ type: "text", text: `\u{1F50D} Actividad capturada (${obs.length}):
28671
+
28672
+ ${formatted}` }] };
28673
+ }
28674
+ );
28675
+ server.registerTool(
28676
+ "memory_consolidate",
28677
+ {
28678
+ title: "Consolidate Memory",
28679
+ description: "Consolida la memoria eliminando entradas con contenido id\xE9ntico (mantiene la primera). Determinista, sin LLM.",
28680
+ inputSchema: {}
28681
+ },
28682
+ async () => {
28683
+ const result = consolidateEntries();
28684
+ if (result.removed === 0) {
28685
+ return { content: [{ type: "text", text: `\u2705 Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] };
28686
+ }
28687
+ return {
28688
+ content: [{
28689
+ type: "text",
28690
+ text: `\u{1F9F9} Consolidadas ${result.removed} entradas duplicadas.
28691
+ Quedan ${result.kept} activas.
28692
+ Duplicados: ${result.duplicates.join(", ")}`
28693
+ }]
28694
+ };
28695
+ }
28696
+ );
28697
+ server.registerTool(
28698
+ "memory_sessions",
28699
+ {
28700
+ title: "Active Sessions & Conflicts",
28701
+ 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.",
28702
+ inputSchema: {
28703
+ conflictsOnly: external_exports.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves")
28704
+ }
28705
+ },
28706
+ async ({ conflictsOnly }) => {
28707
+ const selfId = resolveSessionId();
28708
+ const { active, conflicts } = coordinationView(selfId);
28709
+ if (conflictsOnly) {
28710
+ if (conflicts.length === 0) {
28711
+ return { content: [{ type: "text", text: "\u2705 No hay conflictos suaves entre sesiones activas." }] };
28712
+ }
28713
+ const lines = conflicts.map((c) => {
28714
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ");
28715
+ return `\u26A0\uFE0F ${c.file}
28716
+ \u2194 ${who}`;
28717
+ });
28718
+ return {
28719
+ content: [{ type: "text", text: `\u{1F525} Conflictos suaves (${conflicts.length}):
28720
+
28721
+ ${lines.join("\n\n")}` }]
28722
+ };
28723
+ }
28724
+ if (active.length === 0) {
28725
+ return {
28726
+ content: [{
28727
+ type: "text",
28728
+ text: "\u{1F7E2} No hay otras sesiones activas en este proyecto.\n(Esta sesi\xF3n: " + selfId + " @ " + currentBranch() + ")"
28729
+ }]
28730
+ };
28731
+ }
28732
+ const ttlMin = Math.round(SESSION_TTL_MS / 6e4);
28733
+ const section = (s) => {
28734
+ const mins = Math.max(0, Math.round(s.ageMs / 6e4));
28735
+ const tag = s.id === selfId ? " (t\xFA)" : "";
28736
+ const ended = s.ended ? " \u{1F3C1}" : "";
28737
+ const files = Object.keys(s.files).slice(0, 8).map((f) => ` \u2022 ${f}`).join("\n");
28738
+ const fileBlock = files ? `
28739
+ Archivos:
28740
+ ${files}` : "";
28741
+ return `\u2022 ${s.agent} @ ${s.branch}${tag}${ended}
28742
+ id: ${s.id}
28743
+ hace ${mins} min${fileBlock}`;
28744
+ };
28745
+ const parts = [
28746
+ `\u{1F9ED} Sesiones activas (${active.length}) \u2014 ventana ${ttlMin} min:`,
28747
+ "",
28748
+ ...active.map(section)
28749
+ ];
28750
+ if (conflicts.length > 0) {
28751
+ parts.push("", `\u{1F525} Conflictos suaves (${conflicts.length}):`);
28752
+ for (const c of conflicts) {
28753
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ");
28754
+ parts.push(` \u26A0\uFE0F ${c.file} \u2194 ${who}`);
28755
+ }
28756
+ } else {
28757
+ parts.push("", "\u2705 Sin conflictos suaves detectados.");
28758
+ }
28759
+ return { content: [{ type: "text", text: parts.join("\n") }] };
28760
+ }
28761
+ );
28762
+ try {
28763
+ pruneExpiredEntries();
28764
+ } catch {
28765
+ }
28215
28766
  var transport = new StdioServerTransport();
28216
28767
  await server.connect(transport);
28217
28768
  /*! Bundled license information: