toon-memory 2.0.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
@@ -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");
@@ -27817,7 +28029,46 @@ function findRelatedEntries(text, excludeKey = "", limit = 3) {
27817
28029
  }).filter(Boolean).sort((a, b) => b.score - a.score).slice(0, limit);
27818
28030
  return scored;
27819
28031
  }
27820
- function archiveOldEntries() {
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 = {}) {
27821
28072
  const data = readMemory();
27822
28073
  const lines = data.split("\n");
27823
28074
  const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
@@ -27827,28 +28078,28 @@ function archiveOldEntries() {
27827
28078
  cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS);
27828
28079
  const cutoffStr = cutoff.toISOString().split("T")[0];
27829
28080
  const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
27830
- const toArchive = [];
27831
- const toKeep = [];
27832
- for (const line of entryLines) {
28081
+ const toArchive = /* @__PURE__ */ new Set();
28082
+ entryLines.forEach((line, idx) => {
27833
28083
  const parts = line.trim().split("|");
27834
- if (parts.length >= 7) {
27835
- const date5 = parts[6];
27836
- const ttl = parts[7] || "";
27837
- const isOld = date5 < cutoffStr;
27838
- const isTtlExpired = ttl && isExpired(ttl);
27839
- if (isOld || isTtlExpired) {
27840
- toArchive.push(line.trim());
27841
- } else {
27842
- toKeep.push(line.trim());
27843
- }
27844
- } else {
27845
- 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);
27846
28095
  }
27847
28096
  }
27848
- 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());
27849
28100
  let archiveContent = "";
27850
- if (existsSync(ARCHIVE_FILE)) {
27851
- archiveContent = readFileSync(ARCHIVE_FILE, "utf-8");
28101
+ if (existsSync3(ARCHIVE_FILE)) {
28102
+ archiveContent = readFileSync3(ARCHIVE_FILE, "utf-8");
27852
28103
  } else {
27853
28104
  archiveContent = `version: 1
27854
28105
  archived:
@@ -27862,18 +28113,83 @@ archived:
27862
28113
  }
27863
28114
  const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/);
27864
28115
  const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0;
27865
- for (const entry of toArchive) {
28116
+ for (const entry of toArchiveLines) {
27866
28117
  archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`);
27867
28118
  }
27868
- archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchive.length}|`);
27869
- writeFileSync(ARCHIVE_FILE, archiveLines.join("\n"));
27870
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeep.length}|`);
27871
- 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()}`));
27872
28129
  writeMemory(lines.join("\n"));
27873
- return { archived: toArchive.length, kept: toKeep.length };
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}`));
28188
+ writeMemory(lines.join("\n"));
28189
+ return { removed: duplicates.length, kept: order.length, duplicates };
27874
28190
  }
27875
28191
  var server = new McpServer(
27876
- { name: "toon-memory", version: "2.0.0" },
28192
+ { name: "toon-memory", version: "2.1.0" },
27877
28193
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
27878
28194
  );
