toon-memory 2.5.1 → 2.7.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 = "", normalize4) {
16510
- if (normalize4 !== false) id = normalizeId(id);
16509
+ function getFullPath(resolver, id = "", normalize6) {
16510
+ if (normalize6 !== 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 normalize4(uri, options) {
17605
+ function normalize6(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;
@@ -17613,41 +17613,41 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17613
17613
  schemelessOptions.skipEscape = true;
17614
17614
  return serialize(resolved, schemelessOptions);
17615
17615
  }
17616
- function resolveComponent(base, relative, options, skipNormalization) {
17616
+ function resolveComponent(base, relative2, options, skipNormalization) {
17617
17617
  const target = {};
17618
17618
  if (!skipNormalization) {
17619
17619
  base = parse3(serialize(base, options), options);
17620
- relative = parse3(serialize(relative, options), options);
17620
+ relative2 = parse3(serialize(relative2, options), options);
17621
17621
  }
17622
17622
  options = options || {};
17623
- if (!options.tolerant && relative.scheme) {
17624
- target.scheme = relative.scheme;
17625
- target.userinfo = relative.userinfo;
17626
- target.host = relative.host;
17627
- target.port = relative.port;
17628
- target.path = removeDotSegments(relative.path || "");
17629
- target.query = relative.query;
17623
+ if (!options.tolerant && relative2.scheme) {
17624
+ target.scheme = relative2.scheme;
17625
+ target.userinfo = relative2.userinfo;
17626
+ target.host = relative2.host;
17627
+ target.port = relative2.port;
17628
+ target.path = removeDotSegments(relative2.path || "");
17629
+ target.query = relative2.query;
17630
17630
  } else {
17631
- if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
17632
- target.userinfo = relative.userinfo;
17633
- target.host = relative.host;
17634
- target.port = relative.port;
17635
- target.path = removeDotSegments(relative.path || "");
17636
- target.query = relative.query;
17631
+ if (relative2.userinfo !== void 0 || relative2.host !== void 0 || relative2.port !== void 0) {
17632
+ target.userinfo = relative2.userinfo;
17633
+ target.host = relative2.host;
17634
+ target.port = relative2.port;
17635
+ target.path = removeDotSegments(relative2.path || "");
17636
+ target.query = relative2.query;
17637
17637
  } else {
17638
- if (!relative.path) {
17638
+ if (!relative2.path) {
17639
17639
  target.path = base.path;
17640
- if (relative.query !== void 0) target.query = relative.query;
17640
+ if (relative2.query !== void 0) target.query = relative2.query;
17641
17641
  else target.query = base.query;
17642
17642
  } else {
17643
- if (relative.path[0] === "/") target.path = removeDotSegments(relative.path);
17643
+ if (relative2.path[0] === "/") target.path = removeDotSegments(relative2.path);
17644
17644
  else {
17645
- if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path;
17646
- else if (!base.path) target.path = relative.path;
17647
- else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
17645
+ if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative2.path;
17646
+ else if (!base.path) target.path = relative2.path;
17647
+ else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative2.path;
17648
17648
  target.path = removeDotSegments(target.path);
17649
17649
  }
17650
- target.query = relative.query;
17650
+ target.query = relative2.query;
17651
17651
  }
17652
17652
  target.userinfo = base.userinfo;
17653
17653
  target.host = base.host;
@@ -17655,7 +17655,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17655
17655
  }
17656
17656
  target.scheme = base.scheme;
17657
17657
  }
17658
- target.fragment = relative.fragment;
17658
+ target.fragment = relative2.fragment;
17659
17659
  return target;
17660
17660
  }
17661
17661
  function equal(uriA, uriB, options) {
@@ -17780,7 +17780,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17780
17780
  }
17781
17781
  const fastUri = {
17782
17782
  SCHEMES,
17783
- normalize: normalize4,
17783
+ normalize: normalize6,
17784
17784
  resolve,
17785
17785
  resolveComponent,
17786
17786
  equal,
@@ -27638,11 +27638,8 @@ var StdioServerTransport = class {
27638
27638
  }
27639
27639
  };
27640
27640
 
27641
- // src/mcp/server.ts
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
- import { fileURLToPath } from "url";
27645
- import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
27641
+ // src/mcp/tools.ts
27642
+ import { readFileSync as readFileSync10, writeFileSync as writeFileSync4, existsSync as existsSync10 } from "fs";
27646
27643
 
27647
27644
  // src/lib/lock.ts
27648
27645
  import { openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, renameSync } from "fs";
@@ -27738,168 +27735,396 @@ function readUnderLock(file2, encoding = "utf-8") {
27738
27735
  return content;
27739
27736
  }
27740
27737
 
27741
- // src/lib/sessions.ts
27742
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, readdirSync, unlinkSync as unlinkSync2, statSync as statSync2 } from "fs";
27738
+ // src/mcp/config.ts
27739
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync } from "fs";
27743
27740
  import { join } from "path";
27744
- var SESSION_TTL_MS = 10 * 60 * 1e3;
27745
- var PRUNE_STALE_MS = 10 * 60 * 1e3;
27746
- function isAlive2(pid) {
27747
- if (!pid || pid <= 0) return false;
27741
+ var MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory");
27742
+ var MEMORY_FILE = join(MEMORY_DIR, "data.toon");
27743
+ var ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon");
27744
+ var OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon");
27745
+ var CONFIG_FILE = join(MEMORY_DIR, "config.json");
27746
+ var MAX_ENTRIES = 100;
27747
+ var ARCHIVE_DAYS = 30;
27748
+ var ALGORITHM = "aes-256-gcm";
27749
+ function loadConfig() {
27750
+ if (!existsSync2(CONFIG_FILE)) {
27751
+ return { encrypted: false };
27752
+ }
27748
27753
  try {
27749
- process.kill(pid, 0);
27750
- return true;
27754
+ return JSON.parse(readFileSync2(CONFIG_FILE, "utf-8"));
27751
27755
  } catch {
27752
- return false;
27756
+ return { encrypted: false };
27753
27757
  }
27754
27758
  }
27755
- function sessionDir() {
27756
- return join(process.cwd(), ".toon-memory", "memory", "sessions");
27757
- }
27758
- function resolveSessionId(payload = {}) {
27759
- const fromPayload = payload.session_id || payload.sessionId || payload.session_id_untruncated;
27760
- if (fromPayload && fromPayload.trim()) return fromPayload.trim();
27761
- if (process.env.TOON_MEMORY_SESSION_ID && process.env.TOON_MEMORY_SESSION_ID.trim()) {
27762
- return process.env.TOON_MEMORY_SESSION_ID.trim();
27759
+ function saveConfig(config2) {
27760
+ ensureMemoryDir();
27761
+ let existing = {};
27762
+ if (existsSync2(CONFIG_FILE)) {
27763
+ try {
27764
+ existing = JSON.parse(readFileSync2(CONFIG_FILE, "utf-8"));
27765
+ } catch {
27766
+ existing = {};
27767
+ }
27763
27768
  }
27764
- return `proc-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
27769
+ writeFileSync2(CONFIG_FILE, JSON.stringify({ ...existing, ...config2 }, null, 2));
27765
27770
  }
27766
- function currentBranch() {
27767
- if (process.env.TOON_MEMORY_BRANCH && process.env.TOON_MEMORY_BRANCH.trim()) {
27768
- return process.env.TOON_MEMORY_BRANCH.trim();
27769
- }
27770
- try {
27771
- let gitDir = join(process.cwd(), ".git");
27772
- if (existsSync2(gitDir) && !statSync2(gitDir).isDirectory()) {
27773
- const pointer = readFileSync2(gitDir, "utf-8").trim();
27774
- if (pointer.startsWith("gitdir:")) {
27775
- const target = pointer.slice(7).trim();
27776
- gitDir = target.startsWith("/") ? target : join(process.cwd(), target);
27777
- }
27778
- }
27779
- const headPath = join(gitDir, "HEAD");
27780
- if (!existsSync2(headPath)) return "unknown";
27781
- const head = readFileSync2(headPath, "utf-8").trim();
27782
- if (head.startsWith("ref:")) {
27783
- const ref = head.slice(4).trim();
27784
- const parts = ref.split("/");
27785
- return parts[parts.length - 1] || "unknown";
27786
- }
27787
- return head ? head.slice(0, 7) : "unknown";
27788
- } catch {
27789
- return "unknown";
27771
+ function getKey() {
27772
+ return process.env.TOON_MEMORY_KEY;
27773
+ }
27774
+ function ensureMemoryDir() {
27775
+ if (!existsSync2(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true });
27776
+ }
27777
+ function ensureMemoryFile() {
27778
+ ensureMemoryDir();
27779
+ if (!existsSync2(MEMORY_FILE)) {
27780
+ writeFileSync2(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n");
27790
27781
  }
27791
27782
  }
27792
- function recentIso(iso) {
27793
- const t = new Date(iso).getTime();
27794
- return !isNaN(t) && Date.now() - t <= SESSION_TTL_MS;
27783
+
27784
+ // src/mcp/crypto.ts
27785
+ import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
27786
+ function encrypt(text, key) {
27787
+ const keyBuffer = Buffer.from(key, "hex");
27788
+ const iv = randomBytes(16);
27789
+ const cipher = createCipheriv(ALGORITHM, keyBuffer, iv);
27790
+ let encrypted = cipher.update(text, "utf8", "hex");
27791
+ encrypted += cipher.final("hex");
27792
+ const authTag = cipher.getAuthTag();
27793
+ return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
27795
27794
  }
27796
- function listSessions() {
27797
- const dir = sessionDir();
27798
- if (!existsSync2(dir)) return [];
27799
- return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => {
27800
- try {
27801
- return JSON.parse(readFileSync2(join(dir, f), "utf-8"));
27802
- } catch {
27803
- return null;
27804
- }
27805
- }).filter(Boolean).map((r) => {
27806
- const rec = r;
27807
- const active = recentIso(rec.lastSeen);
27808
- return { ...rec, active, ageMs: Date.now() - new Date(rec.lastSeen).getTime() };
27809
- }).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
27795
+ function decrypt(encryptedData, key) {
27796
+ const keyBuffer = Buffer.from(key, "hex");
27797
+ const parts = encryptedData.split(":");
27798
+ if (parts.length !== 3) {
27799
+ throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext");
27800
+ }
27801
+ const [ivHex, authTagHex, encrypted] = parts;
27802
+ const iv = Buffer.from(ivHex, "hex");
27803
+ const authTag = Buffer.from(authTagHex, "hex");
27804
+ const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv);
27805
+ decipher.setAuthTag(authTag);
27806
+ let decrypted = decipher.update(encrypted, "hex", "utf8");
27807
+ decrypted += decipher.final("utf8");
27808
+ return decrypted;
27810
27809
  }
27811
- function pruneSessions() {
27812
- const pruned = [];
27813
- const dir = sessionDir();
27814
- if (!existsSync2(dir)) return pruned;
27815
- for (const f of readdirSync(dir).filter((x) => x.endsWith(".json"))) {
27816
- const p = join(dir, f);
27817
- let rec = null;
27810
+
27811
+ // src/mcp/memory-io.ts
27812
+ function safeWrite(file2, content) {
27813
+ withLockSync(file2, () => atomicWrite(file2, content));
27814
+ }
27815
+ function readMemory() {
27816
+ ensureMemoryFile();
27817
+ const config2 = loadConfig();
27818
+ const data = readUnderLock(MEMORY_FILE);
27819
+ if (config2.encrypted) {
27820
+ const key = getKey();
27821
+ if (!key) return "";
27818
27822
  try {
27819
- rec = JSON.parse(readFileSync2(p, "utf-8"));
27823
+ return decrypt(data, key);
27820
27824
  } catch {
27821
- continue;
27822
- }
27823
- if (!rec) continue;
27824
- const stale = Date.now() - new Date(rec.lastSeen).getTime() > PRUNE_STALE_MS;
27825
- if (stale && !isAlive2(rec.pid)) {
27826
- try {
27827
- unlinkSync2(p);
27828
- pruned.push(rec.id);
27829
- } catch {
27830
- }
27825
+ return "";
27831
27826
  }
27832
27827
  }
27833
- return pruned;
27828
+ return data;
27834
27829
  }
27835
- function detectConflicts(active = listSessions().filter((s) => s.active)) {
27836
- const byFile = /* @__PURE__ */ new Map();
27837
- for (const s of active) {
27838
- if (s.ended) continue;
27839
- for (const file2 of Object.keys(s.files)) {
27840
- if (!byFile.has(file2)) byFile.set(file2, []);
27841
- byFile.get(file2).push({ id: s.id, agent: s.agent, branch: s.branch });
27842
- }
27843
- }
27844
- const conflicts = [];
27845
- for (const [file2, sessions] of byFile) {
27846
- if (sessions.length >= 2) conflicts.push({ file: file2, sessions });
27830
+ function writeMemory(content) {
27831
+ ensureMemoryFile();
27832
+ const config2 = loadConfig();
27833
+ if (config2.encrypted) {
27834
+ const key = getKey();
27835
+ if (!key) return;
27836
+ const encrypted = encrypt(content, key);
27837
+ safeWrite(MEMORY_FILE, encrypted);
27838
+ return;
27847
27839
  }
27848
- return conflicts;
27849
- }
27850
- function coordinationView(selfId) {
27851
- const all = listSessions();
27852
- const active = all.filter((s) => s.active);
27853
- const conflicts = detectConflicts(active);
27854
- const self = selfId ? all.find((s) => s.id === selfId) : void 0;
27855
- pruneSessions();
27856
- return { active, conflicts, self };
27840
+ safeWrite(MEMORY_FILE, content);
27857
27841
  }
27858
27842
 
27859
- // src/lib/graph.ts
27860
- var isExpiredLocal = (ttl) => {
27843
+ // src/mcp/entries.ts
27844
+ import { randomBytes as randomBytes2 } from "crypto";
27845
+ function generateId() {
27846
+ return randomBytes2(4).toString("hex");
27847
+ }
27848
+ function parseTTL(ttl) {
27849
+ if (!ttl || !ttl.trim()) return "";
27850
+ const trimmed = ttl.trim();
27851
+ const dayMatch = trimmed.match(/^(\d+)d$/);
27852
+ if (dayMatch) {
27853
+ const days = parseInt(dayMatch[1]);
27854
+ const d = /* @__PURE__ */ new Date();
27855
+ d.setDate(d.getDate() + days);
27856
+ return d.toISOString().split("T")[0];
27857
+ }
27858
+ if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
27859
+ return "";
27860
+ }
27861
+ function isExpired(ttl) {
27861
27862
  if (!ttl) return false;
27863
+ const ttlDate = parseTTL(ttl) || ttl;
27862
27864
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
27863
- return ttl <= today;
27865
+ return ttlDate <= today;
27866
+ }
27867
+ var TAG_VOCABULARY = {
27868
+ "redis": ["redis", "cache", "caching", "memcached"],
27869
+ "auth": ["auth", "authentication", "authorization", "login", "token", "jwt", "session", "oauth"],
27870
+ "api": ["api", "endpoint", "rest", "graphql", "route", "router", "controller"],
27871
+ "db": ["database", "db", "sql", "postgres", "mysql", "mongo", "query", "migration", "schema"],
27872
+ "security": ["security", "encrypt", "decrypt", "vulnerability", "xss", "csrf", "cors", "sanitiz"],
27873
+ "test": ["test", "testing", "vitest", "jest", "spec", "mock", "assert", "coverage"],
27874
+ "deploy": ["deploy", "docker", "ci/cd", "github actions", "pipeline", "kubernetes", "k8s"],
27875
+ "config": ["config", "configuration", "settings", "env", "environment", "dotenv"],
27876
+ "performance": ["performance", "optimize", "benchmark", "latency", "throughput", "cache"],
27877
+ "refactor": ["refactor", "cleanup", "restructure", "reorganize", "rework"],
27878
+ "error": ["error", "exception", "throw", "catch", "handling", "retry", "fallback"],
27879
+ "logging": ["log", "logging", "logger", "debug", "trace", "monitor", "observability"],
27880
+ "types": ["typescript", "types", "type", "interface", "generic", "enum", "zod", "schema"],
27881
+ "async": ["async", "await", "promise", "concurrent", "parallel", "worker", "queue"],
27882
+ "state": ["state", "store", "redux", "context", "reducer", "action", "observable"],
27883
+ "ui": ["ui", "component", "render", "dom", "css", "style", "layout", "responsive"],
27884
+ "storage": ["storage", "file", "filesystem", "s3", "blob", "upload", "download"],
27885
+ "email": ["email", "mail", "smtp", "sendgrid", "newsletter", "notification"],
27886
+ "payment": ["payment", "stripe", "billing", "invoice", "checkout", "subscription"],
27887
+ "webhook": ["webhook", "callback", "event", "listener", "hook"]
27864
27888
  };
27865
- var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
27866
- var entryLines = (data) => data.split("\n").filter(
27867
- (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
27868
- );
27869
- function parseEntries(data) {
27870
- const out = [];
27871
- for (const line of entryLines(data)) {
27872
- const parts = line.trim().split("|");
27873
- if (parts.length < 7) continue;
27874
- const [id, category, key, content, file2, tags, date5, ttl, accessedRaw, linksRaw] = parts;
27875
- out.push({
27876
- id,
27877
- category,
27878
- key,
27879
- content,
27880
- file: file2 || "",
27881
- tags: (tags || "").split(";").map((t) => t.trim()).filter(Boolean),
27882
- date: date5 || "",
27883
- ttl: ttl || "",
27884
- accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
27885
- links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean)
27886
- });
27889
+ function inferTags(content, key, vocab) {
27890
+ const text = `${key} ${content}`.toLowerCase();
27891
+ const matched = [];
27892
+ for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
27893
+ if (keywords.some((kw) => text.includes(kw))) {
27894
+ matched.push(tag);
27895
+ }
27887
27896
  }
27888
- return out;
27897
+ if (vocab) {
27898
+ for (const [tag, keywords] of Object.entries(vocab)) {
27899
+ if (keywords.some((kw) => text.includes(kw))) {
27900
+ matched.push(tag);
27901
+ }
27902
+ }
27903
+ }
27904
+ return matched.join(";");
27889
27905
  }
27890
- function buildGraph(entries) {
27891
- const byKey = /* @__PURE__ */ new Map();
27892
- for (const e of entries) {
27893
- if (!byKey.has(e.key)) byKey.set(e.key, e);
27906
+ function parseRelativeDate(since) {
27907
+ const trimmed = since.trim();
27908
+ const hourMatch = trimmed.match(/^(\d+)h$/);
27909
+ if (hourMatch) {
27910
+ const d = /* @__PURE__ */ new Date();
27911
+ d.setHours(d.getHours() - parseInt(hourMatch[1]));
27912
+ return d.toISOString().split("T")[0];
27894
27913
  }
27895
- const adj = /* @__PURE__ */ new Map();
27896
- const link = (a, b) => {
27897
- if (a === b) return;
27898
- if (!byKey.has(a) || !byKey.has(b)) return;
27899
- if (!adj.has(a)) adj.set(a, /* @__PURE__ */ new Set());
27900
- adj.get(a).add(b);
27901
- if (!adj.has(b)) adj.set(b, /* @__PURE__ */ new Set());
27902
- adj.get(b).add(a);
27914
+ const dayMatch = trimmed.match(/^(\d+)d$/);
27915
+ if (dayMatch) {
27916
+ const d = /* @__PURE__ */ new Date();
27917
+ d.setDate(d.getDate() - parseInt(dayMatch[1]));
27918
+ return d.toISOString().split("T")[0];
27919
+ }
27920
+ if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
27921
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
27922
+ return today;
27923
+ }
27924
+ var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
27925
+
27926
+ // src/mcp/scoring.ts
27927
+ function entryScore(dateStr, accessed) {
27928
+ const days = (Date.now() - (/* @__PURE__ */ new Date(`${dateStr}T00:00:00`)).getTime()) / 864e5;
27929
+ const recency = Math.max(0, 30 - days) / 30;
27930
+ const freq = Math.min(1, accessed / 5);
27931
+ return recency * 0.6 + freq * 0.4;
27932
+ }
27933
+ function entryScoreForLine(line) {
27934
+ const parts = line.trim().split("|");
27935
+ const date5 = parts[6] || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
27936
+ const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0;
27937
+ return entryScore(date5, accessed);
27938
+ }
27939
+ function findRelatedEntries(text, excludeKey = "", limit = 3) {
27940
+ const data = readMemory();
27941
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
27942
+ const queryTokens = normalize(text).split(" ").filter(Boolean);
27943
+ const scored = lines.map((line) => {
27944
+ const trimmed = line.trim();
27945
+ const parts = trimmed.split("|");
27946
+ if (parts.length < 7) return null;
27947
+ const [id, cat, key, content, file2, tags, date5] = parts;
27948
+ if (key === excludeKey) return null;
27949
+ const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
27950
+ let score = 0;
27951
+ for (const token of queryTokens) {
27952
+ if (searchStr.includes(token)) score++;
27953
+ }
27954
+ if (score === 0) return null;
27955
+ return { id, cat, key, content, file: file2, tags, date: date5, score };
27956
+ }).filter(Boolean).sort((a, b) => b.score - a.score).slice(0, limit);
27957
+ return scored;
27958
+ }
27959
+ function bumpAccessed(ids) {
27960
+ if (ids.length === 0) return;
27961
+ const idSet = new Set(ids);
27962
+ const data = readMemory();
27963
+ const lines = data.split("\n");
27964
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
27965
+ if (headerIdx === -1) return;
27966
+ for (let i = headerIdx + 1; i < lines.length; i++) {
27967
+ const line = lines[i];
27968
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
27969
+ if (line.startsWith(" summaries:")) break;
27970
+ const parts = line.trim().split("|");
27971
+ if (idSet.has(parts[0])) {
27972
+ const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1;
27973
+ parts[8] = String(accessed);
27974
+ lines[i] = ` ${parts.join("|")}`;
27975
+ }
27976
+ }
27977
+ writeMemory(lines.join("\n"));
27978
+ }
27979
+
27980
+ // src/mcp/observations.ts
27981
+ import { readFileSync as readFileSync3, existsSync as existsSync3 } from "fs";
27982
+ function readObservations() {
27983
+ if (!existsSync3(OBSERVATIONS_FILE)) return [];
27984
+ return readFileSync3(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
27985
+ const p = l.trim().split("|");
27986
+ return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" };
27987
+ });
27988
+ }
27989
+
27990
+ // src/mcp/archive.ts
27991
+ import { readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
27992
+ function archiveOldEntries(opts = {}) {
27993
+ const data = readMemory();
27994
+ const lines = data.split("\n");
27995
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
27996
+ if (headerIdx === -1) return { archived: 0, kept: 0 };
27997
+ const today = /* @__PURE__ */ new Date();
27998
+ const cutoff = new Date(today);
27999
+ cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS);
28000
+ const cutoffStr = cutoff.toISOString().split("T")[0];
28001
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
28002
+ const toArchive = /* @__PURE__ */ new Set();
28003
+ entryLines2.forEach((line, idx) => {
28004
+ const parts = line.trim().split("|");
28005
+ if (parts.length < 7) return;
28006
+ const date5 = parts[6];
28007
+ const ttl = parts[7] || "";
28008
+ if (date5 < cutoffStr || ttl && isExpired(ttl)) toArchive.add(idx);
28009
+ });
28010
+ if (opts.trimToMax) {
28011
+ const remaining = entryLines2.length - toArchive.size;
28012
+ if (remaining > MAX_ENTRIES) {
28013
+ const need = remaining - MAX_ENTRIES;
28014
+ const candidates = entryLines2.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c) => !toArchive.has(c.idx)).sort((a, b) => a.score - b.score);
28015
+ for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx);
28016
+ }
28017
+ }
28018
+ if (toArchive.size === 0) return { archived: 0, kept: entryLines2.length };
28019
+ const toArchiveLines = entryLines2.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim());
28020
+ const toKeepLines = entryLines2.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim());
28021
+ let archiveContent = "";
28022
+ if (existsSync4(ARCHIVE_FILE)) {
28023
+ archiveContent = readFileSync4(ARCHIVE_FILE, "utf-8");
28024
+ } else {
28025
+ archiveContent = `version: 1
28026
+ archived:
28027
+ `;
28028
+ }
28029
+ const archiveLines = archiveContent.split("\n");
28030
+ let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["));
28031
+ if (archiveHeaderIdx === -1) {
28032
+ archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`);
28033
+ archiveHeaderIdx = archiveLines.length - 1;
28034
+ }
28035
+ const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/);
28036
+ const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0;
28037
+ for (const entry of toArchiveLines) {
28038
+ archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`);
28039
+ }
28040
+ archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`);
28041
+ safeWrite(ARCHIVE_FILE, archiveLines.join("\n"));
28042
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`);
28043
+ const keepSet = new Set(toKeepLines);
28044
+ const allEntryLines = lines.slice(headerIdx + 1);
28045
+ const newEntryLines = allEntryLines.filter((l) => {
28046
+ if (l.trim().length === 0) return false;
28047
+ return keepSet.has(l.trim());
28048
+ });
28049
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`));
28050
+ writeMemory(lines.join("\n"));
28051
+ return { archived: toArchiveLines.length, kept: toKeepLines.length };
28052
+ }
28053
+ function pruneExpiredEntries() {
28054
+ ensureMemoryFile();
28055
+ if (!existsSync4(MEMORY_FILE)) return 0;
28056
+ let pruned = 0;
28057
+ withLockSync(MEMORY_FILE, () => {
28058
+ const data = readMemory();
28059
+ const lines = data.split("\n");
28060
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
28061
+ if (headerIdx === -1) return;
28062
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28063
+ const kept = entryLines2.filter((l) => {
28064
+ const parts = l.trim().split("|");
28065
+ if (parts.length < 8) return true;
28066
+ const ttl = parts[7] || "";
28067
+ if (ttl && isExpired(ttl)) {
28068
+ pruned++;
28069
+ return false;
28070
+ }
28071
+ return true;
28072
+ });
28073
+ if (pruned === 0) return;
28074
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`);
28075
+ const keepSet = new Set(kept.map((l) => l.trim()));
28076
+ const allEntryLines = lines.slice(headerIdx + 1);
28077
+ const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()));
28078
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => l.trim().length ? ` ${l.trim()}` : l));
28079
+ writeMemory(lines.join("\n"));
28080
+ });
28081
+ return pruned;
28082
+ }
28083
+
28084
+ // src/lib/graph.ts
28085
+ var isExpiredLocal = (ttl) => {
28086
+ if (!ttl) return false;
28087
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28088
+ return ttl <= today;
28089
+ };
28090
+ var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28091
+ var entryLines = (data) => data.split("\n").filter(
28092
+ (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
28093
+ );
28094
+ function parseEntries(data) {
28095
+ const out = [];
28096
+ for (const line of entryLines(data)) {
28097
+ const parts = line.trim().split("|");
28098
+ if (parts.length < 7) continue;
28099
+ const [id, category, key, content, file2, tags, date5, ttl, accessedRaw, linksRaw] = parts;
28100
+ out.push({
28101
+ id,
28102
+ category,
28103
+ key,
28104
+ content,
28105
+ file: file2 || "",
28106
+ tags: (tags || "").split(";").map((t) => t.trim()).filter(Boolean),
28107
+ date: date5 || "",
28108
+ ttl: ttl || "",
28109
+ accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
28110
+ links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean)
28111
+ });
28112
+ }
28113
+ return out;
28114
+ }
28115
+ function buildGraph(entries) {
28116
+ const byKey = /* @__PURE__ */ new Map();
28117
+ for (const e of entries) {
28118
+ if (!byKey.has(e.key)) byKey.set(e.key, e);
28119
+ }
28120
+ const adj = /* @__PURE__ */ new Map();
28121
+ const link = (a, b) => {
28122
+ if (a === b) return;
28123
+ if (!byKey.has(a) || !byKey.has(b)) return;
28124
+ if (!adj.has(a)) adj.set(a, /* @__PURE__ */ new Set());
28125
+ adj.get(a).add(b);
28126
+ if (!adj.has(b)) adj.set(b, /* @__PURE__ */ new Set());
28127
+ adj.get(b).add(a);
27903
28128
  };
27904
28129
  for (const e of entries) {
27905
28130
  for (const l of e.links) link(e.key, l);
@@ -27917,7 +28142,7 @@ var importance = (e) => {
27917
28142
  const freq = Math.min(1, e.accessed / 5);
27918
28143
  return recency * 0.6 + freq * 0.4;
27919
28144
  };
27920
- var tokenize = (s) => normalize(s).split(" ").filter(Boolean);
28145
+ var tokenize = (s) => normalize2(s).split(" ").filter(Boolean);
27921
28146
  function bm25Scores(entries, query) {
27922
28147
  const N = entries.length;
27923
28148
  const scores = /* @__PURE__ */ new Map();
@@ -27979,7 +28204,7 @@ function graphRecallDetailed(data, query, opts = {}) {
27979
28204
  if (from_date && e.date < from_date) continue;
27980
28205
  if (to_date && e.date > to_date) continue;
27981
28206
  if (e.ttl && isExpiredLocal(e.ttl)) continue;
27982
- const text = normalize(
28207
+ const text = normalize2(
27983
28208
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
27984
28209
  );
27985
28210
  if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue;
@@ -28051,8 +28276,8 @@ function renderCompact(entries, opts = {}) {
28051
28276
  }
28052
28277
 
28053
28278
  // src/lib/quality.ts
28054
- var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28055
- var tokenize2 = (s) => normalize2(s).split(" ").filter(Boolean);
28279
+ var normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28280
+ var tokenize2 = (s) => normalize3(s).split(" ").filter(Boolean);
28056
28281
  var isExpiredLocal2 = (ttl) => {
28057
28282
  if (!ttl) return false;
28058
28283
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -28131,7 +28356,7 @@ function generateSmartRecall(data, intent, opts = {}) {
28131
28356
  if (e.ttl && isExpiredLocal2(e.ttl)) return false;
28132
28357
  return true;
28133
28358
  }).map((e) => {
28134
- const text = normalize2(
28359
+ const text = normalize3(
28135
28360
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
28136
28361
  );
28137
28362
  const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t));
@@ -28192,1030 +28417,1779 @@ function generateSystemPrimer(data) {
28192
28417
  return lines.join("\n");
28193
28418
  }
28194
28419
 
28195
- // src/mcp/server.ts
28196
- var __dirname = dirname(fileURLToPath(import.meta.url));
28197
- var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
28198
- var MEMORY_FILE = join2(MEMORY_DIR, "data.toon");
28199
- var ARCHIVE_FILE = join2(MEMORY_DIR, "archive.toon");
28200
- var OBSERVATIONS_FILE = join2(MEMORY_DIR, "observations.toon");
28201
- var CONFIG_FILE = join2(MEMORY_DIR, "config.json");
28202
- var MAX_ENTRIES = 100;
28203
- var ARCHIVE_DAYS = 30;
28204
- function safeWrite(file2, content) {
28205
- withLockSync(file2, () => atomicWrite(file2, content));
28206
- }
28207
- var ALGORITHM = "aes-256-gcm";
28208
- function loadConfig() {
28209
- if (!existsSync3(CONFIG_FILE)) {
28210
- return { encrypted: false };
28211
- }
28212
- try {
28213
- return JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
28214
- } catch {
28215
- return { encrypted: false };
28216
- }
28217
- }
28218
- function saveConfig(config2) {
28219
- ensureMemoryDir();
28220
- let existing = {};
28221
- if (existsSync3(CONFIG_FILE)) {
28222
- try {
28223
- existing = JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
28224
- } catch {
28225
- existing = {};
28420
+ // src/mcp/consolidation.ts
28421
+ function consolidateEntries() {
28422
+ const data = readMemory();
28423
+ const lines = data.split("\n");
28424
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28425
+ if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
28426
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28427
+ const byKey = /* @__PURE__ */ new Map();
28428
+ const keyOrder = [];
28429
+ const mergedAway = [];
28430
+ for (let i = 0; i < entryLines2.length; i++) {
28431
+ const line = entryLines2[i].trim();
28432
+ const parts = line.split("|");
28433
+ if (parts.length < 3) continue;
28434
+ const key = parts[2];
28435
+ const existingIdx = keyOrder.findIndex((idx) => {
28436
+ const ep = entryLines2[idx].trim().split("|");
28437
+ return ep[2] === key;
28438
+ });
28439
+ if (existingIdx !== -1) {
28440
+ const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx]), line);
28441
+ byKey.set(keyOrder[existingIdx], mergedLine);
28442
+ mergedAway.push(i);
28443
+ } else {
28444
+ byKey.set(i, line);
28445
+ keyOrder.push(i);
28226
28446
  }
28227
28447
  }
28228
- writeFileSync3(CONFIG_FILE, JSON.stringify({ ...existing, ...config2 }, null, 2));
28229
- }
28230
- function getKey() {
28231
- return process.env.TOON_MEMORY_KEY;
28232
- }
28233
- function ensureMemoryDir() {
28234
- if (!existsSync3(MEMORY_DIR)) mkdirSync2(MEMORY_DIR, { recursive: true });
28448
+ const contentSeen = /* @__PURE__ */ new Map();
28449
+ const order = [];
28450
+ const duplicates = [];
28451
+ for (const idx of keyOrder) {
28452
+ const line = byKey.get(idx);
28453
+ const parts = line.split("|");
28454
+ if (parts.length < 3) {
28455
+ order.push(line);
28456
+ continue;
28457
+ }
28458
+ const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim();
28459
+ if (contentSeen.has(content)) {
28460
+ duplicates.push(parts[2]);
28461
+ continue;
28462
+ }
28463
+ contentSeen.set(content, line);
28464
+ order.push(line);
28465
+ }
28466
+ const totalRemoved = mergedAway.length + duplicates.length;
28467
+ if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] };
28468
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`);
28469
+ lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`));
28470
+ writeMemory(lines.join("\n"));
28471
+ return { removed: totalRemoved, kept: order.length, duplicates };
28235
28472
  }
28236
- function ensureMemoryFile() {
28237
- ensureMemoryDir();
28238
- if (!existsSync3(MEMORY_FILE)) {
28239
- writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n");
28473
+
28474
+ // src/lib/context.ts
28475
+ import { existsSync as existsSync9 } from "fs";
28476
+ import { join as join6 } from "path";
28477
+
28478
+ // src/lib/sessions.ts
28479
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3, readdirSync, unlinkSync as unlinkSync2, statSync as statSync2 } from "fs";
28480
+ import { join as join2 } from "path";
28481
+ var SESSION_TTL_MS = 10 * 60 * 1e3;
28482
+ var PRUNE_STALE_MS = 10 * 60 * 1e3;
28483
+ function isAlive2(pid) {
28484
+ if (!pid || pid <= 0) return false;
28485
+ try {
28486
+ process.kill(pid, 0);
28487
+ return true;
28488
+ } catch {
28489
+ return false;
28240
28490
  }
28241
28491
  }
28242
- function encrypt(text, key) {
28243
- const keyBuffer = Buffer.from(key, "hex");
28244
- const iv = randomBytes(16);
28245
- const cipher = createCipheriv(ALGORITHM, keyBuffer, iv);
28246
- let encrypted = cipher.update(text, "utf8", "hex");
28247
- encrypted += cipher.final("hex");
28248
- const authTag = cipher.getAuthTag();
28249
- return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
28492
+ function sessionDir() {
28493
+ return join2(process.cwd(), ".toon-memory", "memory", "sessions");
28250
28494
  }
28251
- function decrypt(encryptedData, key) {
28252
- const keyBuffer = Buffer.from(key, "hex");
28253
- const parts = encryptedData.split(":");
28254
- if (parts.length !== 3) {
28255
- throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext");
28495
+ function resolveSessionId(payload = {}) {
28496
+ const fromPayload = payload.session_id || payload.sessionId || payload.session_id_untruncated;
28497
+ if (fromPayload && fromPayload.trim()) return fromPayload.trim();
28498
+ if (process.env.TOON_MEMORY_SESSION_ID && process.env.TOON_MEMORY_SESSION_ID.trim()) {
28499
+ return process.env.TOON_MEMORY_SESSION_ID.trim();
28256
28500
  }
28257
- const [ivHex, authTagHex, encrypted] = parts;
28258
- const iv = Buffer.from(ivHex, "hex");
28259
- const authTag = Buffer.from(authTagHex, "hex");
28260
- const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv);
28261
- decipher.setAuthTag(authTag);
28262
- let decrypted = decipher.update(encrypted, "hex", "utf8");
28263
- decrypted += decipher.final("utf8");
28264
- return decrypted;
28501
+ return `proc-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
28265
28502
  }
28266
- function readMemory() {
28267
- ensureMemoryFile();
28268
- const config2 = loadConfig();
28269
- const data = readUnderLock(MEMORY_FILE);
28270
- if (config2.encrypted) {
28271
- const key = getKey();
28272
- if (!key) return "";
28503
+ function currentBranch() {
28504
+ if (process.env.TOON_MEMORY_BRANCH && process.env.TOON_MEMORY_BRANCH.trim()) {
28505
+ return process.env.TOON_MEMORY_BRANCH.trim();
28506
+ }
28507
+ try {
28508
+ let gitDir2 = join2(process.cwd(), ".git");
28509
+ if (existsSync5(gitDir2) && !statSync2(gitDir2).isDirectory()) {
28510
+ const pointer = readFileSync5(gitDir2, "utf-8").trim();
28511
+ if (pointer.startsWith("gitdir:")) {
28512
+ const target = pointer.slice(7).trim();
28513
+ gitDir2 = target.startsWith("/") ? target : join2(process.cwd(), target);
28514
+ }
28515
+ }
28516
+ const headPath = join2(gitDir2, "HEAD");
28517
+ if (!existsSync5(headPath)) return "unknown";
28518
+ const head = readFileSync5(headPath, "utf-8").trim();
28519
+ if (head.startsWith("ref:")) {
28520
+ const ref = head.slice(4).trim();
28521
+ const parts = ref.split("/");
28522
+ return parts[parts.length - 1] || "unknown";
28523
+ }
28524
+ return head ? head.slice(0, 7) : "unknown";
28525
+ } catch {
28526
+ return "unknown";
28527
+ }
28528
+ }
28529
+ function recentIso(iso) {
28530
+ const t = new Date(iso).getTime();
28531
+ return !isNaN(t) && Date.now() - t <= SESSION_TTL_MS;
28532
+ }
28533
+ function listSessions() {
28534
+ const dir = sessionDir();
28535
+ if (!existsSync5(dir)) return [];
28536
+ return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => {
28273
28537
  try {
28274
- return decrypt(data, key);
28538
+ return JSON.parse(readFileSync5(join2(dir, f), "utf-8"));
28275
28539
  } catch {
28276
- return "";
28540
+ return null;
28541
+ }
28542
+ }).filter(Boolean).map((r) => {
28543
+ const rec = r;
28544
+ const active = recentIso(rec.lastSeen);
28545
+ return { ...rec, active, ageMs: Date.now() - new Date(rec.lastSeen).getTime() };
28546
+ }).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
28547
+ }
28548
+ function pruneSessions() {
28549
+ const pruned = [];
28550
+ const dir = sessionDir();
28551
+ if (!existsSync5(dir)) return pruned;
28552
+ for (const f of readdirSync(dir).filter((x) => x.endsWith(".json"))) {
28553
+ const p = join2(dir, f);
28554
+ let rec = null;
28555
+ try {
28556
+ rec = JSON.parse(readFileSync5(p, "utf-8"));
28557
+ } catch {
28558
+ continue;
28559
+ }
28560
+ if (!rec) continue;
28561
+ const stale = Date.now() - new Date(rec.lastSeen).getTime() > PRUNE_STALE_MS;
28562
+ if (stale && !isAlive2(rec.pid)) {
28563
+ try {
28564
+ unlinkSync2(p);
28565
+ pruned.push(rec.id);
28566
+ } catch {
28567
+ }
28277
28568
  }
28278
28569
  }
28279
- return data;
28570
+ return pruned;
28280
28571
  }
28281
- function writeMemory(content) {
28282
- ensureMemoryFile();
28283
- const config2 = loadConfig();
28284
- if (config2.encrypted) {
28285
- const key = getKey();
28286
- if (!key) return;
28287
- const encrypted = encrypt(content, key);
28288
- safeWrite(MEMORY_FILE, encrypted);
28289
- return;
28572
+ function detectConflicts(active = listSessions().filter((s) => s.active)) {
28573
+ const byFile = /* @__PURE__ */ new Map();
28574
+ for (const s of active) {
28575
+ if (s.ended) continue;
28576
+ for (const file2 of Object.keys(s.files)) {
28577
+ if (!byFile.has(file2)) byFile.set(file2, []);
28578
+ byFile.get(file2).push({ id: s.id, agent: s.agent, branch: s.branch });
28579
+ }
28290
28580
  }
28291
- safeWrite(MEMORY_FILE, content);
28581
+ const conflicts = [];
28582
+ for (const [file2, sessions] of byFile) {
28583
+ if (sessions.length >= 2) conflicts.push({ file: file2, sessions });
28584
+ }
28585
+ return conflicts;
28292
28586
  }
28293
- function generateId() {
28294
- return randomBytes(4).toString("hex");
28587
+ function coordinationView(selfId) {
28588
+ const all = listSessions();
28589
+ const active = all.filter((s) => s.active);
28590
+ const conflicts = detectConflicts(active);
28591
+ const self = selfId ? all.find((s) => s.id === selfId) : void 0;
28592
+ pruneSessions();
28593
+ return { active, conflicts, self };
28295
28594
  }
28296
- function parseTTL(ttl) {
28297
- if (!ttl || !ttl.trim()) return "";
28298
- const trimmed = ttl.trim();
28299
- const dayMatch = trimmed.match(/^(\d+)d$/);
28300
- if (dayMatch) {
28301
- const days = parseInt(dayMatch[1]);
28302
- const d = /* @__PURE__ */ new Date();
28303
- d.setDate(d.getDate() + days);
28304
- return d.toISOString().split("T")[0];
28595
+
28596
+ // src/lib/git.ts
28597
+ import { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync3 } from "fs";
28598
+ import { join as join3 } from "path";
28599
+ import { inflateSync } from "zlib";
28600
+ function gitDir(cwd) {
28601
+ const dotgit = join3(cwd || process.cwd(), ".git");
28602
+ if (!existsSync6(dotgit)) return null;
28603
+ if (statSync3(dotgit).isDirectory()) return dotgit;
28604
+ const pointer = readFileSync6(dotgit, "utf-8").trim();
28605
+ if (pointer.startsWith("gitdir:")) {
28606
+ const target = pointer.slice(7).trim();
28607
+ return target.startsWith("/") ? target : join3(process.cwd(), target);
28608
+ }
28609
+ return null;
28610
+ }
28611
+ function resolveHead(cwd) {
28612
+ const dir = gitDir(cwd);
28613
+ if (!dir) return null;
28614
+ const headPath = join3(dir, "HEAD");
28615
+ if (!existsSync6(headPath)) return null;
28616
+ const head = readFileSync6(headPath, "utf-8").trim();
28617
+ if (head.startsWith("ref:")) {
28618
+ const refPath = join3(dir, head.slice(4).trim());
28619
+ if (!existsSync6(refPath)) return null;
28620
+ return readFileSync6(refPath, "utf-8").trim();
28621
+ }
28622
+ return head || null;
28623
+ }
28624
+ function parseIndex(dir) {
28625
+ const indexPath = join3(dir, "index");
28626
+ if (!existsSync6(indexPath)) return [];
28627
+ const buf = readFileSync6(indexPath);
28628
+ if (buf.length < 12) return [];
28629
+ const sig = buf.toString("ascii", 0, 4);
28630
+ if (sig !== "DIRC") return [];
28631
+ const version2 = buf.readUInt32BE(4);
28632
+ const count = buf.readUInt32BE(8);
28633
+ if (version2 < 2 || version2 > 4) return [];
28634
+ const entries = [];
28635
+ let offset = 12;
28636
+ for (let i = 0; i < count && offset + 62 <= buf.length; i++) {
28637
+ const entryStart = offset;
28638
+ const mtimeSec = buf.readUInt32BE(offset);
28639
+ const mtimeNsec = buf.readUInt32BE(offset + 4);
28640
+ const dev = buf.readUInt32BE(offset + 8);
28641
+ const ino = buf.readUInt32BE(offset + 12);
28642
+ const mode = buf.readUInt32BE(offset + 16);
28643
+ const uid = buf.readUInt32BE(offset + 20);
28644
+ const gid = buf.readUInt32BE(offset + 24);
28645
+ const size = buf.readUInt32BE(offset + 28);
28646
+ const sha = buf.slice(offset + 32, offset + 52).toString("hex");
28647
+ const flags = buf.readUInt16BE(offset + 52);
28648
+ const nameLen = flags & 4095;
28649
+ const nameStart = entryStart + 62;
28650
+ let name;
28651
+ if (nameLen > 0 && nameStart + nameLen <= buf.length) {
28652
+ name = buf.toString("utf-8", nameStart, nameStart + nameLen);
28653
+ } else {
28654
+ const end = buf.indexOf(0, nameStart);
28655
+ name = end >= 0 ? buf.toString("utf-8", nameStart, end) : buf.toString("utf-8", nameStart);
28656
+ }
28657
+ if (version2 >= 3) {
28658
+ }
28659
+ const rawLen = 62 + name.length;
28660
+ const paddedLen = Math.ceil(rawLen / 8) * 8;
28661
+ offset = entryStart + paddedLen;
28662
+ entries.push({ mtimeSec, mtimeNsec, dev, ino, mode, uid, gid, size, sha, flags, name });
28305
28663
  }
28306
- if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
28307
- return "";
28664
+ return entries;
28308
28665
  }
28309
- function isExpired(ttl) {
28310
- if (!ttl) return false;
28311
- const ttlDate = parseTTL(ttl) || ttl;
28312
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28313
- return ttlDate <= today;
28666
+ function readGitIndex(cwd) {
28667
+ const dir = gitDir(cwd);
28668
+ if (!dir) return [];
28669
+ return parseIndex(dir).map((e) => e.name);
28314
28670
  }
28315
- var TAG_VOCABULARY = {
28316
- "redis": ["redis", "cache", "caching", "memcached"],
28317
- "auth": ["auth", "authentication", "authorization", "login", "token", "jwt", "session", "oauth"],
28318
- "api": ["api", "endpoint", "rest", "graphql", "route", "router", "controller"],
28319
- "db": ["database", "db", "sql", "postgres", "mysql", "mongo", "query", "migration", "schema"],
28320
- "security": ["security", "encrypt", "decrypt", "vulnerability", "xss", "csrf", "cors", "sanitiz"],
28321
- "test": ["test", "testing", "vitest", "jest", "spec", "mock", "assert", "coverage"],
28322
- "deploy": ["deploy", "docker", "ci/cd", "github actions", "pipeline", "kubernetes", "k8s"],
28323
- "config": ["config", "configuration", "settings", "env", "environment", "dotenv"],
28324
- "performance": ["performance", "optimize", "benchmark", "latency", "throughput", "cache"],
28325
- "refactor": ["refactor", "cleanup", "restructure", "reorganize", "rework"],
28326
- "error": ["error", "exception", "throw", "catch", "handling", "retry", "fallback"],
28327
- "logging": ["log", "logging", "logger", "debug", "trace", "monitor", "observability"],
28328
- "types": ["typescript", "types", "type", "interface", "generic", "enum", "zod", "schema"],
28329
- "async": ["async", "await", "promise", "concurrent", "parallel", "worker", "queue"],
28330
- "state": ["state", "store", "redux", "context", "reducer", "action", "observable"],
28331
- "ui": ["ui", "component", "render", "dom", "css", "style", "layout", "responsive"],
28332
- "storage": ["storage", "file", "filesystem", "s3", "blob", "upload", "download"],
28333
- "email": ["email", "mail", "smtp", "sendgrid", "newsletter", "notification"],
28334
- "payment": ["payment", "stripe", "billing", "invoice", "checkout", "subscription"],
28335
- "webhook": ["webhook", "callback", "event", "listener", "hook"]
28336
- };
28337
- function inferTags(content, key, vocab) {
28338
- const text = `${key} ${content}`.toLowerCase();
28339
- const matched = [];
28340
- for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
28341
- if (keywords.some((kw) => text.includes(kw))) {
28342
- matched.push(tag);
28671
+ function readObject(sha, cwd) {
28672
+ const dir = gitDir(cwd);
28673
+ if (!dir) return null;
28674
+ const objPath = join3(dir, "objects", sha.slice(0, 2), sha.slice(2));
28675
+ if (!existsSync6(objPath)) return null;
28676
+ try {
28677
+ const compressed = readFileSync6(objPath);
28678
+ const decompressed = inflateSync(compressed);
28679
+ const str = decompressed.toString("utf-8");
28680
+ const nullIdx = str.indexOf("\0");
28681
+ if (nullIdx < 0) return null;
28682
+ const header = str.slice(0, nullIdx);
28683
+ const type = header.split(" ")[0];
28684
+ const content = str.slice(nullIdx + 1);
28685
+ return { type, content };
28686
+ } catch {
28687
+ return null;
28688
+ }
28689
+ }
28690
+ function readRecentCommits(count = 10, cwd) {
28691
+ const sha = resolveHead(cwd);
28692
+ if (!sha) return [];
28693
+ const commits = [];
28694
+ const visited = /* @__PURE__ */ new Set();
28695
+ let current = sha;
28696
+ while (commits.length < count && current && !visited.has(current)) {
28697
+ visited.add(current);
28698
+ const obj = readObject(current, cwd);
28699
+ if (!obj || obj.type !== "commit") break;
28700
+ const lines = obj.content.split("\n");
28701
+ let subject = "";
28702
+ let author = "";
28703
+ let date5 = "";
28704
+ let parent = null;
28705
+ let pastHeaders = false;
28706
+ for (const line of lines) {
28707
+ if (line.startsWith("author ")) {
28708
+ const match = line.match(/^author\s+(.+?)\s+<[^>]+>\s+(\d+)/);
28709
+ if (match) {
28710
+ author = match[1];
28711
+ const ts = parseInt(match[2]);
28712
+ date5 = new Date(ts * 1e3).toISOString().split("T")[0];
28713
+ }
28714
+ } else if (line.startsWith("parent ")) {
28715
+ parent = line.slice(7).trim();
28716
+ } else if (line.startsWith("tree ")) {
28717
+ } else if (line.startsWith("committer ")) {
28718
+ pastHeaders = true;
28719
+ } else if (pastHeaders && !subject && line.trim()) {
28720
+ subject = line.trim();
28721
+ }
28722
+ }
28723
+ commits.push({
28724
+ hash: current,
28725
+ shortHash: current.slice(0, 7),
28726
+ subject,
28727
+ author,
28728
+ date: date5
28729
+ });
28730
+ current = parent || "";
28731
+ }
28732
+ return commits;
28733
+ }
28734
+ function gitStatusSummary(cwd) {
28735
+ const branch = currentBranch();
28736
+ const head = resolveHead(cwd);
28737
+ const trackedFiles = readGitIndex(cwd).length;
28738
+ const recentCommits = readRecentCommits(5, cwd);
28739
+ const hasGitignore = existsSync6(join3(cwd || process.cwd(), ".gitignore"));
28740
+ return { branch, head, trackedFiles, recentCommits, hasGitignore };
28741
+ }
28742
+
28743
+ // src/lib/project-scan.ts
28744
+ import { existsSync as existsSync7, readFileSync as readFileSync7, readdirSync as readdirSync3, statSync as statSync4 } from "fs";
28745
+ import { join as join4, extname } from "path";
28746
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
28747
+ "node_modules",
28748
+ ".git",
28749
+ ".toon-memory",
28750
+ "dist",
28751
+ "build",
28752
+ ".next",
28753
+ ".nuxt",
28754
+ "coverage",
28755
+ "__pycache__",
28756
+ ".venv",
28757
+ "vendor",
28758
+ ".cache",
28759
+ ".turbo"
28760
+ ]);
28761
+ function scanProjectStructure(root, maxDepth = 2) {
28762
+ const dirs = [];
28763
+ const rootFiles = [];
28764
+ let sourceFileCount = 0;
28765
+ const extensions = {};
28766
+ function walk(dir, depth) {
28767
+ if (depth > maxDepth) return;
28768
+ let entries;
28769
+ try {
28770
+ entries = readdirSync3(dir);
28771
+ } catch {
28772
+ return;
28773
+ }
28774
+ for (const entry of entries) {
28775
+ if (entry.startsWith(".") && depth === 0 && entry !== ".env.example" && entry !== ".env.template") continue;
28776
+ const fullPath = join4(dir, entry);
28777
+ let isDir;
28778
+ try {
28779
+ isDir = statSync4(fullPath).isDirectory();
28780
+ } catch {
28781
+ continue;
28782
+ }
28783
+ if (isDir) {
28784
+ if (SKIP_DIRS.has(entry)) continue;
28785
+ if (depth === 0) dirs.push(entry);
28786
+ walk(fullPath, depth + 1);
28787
+ } else {
28788
+ if (depth === 0) rootFiles.push(entry);
28789
+ sourceFileCount++;
28790
+ const ext = extname(entry) || "(no ext)";
28791
+ extensions[ext] = (extensions[ext] || 0) + 1;
28792
+ }
28343
28793
  }
28344
28794
  }
28345
- if (vocab) {
28346
- for (const [tag, keywords] of Object.entries(vocab)) {
28347
- if (keywords.some((kw) => text.includes(kw))) {
28348
- matched.push(tag);
28795
+ walk(root, 0);
28796
+ return { dirs: dirs.sort(), rootFiles: rootFiles.sort(), sourceFileCount, extensions };
28797
+ }
28798
+ function readEnvExample(root) {
28799
+ const candidates = [".env.example", ".env.template", ".env.sample"];
28800
+ for (const name of candidates) {
28801
+ const p = join4(root, name);
28802
+ if (existsSync7(p)) {
28803
+ try {
28804
+ const content = readFileSync7(p, "utf-8");
28805
+ return parseEnvContent(content);
28806
+ } catch {
28807
+ return [];
28349
28808
  }
28350
28809
  }
28351
28810
  }
28352
- return matched.join(";");
28811
+ return [];
28353
28812
  }
28354
- function parseRelativeDate(since) {
28355
- const trimmed = since.trim();
28356
- const hourMatch = trimmed.match(/^(\d+)h$/);
28357
- if (hourMatch) {
28358
- const d = /* @__PURE__ */ new Date();
28359
- d.setHours(d.getHours() - parseInt(hourMatch[1]));
28360
- return d.toISOString().split("T")[0];
28813
+ function parseEnvContent(content) {
28814
+ const vars = [];
28815
+ for (const raw of content.split("\n")) {
28816
+ const line = raw.trim();
28817
+ if (!line || line.startsWith("#")) continue;
28818
+ const eqIdx = line.indexOf("=");
28819
+ if (eqIdx < 0) continue;
28820
+ const name = line.slice(0, eqIdx).trim();
28821
+ const rest = line.slice(eqIdx + 1);
28822
+ const hashIdx = rest.indexOf("#");
28823
+ const defaultVal = (hashIdx >= 0 ? rest.slice(0, hashIdx) : rest).trim();
28824
+ const comment = hashIdx >= 0 ? rest.slice(hashIdx + 1).trim() : "";
28825
+ vars.push({ name, comment, default: defaultVal });
28361
28826
  }
28362
- const dayMatch = trimmed.match(/^(\d+)d$/);
28363
- if (dayMatch) {
28364
- const d = /* @__PURE__ */ new Date();
28365
- d.setDate(d.getDate() - parseInt(dayMatch[1]));
28366
- return d.toISOString().split("T")[0];
28827
+ return vars;
28828
+ }
28829
+ function readManifest(root) {
28830
+ const pkgPath = join4(root, "package.json");
28831
+ if (existsSync7(pkgPath)) {
28832
+ try {
28833
+ const pkg = JSON.parse(readFileSync7(pkgPath, "utf-8"));
28834
+ return {
28835
+ name: pkg.name || "",
28836
+ version: pkg.version || "",
28837
+ language: "javascript",
28838
+ description: pkg.description || "",
28839
+ scripts: pkg.scripts || {},
28840
+ deps: Object.keys(pkg.dependencies || {}),
28841
+ devDeps: Object.keys(pkg.devDependencies || {})
28842
+ };
28843
+ } catch {
28844
+ }
28367
28845
  }
28368
- if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
28369
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28370
- return today;
28846
+ const cargoPath = join4(root, "Cargo.toml");
28847
+ if (existsSync7(cargoPath)) {
28848
+ try {
28849
+ const txt = readFileSync7(cargoPath, "utf-8");
28850
+ const nameMatch = txt.match(/^name\s*=\s*"([^"]+)"/m);
28851
+ const verMatch = txt.match(/^version\s*=\s*"([^"]+)"/m);
28852
+ const depsBlock = txt.match(/\[dependencies\]([\s\S]*?)(?:\[|$)/)?.[1] || "";
28853
+ const deps = [...depsBlock.matchAll(/^\s*([A-Za-z0-9_-]+)\s*=/gm)].map((m) => m[1]);
28854
+ return {
28855
+ name: nameMatch?.[1] || "",
28856
+ version: verMatch?.[1] || "",
28857
+ language: "rust",
28858
+ description: "",
28859
+ scripts: {},
28860
+ deps,
28861
+ devDeps: []
28862
+ };
28863
+ } catch {
28864
+ }
28865
+ }
28866
+ const pyPath = join4(root, "pyproject.toml");
28867
+ if (existsSync7(pyPath)) {
28868
+ try {
28869
+ const txt = readFileSync7(pyPath, "utf-8");
28870
+ const nameMatch = txt.match(/^name\s*=\s*"([^"]+)"/m);
28871
+ const verMatch = txt.match(/^version\s*=\s*"([^"]+)"/m);
28872
+ return {
28873
+ name: nameMatch?.[1] || "",
28874
+ version: verMatch?.[1] || "",
28875
+ language: "python",
28876
+ description: "",
28877
+ scripts: {},
28878
+ deps: [],
28879
+ devDeps: []
28880
+ };
28881
+ } catch {
28882
+ }
28883
+ }
28884
+ const goPath = join4(root, "go.mod");
28885
+ if (existsSync7(goPath)) {
28886
+ try {
28887
+ const txt = readFileSync7(goPath, "utf-8");
28888
+ const moduleMatch = txt.match(/^module\s+(.+)$/m);
28889
+ const deps = [...txt.matchAll(/^\s*([A-Za-z0-9_./-]+)\s+v[\d.]+/gm)].map((m) => m[1]);
28890
+ return {
28891
+ name: moduleMatch?.[1] || "",
28892
+ version: "",
28893
+ language: "go",
28894
+ description: "",
28895
+ scripts: {},
28896
+ deps,
28897
+ devDeps: []
28898
+ };
28899
+ } catch {
28900
+ }
28901
+ }
28902
+ return null;
28371
28903
  }
28372
- var normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28373
- function findRelatedEntries(text, excludeKey = "", limit = 3) {
28374
- const data = readMemory();
28375
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28376
- const queryTokens = normalize3(text).split(" ").filter(Boolean);
28377
- const scored = lines.map((line) => {
28378
- const trimmed = line.trim();
28379
- const parts = trimmed.split("|");
28380
- if (parts.length < 7) return null;
28381
- const [id, cat, key, content, file2, tags, date5] = parts;
28382
- if (key === excludeKey) return null;
28383
- const searchStr = normalize3(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28384
- let score = 0;
28385
- for (const token of queryTokens) {
28386
- if (searchStr.includes(token)) score++;
28904
+
28905
+ // src/lib/code-search.ts
28906
+ import { readFileSync as readFileSync8, readdirSync as readdirSync4, statSync as statSync5 } from "fs";
28907
+ import { join as join5, extname as extname2, relative } from "path";
28908
+ var SOURCE_EXTS = /* @__PURE__ */ new Set([
28909
+ ".ts",
28910
+ ".tsx",
28911
+ ".js",
28912
+ ".jsx",
28913
+ ".mjs",
28914
+ ".cjs",
28915
+ ".py",
28916
+ ".rb",
28917
+ ".go",
28918
+ ".rs",
28919
+ ".java",
28920
+ ".kt",
28921
+ ".swift",
28922
+ ".c",
28923
+ ".cpp",
28924
+ ".h",
28925
+ ".hpp",
28926
+ ".cs",
28927
+ ".vue",
28928
+ ".svelte",
28929
+ ".astro"
28930
+ ]);
28931
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set([
28932
+ "node_modules",
28933
+ ".git",
28934
+ ".toon-memory",
28935
+ "dist",
28936
+ "build",
28937
+ ".next",
28938
+ ".nuxt",
28939
+ "coverage",
28940
+ "__pycache__",
28941
+ ".venv",
28942
+ "vendor",
28943
+ ".cache",
28944
+ ".turbo"
28945
+ ]);
28946
+ function findFilesByPattern(root, pattern) {
28947
+ const results = [];
28948
+ const pat = pattern.toLowerCase();
28949
+ function walk(dir) {
28950
+ let entries;
28951
+ try {
28952
+ entries = readdirSync4(dir);
28953
+ } catch {
28954
+ return;
28387
28955
  }
28388
- if (score === 0) return null;
28389
- return { id, cat, key, content, file: file2, tags, date: date5, score };
28390
- }).filter(Boolean).sort((a, b) => b.score - a.score).slice(0, limit);
28391
- return scored;
28956
+ for (const entry of entries) {
28957
+ if (SKIP_DIRS2.has(entry)) continue;
28958
+ const fullPath = join5(dir, entry);
28959
+ let isDir;
28960
+ try {
28961
+ isDir = statSync5(fullPath).isDirectory();
28962
+ } catch {
28963
+ continue;
28964
+ }
28965
+ if (isDir) {
28966
+ walk(fullPath);
28967
+ } else if (entry.toLowerCase().includes(pat)) {
28968
+ results.push(relative(root, fullPath));
28969
+ }
28970
+ }
28971
+ }
28972
+ walk(root);
28973
+ return results.sort();
28392
28974
  }
28393
- function entryScore(dateStr, accessed) {
28394
- const days = (Date.now() - (/* @__PURE__ */ new Date(`${dateStr}T00:00:00`)).getTime()) / 864e5;
28975
+ function findCallers(root, symbol2) {
28976
+ const results = [];
28977
+ const maxResults = 30;
28978
+ const escaped = symbol2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28979
+ const regex = new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, "g");
28980
+ function walk(dir) {
28981
+ if (results.length >= maxResults) return;
28982
+ let entries;
28983
+ try {
28984
+ entries = readdirSync4(dir);
28985
+ } catch {
28986
+ return;
28987
+ }
28988
+ for (const entry of entries) {
28989
+ if (results.length >= maxResults) return;
28990
+ if (SKIP_DIRS2.has(entry)) continue;
28991
+ const fullPath = join5(dir, entry);
28992
+ let isDir;
28993
+ try {
28994
+ isDir = statSync5(fullPath).isDirectory();
28995
+ } catch {
28996
+ continue;
28997
+ }
28998
+ if (isDir) {
28999
+ walk(fullPath);
29000
+ } else {
29001
+ const ext = extname2(entry);
29002
+ if (!SOURCE_EXTS.has(ext)) continue;
29003
+ try {
29004
+ const content = readFileSync8(fullPath, "utf-8");
29005
+ const lines = content.split("\n");
29006
+ for (let i = 0; i < lines.length; i++) {
29007
+ if (results.length >= maxResults) return;
29008
+ regex.lastIndex = 0;
29009
+ if (regex.test(lines[i])) {
29010
+ results.push({
29011
+ file: relative(root, fullPath),
29012
+ line: i + 1,
29013
+ content: lines[i].trim()
29014
+ });
29015
+ }
29016
+ }
29017
+ } catch {
29018
+ }
29019
+ }
29020
+ }
29021
+ }
29022
+ walk(root);
29023
+ return results;
29024
+ }
29025
+
29026
+ // src/lib/context.ts
29027
+ var normalize4 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
29028
+ var tokenize3 = (s) => normalize4(s).split(" ").filter(Boolean);
29029
+ var isExpiredLocal3 = (ttl) => {
29030
+ if (!ttl) return false;
29031
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
29032
+ return ttl <= today;
29033
+ };
29034
+ var importance3 = (e) => {
29035
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
29036
+ const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
28395
29037
  const recency = Math.max(0, 30 - days) / 30;
28396
- const freq = Math.min(1, accessed / 5);
29038
+ const freq = Math.min(1, e.accessed / 5);
28397
29039
  return recency * 0.6 + freq * 0.4;
29040
+ };
29041
+ function formatOverview(data) {
29042
+ const entries = parseEntries(data);
29043
+ if (entries.length === 0) return "Memoria: vac\xEDa";
29044
+ const byCategory = {};
29045
+ let expired = 0;
29046
+ for (const e of entries) {
29047
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1;
29048
+ if (e.ttl && isExpiredLocal3(e.ttl)) expired++;
29049
+ }
29050
+ const cats = Object.entries(byCategory).map(([k, v]) => `${k}:${v}`).join(" ");
29051
+ const ttlNote = expired > 0 ? ` | ${expired} expiradas` : "";
29052
+ return `## Memoria (${entries.length} entradas)${ttlNote}
29053
+ ${cats}`;
29054
+ }
29055
+ function formatRelevantEntries(data, task, limit = 6) {
29056
+ const entries = parseEntries(data);
29057
+ if (entries.length === 0) return "";
29058
+ const { adjacency, byKey } = buildGraph(entries);
29059
+ const bm25 = bm25Scores(entries, task);
29060
+ const cent = centrality(adjacency);
29061
+ const qTokens = tokenize3(task);
29062
+ const scored = entries.filter((e) => !(e.ttl && isExpiredLocal3(e.ttl))).map((e) => {
29063
+ const text = normalize4(
29064
+ `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
29065
+ );
29066
+ const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t));
29067
+ const bm25Score = bm25.get(e.key) || 0;
29068
+ const centScore = cent.get(e.key) || 0;
29069
+ const impScore = importance3(e);
29070
+ const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0);
29071
+ return { entry: e, score: combined, matchesQuery };
29072
+ }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b) => b.score - a.score).slice(0, limit);
29073
+ if (scored.length === 0) return "";
29074
+ const selectedKeys = new Set(scored.map((x) => x.entry.key));
29075
+ const subAdj = /* @__PURE__ */ new Map();
29076
+ for (const x of scored) {
29077
+ const nb = (adjacency.get(x.entry.key) || []).filter((k) => selectedKeys.has(k));
29078
+ if (nb.length) subAdj.set(x.entry.key, nb);
29079
+ }
29080
+ const seeds = new Set(scored.filter((x) => x.matchesQuery).map((x) => x.entry.key));
29081
+ const rendered = renderCompact(
29082
+ scored.map((x) => x.entry),
29083
+ { adjacency: subAdj, seeds, snippetLen: 80 }
29084
+ );
29085
+ return `## Entradas relevantes
29086
+ ${rendered}`;
28398
29087
  }
28399
- function entryScoreForLine(line) {
28400
- const parts = line.trim().split("|");
28401
- const date5 = parts[6] || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28402
- const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0;
28403
- return entryScore(date5, accessed);
29088
+ function formatPatterns(data) {
29089
+ const entries = parseEntries(data);
29090
+ const patterns = entries.filter((e) => e.category === "pattern").sort((a, b) => importance3(b) - importance3(a)).slice(0, 5);
29091
+ if (patterns.length === 0) return "";
29092
+ const lines = patterns.map(
29093
+ (e) => `- **${e.key}**: ${e.content.slice(0, 120)}`
29094
+ );
29095
+ return `## Patrones establecidos
29096
+ ${lines.join("\n")}`;
28404
29097
  }
28405
- function bumpAccessed(ids) {
28406
- if (ids.length === 0) return;
28407
- const idSet = new Set(ids);
28408
- const data = readMemory();
28409
- const lines = data.split("\n");
28410
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28411
- if (headerIdx === -1) return;
28412
- for (let i = headerIdx + 1; i < lines.length; i++) {
28413
- const line = lines[i];
28414
- if (!line.startsWith(" ") || !line.includes("|")) continue;
28415
- if (line.startsWith(" summaries:")) break;
28416
- const parts = line.trim().split("|");
28417
- if (idSet.has(parts[0])) {
28418
- const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1;
28419
- parts[8] = String(accessed);
28420
- lines[i] = ` ${parts.join("|")}`;
29098
+ function formatSessions() {
29099
+ pruneSessions();
29100
+ const { active, conflicts } = coordinationView();
29101
+ const branch = currentBranch();
29102
+ if (active.length === 0 && conflicts.length === 0) {
29103
+ return `## Sesiones
29104
+ Rama: ${branch} | Sin otras sesiones activas`;
29105
+ }
29106
+ const lines = [`## Sesiones (${active.length} activa${active.length !== 1 ? "s" : ""}) \u2014rama: ${branch}`];
29107
+ for (const s of active.slice(0, 5)) {
29108
+ const mins = Math.max(0, Math.round(s.ageMs / 6e4));
29109
+ const files = Object.keys(s.files).length;
29110
+ lines.push(`- ${s.agent}@${s.branch} (${mins}min, ${files} archivos)`);
29111
+ }
29112
+ if (conflicts.length > 0) {
29113
+ lines.push("", `**Conflictos suaves (${conflicts.length}):**`);
29114
+ for (const c of conflicts.slice(0, 3)) {
29115
+ const who = c.sessions.map((s) => s.agent).join(" + ");
29116
+ lines.push(`- ${c.file} \u2194 ${who}`);
28421
29117
  }
28422
29118
  }
28423
- writeMemory(lines.join("\n"));
29119
+ return lines.join("\n");
28424
29120
  }
28425
- function readObservations() {
28426
- if (!existsSync3(OBSERVATIONS_FILE)) return [];
28427
- return readFileSync3(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
28428
- const p = l.trim().split("|");
28429
- return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" };
28430
- });
29121
+ function formatHealth(data) {
29122
+ const entries = parseEntries(data);
29123
+ const warnings = [];
29124
+ const expired = entries.filter((e) => e.ttl && isExpiredLocal3(e.ttl));
29125
+ if (expired.length > 0) {
29126
+ warnings.push(`${expired.length} entradas con TTL expirado (ejecutar memory_archive)`);
29127
+ }
29128
+ if (entries.length > 80) {
29129
+ warnings.push(`${entries.length} entradas (cerca del l\xEDmite de 100, auto-archive se activar\xE1)`);
29130
+ }
29131
+ const orphanLinks = findOrphanLinks(entries);
29132
+ if (orphanLinks.length > 0) {
29133
+ warnings.push(`${orphanLinks.length} links hu\xE9rfanos: ${orphanLinks.slice(0, 3).join(", ")}`);
29134
+ }
29135
+ if (warnings.length === 0) return "";
29136
+ return `## Salud
29137
+ \u26A0\uFE0F ${warnings.join("\n\u26A0\uFE0F ")}`;
28431
29138
  }
28432
- function archiveOldEntries(opts = {}) {
28433
- const data = readMemory();
28434
- const lines = data.split("\n");
28435
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
28436
- if (headerIdx === -1) return { archived: 0, kept: 0 };
28437
- const today = /* @__PURE__ */ new Date();
28438
- const cutoff = new Date(today);
28439
- cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS);
28440
- const cutoffStr = cutoff.toISOString().split("T")[0];
28441
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
28442
- const toArchive = /* @__PURE__ */ new Set();
28443
- entryLines2.forEach((line, idx) => {
28444
- const parts = line.trim().split("|");
28445
- if (parts.length < 7) return;
28446
- const date5 = parts[6];
28447
- const ttl = parts[7] || "";
28448
- if (date5 < cutoffStr || ttl && isExpired(ttl)) toArchive.add(idx);
28449
- });
28450
- if (opts.trimToMax) {
28451
- const remaining = entryLines2.length - toArchive.size;
28452
- if (remaining > MAX_ENTRIES) {
28453
- const need = remaining - MAX_ENTRIES;
28454
- const candidates = entryLines2.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c) => !toArchive.has(c.idx)).sort((a, b) => a.score - b.score);
28455
- for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx);
29139
+ function findOrphanLinks(entries) {
29140
+ const keys = new Set(entries.map((e) => e.key));
29141
+ const orphans = [];
29142
+ for (const e of entries) {
29143
+ for (const link of e.links) {
29144
+ if (!keys.has(link)) orphans.push(`${e.key}->${link}`);
28456
29145
  }
28457
29146
  }
28458
- if (toArchive.size === 0) return { archived: 0, kept: entryLines2.length };
28459
- const toArchiveLines = entryLines2.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim());
28460
- const toKeepLines = entryLines2.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim());
28461
- let archiveContent = "";
28462
- if (existsSync3(ARCHIVE_FILE)) {
28463
- archiveContent = readFileSync3(ARCHIVE_FILE, "utf-8");
29147
+ return orphans;
29148
+ }
29149
+ function generateContextBrief(data, opts = {}) {
29150
+ const sections = [];
29151
+ sections.push(formatOverview(data));
29152
+ if (opts.task) {
29153
+ const relevant = formatRelevantEntries(data, opts.task, opts.limit);
29154
+ if (relevant) sections.push(relevant);
28464
29155
  } else {
28465
- archiveContent = `version: 1
28466
- archived:
28467
- `;
29156
+ const top = formatTopEntries(data, opts.limit ?? 6);
29157
+ if (top) sections.push(top);
28468
29158
  }
28469
- const archiveLines = archiveContent.split("\n");
28470
- let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["));
28471
- if (archiveHeaderIdx === -1) {
28472
- archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`);
28473
- archiveHeaderIdx = archiveLines.length - 1;
29159
+ sections.push(formatPatterns(data));
29160
+ sections.push(formatSessions());
29161
+ sections.push(formatHealth(data));
29162
+ return sections.filter(Boolean).join("\n\n");
29163
+ }
29164
+ function formatTopEntries(data, limit) {
29165
+ const entries = parseEntries(data);
29166
+ if (entries.length === 0) return "";
29167
+ const top = [...entries].filter((e) => !(e.ttl && isExpiredLocal3(e.ttl))).sort((a, b) => importance3(b) - importance3(a)).slice(0, limit);
29168
+ if (top.length === 0) return "";
29169
+ const rendered = renderCompact(top);
29170
+ return `## Top memorias
29171
+ ${rendered}`;
29172
+ }
29173
+ function generateContextGenerate(data, root, opts = {}) {
29174
+ const sections = [];
29175
+ const manifest = readManifest(root);
29176
+ if (manifest) {
29177
+ const deps = manifest.deps.length > 0 ? manifest.deps.slice(0, 15).join(", ") : "ninguna";
29178
+ const version2 = manifest.version ? ` v${manifest.version}` : "";
29179
+ sections.push(`## Proyecto
29180
+ ${manifest.name}${version2} (${manifest.language})
29181
+ Deps: ${deps}`);
29182
+ }
29183
+ const structure = scanProjectStructure(root);
29184
+ if (structure.dirs.length > 0 || structure.rootFiles.length > 0) {
29185
+ const dirs = structure.dirs.length > 0 ? `Dirs: ${structure.dirs.join(", ")}` : "";
29186
+ const files = structure.rootFiles.length > 0 ? `Root: ${structure.rootFiles.slice(0, 10).join(", ")}` : "";
29187
+ const exts = Object.entries(structure.extensions).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([k, v]) => `${k}:${v}`).join(" ");
29188
+ const src = `${structure.sourceFileCount} archivos fuente`;
29189
+ const parts = [dirs, files, `${src} ${exts ? `(${exts})` : ""}`].filter(Boolean);
29190
+ if (parts.length > 0) sections.push(`## Estructura
29191
+ ${parts.join("\n")}`);
29192
+ }
29193
+ const envVars = readEnvExample(root);
29194
+ if (envVars.length > 0) {
29195
+ const envLines = envVars.slice(0, 8).map((v) => `- ${v.name}${v.comment ? ` \u2014 ${v.comment}` : ""}`);
29196
+ sections.push(`## Env vars (${envVars.length})
29197
+ ${envLines.join("\n")}`);
29198
+ }
29199
+ const git = gitStatusSummary(root);
29200
+ if (git.branch !== "unknown") {
29201
+ const recent = git.recentCommits.slice(0, 3);
29202
+ const commitLines = recent.map((c) => `- ${c.shortHash} ${c.subject}`);
29203
+ const parts = [`Rama: ${git.branch}`, `Archivos tracked: ${git.trackedFiles}`];
29204
+ if (commitLines.length > 0) parts.push(`\xDAltimos commits:
29205
+ ${commitLines.join("\n")}`);
29206
+ sections.push(`## Git
29207
+ ${parts.join("\n")}`);
29208
+ }
29209
+ sections.push(formatOverview(data));
29210
+ if (opts.task) {
29211
+ const relevant = formatRelevantEntries(data, opts.task, 6);
29212
+ if (relevant) sections.push(relevant);
29213
+ } else {
29214
+ const top = formatTopEntries(data, 6);
29215
+ if (top) sections.push(top);
29216
+ }
29217
+ sections.push(formatPatterns(data));
29218
+ sections.push(formatSessions());
29219
+ sections.push(formatHealth(data));
29220
+ return sections.filter(Boolean).join("\n\n");
29221
+ }
29222
+ function generateContextDiff(data, root, since) {
29223
+ const sections = [];
29224
+ const commits = readRecentCommits(10, root);
29225
+ if (commits.length > 0) {
29226
+ const cutoff = since || commits[0]?.date || "";
29227
+ const recent = cutoff ? commits.filter((c) => c.date >= cutoff) : commits.slice(0, 5);
29228
+ if (recent.length > 0) {
29229
+ const lines = recent.map((c) => `- ${c.shortHash} (${c.date}) ${c.subject}`);
29230
+ sections.push(`## Git commits (${recent.length})
29231
+ ${lines.join("\n")}`);
29232
+ }
29233
+ }
29234
+ const tracked = readGitIndex(root);
29235
+ if (tracked.length > 0) {
29236
+ sections.push(`## Archivos tracked (${tracked.length})
29237
+ ${tracked.slice(0, 20).join("\n")}`);
28474
29238
  }
28475
- const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/);
28476
- const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0;
28477
- for (const entry of toArchiveLines) {
28478
- archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`);
29239
+ const entries = parseEntries(data);
29240
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
29241
+ const sinceDate = since || today;
29242
+ const recentEntries = entries.filter((e) => e.date >= sinceDate);
29243
+ if (recentEntries.length > 0) {
29244
+ const created = recentEntries.filter((e) => e.date === today);
29245
+ const updated = recentEntries.filter((e) => e.date !== today);
29246
+ const parts = [];
29247
+ if (created.length > 0) parts.push(`Nuevas: ${created.map((e) => e.key).join(", ")}`);
29248
+ if (updated.length > 0) parts.push(`Actualizadas: ${updated.map((e) => e.key).join(", ")}`);
29249
+ if (parts.length > 0) sections.push(`## Memoria (${recentEntries.length} cambios)
29250
+ ${parts.join("\n")}`);
29251
+ }
29252
+ const sessions = listSessions().filter((s) => s.active);
29253
+ if (sessions.length > 0) {
29254
+ const lines = sessions.slice(0, 5).map((s) => `- ${s.agent}@${s.branch} (${Object.keys(s.files).length} archivos)`);
29255
+ sections.push(`## Sesiones activas (${sessions.length})
29256
+ ${lines.join("\n")}`);
29257
+ }
29258
+ if (sections.length === 0) return "Sin cambios recientes.";
29259
+ return sections.filter(Boolean).join("\n\n");
29260
+ }
29261
+ function generateContextFocus(data, root, task, opts = {}) {
29262
+ const sections = [];
29263
+ const limit = opts.limit ?? 6;
29264
+ const relevant = formatRelevantEntries(data, task, limit);
29265
+ if (relevant) sections.push(relevant);
29266
+ const keywords = task.toLowerCase().split(/\s+/).filter((w) => w.length > 2);
29267
+ const allFiles = [];
29268
+ for (const kw of keywords) {
29269
+ allFiles.push(...findFilesByPattern(root, kw));
29270
+ }
29271
+ const uniqueFiles = [...new Set(allFiles)].slice(0, 10);
29272
+ if (uniqueFiles.length > 0) {
29273
+ sections.push(`## Archivos relacionados
29274
+ ${uniqueFiles.join("\n")}`);
29275
+ }
29276
+ for (const kw of keywords.slice(0, 3)) {
29277
+ const callers = findCallers(root, kw);
29278
+ if (callers.length > 0) {
29279
+ const lines = callers.slice(0, 5).map((c) => `${c.file}:${c.line} \u2014 ${c.content.slice(0, 80)}`);
29280
+ sections.push(`## Referencias: ${kw}
29281
+ ${lines.join("\n")}`);
29282
+ }
29283
+ }
29284
+ const testFiles = [];
29285
+ for (const kw of keywords.slice(0, 2)) {
29286
+ const tests = findFilesByPattern(root, ".test.").filter((f) => f.toLowerCase().includes(kw));
29287
+ testFiles.push(...tests);
29288
+ }
29289
+ const uniqueTests = [...new Set(testFiles)].slice(0, 5);
29290
+ if (uniqueTests.length > 0) {
29291
+ sections.push(`## Tests existentes
29292
+ ${uniqueTests.join("\n")}`);
29293
+ }
29294
+ if (sections.length === 0) return `Sin contexto encontrado para "${task}".`;
29295
+ return sections.filter(Boolean).join("\n\n");
29296
+ }
29297
+ function generateContextHealth(data, root) {
29298
+ const entries = parseEntries(data);
29299
+ const critical = [];
29300
+ const warnings = [];
29301
+ const info = [];
29302
+ let score = 100;
29303
+ const keys = new Set(entries.map((e) => e.key));
29304
+ const orphanLinks = [];
29305
+ for (const e of entries) {
29306
+ for (const link of e.links) {
29307
+ if (!keys.has(link)) orphanLinks.push(`${e.key}->${link}`);
29308
+ }
28479
29309
  }
28480
- archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`);
28481
- safeWrite(ARCHIVE_FILE, archiveLines.join("\n"));
28482
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`);
28483
- const keepSet = new Set(toKeepLines);
28484
- const allEntryLines = lines.slice(headerIdx + 1);
28485
- const newEntryLines = allEntryLines.filter((l) => {
28486
- if (l.trim().length === 0) return false;
28487
- return keepSet.has(l.trim());
29310
+ if (orphanLinks.length > 0) {
29311
+ warnings.push(`${orphanLinks.length} links hu\xE9rfanos: ${orphanLinks.slice(0, 5).join(", ")}`);
29312
+ score -= 5;
29313
+ }
29314
+ const contentMap = /* @__PURE__ */ new Map();
29315
+ for (const e of entries) {
29316
+ const existing = contentMap.get(e.content) || [];
29317
+ existing.push(e.key);
29318
+ contentMap.set(e.content, existing);
29319
+ }
29320
+ const duplicates = [];
29321
+ for (const [_, keys2] of contentMap) {
29322
+ if (keys2.length > 1) duplicates.push(keys2.join(" = "));
29323
+ }
29324
+ if (duplicates.length > 0) {
29325
+ warnings.push(`${duplicates.length} entradas duplicadas: ${duplicates.slice(0, 3).join("; ")}`);
29326
+ score -= 5;
29327
+ }
29328
+ const missingQuality = entries.filter((e) => {
29329
+ return !e.accessed && e.accessed !== 0;
28488
29330
  });
28489
- lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`));
28490
- writeMemory(lines.join("\n"));
28491
- return { archived: toArchiveLines.length, kept: toKeepLines.length };
28492
- }
28493
- function pruneExpiredEntries() {
28494
- ensureMemoryFile();
28495
- if (!existsSync3(MEMORY_FILE)) return 0;
28496
- let pruned = 0;
28497
- withLockSync(MEMORY_FILE, () => {
28498
- const data = readMemory();
28499
- const lines = data.split("\n");
28500
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
28501
- if (headerIdx === -1) return;
28502
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28503
- const kept = entryLines2.filter((l) => {
28504
- const parts = l.trim().split("|");
28505
- if (parts.length < 8) return true;
28506
- const ttl = parts[7] || "";
28507
- if (ttl && isExpired(ttl)) {
28508
- pruned++;
28509
- return false;
29331
+ if (missingQuality.length > 0) {
29332
+ info.push(`${missingQuality.length} entradas sin quality score`);
29333
+ score -= 2;
29334
+ }
29335
+ const expired = entries.filter((e) => e.ttl && isExpiredLocal3(e.ttl));
29336
+ if (expired.length > 0) {
29337
+ info.push(`${expired.length} entradas con TTL expirado (auto-prune en pr\xF3ximo inicio)`);
29338
+ score -= 3;
29339
+ }
29340
+ const brokenFiles = [];
29341
+ for (const e of entries) {
29342
+ if (e.file) {
29343
+ const filePath = e.file.split(":")[0];
29344
+ if (filePath && !existsSync9(join6(root, filePath))) {
29345
+ brokenFiles.push(`${e.key}: ${e.file}`);
28510
29346
  }
28511
- return true;
28512
- });
28513
- if (pruned === 0) return;
28514
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`);
28515
- const keepSet = new Set(kept.map((l) => l.trim()));
28516
- const allEntryLines = lines.slice(headerIdx + 1);
28517
- const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()));
28518
- lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => l.trim().length ? ` ${l.trim()}` : l));
28519
- writeMemory(lines.join("\n"));
28520
- });
28521
- return pruned;
28522
- }
28523
- function consolidateEntries() {
28524
- const data = readMemory();
28525
- const lines = data.split("\n");
28526
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28527
- if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
28528
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28529
- const byKey = /* @__PURE__ */ new Map();
28530
- const keyOrder = [];
28531
- const mergedAway = [];
28532
- for (let i = 0; i < entryLines2.length; i++) {
28533
- const line = entryLines2[i].trim();
28534
- const parts = line.split("|");
28535
- if (parts.length < 3) continue;
28536
- const key = parts[2];
28537
- const existingIdx = keyOrder.findIndex((idx) => {
28538
- const ep = entryLines2[idx].trim().split("|");
28539
- return ep[2] === key;
28540
- });
28541
- if (existingIdx !== -1) {
28542
- const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx]), line);
28543
- byKey.set(keyOrder[existingIdx], mergedLine);
28544
- mergedAway.push(i);
28545
- } else {
28546
- byKey.set(i, line);
28547
- keyOrder.push(i);
28548
29347
  }
28549
29348
  }
28550
- const contentSeen = /* @__PURE__ */ new Map();
28551
- const order = [];
28552
- const duplicates = [];
28553
- for (const idx of keyOrder) {
28554
- const line = byKey.get(idx);
28555
- const parts = line.split("|");
28556
- if (parts.length < 3) {
28557
- order.push(line);
28558
- continue;
28559
- }
28560
- const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim();
28561
- if (contentSeen.has(content)) {
28562
- duplicates.push(parts[2]);
28563
- continue;
28564
- }
28565
- contentSeen.set(content, line);
28566
- order.push(line);
29349
+ if (brokenFiles.length > 0) {
29350
+ warnings.push(`${brokenFiles.length} refs a archivos inexistentes: ${brokenFiles.slice(0, 3).join("; ")}`);
29351
+ score -= 5;
28567
29352
  }
28568
- const totalRemoved = mergedAway.length + duplicates.length;
28569
- if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] };
28570
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`);
28571
- lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`));
28572
- writeMemory(lines.join("\n"));
28573
- return { removed: totalRemoved, kept: order.length, duplicates };
28574
- }
28575
- var server = new McpServer(
28576
- { name: "toon-memory", version: "2.4.3" },
28577
- { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
28578
- );
28579
- server.registerResource(
28580
- "memory-entries",
28581
- "toon://memory/entries",
28582
- { title: "Memory Entries", mimeType: "text/plain" },
28583
- async (uri) => {
28584
- const data = readMemory();
28585
- return { contents: [{ uri: uri.href, text: data }] };
29353
+ const sessions = listSessions();
29354
+ const stale = sessions.filter((s) => !s.active && !s.ended);
29355
+ if (stale.length > 0) {
29356
+ info.push(`${stale.length} sesiones stale (ser\xE1n pruned autom\xE1ticamente)`);
28586
29357
  }
28587
- );
28588
- server.registerResource(
28589
- "memory-stats",
28590
- "toon://memory/stats",
28591
- { title: "Memory Stats", mimeType: "text/plain" },
28592
- async (uri) => {
28593
- const data = readMemory();
28594
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28595
- const entries = lines.map((l) => {
28596
- const parts = l.trim().split("|");
28597
- return { category: parts[1] || "unknown", ttl: parts[7] || "" };
28598
- });
28599
- const byCategory = {};
28600
- for (const e of entries) {
28601
- byCategory[e.category] = (byCategory[e.category] || 0) + 1;
28602
- }
28603
- const withTtl = entries.filter((e) => e.ttl).length;
28604
- const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length;
28605
- const text = [
28606
- `Entradas totales: ${entries.length}`,
28607
- `TTL: ${withTtl} con expiraci\xF3n, ${expired} expiradas`,
28608
- "Por categor\xEDa:",
28609
- ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`)
28610
- ].join("\n");
28611
- return { contents: [{ uri: uri.href, text }] };
29358
+ if (entries.length > 80) {
29359
+ warnings.push(`${entries.length} entradas (cerca del l\xEDmite de 100)`);
29360
+ score -= 3;
29361
+ } else if (entries.length === 0) {
29362
+ info.push("Memoria vac\xEDa");
28612
29363
  }
28613
- );
28614
- server.registerResource(
28615
- "memory-summaries",
28616
- "toon://memory/summaries",
28617
- { title: "Memory Summaries", mimeType: "text/plain" },
28618
- async (uri) => {
28619
- const data = readMemory();
28620
- const primer = generateSystemPrimer(data);
28621
- return { contents: [{ uri: uri.href, text: primer }] };
29364
+ score = Math.max(0, score);
29365
+ const report = { score, warnings, info, critical };
29366
+ const parts = [`## Memory Health: ${score >= 90 ? "\u2705" : score >= 70 ? "\u26A0\uFE0F" : "\u274C"} ${score}/100`];
29367
+ if (critical.length > 0) {
29368
+ parts.push("", "### Cr\xEDtico", ...critical.map((w) => `- ${w}`));
28622
29369
  }
28623
- );
28624
- server.registerTool(
28625
- "memory_remember",
28626
- {
28627
- title: "Save to Memory",
28628
- description: "Guarda un hecho en la memoria persistente del proyecto (decisiones, patrones, bugs, conocimiento). Se recuerda entre sesiones.",
28629
- inputSchema: {
28630
- category: external_exports.enum(["decision", "pattern", "bug", "knowledge"]).describe("Categor\xEDa del hecho"),
28631
- key: external_exports.string().describe("T\xEDtulo corto en kebab-case (ej: risk-engine-prioridad)"),
28632
- content: external_exports.string().describe("Contenido detallado del hecho"),
28633
- file: external_exports.string().optional().default("").describe("Archivo o l\xEDnea relacionada (ej: spec.md:145)"),
28634
- tags: external_exports.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
28635
- ttl: external_exports.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vac\xEDo = sin expiraci\xF3n"),
28636
- 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.")
29370
+ if (warnings.length > 0) {
29371
+ parts.push("", "### Warnings", ...warnings.map((w) => `- ${w}`));
29372
+ }
29373
+ if (info.length > 0) {
29374
+ parts.push("", "### Info", ...info.map((i) => `- ${i}`));
29375
+ }
29376
+ return { report, markdown: parts.join("\n") };
29377
+ }
29378
+ function generateContextExport(data, format = "full") {
29379
+ const entries = parseEntries(data);
29380
+ const sections = [];
29381
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
29382
+ sections.push(`# toon-memory export
29383
+ Fecha: ${today} | Entradas: ${entries.length}
29384
+ `);
29385
+ if (entries.length === 0) {
29386
+ sections.push("Memoria vac\xEDa.");
29387
+ return sections.join("\n");
29388
+ }
29389
+ const byCategory = {};
29390
+ for (const e of entries) {
29391
+ if (!byCategory[e.category]) byCategory[e.category] = [];
29392
+ byCategory[e.category].push(e);
29393
+ }
29394
+ const categoryLabels = {
29395
+ decision: "Decisiones",
29396
+ pattern: "Patrones",
29397
+ bug: "Bugs",
29398
+ knowledge: "Conocimiento"
29399
+ };
29400
+ for (const [cat, items] of Object.entries(byCategory)) {
29401
+ const label = categoryLabels[cat] || cat;
29402
+ sections.push(`## ${label} (${items.length})`);
29403
+ for (const e of items) {
29404
+ if (format === "compact") {
29405
+ sections.push(`- **${e.key}**: ${e.content.slice(0, 120)}`);
29406
+ } else {
29407
+ const tags = e.tags.length > 0 ? ` \xB7 tags: ${e.tags.join(";")}` : "";
29408
+ const links = e.links.length > 0 ? ` \xB7 links: ${e.links.join(", ")}` : "";
29409
+ const file2 = e.file ? ` \xB7 file: ${e.file}` : "";
29410
+ sections.push(`### ${e.key}
29411
+ ${e.content}
29412
+ _${e.date}${tags}${file2}${links}_`);
29413
+ }
28637
29414
  }
28638
- },
28639
- async ({ category, key, content, file: file2, tags, ttl, links }) => {
28640
- const data = readMemory();
28641
- const newId = generateId();
28642
- const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28643
- const lines = data.split("\n");
28644
- let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28645
- if (headerIdx === -1) {
28646
- lines.push(`[0|]`);
28647
- headerIdx = lines.length - 1;
28648
- }
28649
- let existingIdx = -1;
28650
- let existingId = newId;
28651
- for (let i = headerIdx + 1; i < lines.length; i++) {
28652
- const line = lines[i];
28653
- if (!line.startsWith(" ") || !line.includes("|")) continue;
28654
- if (line.startsWith(" summaries:")) break;
28655
- const parts = line.trim().split("|");
28656
- if (parts[2] === key) {
28657
- existingIdx = i;
28658
- existingId = parts[0];
28659
- break;
29415
+ sections.push("");
29416
+ }
29417
+ if (format === "full") {
29418
+ const { adjacency } = buildGraph(entries);
29419
+ if (adjacency.size > 0) {
29420
+ const edges = [];
29421
+ for (const [key, neighbors] of adjacency) {
29422
+ for (const n of neighbors) {
29423
+ if (key < n) edges.push(`${key} -> ${n}`);
29424
+ }
29425
+ }
29426
+ if (edges.length > 0) {
29427
+ sections.push(`## Grafo (${edges.length} edges)`);
29428
+ sections.push(edges.slice(0, 20).join("\n"));
28660
29429
  }
28661
29430
  }
28662
- const entryId = existingIdx !== -1 ? existingId : newId;
28663
- const resolvedTtl = parseTTL(ttl);
28664
- const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab);
28665
- const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
28666
- const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
28667
- let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
28668
- let action = "Guardado";
28669
- let mergeInfo = "";
28670
- const tagsInferred = !tags && resolvedTags ? true : false;
28671
- if (existingIdx !== -1) {
28672
- newEntry = mergeEntries(lines[existingIdx].trim(), newEntry);
28673
- lines[existingIdx] = ` ${newEntry}`;
28674
- action = "Actualizado";
28675
- mergeInfo = "\n\u{1F517} Merge: tags combinados, fecha y links actualizados";
28676
- } else {
28677
- const quality = qualityScore(resolvedTags, resolvedLinks, content, date5);
28678
- const confidence = 1;
28679
- newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}|${quality.toFixed(2)}|${confidence}`;
28680
- const match = lines[headerIdx].match(/\[(\d+)\|/);
28681
- const count = match ? parseInt(match[1]) : 0;
28682
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
28683
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
29431
+ }
29432
+ const sessions = listSessions();
29433
+ if (sessions.length > 0) {
29434
+ const active = sessions.filter((s) => s.active);
29435
+ sections.push(`## Sesiones (${active.length} activas / ${sessions.length} total)`);
29436
+ for (const s of sessions.slice(0, 5)) {
29437
+ const status = s.active ? "\u{1F7E2}" : "\u26AA";
29438
+ sections.push(`- ${status} ${s.agent}@${s.branch} (${s.id})`);
28684
29439
  }
28685
- writeMemory(lines.join("\n"));
28686
- const headerMatch = lines[headerIdx].match(/\[(\d+)\|/);
28687
- const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0;
28688
- let archiveMsg = "";
28689
- if (entryCount > MAX_ENTRIES) {
28690
- const result = archiveOldEntries({ trimToMax: true });
28691
- if (result.archived > 0) {
28692
- archiveMsg = `
29440
+ }
29441
+ return sections.filter(Boolean).join("\n");
29442
+ }
29443
+
29444
+ // src/mcp/tools.ts
29445
+ var normalize5 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
29446
+ function registerTools(server2) {
29447
+ server2.registerTool(
29448
+ "memory_remember",
29449
+ {
29450
+ title: "Save to Memory",
29451
+ description: "Guarda un hecho en la memoria persistente del proyecto (decisiones, patrones, bugs, conocimiento). Se recuerda entre sesiones.",
29452
+ inputSchema: {
29453
+ category: external_exports.enum(["decision", "pattern", "bug", "knowledge"]).describe("Categor\xEDa del hecho"),
29454
+ key: external_exports.string().describe("T\xEDtulo corto en kebab-case (ej: risk-engine-prioridad)"),
29455
+ content: external_exports.string().describe("Contenido detallado del hecho"),
29456
+ file: external_exports.string().optional().default("").describe("Archivo o l\xEDnea relacionada (ej: spec.md:145)"),
29457
+ tags: external_exports.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
29458
+ ttl: external_exports.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vac\xEDo = sin expiraci\xF3n"),
29459
+ 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.")
29460
+ }
29461
+ },
29462
+ async ({ category, key, content, file: file2, tags, ttl, links }) => {
29463
+ const data = readMemory();
29464
+ const newId = generateId();
29465
+ const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
29466
+ const lines = data.split("\n");
29467
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
29468
+ if (headerIdx === -1) {
29469
+ lines.push(`[0|]`);
29470
+ headerIdx = lines.length - 1;
29471
+ }
29472
+ let existingIdx = -1;
29473
+ let existingId = newId;
29474
+ for (let i = headerIdx + 1; i < lines.length; i++) {
29475
+ const line = lines[i];
29476
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
29477
+ if (line.startsWith(" summaries:")) break;
29478
+ const parts = line.trim().split("|");
29479
+ if (parts[2] === key) {
29480
+ existingIdx = i;
29481
+ existingId = parts[0];
29482
+ break;
29483
+ }
29484
+ }
29485
+ const entryId = existingIdx !== -1 ? existingId : newId;
29486
+ const resolvedTtl = parseTTL(ttl);
29487
+ const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab);
29488
+ const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
29489
+ const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
29490
+ let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
29491
+ let action = "Guardado";
29492
+ let mergeInfo = "";
29493
+ const tagsInferred = !tags && resolvedTags ? true : false;
29494
+ if (existingIdx !== -1) {
29495
+ newEntry = mergeEntries(lines[existingIdx].trim(), newEntry);
29496
+ lines[existingIdx] = ` ${newEntry}`;
29497
+ action = "Actualizado";
29498
+ mergeInfo = "\n\u{1F517} Merge: tags combinados, fecha y links actualizados";
29499
+ } else {
29500
+ const quality = qualityScore(resolvedTags, resolvedLinks, content, date5);
29501
+ const confidence = 1;
29502
+ newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}|${quality.toFixed(2)}|${confidence}`;
29503
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
29504
+ const count = match ? parseInt(match[1]) : 0;
29505
+ lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
29506
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
29507
+ }
29508
+ writeMemory(lines.join("\n"));
29509
+ const headerMatch = lines[headerIdx].match(/\[(\d+)\|/);
29510
+ const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0;
29511
+ let archiveMsg = "";
29512
+ if (entryCount > MAX_ENTRIES) {
29513
+ const result = archiveOldEntries({ trimToMax: true });
29514
+ if (result.archived > 0) {
29515
+ archiveMsg = `
28693
29516
  \u{1F4E6} Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`;
29517
+ }
28694
29518
  }
28695
- }
28696
- const ttlMsg = resolvedTtl ? `
29519
+ const ttlMsg = resolvedTtl ? `
28697
29520
  \u23F0 TTL: ${resolvedTtl}` : "";
28698
- const inferredMsg = tagsInferred ? `
29521
+ const inferredMsg = tagsInferred ? `
28699
29522
  \u{1F3F7}\uFE0F Tags inferidos: ${resolvedTags}` : "";
28700
- const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3);
28701
- let relatedMsg = "";
28702
- if (related.length > 0) {
28703
- const items = related.map((r) => ` [${r.cat}] ${r.key} \u2014 ${r.content.slice(0, 80)}`).join("\n");
28704
- relatedMsg = `
29523
+ const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3);
29524
+ let relatedMsg = "";
29525
+ if (related.length > 0) {
29526
+ const items = related.map((r) => ` [${r.cat}] ${r.key} \u2014 ${r.content.slice(0, 80)}`).join("\n");
29527
+ relatedMsg = `
28705
29528
 
28706
29529
  \u{1F517} Entradas relacionadas:
28707
29530
  ${items}`;
28708
- }
28709
- return {
28710
- content: [{ type: "text", text: `\u{1F9E0} ${action}: ${category}/${key} (${entryId})
29531
+ }
29532
+ return {
29533
+ content: [{ type: "text", text: `\u{1F9E0} ${action}: ${category}/${key} (${entryId})
28711
29534
  ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
28712
- };
28713
- }
28714
- );
28715
- server.registerTool(
28716
- "memory_recall",
28717
- {
28718
- title: "Search Memory",
28719
- description: "Busca en la memoria persistente del proyecto. Devuelve entradas relevantes. Usar ANTES de leer archivos.",
28720
- inputSchema: {
28721
- query: external_exports.string().describe("Texto a buscar"),
28722
- category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)"),
28723
- from_date: external_exports.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
28724
- to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
28725
- 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)."),
28726
- hops: external_exports.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
28727
- compact: external_exports.boolean().optional().default(false).describe("Salida token-efficient: \xEDndices num\xE9ricos (1, 2), omite id/fecha/archivo (conserva tags), aristas como '->2', y trunca vecinos del grafo a un snippet. No muta el archivo .toon.")
29535
+ };
28728
29536
  }
28729
- },
28730
- async ({ query, category, from_date, to_date, mode, hops, compact }) => {
28731
- const data = readMemory();
28732
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28733
- const normalize4 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28734
- const queryTokens = normalize4(query).split(" ").filter(Boolean);
28735
- const results = lines.map((line) => {
28736
- const trimmed = line.trim();
28737
- const parts = trimmed.split("|");
28738
- if (parts.length < 7) return null;
28739
- const [id, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
28740
- const qualityRaw = parts[10] || "";
28741
- const confidenceRaw = parts[11] || "";
28742
- if (category && cat !== category) return null;
28743
- if (from_date && date5 < from_date) return null;
28744
- if (to_date && date5 > to_date) return null;
28745
- if (ttl && isExpired(ttl)) return null;
28746
- const searchStr = normalize4(`${id} ${cat} ${key} ${content} ${file2} ${tags} ${qualityRaw} ${confidenceRaw}`);
28747
- if (!queryTokens.every((token) => searchStr.includes(token))) return null;
28748
- const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
28749
- return { id, cat, key, content, file: file2, tags, date: date5, accessed, qualityRaw, confidenceRaw };
28750
- }).filter(Boolean);
28751
- if (results.length === 0) {
28752
- return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28753
- }
28754
- if (mode === "graph") {
28755
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops });
28756
- if (detail.entries.length === 0) {
28757
- return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
29537
+ );
29538
+ server2.registerTool(
29539
+ "memory_recall",
29540
+ {
29541
+ title: "Search Memory",
29542
+ description: "Busca en la memoria persistente del proyecto. Devuelve entradas relevantes. Usar ANTES de leer archivos.",
29543
+ inputSchema: {
29544
+ query: external_exports.string().describe("Texto a buscar"),
29545
+ category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)"),
29546
+ from_date: external_exports.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
29547
+ to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
29548
+ 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)."),
29549
+ hops: external_exports.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
29550
+ compact: external_exports.boolean().optional().default(false).describe("Salida token-efficient: \xEDndices num\xE9ricos (1, 2), omite id/fecha/archivo (conserva tags), aristas como '->2', y trunca vecinos del grafo a un snippet. No muta el archivo .toon.")
28758
29551
  }
28759
- bumpAccessed(detail.entries.map((e) => e.id));
28760
- if (compact) {
28761
- const formatted3 = renderCompact(detail.entries, {
28762
- adjacency: detail.adjacency,
28763
- seeds: detail.seeds,
28764
- snippetLen: 90
28765
- });
28766
- return { content: [{ type: "text", text: formatted3 }] };
29552
+ },
29553
+ async ({ query, category, from_date, to_date, mode, hops, compact }) => {
29554
+ const data = readMemory();
29555
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
29556
+ const queryTokens = normalize5(query).split(" ").filter(Boolean);
29557
+ const results = lines.map((line) => {
29558
+ const trimmed = line.trim();
29559
+ const parts = trimmed.split("|");
29560
+ if (parts.length < 7) return null;
29561
+ const [id, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
29562
+ const qualityRaw = parts[10] || "";
29563
+ const confidenceRaw = parts[11] || "";
29564
+ if (category && cat !== category) return null;
29565
+ if (from_date && date5 < from_date) return null;
29566
+ if (to_date && date5 > to_date) return null;
29567
+ if (ttl && isExpired(ttl)) return null;
29568
+ const searchStr = normalize5(`${id} ${cat} ${key} ${content} ${file2} ${tags} ${qualityRaw} ${confidenceRaw}`);
29569
+ if (!queryTokens.every((token) => searchStr.includes(token))) return null;
29570
+ const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
29571
+ return { id, cat, key, content, file: file2, tags, date: date5, accessed, qualityRaw, confidenceRaw };
29572
+ }).filter(Boolean);
29573
+ if (results.length === 0) {
29574
+ return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28767
29575
  }
28768
- const formatted2 = detail.entries.map((r) => {
28769
- const links = r.links.length ? `
29576
+ if (mode === "graph") {
29577
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops });
29578
+ if (detail.entries.length === 0) {
29579
+ return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
29580
+ }
29581
+ bumpAccessed(detail.entries.map((e) => e.id));
29582
+ if (compact) {
29583
+ const formatted3 = renderCompact(detail.entries, {
29584
+ adjacency: detail.adjacency,
29585
+ seeds: detail.seeds,
29586
+ snippetLen: 90
29587
+ });
29588
+ return { content: [{ type: "text", text: formatted3 }] };
29589
+ }
29590
+ const formatted2 = detail.entries.map((r) => {
29591
+ const links = r.links.length ? `
28770
29592
  links: ${r.links.join(", ")}` : "";
28771
- return `[${r.category}] ${r.key} (${r.id})
29593
+ return `[${r.category}] ${r.key} (${r.id})
28772
29594
  ${r.content}
28773
29595
  File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`;
28774
- }).join("\n\n");
28775
- return { content: [{ type: "text", text: formatted2 }] };
28776
- }
28777
- const ranked = results.map((r) => {
28778
- const quality = r.qualityRaw ? parseFloat(r.qualityRaw) || 0 : 0;
28779
- const qualityBoost = quality * 0.15;
28780
- return { ...r, score: entryScore(r.date, r.accessed) + qualityBoost };
28781
- }).sort((a, b) => b.score - a.score);
28782
- bumpAccessed(ranked.map((r) => r.id));
28783
- if (compact) {
28784
- const entries = ranked.map((r) => ({
28785
- id: r.id,
28786
- category: r.cat,
28787
- key: r.key,
28788
- content: r.content,
28789
- file: r.file,
28790
- tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
28791
- date: r.date,
28792
- ttl: "",
28793
- accessed: r.accessed,
28794
- links: []
28795
- }));
28796
- const formatted2 = renderCompact(entries);
28797
- return { content: [{ type: "text", text: formatted2 }] };
28798
- }
28799
- const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
29596
+ }).join("\n\n");
29597
+ return { content: [{ type: "text", text: formatted2 }] };
29598
+ }
29599
+ const ranked = results.map((r) => {
29600
+ const quality = r.qualityRaw ? parseFloat(r.qualityRaw) || 0 : 0;
29601
+ const qualityBoost = quality * 0.15;
29602
+ return { ...r, score: entryScore(r.date, r.accessed) + qualityBoost };
29603
+ }).sort((a, b) => b.score - a.score);
29604
+ bumpAccessed(ranked.map((r) => r.id));
29605
+ if (compact) {
29606
+ const entries = ranked.map((r) => ({
29607
+ id: r.id,
29608
+ category: r.cat,
29609
+ key: r.key,
29610
+ content: r.content,
29611
+ file: r.file,
29612
+ tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
29613
+ date: r.date,
29614
+ ttl: "",
29615
+ accessed: r.accessed,
29616
+ links: []
29617
+ }));
29618
+ const formatted2 = renderCompact(entries);
29619
+ return { content: [{ type: "text", text: formatted2 }] };
29620
+ }
29621
+ const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
28800
29622
  ${r.content}
28801
29623
  File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
28802
- return { content: [{ type: "text", text: formatted }] };
28803
- }
28804
- );
28805
- server.registerTool(
28806
- "memory_forget",
28807
- {
28808
- title: "Delete from Memory",
28809
- description: "Elimina una entrada de la memoria por su key o id.",
28810
- inputSchema: {
28811
- key: external_exports.string().describe("Key o id de la entrada a eliminar")
29624
+ return { content: [{ type: "text", text: formatted }] };
28812
29625
  }
28813
- },
28814
- async ({ key }) => {
28815
- const data = readMemory();
28816
- const lines = data.split("\n");
28817
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28818
- if (headerIdx === -1) {
28819
- return { content: [{ type: "text", text: "No hay entradas en memoria" }] };
29626
+ );
29627
+ server2.registerTool(
29628
+ "memory_forget",
29629
+ {
29630
+ title: "Delete from Memory",
29631
+ description: "Elimina una entrada de la memoria por su key o id.",
29632
+ inputSchema: {
29633
+ key: external_exports.string().describe("Key o id de la entrada a eliminar")
29634
+ }
29635
+ },
29636
+ async ({ key }) => {
29637
+ const data = readMemory();
29638
+ const lines = data.split("\n");
29639
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
29640
+ if (headerIdx === -1) {
29641
+ return { content: [{ type: "text", text: "No hay entradas en memoria" }] };
29642
+ }
29643
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
29644
+ const filtered = entryLines2.filter((l) => {
29645
+ const parts = l.trim().split("|");
29646
+ return parts[0] !== key && parts[2] !== key;
29647
+ });
29648
+ const removed = entryLines2.length - filtered.length;
29649
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
29650
+ const count = match ? parseInt(match[1]) : 0;
29651
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
29652
+ lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
29653
+ writeMemory(lines.join("\n"));
29654
+ return {
29655
+ content: [{ type: "text", text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }]
29656
+ };
28820
29657
  }
28821
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28822
- const filtered = entryLines2.filter((l) => {
28823
- const parts = l.trim().split("|");
28824
- return parts[0] !== key && parts[2] !== key;
28825
- });
28826
- const removed = entryLines2.length - filtered.length;
28827
- const match = lines[headerIdx].match(/\[(\d+)\|/);
28828
- const count = match ? parseInt(match[1]) : 0;
28829
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
28830
- lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
28831
- writeMemory(lines.join("\n"));
28832
- return {
28833
- content: [{ type: "text", text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }]
28834
- };
28835
- }
28836
- );
28837
- server.registerTool(
28838
- "memory_stats",
28839
- {
28840
- title: "Memory Stats",
28841
- description: "Muestra estad\xEDsticas de la memoria del proyecto.",
28842
- inputSchema: {}
28843
- },
28844
- async () => {
28845
- const data = readMemory();
28846
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28847
- const entries = lines.map((l) => {
28848
- const parts = l.trim().split("|");
28849
- return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" };
28850
- });
28851
- const byCategory = {};
28852
- for (const e of entries) {
28853
- byCategory[e.category] = (byCategory[e.category] || 0) + 1;
28854
- }
28855
- const withTtl = entries.filter((e) => e.ttl).length;
28856
- const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length;
28857
- const withQuality = entries.filter((e) => e.quality).length;
28858
- const avgQuality = withQuality > 0 ? (entries.reduce((sum, e) => sum + (e.quality ? parseFloat(e.quality) : 0), 0) / withQuality).toFixed(2) : "N/A";
28859
- const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l));
28860
- const stats = [
28861
- `Entradas totales: ${entries.length}`,
28862
- `Res\xFAmenes de archivos: ${summaryLines.length}`,
28863
- "",
28864
- "Por categor\xEDa:",
28865
- ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
28866
- "",
28867
- `TTL: ${withTtl} con expiraci\xF3n, ${expired} expiradas`,
28868
- `Calidad promedio: ${avgQuality} (${withQuality} con score)`,
28869
- "",
28870
- `\xDAltimas 5 entradas:`,
28871
- ...lines.slice(-5).map((l) => {
29658
+ );
29659
+ server2.registerTool(
29660
+ "memory_stats",
29661
+ {
29662
+ title: "Memory Stats",
29663
+ description: "Muestra estad\xEDsticas de la memoria del proyecto.",
29664
+ inputSchema: {}
29665
+ },
29666
+ async () => {
29667
+ const data = readMemory();
29668
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
29669
+ const entries = lines.map((l) => {
28872
29670
  const parts = l.trim().split("|");
28873
- const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : "";
28874
- const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : "";
28875
- return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}`;
28876
- })
28877
- ];
28878
- return { content: [{ type: "text", text: stats.join("\n") }] };
28879
- }
28880
- );
28881
- server.registerTool(
28882
- "memory_diff",
28883
- {
28884
- title: "Memory Diff",
28885
- description: "Muestra qu\xE9 cambi\xF3 en la memoria desde una fecha. \xDAtil para saber qu\xE9 se aprendi\xF3 desde la \xFAltima sesi\xF3n.",
28886
- inputSchema: {
28887
- since: external_exports.string().describe("Desde cu\xE1ndo mostrar cambios (ej: 24h, 7d, 2026-07-10)"),
28888
- type: external_exports.enum(["all", "created", "updated"]).optional().default("all").describe("Filtrar por tipo de cambio")
29671
+ return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" };
29672
+ });
29673
+ const byCategory = {};
29674
+ for (const e of entries) {
29675
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1;
29676
+ }
29677
+ const withTtl = entries.filter((e) => e.ttl).length;
29678
+ const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length;
29679
+ const withQuality = entries.filter((e) => e.quality).length;
29680
+ const avgQuality = withQuality > 0 ? (entries.reduce((sum, e) => sum + (e.quality ? parseFloat(e.quality) : 0), 0) / withQuality).toFixed(2) : "N/A";
29681
+ const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l));
29682
+ const stats = [
29683
+ `Entradas totales: ${entries.length}`,
29684
+ `Res\xFAmenes de archivos: ${summaryLines.length}`,
29685
+ "",
29686
+ "Por categor\xEDa:",
29687
+ ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
29688
+ "",
29689
+ `TTL: ${withTtl} con expiraci\xF3n, ${expired} expiradas`,
29690
+ `Calidad promedio: ${avgQuality} (${withQuality} con score)`,
29691
+ "",
29692
+ `\xDAltimas 5 entradas:`,
29693
+ ...lines.slice(-5).map((l) => {
29694
+ const parts = l.trim().split("|");
29695
+ const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : "";
29696
+ const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : "";
29697
+ return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}`;
29698
+ })
29699
+ ];
29700
+ return { content: [{ type: "text", text: stats.join("\n") }] };
28889
29701
  }
28890
- },
28891
- async ({ since, type }) => {
28892
- const sinceDate = parseRelativeDate(since);
28893
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28894
- const data = readMemory();
28895
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28896
- const results = lines.map((line) => {
28897
- const trimmed = line.trim();
28898
- const parts = trimmed.split("|");
28899
- if (parts.length < 7) return null;
28900
- const [id, cat, key, content, file2, tags, date5] = parts;
28901
- if (date5 < sinceDate) return null;
28902
- const changeType = date5 === today ? "created" : "updated";
28903
- if (type !== "all" && changeType !== type) return null;
28904
- return { id, cat, key, content, file: file2, tags, date: date5, changeType };
28905
- }).filter(Boolean);
28906
- if (results.length === 0) {
28907
- return { content: [{ type: "text", text: `No hay cambios desde ${sinceDate}` }] };
28908
- }
28909
- const created = results.filter((r) => r.changeType === "created");
28910
- const updated = results.filter((r) => r.changeType === "updated");
28911
- const sections = [`\u{1F4CB} Cambios desde ${sinceDate}:`, ""];
28912
- if (created.length > 0 && (type === "all" || type === "created")) {
28913
- sections.push(`\u2795 Nuevas (${created.length}):`);
28914
- for (const r of created) {
28915
- sections.push(` [${r.cat}] ${r.key} (${r.id})
29702
+ );
29703
+ server2.registerTool(
29704
+ "memory_diff",
29705
+ {
29706
+ title: "Memory Diff",
29707
+ description: "Muestra qu\xE9 cambi\xF3 en la memoria desde una fecha. \xDAtil para saber qu\xE9 se aprendi\xF3 desde la \xFAltima sesi\xF3n.",
29708
+ inputSchema: {
29709
+ since: external_exports.string().describe("Desde cu\xE1ndo mostrar cambios (ej: 24h, 7d, 2026-07-10)"),
29710
+ type: external_exports.enum(["all", "created", "updated"]).optional().default("all").describe("Filtrar por tipo de cambio")
29711
+ }
29712
+ },
29713
+ async ({ since, type }) => {
29714
+ const sinceDate = parseRelativeDate(since);
29715
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
29716
+ const data = readMemory();
29717
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
29718
+ const results = lines.map((line) => {
29719
+ const trimmed = line.trim();
29720
+ const parts = trimmed.split("|");
29721
+ if (parts.length < 7) return null;
29722
+ const [id, cat, key, content, file2, tags, date5] = parts;
29723
+ if (date5 < sinceDate) return null;
29724
+ const changeType = date5 === today ? "created" : "updated";
29725
+ if (type !== "all" && changeType !== type) return null;
29726
+ return { id, cat, key, content, file: file2, tags, date: date5, changeType };
29727
+ }).filter(Boolean);
29728
+ if (results.length === 0) {
29729
+ return { content: [{ type: "text", text: `No hay cambios desde ${sinceDate}` }] };
29730
+ }
29731
+ const created = results.filter((r) => r.changeType === "created");
29732
+ const updated = results.filter((r) => r.changeType === "updated");
29733
+ const sections = [`\u{1F4CB} Cambios desde ${sinceDate}:`, ""];
29734
+ if (created.length > 0 && (type === "all" || type === "created")) {
29735
+ sections.push(`\u2795 Nuevas (${created.length}):`);
29736
+ for (const r of created) {
29737
+ sections.push(` [${r.cat}] ${r.key} (${r.id})
28916
29738
  ${r.content}`);
29739
+ }
29740
+ sections.push("");
28917
29741
  }
28918
- sections.push("");
28919
- }
28920
- if (updated.length > 0 && (type === "all" || type === "updated")) {
28921
- sections.push(`\u270F\uFE0F Actualizadas (${updated.length}):`);
28922
- for (const r of updated) {
28923
- sections.push(` [${r.cat}] ${r.key} (${r.id}) \u2014 ${r.date}`);
29742
+ if (updated.length > 0 && (type === "all" || type === "updated")) {
29743
+ sections.push(`\u270F\uFE0F Actualizadas (${updated.length}):`);
29744
+ for (const r of updated) {
29745
+ sections.push(` [${r.cat}] ${r.key} (${r.id}) \u2014 ${r.date}`);
29746
+ }
29747
+ sections.push("");
28924
29748
  }
28925
- sections.push("");
28926
- }
28927
- return { content: [{ type: "text", text: sections.join("\n") }] };
28928
- }
28929
- );
28930
- server.registerTool(
28931
- "memory_suggest",
28932
- {
28933
- title: "Suggest Related Memories",
28934
- description: "Sugiere entradas de memoria relacionadas con un contexto dado. \xDAtil para obtener contexto antes de una tarea.",
28935
- inputSchema: {
28936
- context: external_exports.string().describe("Texto o contexto para buscar sugerencias"),
28937
- limit: external_exports.number().optional().default(5).describe("M\xE1ximo de sugerencias")
29749
+ return { content: [{ type: "text", text: sections.join("\n") }] };
28938
29750
  }
28939
- },
28940
- async ({ context, limit }) => {
28941
- const related = findRelatedEntries(context, "", limit);
28942
- if (related.length === 0) {
28943
- return { content: [{ type: "text", text: `No se encontraron entradas relacionadas con "${context}"` }] };
28944
- }
28945
- const formatted = related.map((r) => `[${r.cat}] ${r.key} (${r.id})
29751
+ );
29752
+ server2.registerTool(
29753
+ "memory_suggest",
29754
+ {
29755
+ title: "Suggest Related Memories",
29756
+ description: "Sugiere entradas de memoria relacionadas con un contexto dado. \xDAtil para obtener contexto antes de una tarea.",
29757
+ inputSchema: {
29758
+ context: external_exports.string().describe("Texto o contexto para buscar sugerencias"),
29759
+ limit: external_exports.number().optional().default(5).describe("M\xE1ximo de sugerencias")
29760
+ }
29761
+ },
29762
+ async ({ context, limit }) => {
29763
+ const related = findRelatedEntries(context, "", limit);
29764
+ if (related.length === 0) {
29765
+ return { content: [{ type: "text", text: `No se encontraron entradas relacionadas con "${context}"` }] };
29766
+ }
29767
+ const formatted = related.map((r) => `[${r.cat}] ${r.key} (${r.id})
28946
29768
  ${r.content}
28947
29769
  File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
28948
- return { content: [{ type: "text", text: `\u{1F50D} Sugerencias para "${context}":
29770
+ return { content: [{ type: "text", text: `\u{1F50D} Sugerencias para "${context}":
28949
29771
 
28950
29772
  ${formatted}` }] };
28951
- }
28952
- );
28953
- server.registerTool(
28954
- "memory_smart_recall",
28955
- {
28956
- title: "Smart Recall (Unified)",
28957
- description: "Recuperaci\xF3n unificada: combina BM25 + grafo + decay + calidad en una sola llamada. Usar al INICIO de cada tarea para obtener todo el contexto relevante de memoria.",
28958
- inputSchema: {
28959
- intent: external_exports.string().describe("Describe qu\xE9 necesitas saber (ej: 'dise\xF1o de base de datos para backend')"),
28960
- limit: external_exports.number().optional().default(8).describe("M\xE1ximo de entradas a devolver"),
28961
- category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)")
28962
29773
  }
28963
- },
28964
- async ({ intent, limit, category }) => {
28965
- const data = readMemory();
28966
- const result = generateSmartRecall(data, intent, { limit, category });
28967
- return { content: [{ type: "text", text: result }] };
28968
- }
28969
- );
28970
- server.registerTool(
28971
- "memory_summary",
28972
- {
28973
- title: "File Summary",
28974
- description: "Guarda o recupera un resumen de un archivo grande para ahorrar tokens.",
28975
- inputSchema: {
28976
- action: external_exports.enum(["get", "set"]).describe("get para leer, set para guardar"),
28977
- file: external_exports.string().describe("Ruta del archivo"),
28978
- summary: external_exports.string().optional().default("").describe("Resumen del archivo (solo para set)")
29774
+ );
29775
+ server2.registerTool(
29776
+ "memory_smart_recall",
29777
+ {
29778
+ title: "Smart Recall (Unified)",
29779
+ description: "Recuperaci\xF3n unificada: combina BM25 + grafo + decay + calidad en una sola llamada. Usar al INICIO de cada tarea para obtener todo el contexto relevante de memoria.",
29780
+ inputSchema: {
29781
+ intent: external_exports.string().describe("Describe qu\xE9 necesitas saber (ej: 'dise\xF1o de base de datos para backend')"),
29782
+ limit: external_exports.number().optional().default(8).describe("M\xE1ximo de entradas a devolver"),
29783
+ category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)")
29784
+ }
29785
+ },
29786
+ async ({ intent, limit, category }) => {
29787
+ const data = readMemory();
29788
+ const result = generateSmartRecall(data, intent, { limit, category });
29789
+ return { content: [{ type: "text", text: result }] };
28979
29790
  }
28980
- },
28981
- async ({ action, file: file2, summary }) => {
28982
- const data = readMemory();
28983
- if (action === "get") {
28984
- const lines2 = data.split("\n");
28985
- const summaryIdx2 = lines2.findIndex((l) => l.trim().startsWith("summaries:"));
28986
- if (summaryIdx2 === -1) {
28987
- return { content: [{ type: "text", text: `No hay res\xFAmenes guardados para "${file2}"` }] };
29791
+ );
29792
+ server2.registerTool(
29793
+ "memory_summary",
29794
+ {
29795
+ title: "File Summary",
29796
+ description: "Guarda o recupera un resumen de un archivo grande para ahorrar tokens.",
29797
+ inputSchema: {
29798
+ action: external_exports.enum(["get", "set"]).describe("get para leer, set para guardar"),
29799
+ file: external_exports.string().describe("Ruta del archivo"),
29800
+ summary: external_exports.string().optional().default("").describe("Resumen del archivo (solo para set)")
28988
29801
  }
28989
- const summaryLines2 = lines2.slice(summaryIdx2 + 1).filter((l) => l.includes(":"));
28990
- const match = summaryLines2.find((l) => l.startsWith(` ${file2}:`));
28991
- if (!match) {
28992
- return { content: [{ type: "text", text: `No hay resumen para "${file2}"` }] };
29802
+ },
29803
+ async ({ action, file: file2, summary }) => {
29804
+ const data = readMemory();
29805
+ if (action === "get") {
29806
+ const lines2 = data.split("\n");
29807
+ const summaryIdx2 = lines2.findIndex((l) => l.trim().startsWith("summaries:"));
29808
+ if (summaryIdx2 === -1) {
29809
+ return { content: [{ type: "text", text: `No hay res\xFAmenes guardados para "${file2}"` }] };
29810
+ }
29811
+ const summaryLines2 = lines2.slice(summaryIdx2 + 1).filter((l) => l.includes(":"));
29812
+ const match = summaryLines2.find((l) => l.startsWith(` ${file2}:`));
29813
+ if (!match) {
29814
+ return { content: [{ type: "text", text: `No hay resumen para "${file2}"` }] };
29815
+ }
29816
+ const summaryText = match.replace(` ${file2}: `, "");
29817
+ return { content: [{ type: "text", text: summaryText }] };
29818
+ }
29819
+ const lines = data.split("\n");
29820
+ let summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"));
29821
+ if (summaryIdx === -1) {
29822
+ lines.push("", "summaries:");
29823
+ summaryIdx = lines.length - 1;
29824
+ }
29825
+ const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"));
29826
+ const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file2}:`));
29827
+ if (existingIdx !== -1) {
29828
+ summaryLines[existingIdx] = ` ${file2}: ${summary}`;
29829
+ } else {
29830
+ summaryLines.push(` ${file2}: ${summary}`);
28993
29831
  }
28994
- const summaryText = match.replace(` ${file2}: `, "");
28995
- return { content: [{ type: "text", text: summaryText }] };
28996
- }
28997
- const lines = data.split("\n");
28998
- let summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"));
28999
- if (summaryIdx === -1) {
29000
- lines.push("", "summaries:");
29001
- summaryIdx = lines.length - 1;
29002
- }
29003
- const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"));
29004
- const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file2}:`));
29005
- if (existingIdx !== -1) {
29006
- summaryLines[existingIdx] = ` ${file2}: ${summary}`;
29007
- } else {
29008
- summaryLines.push(` ${file2}: ${summary}`);
29009
- }
29010
- lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines);
29011
- writeMemory(lines.join("\n"));
29012
- return {
29013
- content: [{ type: "text", text: `\u{1F4DD} Resumen guardado para ${file2}` }]
29014
- };
29015
- }
29016
- );
29017
- server.registerTool(
29018
- "memory_archive",
29019
- {
29020
- title: "Archive Old Entries",
29021
- description: "Mover entradas antiguas (>30 d\xEDas) a archive.toon para mantener la memoria limpia.",
29022
- inputSchema: {}
29023
- },
29024
- async () => {
29025
- const result = archiveOldEntries();
29026
- if (result.archived === 0) {
29027
- return { content: [{ type: "text", text: "No hay entradas antiguas para archivar" }] };
29028
- }
29029
- return {
29030
- content: [{
29031
- type: "text",
29032
- text: `\u{1F4E6} Archivadas ${result.archived} entradas antiguas
29033
- \u{1F4CB} Quedan ${result.kept} entradas activas`
29034
- }]
29035
- };
29036
- }
29037
- );
29038
- server.registerTool(
29039
- "memory_encrypt",
29040
- {
29041
- title: "Enable Encryption",
29042
- description: "Habilita encriptaci\xF3n AES-256-GCM para la memoria. La clave se genera autom\xE1ticamente.",
29043
- inputSchema: {}
29044
- },
29045
- async () => {
29046
- const config2 = loadConfig();
29047
- if (config2.encrypted) {
29048
- return { content: [{ type: "text", text: "La encriptaci\xF3n ya est\xE1 habilitada" }] };
29049
- }
29050
- const key = getKey();
29051
- if (!key) {
29052
- return { content: [{ type: "text", text: "\u274C Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] };
29053
- }
29054
- const data = readFileSync3(MEMORY_FILE, "utf-8");
29055
- const encrypted = encrypt(data, key);
29056
- writeFileSync3(MEMORY_FILE, encrypted);
29057
- saveConfig({ encrypted: true });
29058
- return {
29059
- content: [{ type: "text", text: "\u{1F510} Encriptaci\xF3n habilitada" }]
29060
- };
29061
- }
29062
- );
29063
- server.registerTool(
29064
- "memory_decrypt",
29065
- {
29066
- title: "Disable Encryption",
29067
- description: "Deshabilita la encriptaci\xF3n y decodifica la memoria.",
29068
- inputSchema: {
29069
- key: external_exports.string().describe("Clave de encriptaci\xF3n")
29070
- }
29071
- },
29072
- async ({ key }) => {
29073
- const config2 = loadConfig();
29074
- if (!config2.encrypted) {
29075
- return { content: [{ type: "text", text: "La encriptaci\xF3n no est\xE1 habilitada" }] };
29076
- }
29077
- const resolvedKey = key || getKey() || "";
29078
- if (!resolvedKey) {
29079
- return { content: [{ type: "text", text: "\u274C No hay clave. P\xE1sala como argumento o la del archivo .env" }] };
29080
- }
29081
- try {
29082
- const data = readFileSync3(MEMORY_FILE, "utf-8");
29083
- const decrypted = decrypt(data, resolvedKey);
29084
- writeFileSync3(MEMORY_FILE, decrypted);
29085
- saveConfig({ encrypted: false });
29832
+ lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines);
29833
+ writeMemory(lines.join("\n"));
29086
29834
  return {
29087
- content: [{ type: "text", text: "\u{1F513} Encriptaci\xF3n deshabilitada" }]
29835
+ content: [{ type: "text", text: `\u{1F4DD} Resumen guardado para ${file2}` }]
29088
29836
  };
29089
- } catch {
29090
- return { content: [{ type: "text", text: "\u274C Clave incorrecta o datos corruptos" }] };
29091
- }
29092
- }
29093
- );
29094
- server.registerTool(
29095
- "memory_captured",
29096
- {
29097
- title: "List Captured Activity",
29098
- 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.",
29099
- inputSchema: {
29100
- limit: external_exports.number().optional().default(20).describe("M\xE1ximo de observaciones a mostrar"),
29101
- tool: external_exports.string().optional().default("").describe("Filtrar por nombre de herramienta"),
29102
- file: external_exports.string().optional().default("").describe("Filtrar por archivo"),
29103
- clear: external_exports.boolean().optional().default(false).describe("Si true, limpia el log de captura")
29104
29837
  }
29105
- },
29106
- async ({ limit, tool, file: file2, clear }) => {
29107
- if (clear) {
29108
- if (existsSync3(OBSERVATIONS_FILE)) {
29109
- writeFileSync3(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n");
29110
- }
29111
- return { content: [{ type: "text", text: "\u{1F9F9} Log de captura limpiado" }] };
29112
- }
29113
- let obs = readObservations();
29114
- if (tool) obs = obs.filter((o) => o.tool.toLowerCase().includes(tool.toLowerCase()));
29115
- if (file2) obs = obs.filter((o) => o.file.toLowerCase().includes(file2.toLowerCase()));
29116
- obs = obs.slice(-limit).reverse();
29117
- if (obs.length === 0) {
29838
+ );
29839
+ server2.registerTool(
29840
+ "memory_archive",
29841
+ {
29842
+ title: "Archive Old Entries",
29843
+ description: "Mover entradas antiguas (>30 d\xEDas) a archive.toon para mantener la memoria limpia.",
29844
+ inputSchema: {}
29845
+ },
29846
+ async () => {
29847
+ const result = archiveOldEntries();
29848
+ if (result.archived === 0) {
29849
+ return { content: [{ type: "text", text: "No hay entradas antiguas para archivar" }] };
29850
+ }
29118
29851
  return {
29119
29852
  content: [{
29120
29853
  type: "text",
29121
- text: "No hay actividad capturada. La captura est\xE1 desactivada por defecto; act\xEDvala con `toon-memory capture on`."
29854
+ text: `\u{1F4E6} Archivadas ${result.archived} entradas antiguas
29855
+ \u{1F4CB} Quedan ${result.kept} entradas activas`
29122
29856
  }]
29123
29857
  };
29124
29858
  }
29125
- const formatted = obs.map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}
29126
- ${o.summary}`).join("\n\n");
29127
- return { content: [{ type: "text", text: `\u{1F50D} Actividad capturada (${obs.length}):
29128
-
29129
- ${formatted}` }] };
29130
- }
29131
- );
29132
- server.registerTool(
29133
- "memory_consolidate",
29134
- {
29135
- title: "Consolidate Memory",
29136
- description: "Consolida la memoria eliminando entradas con contenido id\xE9ntico (mantiene la primera). Determinista, sin LLM.",
29137
- inputSchema: {}
29138
- },
29139
- async () => {
29140
- const result = consolidateEntries();
29141
- if (result.removed === 0) {
29142
- return { content: [{ type: "text", text: `\u2705 Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] };
29859
+ );
29860
+ server2.registerTool(
29861
+ "memory_encrypt",
29862
+ {
29863
+ title: "Enable Encryption",
29864
+ description: "Habilita encriptaci\xF3n AES-256-GCM para la memoria. La clave se genera autom\xE1ticamente.",
29865
+ inputSchema: {}
29866
+ },
29867
+ async () => {
29868
+ const config2 = loadConfig();
29869
+ if (config2.encrypted) {
29870
+ return { content: [{ type: "text", text: "La encriptaci\xF3n ya est\xE1 habilitada" }] };
29871
+ }
29872
+ const key = getKey();
29873
+ if (!key) {
29874
+ return { content: [{ type: "text", text: "\u274C Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] };
29875
+ }
29876
+ const data = readFileSync10(MEMORY_FILE, "utf-8");
29877
+ const encrypted = encrypt(data, key);
29878
+ writeFileSync4(MEMORY_FILE, encrypted);
29879
+ saveConfig({ encrypted: true });
29880
+ return {
29881
+ content: [{ type: "text", text: "\u{1F510} Encriptaci\xF3n habilitada" }]
29882
+ };
29143
29883
  }
29144
- return {
29145
- content: [{
29146
- type: "text",
29147
- text: `\u{1F9F9} Consolidadas ${result.removed} entradas duplicadas.
29148
- Quedan ${result.kept} activas.
29149
- Duplicados: ${result.duplicates.join(", ")}`
29150
- }]
29151
- };
29152
- }
29153
- );
29154
- server.registerTool(
29155
- "memory_sessions",
29156
- {
29157
- title: "Active Sessions & Conflicts",
29158
- 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.",
29159
- inputSchema: {
29160
- conflictsOnly: external_exports.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves")
29884
+ );
29885
+ server2.registerTool(
29886
+ "memory_decrypt",
29887
+ {
29888
+ title: "Disable Encryption",
29889
+ description: "Deshabilita la encriptaci\xF3n y decodifica la memoria.",
29890
+ inputSchema: {
29891
+ key: external_exports.string().describe("Clave de encriptaci\xF3n")
29892
+ }
29893
+ },
29894
+ async ({ key }) => {
29895
+ const config2 = loadConfig();
29896
+ if (!config2.encrypted) {
29897
+ return { content: [{ type: "text", text: "La encriptaci\xF3n no est\xE1 habilitada" }] };
29898
+ }
29899
+ const resolvedKey = key || getKey() || "";
29900
+ if (!resolvedKey) {
29901
+ return { content: [{ type: "text", text: "\u274C No hay clave. P\xE1sala como argumento o la del archivo .env" }] };
29902
+ }
29903
+ try {
29904
+ const data = readFileSync10(MEMORY_FILE, "utf-8");
29905
+ const decrypted = decrypt(data, resolvedKey);
29906
+ writeFileSync4(MEMORY_FILE, decrypted);
29907
+ saveConfig({ encrypted: false });
29908
+ return {
29909
+ content: [{ type: "text", text: "\u{1F513} Encriptaci\xF3n deshabilitada" }]
29910
+ };
29911
+ } catch {
29912
+ return { content: [{ type: "text", text: "\u274C Clave incorrecta o datos corruptos" }] };
29913
+ }
29161
29914
  }
29162
- },
29163
- async ({ conflictsOnly }) => {
29164
- const selfId = resolveSessionId();
29165
- const { active, conflicts } = coordinationView(selfId);
29166
- if (conflictsOnly) {
29167
- if (conflicts.length === 0) {
29168
- return { content: [{ type: "text", text: "\u2705 No hay conflictos suaves entre sesiones activas." }] };
29169
- }
29170
- const lines = conflicts.map((c) => {
29171
- const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ");
29172
- return `\u26A0\uFE0F ${c.file}
29173
- \u2194 ${who}`;
29174
- });
29175
- return {
29176
- content: [{ type: "text", text: `\u{1F525} Conflictos suaves (${conflicts.length}):
29915
+ );
29916
+ server2.registerTool(
29917
+ "memory_captured",
29918
+ {
29919
+ title: "List Captured Activity",
29920
+ 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.",
29921
+ inputSchema: {
29922
+ limit: external_exports.number().optional().default(20).describe("M\xE1ximo de observaciones a mostrar"),
29923
+ tool: external_exports.string().optional().default("").describe("Filtrar por nombre de herramienta"),
29924
+ file: external_exports.string().optional().default("").describe("Filtrar por archivo"),
29925
+ clear: external_exports.boolean().optional().default(false).describe("Si true, limpia el log de captura")
29926
+ }
29927
+ },
29928
+ async ({ limit, tool, file: file2, clear }) => {
29929
+ if (clear) {
29930
+ if (existsSync10(OBSERVATIONS_FILE)) {
29931
+ writeFileSync4(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n");
29932
+ }
29933
+ return { content: [{ type: "text", text: "\u{1F9F9} Log de captura limpiado" }] };
29934
+ }
29935
+ let obs = readObservations();
29936
+ if (tool) obs = obs.filter((o) => o.tool.toLowerCase().includes(tool.toLowerCase()));
29937
+ if (file2) obs = obs.filter((o) => o.file.toLowerCase().includes(file2.toLowerCase()));
29938
+ obs = obs.slice(-limit).reverse();
29939
+ if (obs.length === 0) {
29940
+ return {
29941
+ content: [{
29942
+ type: "text",
29943
+ text: "No hay actividad capturada. La captura est\xE1 desactivada por defecto; act\xEDvala con `toon-memory capture on`."
29944
+ }]
29945
+ };
29946
+ }
29947
+ const formatted = obs.map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}
29948
+ ${o.summary}`).join("\n\n");
29949
+ return { content: [{ type: "text", text: `\u{1F50D} Actividad capturada (${obs.length}):
29177
29950
 
29178
- ${lines.join("\n\n")}` }]
29179
- };
29951
+ ${formatted}` }] };
29180
29952
  }
29181
- if (active.length === 0) {
29953
+ );
29954
+ server2.registerTool(
29955
+ "memory_consolidate",
29956
+ {
29957
+ title: "Consolidate Memory",
29958
+ description: "Consolida la memoria eliminando entradas con contenido id\xE9ntico (mantiene la primera). Determinista, sin LLM.",
29959
+ inputSchema: {}
29960
+ },
29961
+ async () => {
29962
+ const result = consolidateEntries();
29963
+ if (result.removed === 0) {
29964
+ return { content: [{ type: "text", text: `\u2705 Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] };
29965
+ }
29182
29966
  return {
29183
29967
  content: [{
29184
29968
  type: "text",
29185
- text: "\u{1F7E2} No hay otras sesiones activas en este proyecto.\n(Esta sesi\xF3n: " + selfId + " @ " + currentBranch() + ")"
29969
+ text: `\u{1F9F9} Consolidadas ${result.removed} entradas duplicadas.
29970
+ Quedan ${result.kept} activas.
29971
+ Duplicados: ${result.duplicates.join(", ")}`
29186
29972
  }]
29187
29973
  };
29188
29974
  }
29189
- const ttlMin = Math.round(SESSION_TTL_MS / 6e4);
29190
- const section = (s) => {
29191
- const mins = Math.max(0, Math.round(s.ageMs / 6e4));
29192
- const tag = s.id === selfId ? " (t\xFA)" : "";
29193
- const ended = s.ended ? " \u{1F3C1}" : "";
29194
- const files = Object.keys(s.files).slice(0, 8).map((f) => ` \u2022 ${f}`).join("\n");
29195
- const fileBlock = files ? `
29975
+ );
29976
+ server2.registerTool(
29977
+ "memory_sessions",
29978
+ {
29979
+ title: "Active Sessions & Conflicts",
29980
+ 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.",
29981
+ inputSchema: {
29982
+ conflictsOnly: external_exports.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves")
29983
+ }
29984
+ },
29985
+ async ({ conflictsOnly }) => {
29986
+ const selfId = resolveSessionId();
29987
+ const { active, conflicts } = coordinationView(selfId);
29988
+ if (conflictsOnly) {
29989
+ if (conflicts.length === 0) {
29990
+ return { content: [{ type: "text", text: "\u2705 No hay conflictos suaves entre sesiones activas." }] };
29991
+ }
29992
+ const lines = conflicts.map((c) => {
29993
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ");
29994
+ return `\u26A0\uFE0F ${c.file}
29995
+ \u2194 ${who}`;
29996
+ });
29997
+ return {
29998
+ content: [{ type: "text", text: `\u{1F525} Conflictos suaves (${conflicts.length}):
29999
+
30000
+ ${lines.join("\n\n")}` }]
30001
+ };
30002
+ }
30003
+ if (active.length === 0) {
30004
+ return {
30005
+ content: [{
30006
+ type: "text",
30007
+ text: "\u{1F7E2} No hay otras sesiones activas en este proyecto.\n(Esta sesi\xF3n: " + selfId + " @ " + currentBranch() + ")"
30008
+ }]
30009
+ };
30010
+ }
30011
+ const ttlMin = Math.round(SESSION_TTL_MS / 6e4);
30012
+ const section = (s) => {
30013
+ const mins = Math.max(0, Math.round(s.ageMs / 6e4));
30014
+ const tag = s.id === selfId ? " (t\xFA)" : "";
30015
+ const ended = s.ended ? " \u{1F3C1}" : "";
30016
+ const files = Object.keys(s.files).slice(0, 8).map((f) => ` \u2022 ${f}`).join("\n");
30017
+ const fileBlock = files ? `
29196
30018
  Archivos:
29197
30019
  ${files}` : "";
29198
- return `\u2022 ${s.agent} @ ${s.branch}${tag}${ended}
30020
+ return `\u2022 ${s.agent} @ ${s.branch}${tag}${ended}
29199
30021
  id: ${s.id}
29200
30022
  hace ${mins} min${fileBlock}`;
29201
- };
29202
- const parts = [
29203
- `\u{1F9ED} Sesiones activas (${active.length}) \u2014 ventana ${ttlMin} min:`,
29204
- "",
29205
- ...active.map(section)
29206
- ];
29207
- if (conflicts.length > 0) {
29208
- parts.push("", `\u{1F525} Conflictos suaves (${conflicts.length}):`);
29209
- for (const c of conflicts) {
29210
- const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ");
29211
- parts.push(` \u26A0\uFE0F ${c.file} \u2194 ${who}`);
30023
+ };
30024
+ const parts = [
30025
+ `\u{1F9ED} Sesiones activas (${active.length}) \u2014 ventana ${ttlMin} min:`,
30026
+ "",
30027
+ ...active.map(section)
30028
+ ];
30029
+ if (conflicts.length > 0) {
30030
+ parts.push("", `\u{1F525} Conflictos suaves (${conflicts.length}):`);
30031
+ for (const c of conflicts) {
30032
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ");
30033
+ parts.push(` \u26A0\uFE0F ${c.file} \u2194 ${who}`);
30034
+ }
30035
+ } else {
30036
+ parts.push("", "\u2705 Sin conflictos suaves detectados.");
29212
30037
  }
29213
- } else {
29214
- parts.push("", "\u2705 Sin conflictos suaves detectados.");
30038
+ return { content: [{ type: "text", text: parts.join("\n") }] };
29215
30039
  }
29216
- return { content: [{ type: "text", text: parts.join("\n") }] };
29217
- }
30040
+ );
30041
+ server2.registerTool(
30042
+ "context_brief",
30043
+ {
30044
+ title: "Context Briefing",
30045
+ description: "Genera un briefing de contexto compacto: memoria relevante + sesiones activas + salud del proyecto. Un solo call en vez de 5-6 llamadas separadas. Cero LLM, pura l\xF3gica determinista.",
30046
+ inputSchema: {
30047
+ task: external_exports.string().optional().default("").describe("Tarea actual del agente. Si se provee, las entradas se rankean por relevancia a esta tarea. Si est\xE1 vac\xEDo, muestra las top entradas por importancia."),
30048
+ limit: external_exports.number().optional().default(6).describe("M\xE1ximo de entradas relevantes a mostrar")
30049
+ }
30050
+ },
30051
+ async ({ task, limit }) => {
30052
+ const data = readMemory();
30053
+ const brief = generateContextBrief(data, { task: task || void 0, limit });
30054
+ return { content: [{ type: "text", text: brief }] };
30055
+ }
30056
+ );
30057
+ server2.registerTool(
30058
+ "context_generate",
30059
+ {
30060
+ title: "Generate Full Context",
30061
+ description: "Genera un system prompt completo: proyecto (package.json, deps, framework) + git (rama, commits) + memoria (entries relevantes) + sesiones. Un solo call para preparar al agente. Cero LLM.",
30062
+ inputSchema: {
30063
+ task: external_exports.string().optional().default("").describe("Tarea del agente. Si se provee, rankea entries por relevancia a esta tarea.")
30064
+ }
30065
+ },
30066
+ async ({ task }) => {
30067
+ const data = readMemory();
30068
+ const root = process.cwd();
30069
+ const brief = generateContextGenerate(data, root, { task: task || void 0 });
30070
+ return { content: [{ type: "text", text: brief }] };
30071
+ }
30072
+ );
30073
+ server2.registerTool(
30074
+ "context_diff",
30075
+ {
30076
+ title: "Context Diff",
30077
+ description: "Qu\xE9 cambi\xF3 desde la \xFAltima sesi\xF3n: git commits + archivos modificados + entradas de memoria nuevas/actualizadas. Cero LLM.",
30078
+ inputSchema: {
30079
+ since: external_exports.string().optional().default("").describe("Fecha desde (YYYY-MM-DD o relativa como '7d'). Vac\xEDo = \xFAltimos cambios visibles.")
30080
+ }
30081
+ },
30082
+ async ({ since }) => {
30083
+ const data = readMemory();
30084
+ const root = process.cwd();
30085
+ const diff = generateContextDiff(data, root, since || void 0);
30086
+ return { content: [{ type: "text", text: diff }] };
30087
+ }
30088
+ );
30089
+ server2.registerTool(
30090
+ "context_focus",
30091
+ {
30092
+ title: "Focus Context for Task",
30093
+ description: "Contexto hiper-enfocado para una tarea espec\xEDfica: entries relevantes + archivos relacionados + c\xF3digo que referencia el s\xEDmbolo + tests existentes. Cero LLM.",
30094
+ inputSchema: {
30095
+ task: external_exports.string().describe("Tarea o s\xEDmbolo para buscar contexto (ej: 'fix auth bug', 'authenticate')"),
30096
+ limit: external_exports.number().optional().default(6).describe("M\xE1ximo de entries de memoria a incluir")
30097
+ }
30098
+ },
30099
+ async ({ task, limit }) => {
30100
+ const data = readMemory();
30101
+ const root = process.cwd();
30102
+ const focused = generateContextFocus(data, root, task, { limit });
30103
+ return { content: [{ type: "text", text: focused }] };
30104
+ }
30105
+ );
30106
+ server2.registerTool(
30107
+ "context_health",
30108
+ {
30109
+ title: "Memory Health Audit",
30110
+ description: "Auditor\xEDa completa de salud de la memoria: links hu\xE9rfanos, duplicados, refs rotos, TTL expirado, calidad, sesiones stale. Incluye score 0-100. Cero LLM.",
30111
+ inputSchema: {}
30112
+ },
30113
+ async () => {
30114
+ const data = readMemory();
30115
+ const root = process.cwd();
30116
+ const { markdown } = generateContextHealth(data, root);
30117
+ return { content: [{ type: "text", text: markdown }] };
30118
+ }
30119
+ );
30120
+ server2.registerTool(
30121
+ "context_export",
30122
+ {
30123
+ title: "Export Memory as Markdown",
30124
+ description: "Exporta toda la memoria como markdown inyectable para otros agentes o sesiones. Formato full (detallado) o compacto. Cero LLM.",
30125
+ inputSchema: {
30126
+ format: external_exports.enum(["full", "compact"]).optional().default("full").describe("full = detallado con graph, compact = resumido sin edges")
30127
+ }
30128
+ },
30129
+ async ({ format }) => {
30130
+ const data = readMemory();
30131
+ const exported = generateContextExport(data, format);
30132
+ return { content: [{ type: "text", text: exported }] };
30133
+ }
30134
+ );
30135
+ }
30136
+
30137
+ // src/mcp/resources.ts
30138
+ function registerResources(server2) {
30139
+ server2.registerResource(
30140
+ "memory-entries",
30141
+ "toon://memory/entries",
30142
+ { title: "Memory Entries", mimeType: "text/plain" },
30143
+ async (uri) => {
30144
+ const data = readMemory();
30145
+ return { contents: [{ uri: uri.href, text: data }] };
30146
+ }
30147
+ );
30148
+ server2.registerResource(
30149
+ "memory-stats",
30150
+ "toon://memory/stats",
30151
+ { title: "Memory Stats", mimeType: "text/plain" },
30152
+ async (uri) => {
30153
+ const data = readMemory();
30154
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
30155
+ const entries = lines.map((l) => {
30156
+ const parts = l.trim().split("|");
30157
+ return { category: parts[1] || "unknown", ttl: parts[7] || "" };
30158
+ });
30159
+ const byCategory = {};
30160
+ for (const e of entries) {
30161
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1;
30162
+ }
30163
+ const withTtl = entries.filter((e) => e.ttl).length;
30164
+ const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length;
30165
+ const text = [
30166
+ `Entradas totales: ${entries.length}`,
30167
+ `TTL: ${withTtl} con expiraci\xF3n, ${expired} expiradas`,
30168
+ "Por categor\xEDa:",
30169
+ ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`)
30170
+ ].join("\n");
30171
+ return { contents: [{ uri: uri.href, text }] };
30172
+ }
30173
+ );
30174
+ server2.registerResource(
30175
+ "memory-summaries",
30176
+ "toon://memory/summaries",
30177
+ { title: "Memory Summaries", mimeType: "text/plain" },
30178
+ async (uri) => {
30179
+ const data = readMemory();
30180
+ const primer = generateSystemPrimer(data);
30181
+ return { contents: [{ uri: uri.href, text: primer }] };
30182
+ }
30183
+ );
30184
+ }
30185
+
30186
+ // src/mcp/server.ts
30187
+ var server = new McpServer(
30188
+ { name: "toon-memory", version: "2.7.0" },
30189
+ { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
29218
30190
  );
30191
+ registerResources(server);
30192
+ registerTools(server);
29219
30193
  try {
29220
30194
  pruneExpiredEntries();
29221
30195
  } catch {