27879
28195
  server.registerResource(
@@ -27966,7 +28282,7 @@ server.registerTool(
27966
28282
  const entryId = existingIdx !== -1 ? existingId : newId;
27967
28283
  const resolvedTtl = parseTTL(ttl);
27968
28284
  const resolvedTags = tags ? tags : inferTags(content, key);
27969
- const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}`;
28285
+ const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0`;
27970
28286
  let action = "Guardado";
27971
28287
  const tagsInferred = !tags && resolvedTags ? true : false;
27972
28288
  if (existingIdx !== -1) {
@@ -27983,10 +28299,10 @@ server.registerTool(
27983
28299
  const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0;
27984
28300
  let archiveMsg = "";
27985
28301
  if (entryCount > MAX_ENTRIES) {
27986
- const result = archiveOldEntries();
28302
+ const result = archiveOldEntries({ trimToMax: true });
27987
28303
  if (result.archived > 0) {
27988
28304
  archiveMsg = `
27989
- \u{1F4E6} Auto-archived ${result.archived} old entries (${result.kept} kept)`;
28305
+ \u{1F4E6} Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`;
27990
28306
  }
27991
28307
  }
27992
28308
  const ttlMsg = resolvedTtl ? `
@@ -28022,26 +28338,29 @@ server.registerTool(
28022
28338
  },
28023
28339
  async ({ query, category, from_date, to_date }) => {
28024
28340
  const data = readMemory();
28025
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith("summaries:"));
28341
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28026
28342
  const normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28027
28343
  const queryTokens = normalize2(query).split(" ").filter(Boolean);
28028
28344
  const results = lines.map((line) => {
28029
28345
  const trimmed = line.trim();
28030
28346
  const parts = trimmed.split("|");
28031
28347
  if (parts.length < 7) return null;
28032
- const [id, cat, key, content, file2, tags, date5, ttl] = parts;
28348
+ const [id, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
28033
28349
  if (category && cat !== category) return null;
28034
28350
  if (from_date && date5 < from_date) return null;
28035
28351
  if (to_date && date5 > to_date) return null;
28036
28352
  if (ttl && isExpired(ttl)) return null;
28037
28353
  const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28038
28354
  if (!queryTokens.every((token) => searchStr.includes(token))) return null;
28039
- 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 };
28040
28357
  }).filter(Boolean);
28041
28358
  if (results.length === 0) {
28042
28359
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28043
28360
  }
28044
- 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})
28045
28364
  ${r.content}
28046
28365
  File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
28047
28366
  return { content: [{ type: "text", text: formatted }] };
@@ -28063,7 +28382,7 @@ server.registerTool(
28063
28382
  if (headerIdx === -1) {
28064
28383
  return { content: [{ type: "text", text: "No hay entradas en memoria" }] };
28065
28384
  }
28066
- 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:"));
28067
28386
  const filtered = entryLines.filter((l) => {
28068
28387
  const parts = l.trim().split("|");
28069
28388
  return parts[0] !== key && parts[2] !== key;
@@ -28275,9 +28594,9 @@ server.registerTool(
28275
28594
  if (!key) {
28276
28595
  return { content: [{ type: "text", text: "\u274C Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] };
28277
28596
  }
28278
- const data = readFileSync(MEMORY_FILE, "utf-8");
28597
+ const data = readFileSync3(MEMORY_FILE, "utf-8");
28279
28598
  const encrypted = encrypt(data, key);
28280
- writeFileSync(MEMORY_FILE, encrypted);
28599
+ writeFileSync3(MEMORY_FILE, encrypted);
28281
28600
  saveConfig({ encrypted: true });
28282
28601
  return {
28283
28602
  content: [{ type: "text", text: "\u{1F510} Encriptaci\xF3n habilitada" }]
@@ -28303,9 +28622,9 @@ server.registerTool(
28303
28622
  return { content: [{ type: "text", text: "\u274C No hay clave. P\xE1sala como argumento o la del archivo .env" }] };
28304
28623
  }
28305
28624
  try {
28306
- const data = readFileSync(MEMORY_FILE, "utf-8");
28625
+ const data = readFileSync3(MEMORY_FILE, "utf-8");
28307
28626
  const decrypted = decrypt(data, resolvedKey);
28308
- writeFileSync(MEMORY_FILE, decrypted);
28627
+ writeFileSync3(MEMORY_FILE, decrypted);
28309
28628
  saveConfig({ encrypted: false });
28310
28629
  return {
28311
28630
  content: [{ type: "text", text: "\u{1F513} Encriptaci\xF3n deshabilitada" }]
@@ -28315,6 +28634,135 @@ server.registerTool(
28315
28634
  }
28316
28635
  }
28317
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
+ }
28318
28766
  var transport = new StdioServerTransport();
28319
28767
  await server.connect(transport);
28320
28768
  /*! Bundled license information: