toon-memory 4.3.5 → 4.4.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
@@ -1809,8 +1809,8 @@ var init_doc = __esm({
1809
1809
  const lines = content.split("\n").filter((x) => x);
1810
1810
  const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1811
1811
  const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1812
- for (const line of dedented) {
1813
- this.content.push(line);
1812
+ for (const line2 of dedented) {
1813
+ this.content.push(line2);
1814
1814
  }
1815
1815
  }
1816
1816
  compile() {
@@ -15338,13 +15338,13 @@ var require_scope = __commonJS({
15338
15338
  }
15339
15339
  };
15340
15340
  exports.ValueScopeName = ValueScopeName;
15341
- var line = (0, code_1._)`\n`;
15341
+ var line2 = (0, code_1._)`\n`;
15342
15342
  var ValueScope = class extends Scope {
15343
15343
  constructor(opts) {
15344
15344
  super(opts);
15345
15345
  this._values = {};
15346
15346
  this._scope = opts.scope;
15347
- this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
15347
+ this.opts = { ...opts, _n: opts.lines ? line2 : code_1.nil };
15348
15348
  }
15349
15349
  get() {
15350
15350
  return this._scope;
@@ -17886,11 +17886,11 @@ var require_validate = __commonJS({
17886
17886
  jsonPointer = $data;
17887
17887
  data = names_1.default.rootData;
17888
17888
  } else {
17889
- const matches = RELATIVE_JSON_POINTER.exec($data);
17890
- if (!matches)
17889
+ const matches2 = RELATIVE_JSON_POINTER.exec($data);
17890
+ if (!matches2)
17891
17891
  throw new Error(`Invalid JSON-pointer: ${$data}`);
17892
- const up2 = +matches[1];
17893
- jsonPointer = matches[2];
17892
+ const up2 = +matches2[1];
17893
+ jsonPointer = matches2[2];
17894
17894
  if (jsonPointer === "#") {
17895
17895
  if (up2 >= dataLevel)
17896
17896
  throw new Error(errorMsg("property/index", up2));
@@ -18587,11 +18587,11 @@ var require_schemes = __commonJS({
18587
18587
  urnComponent.error = "URN can not be parsed";
18588
18588
  return urnComponent;
18589
18589
  }
18590
- const matches = urnComponent.path.match(URN_REG);
18591
- if (matches) {
18590
+ const matches2 = urnComponent.path.match(URN_REG);
18591
+ if (matches2) {
18592
18592
  const scheme = options.scheme || urnComponent.scheme || "urn";
18593
- urnComponent.nid = matches[1].toLowerCase();
18594
- urnComponent.nss = matches[2];
18593
+ urnComponent.nid = matches2[1].toLowerCase();
18594
+ urnComponent.nss = matches2[2];
18595
18595
  const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
18596
18596
  const schemeHandler = getSchemeHandler(urnScheme);
18597
18597
  urnComponent.path = void 0;
@@ -18862,8 +18862,8 @@ var require_fast_uri = __commonJS({
18862
18862
  }
18863
18863
  var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
18864
18864
  var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
18865
- function getParseError(parsed, matches) {
18866
- if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
18865
+ function getParseError(parsed, matches2) {
18866
+ if (matches2[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
18867
18867
  return 'URI path must start with "/" when authority is present.';
18868
18868
  }
18869
18869
  if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) {
@@ -18896,19 +18896,19 @@ var require_fast_uri = __commonJS({
18896
18896
  parsed.error = "URI authority must not contain a literal backslash.";
18897
18897
  malformedAuthorityOrPort = true;
18898
18898
  }
18899
- const matches = uri.match(URI_PARSE);
18900
- if (matches) {
18901
- parsed.scheme = matches[1];
18902
- parsed.userinfo = matches[3];
18903
- parsed.host = matches[4];
18904
- parsed.port = parseInt(matches[5], 10);
18905
- parsed.path = matches[6] || "";
18906
- parsed.query = matches[7];
18907
- parsed.fragment = matches[8];
18899
+ const matches2 = uri.match(URI_PARSE);
18900
+ if (matches2) {
18901
+ parsed.scheme = matches2[1];
18902
+ parsed.userinfo = matches2[3];
18903
+ parsed.host = matches2[4];
18904
+ parsed.port = parseInt(matches2[5], 10);
18905
+ parsed.path = matches2[6] || "";
18906
+ parsed.query = matches2[7];
18907
+ parsed.fragment = matches2[8];
18908
18908
  if (isNaN(parsed.port)) {
18909
- parsed.port = matches[5];
18909
+ parsed.port = matches2[5];
18910
18910
  }
18911
- const parseError = getParseError(parsed, matches);
18911
+ const parseError = getParseError(parsed, matches2);
18912
18912
  if (parseError !== void 0) {
18913
18913
  parsed.error = parsed.error || parseError;
18914
18914
  malformedAuthorityOrPort = true;
@@ -21748,12 +21748,12 @@ var require_formats = __commonJS({
21748
21748
  var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
21749
21749
  var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
21750
21750
  function date5(str) {
21751
- const matches = DATE.exec(str);
21752
- if (!matches)
21751
+ const matches2 = DATE.exec(str);
21752
+ if (!matches2)
21753
21753
  return false;
21754
- const year = +matches[1];
21755
- const month = +matches[2];
21756
- const day = +matches[3];
21754
+ const year = +matches2[1];
21755
+ const month = +matches2[2];
21756
+ const day = +matches2[3];
21757
21757
  return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
21758
21758
  }
21759
21759
  function compareDate(d1, d2) {
@@ -21768,16 +21768,16 @@ var require_formats = __commonJS({
21768
21768
  var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
21769
21769
  function getTime(strictTimeZone) {
21770
21770
  return function time3(str) {
21771
- const matches = TIME.exec(str);
21772
- if (!matches)
21771
+ const matches2 = TIME.exec(str);
21772
+ if (!matches2)
21773
21773
  return false;
21774
- const hr2 = +matches[1];
21775
- const min = +matches[2];
21776
- const sec = +matches[3];
21777
- const tz = matches[4];
21778
- const tzSign = matches[5] === "-" ? -1 : 1;
21779
- const tzH = +(matches[6] || 0);
21780
- const tzM = +(matches[7] || 0);
21774
+ const hr2 = +matches2[1];
21775
+ const min = +matches2[2];
21776
+ const sec = +matches2[3];
21777
+ const tz = matches2[4];
21778
+ const tzSign = matches2[5] === "-" ? -1 : 1;
21779
+ const tzH = +(matches2[6] || 0);
21780
+ const tzM = +(matches2[7] || 0);
21781
21781
  if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)
21782
21782
  return false;
21783
21783
  if (hr2 <= 23 && min <= 59 && sec < 60)
@@ -21994,11 +21994,67 @@ function importance(e, today = (/* @__PURE__ */ new Date()).toISOString().split(
21994
21994
  const freq = Math.min(1, e.accessed / 5);
21995
21995
  return recency * 0.6 + freq * 0.4;
21996
21996
  }
21997
- var normalize, isExpiredLocal, IMPORTANCE_BOOST, importanceBoost, importanceRank, tokenize, estimateTokens, languageFamily, escField, unescField, parseToonLine, toToonLine, isPrivate;
21997
+ var normalize, STOPWORDS, isExpiredLocal, IMPORTANCE_BOOST, importanceBoost, importanceRank, tokenize, estimateTokens, languageFamily, escField, unescField, parseToonLine, toToonLine, isPrivate;
21998
21998
  var init_utils = __esm({
21999
21999
  "src/lib/utils.ts"() {
22000
22000
  "use strict";
22001
- normalize = (s2) => s2.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
22001
+ normalize = (s2) => s2.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
22002
+ STOPWORDS = /* @__PURE__ */ new Set([
22003
+ "a",
22004
+ "de",
22005
+ "del",
22006
+ "la",
22007
+ "el",
22008
+ "los",
22009
+ "las",
22010
+ "un",
22011
+ "una",
22012
+ "unos",
22013
+ "unas",
22014
+ "y",
22015
+ "o",
22016
+ "en",
22017
+ "al",
22018
+ "por",
22019
+ "para",
22020
+ "con",
22021
+ "sin",
22022
+ "sobre",
22023
+ "como",
22024
+ "que",
22025
+ "cual",
22026
+ "cuando",
22027
+ "donde",
22028
+ "es",
22029
+ "son",
22030
+ "fue",
22031
+ "era",
22032
+ "se",
22033
+ "su",
22034
+ "sus",
22035
+ "lo",
22036
+ "le",
22037
+ "les",
22038
+ "me",
22039
+ "te",
22040
+ "nos",
22041
+ "os",
22042
+ "mi",
22043
+ "tu",
22044
+ "the",
22045
+ "and",
22046
+ "or",
22047
+ "for",
22048
+ "with",
22049
+ "from",
22050
+ "this",
22051
+ "that",
22052
+ "into",
22053
+ "was",
22054
+ "were",
22055
+ "been",
22056
+ "being"
22057
+ ]);
22002
22058
  isExpiredLocal = (ttl, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) => {
22003
22059
  if (!ttl) return false;
22004
22060
  return ttl <= today;
@@ -22016,7 +22072,7 @@ var init_utils = __esm({
22016
22072
  if (level === "low") return 1;
22017
22073
  return 2;
22018
22074
  };
22019
- tokenize = (s2) => s2.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
22075
+ tokenize = (s2) => normalize(s2.replace(/([a-z])([A-Z])/g, "$1 $2")).split(" ").filter((t) => t.length >= 2 && !STOPWORDS.has(t));
22020
22076
  estimateTokens = (s2) => {
22021
22077
  if (!s2) return 0;
22022
22078
  const chars = Math.ceil(s2.length / 4);
@@ -22080,11 +22136,11 @@ var init_utils = __esm({
22080
22136
  }
22081
22137
  return out;
22082
22138
  };
22083
- parseToonLine = (line) => {
22139
+ parseToonLine = (line2) => {
22084
22140
  const parts = [];
22085
22141
  let cur = "";
22086
22142
  let escaped = false;
22087
- for (const c2 of line.trim()) {
22143
+ for (const c2 of line2.trim()) {
22088
22144
  if (escaped) {
22089
22145
  cur += c2;
22090
22146
  escaped = false;
@@ -22311,6 +22367,77 @@ var init_evidence = __esm({
22311
22367
  }
22312
22368
  });
22313
22369
 
22370
+ // src/lib/ngrams.ts
22371
+ function fnv1a32(s2) {
22372
+ let h3 = 2166136261;
22373
+ for (let i = 0; i < s2.length; i++) {
22374
+ h3 ^= s2.charCodeAt(i);
22375
+ h3 = h3 * 16777619 >>> 0;
22376
+ }
22377
+ return h3 >>> 0;
22378
+ }
22379
+ function ngramHashes(text, n = 3) {
22380
+ const out = /* @__PURE__ */ new Set();
22381
+ const tokens = text.split(/\s+/);
22382
+ for (const token of tokens) {
22383
+ if (!token) continue;
22384
+ const padded = "^" + token + "$";
22385
+ for (let i = 0; i + n <= padded.length; i++) {
22386
+ out.add(fnv1a32(padded.slice(i, i + n)));
22387
+ }
22388
+ }
22389
+ return out;
22390
+ }
22391
+ function ngramCosine(a, b2) {
22392
+ if (a.size === 0 || b2.size === 0) return 0;
22393
+ let inter = 0;
22394
+ const [small, large] = a.size <= b2.size ? [a, b2] : [b2, a];
22395
+ for (const h3 of small) if (large.has(h3)) inter++;
22396
+ return inter / Math.sqrt(a.size * b2.size);
22397
+ }
22398
+ function ngramScores(entries, query) {
22399
+ const qHashes = ngramHashes(query);
22400
+ const out = /* @__PURE__ */ new Map();
22401
+ for (const e of entries) {
22402
+ const text = `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")} ${e.path_scope || ""}`;
22403
+ out.set(e.key, ngramCosine(qHashes, ngramHashes(text)));
22404
+ }
22405
+ return out;
22406
+ }
22407
+ var init_ngrams = __esm({
22408
+ "src/lib/ngrams.ts"() {
22409
+ "use strict";
22410
+ }
22411
+ });
22412
+
22413
+ // src/lib/activation.ts
22414
+ function activationScores(edges, seeds, depth = 1) {
22415
+ const out = /* @__PURE__ */ new Map();
22416
+ let frontier = [...new Set(seeds)];
22417
+ for (let d2 = 0; d2 < Math.max(0, depth); d2++) {
22418
+ const next = [];
22419
+ for (const node of frontier) {
22420
+ for (const edge of edges) {
22421
+ let other = "";
22422
+ if (edge.from === node) other = edge.to;
22423
+ else if (edge.to === node) other = edge.from;
22424
+ if (!other || other === node || seeds.includes(other)) continue;
22425
+ const kind = edge.type === "supports" || edge.type === "used_in" ? 1 : edge.type === "contradicts" ? 0.6 : 0.8;
22426
+ const gain = edge.weight * kind * Math.pow(0.5, d2);
22427
+ out.set(other, (out.get(other) || 0) + gain);
22428
+ next.push(other);
22429
+ }
22430
+ }
22431
+ frontier = [...new Set(next)];
22432
+ }
22433
+ return out;
22434
+ }
22435
+ var init_activation = __esm({
22436
+ "src/lib/activation.ts"() {
22437
+ "use strict";
22438
+ }
22439
+ });
22440
+
22314
22441
  // src/lib/graph.ts
22315
22442
  function parseLinkToken(token) {
22316
22443
  const idx = token.lastIndexOf(":");
@@ -22330,8 +22457,8 @@ function typedLinks(links) {
22330
22457
  }
22331
22458
  function parseEntries(data) {
22332
22459
  const out = [];
22333
- for (const line of entryLines(data)) {
22334
- const parts = parseToonLine(line);
22460
+ for (const line2 of entryLines(data)) {
22461
+ const parts = parseToonLine(line2);
22335
22462
  if (parts.length < 3) continue;
22336
22463
  const [id2, category, key, content, file2, tags, date5, ttl, accessedRaw, linksRaw] = parts;
22337
22464
  out.push({
@@ -22528,6 +22655,18 @@ function centrality(adjacency) {
22528
22655
  for (const [k3, d2] of deg) out.set(k3, d2 / maxDeg);
22529
22656
  return out;
22530
22657
  }
22658
+ function localCentrality(adjacency, keys) {
22659
+ let maxDeg = 1;
22660
+ const deg = /* @__PURE__ */ new Map();
22661
+ for (const k3 of keys) {
22662
+ const d2 = (adjacency.get(k3) || []).length;
22663
+ deg.set(k3, d2);
22664
+ if (d2 > maxDeg) maxDeg = d2;
22665
+ }
22666
+ const out = /* @__PURE__ */ new Map();
22667
+ for (const [k3, d2] of deg) out.set(k3, d2 / maxDeg);
22668
+ return out;
22669
+ }
22531
22670
  function buildReason(e, bm25Score, bm25Max, impScore, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
22532
22671
  const parts = [];
22533
22672
  if (bm25Max > 0) {
@@ -22547,6 +22686,23 @@ function buildReason(e, bm25Score, bm25Max, impScore, today = (/* @__PURE__ */ n
22547
22686
  if (e.evidence) parts.push(`evidence ${e.evidence}`);
22548
22687
  return parts.join(" \xB7 ");
22549
22688
  }
22689
+ function entryQuality(e, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
22690
+ let q2 = Math.min(0.3, e.tags.length * 0.1) + Math.min(0.2, e.links.length * 0.1);
22691
+ const len = e.content.length;
22692
+ if (len > 20) q2 += 0.1;
22693
+ if (len > 60) q2 += 0.1;
22694
+ if (len > 150) q2 += 0.1;
22695
+ q2 += importance(e, today) * 0.1;
22696
+ q2 += Math.min(0.15, e.accessed * 0.03);
22697
+ if (e.origin === "human") q2 += 0.1;
22698
+ else if (e.origin === "inferred") q2 -= 0.05;
22699
+ q2 += evidenceBoost(e.evidence);
22700
+ if (e.date) {
22701
+ const age = (Date.parse(`${today}T00:00:00`) - Date.parse(`${e.date}T00:00:00`)) / 864e5;
22702
+ if (age > 30) q2 -= Math.min(0.2, (age - 30) / 90 * 0.2);
22703
+ }
22704
+ return Math.max(0, Math.min(1, Number(q2.toFixed(3))));
22705
+ }
22550
22706
  function graphRecallDetailed(data, query, opts = {}) {
22551
22707
  const entries = parseEntries(data);
22552
22708
  const { adjacency, byKey } = buildGraph(entries);
@@ -22559,6 +22715,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22559
22715
  const expandedTokens = expandSynonyms(qTokens);
22560
22716
  const bm25 = bm25Scores(entries, query);
22561
22717
  const cent = centrality(adjacency);
22718
+ const ngram = ngramScores(entries, query);
22562
22719
  const seedKeys = /* @__PURE__ */ new Set();
22563
22720
  const asOf = opts.asOf || "";
22564
22721
  for (const e of entries) {
@@ -22578,7 +22735,8 @@ function graphRecallDetailed(data, query, opts = {}) {
22578
22735
  const docTokens = text.split(" ");
22579
22736
  const exactMatch = expandedTokens.some((t) => text.includes(t));
22580
22737
  const fuzzy = !exactMatch && fuzzyMatch(qTokens, docTokens);
22581
- if (qTokens.length > 0 && !exactMatch && !fuzzy) continue;
22738
+ const ngMatch = !exactMatch && !fuzzy && (ngram.get(e.key) || 0) >= NGRAM_SEED_MIN;
22739
+ if (qTokens.length > 0 && !exactMatch && !fuzzy && !ngMatch) continue;
22582
22740
  seedKeys.add(e.key);
22583
22741
  }
22584
22742
  let selected;
@@ -22597,8 +22755,8 @@ function graphRecallDetailed(data, query, opts = {}) {
22597
22755
  const ia2 = importanceRank(a.importance);
22598
22756
  const ib2 = importanceRank(b2.importance);
22599
22757
  if (ia2 !== ib2) return ib2 - ia2;
22600
- return importance(b2, opts.today) - importance(a, opts.today);
22601
- }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) + importanceBoost(e.importance) }))
22758
+ return importance(b2, opts.today) + entryQuality(b2, opts.today) * 0.25 - (importance(a, opts.today) + entryQuality(a, opts.today) * 0.25);
22759
+ }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) + entryQuality(e, opts.today) * 0.25 + importanceBoost(e.importance) }))
22602
22760
  );
22603
22761
  } else {
22604
22762
  const best = /* @__PURE__ */ new Map();
@@ -22614,29 +22772,41 @@ function graphRecallDetailed(data, query, opts = {}) {
22614
22772
  queue.push({ key: nb2, dist: dist + 1 });
22615
22773
  }
22616
22774
  }
22617
- const sub = (m3) => new Map([...m3].filter(([k3]) => isVisible.has(k3)));
22775
+ const cand = new Set(best.keys());
22776
+ const sub = (m3) => new Map([...m3].filter(([k3]) => cand.has(k3)));
22777
+ const localCent = localCentrality(adjacency, cand);
22618
22778
  const bm25Rank = rankBy(sub(bm25));
22619
- const centRank = rankBy(sub(cent));
22620
- const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null;
22779
+ const ngRank = rankBy(sub(ngram));
22780
+ const centRank = rankBy(sub(localCent));
22781
+ const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, ngRank, centRank], rrfK(bm25Rank.size)) : null;
22782
+ const base = [...best.keys()].map((k3) => {
22783
+ const e = byKey.get(k3);
22784
+ const dist = best.get(k3);
22785
+ const decay = Math.pow(DECAY, dist);
22786
+ let s2 = fused ? fused.get(k3) || 0 : (bm25.get(k3) || 0) + W_CENT * (cent.get(k3) || 0) + W_IMP * importance(e, opts.today);
22787
+ if (!fused && seedKeys.has(k3)) s2 += SEED_BONUS;
22788
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22789
+ const entryFile = e.file.split(":")[0];
22790
+ if (opts.sessionFiles.some((f3) => f3 === entryFile)) {
22791
+ s2 *= 1.15;
22792
+ }
22793
+ }
22794
+ if (e.category === "warning") s2 += 0.2;
22795
+ s2 += importanceBoost(e.importance);
22796
+ s2 += evidenceBoost(e.evidence);
22797
+ s2 += entryQuality(e, opts.today) * 0.08;
22798
+ if (opts.utility) s2 += (opts.utility.get(k3) || 0) * 0.25;
22799
+ if (opts.dense) s2 += (opts.dense.get(k3) || 0) * (opts.denseWeight ?? 0.25);
22800
+ s2 *= decay;
22801
+ return { e, s: s2, priority: e.priority };
22802
+ });
22803
+ if (opts.activation && opts.edges && base.length > 0) {
22804
+ const seeds = [...base].sort((a, b2) => b2.s - a.s).slice(0, 5).map((x) => x.e.key);
22805
+ const activated = activationScores(opts.edges, seeds, opts.activationDepth ?? 1);
22806
+ for (const x of base) x.s += (activated.get(x.e.key) || 0) * 0.1;
22807
+ }
22621
22808
  scored.push(
22622
- ...[...best.keys()].map((k3) => {
22623
- const e = byKey.get(k3);
22624
- const dist = best.get(k3);
22625
- const decay = Math.pow(DECAY, dist);
22626
- let s2 = fused ? fused.get(k3) || 0 : (bm25.get(k3) || 0) + W_CENT * (cent.get(k3) || 0) + W_IMP * importance(e, opts.today);
22627
- if (!fused && seedKeys.has(k3)) s2 += SEED_BONUS;
22628
- if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22629
- const entryFile = e.file.split(":")[0];
22630
- if (opts.sessionFiles.some((f3) => f3 === entryFile)) {
22631
- s2 *= 1.15;
22632
- }
22633
- }
22634
- if (e.category === "warning") s2 += 0.2;
22635
- s2 += importanceBoost(e.importance);
22636
- s2 += evidenceBoost(e.evidence);
22637
- s2 *= decay;
22638
- return { e, s: s2, priority: e.priority };
22639
- }).sort((a, b2) => {
22809
+ ...base.sort((a, b2) => {
22640
22810
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22641
22811
  return b2.s - a.s;
22642
22812
  }).slice(0, opts.limit ?? 6)
@@ -22780,7 +22950,7 @@ function renderIndex(entries, opts = {}) {
22780
22950
  }
22781
22951
  return lines.join("\n");
22782
22952
  }
22783
- var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
22953
+ var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY, NGRAM_SEED_MIN;
22784
22954
  var init_graph = __esm({
22785
22955
  "src/lib/graph.ts"() {
22786
22956
  "use strict";
@@ -22788,6 +22958,8 @@ var init_graph = __esm({
22788
22958
  init_synonyms();
22789
22959
  init_fuzzy();
22790
22960
  init_evidence();
22961
+ init_ngrams();
22962
+ init_activation();
22791
22963
  DEFAULT_EDGE_TYPE = "related";
22792
22964
  entryLines = (data) => data.split("\n").filter(
22793
22965
  (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
@@ -22796,6 +22968,7 @@ var init_graph = __esm({
22796
22968
  W_IMP = 0.25;
22797
22969
  SEED_BONUS = 1;
22798
22970
  DECAY = 0.5;
22971
+ NGRAM_SEED_MIN = 0.45;
22799
22972
  }
22800
22973
  });
22801
22974
 
@@ -22910,6 +23083,7 @@ function generateSmartRecall(data, intent, opts = {}) {
22910
23083
  const { adjacency } = buildGraph(entries);
22911
23084
  const bm25 = bm25Scores(entries, intent);
22912
23085
  const cent = centrality(adjacency);
23086
+ const ngram = ngramScores(entries, intent);
22913
23087
  const limit = opts.limit ?? 8;
22914
23088
  const category = opts.category || "";
22915
23089
  const mtimes = opts.fileMtimes;
@@ -22921,9 +23095,13 @@ function generateSmartRecall(data, intent, opts = {}) {
22921
23095
  if (e.status === "obsolete" || e.status === "draft") return false;
22922
23096
  return true;
22923
23097
  });
22924
- const bm25Rank = rankBy(new Map([...bm25].filter(([k3]) => eligible.some((e) => e.key === k3))));
22925
- const centRank = rankBy(new Map([...cent].filter(([k3]) => eligible.some((e) => e.key === k3))));
22926
- const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null;
23098
+ const eligibleKeys = new Set(eligible.map((e) => e.key));
23099
+ const sub = (m3) => new Map([...m3].filter(([k3]) => eligibleKeys.has(k3)));
23100
+ const localCent = localCentrality(adjacency, eligibleKeys);
23101
+ const bm25Rank = rankBy(sub(bm25));
23102
+ const ngRank = rankBy(sub(ngram));
23103
+ const centRank = rankBy(sub(localCent));
23104
+ const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, ngRank, centRank], rrfK(bm25Rank.size)) : null;
22927
23105
  const scored = eligible.map((e) => {
22928
23106
  const text = normalize(
22929
23107
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
@@ -22931,7 +23109,8 @@ function generateSmartRecall(data, intent, opts = {}) {
22931
23109
  const docTokens = text.split(" ");
22932
23110
  const exactMatch = qTokens.length === 0 || expandedTokens.some((t) => text.includes(t));
22933
23111
  const fuzzy = !exactMatch && qTokens.length > 0 && fuzzyMatch(qTokens, docTokens);
22934
- const matchesQuery = exactMatch || fuzzy;
23112
+ const ngMatch = !exactMatch && !fuzzy && (ngram.get(e.key) || 0) >= NGRAM_SEED_MIN;
23113
+ const matchesQuery = exactMatch || fuzzy || ngMatch;
22935
23114
  const bm25Score = bm25.get(e.key) || 0;
22936
23115
  const centScore = cent.get(e.key) || 0;
22937
23116
  const impScore = importance(e, opts.today);
@@ -22959,11 +23138,14 @@ function generateSmartRecall(data, intent, opts = {}) {
22959
23138
  const warningBoost = e.category === "warning" ? 0.2 : 0;
22960
23139
  const impBoost = importanceBoost(e.importance);
22961
23140
  const evBoost = evidenceBoost(e.evidence);
23141
+ const ngScore = ngram.get(e.key) || 0;
23142
+ const ngBoost = ngMatch ? ngScore * 0.15 : 0;
22962
23143
  let combined;
23144
+ const utilityBoost = (opts.utility?.get(e.key) || 0) * 0.25;
22963
23145
  if (opts.rrf) {
22964
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost;
23146
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + ngBoost + utilityBoost;
22965
23147
  } else {
22966
- combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost;
23148
+ combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + utilityBoost;
22967
23149
  }
22968
23150
  return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score };
22969
23151
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
@@ -23058,6 +23240,7 @@ var init_quality = __esm({
23058
23240
  init_synonyms();
23059
23241
  init_fuzzy();
23060
23242
  init_evidence();
23243
+ init_ngrams();
23061
23244
  }
23062
23245
  });
23063
23246
 
@@ -23077,7 +23260,7 @@ __export(sessions_exports, {
23077
23260
  resolveSessionId: () => resolveSessionId
23078
23261
  });
23079
23262
  import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync4, readdirSync, unlinkSync as unlinkSync2, statSync as statSync2 } from "fs";
23080
- import { join as join2 } from "path";
23263
+ import { join as join3 } from "path";
23081
23264
  function isAlive2(pid) {
23082
23265
  if (!pid || pid <= 0) return false;
23083
23266
  try {
@@ -23088,10 +23271,10 @@ function isAlive2(pid) {
23088
23271
  }
23089
23272
  }
23090
23273
  function sessionDir() {
23091
- return join2(process.cwd(), ".toon-memory", "memory", "sessions");
23274
+ return join3(process.cwd(), ".toon-memory", "memory", "sessions");
23092
23275
  }
23093
23276
  function sessionPath(id2) {
23094
- return join2(sessionDir(), `${id2}.json`);
23277
+ return join3(sessionDir(), `${id2}.json`);
23095
23278
  }
23096
23279
  function ensureSessionDir() {
23097
23280
  const dir = sessionDir();
@@ -23110,15 +23293,15 @@ function currentBranch() {
23110
23293
  return process.env.TOON_MEMORY_BRANCH.trim();
23111
23294
  }
23112
23295
  try {
23113
- let gitDir2 = join2(process.cwd(), ".git");
23296
+ let gitDir2 = join3(process.cwd(), ".git");
23114
23297
  if (existsSync7(gitDir2) && !statSync2(gitDir2).isDirectory()) {
23115
23298
  const pointer = readFileSync5(gitDir2, "utf-8").trim();
23116
23299
  if (pointer.startsWith("gitdir:")) {
23117
23300
  const target = pointer.slice(7).trim();
23118
- gitDir2 = target.startsWith("/") ? target : join2(process.cwd(), target);
23301
+ gitDir2 = target.startsWith("/") ? target : join3(process.cwd(), target);
23119
23302
  }
23120
23303
  }
23121
- const headPath = join2(gitDir2, "HEAD");
23304
+ const headPath = join3(gitDir2, "HEAD");
23122
23305
  if (!existsSync7(headPath)) return "unknown";
23123
23306
  const head = readFileSync5(headPath, "utf-8").trim();
23124
23307
  if (head.startsWith("ref:")) {
@@ -23171,7 +23354,7 @@ function listSessions() {
23171
23354
  if (!existsSync7(dir)) return [];
23172
23355
  return readdirSync(dir).filter((f3) => f3.endsWith(".json")).map((f3) => {
23173
23356
  try {
23174
- return JSON.parse(readFileSync5(join2(dir, f3), "utf-8"));
23357
+ return JSON.parse(readFileSync5(join3(dir, f3), "utf-8"));
23175
23358
  } catch {
23176
23359
  return null;
23177
23360
  }
@@ -23186,7 +23369,7 @@ function pruneSessions() {
23186
23369
  const dir = sessionDir();
23187
23370
  if (!existsSync7(dir)) return pruned;
23188
23371
  for (const f3 of readdirSync(dir).filter((x) => x.endsWith(".json"))) {
23189
- const p2 = join2(dir, f3);
23372
+ const p2 = join3(dir, f3);
23190
23373
  let rec = null;
23191
23374
  try {
23192
23375
  rec = JSON.parse(readFileSync5(p2, "utf-8"));
@@ -32750,16 +32933,16 @@ var ReadBuffer = class {
32750
32933
  if (index === -1) {
32751
32934
  return null;
32752
32935
  }
32753
- const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
32936
+ const line2 = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
32754
32937
  this._buffer = this._buffer.subarray(index + 1);
32755
- return deserializeMessage(line);
32938
+ return deserializeMessage(line2);
32756
32939
  }
32757
32940
  clear() {
32758
32941
  this._buffer = void 0;
32759
32942
  }
32760
32943
  };
32761
- function deserializeMessage(line) {
32762
- return JSONRPCMessageSchema.parse(JSON.parse(line));
32944
+ function deserializeMessage(line2) {
32945
+ return JSONRPCMessageSchema.parse(JSON.parse(line2));
32763
32946
  }
32764
32947
  function serializeMessage(message) {
32765
32948
  return JSON.stringify(message) + "\n";
@@ -32928,8 +33111,8 @@ function N3(Z, $2, J2, X2, V2) {
32928
33111
  }
32929
33112
 
32930
33113
  // src/mcp/tools.ts
32931
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync5, existsSync as existsSync12, copyFileSync, mkdirSync as mkdirSync3, readdirSync as readdirSync5 } from "fs";
32932
- import { join as join7, basename, dirname } from "path";
33114
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync6, existsSync as existsSync15, copyFileSync, mkdirSync as mkdirSync6, readdirSync as readdirSync5 } from "fs";
33115
+ import { join as join8, basename as basename3, dirname as dirname4 } from "path";
32933
33116
 
32934
33117
  // src/lib/lock.ts
32935
33118
  import { openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, renameSync } from "fs";
@@ -33033,6 +33216,9 @@ var MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory");
33033
33216
  var MEMORY_FILE = join(MEMORY_DIR, "data.toon");
33034
33217
  var ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon");
33035
33218
  var OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon");
33219
+ var FEEDBACK_FILE = join(MEMORY_DIR, "feedback.toon");
33220
+ var EDGES_FILE = join(MEMORY_DIR, "edges.toon");
33221
+ var VECTORS_FILE = join(MEMORY_DIR, "vectors.bin");
33036
33222
  var SECRETS_FILE = join(MEMORY_DIR, "secrets.toon");
33037
33223
  var GLOBAL_FILE = process.env.TOON_MEMORY_GLOBAL_FILE || join(homedir(), ".toon-memory", "memory", "global.toon");
33038
33224
  var CONFIG_FILE = join(MEMORY_DIR, "config.json");
@@ -33198,21 +33384,35 @@ function inferTags(content, key, vocab) {
33198
33384
  }
33199
33385
  function parseRelativeDate(since) {
33200
33386
  const trimmed = since.trim();
33387
+ const iso = (d2) => d2.toISOString().split("T")[0];
33388
+ const shiftDays = (days) => {
33389
+ const d2 = /* @__PURE__ */ new Date();
33390
+ d2.setDate(d2.getDate() - days);
33391
+ return iso(d2);
33392
+ };
33201
33393
  const hourMatch = trimmed.match(/^(\d+)h$/);
33202
33394
  if (hourMatch) {
33203
33395
  const d2 = /* @__PURE__ */ new Date();
33204
33396
  d2.setHours(d2.getHours() - parseInt(hourMatch[1]));
33205
- return d2.toISOString().split("T")[0];
33397
+ return iso(d2);
33206
33398
  }
33207
33399
  const dayMatch = trimmed.match(/^(\d+)d$/);
33208
- if (dayMatch) {
33209
- const d2 = /* @__PURE__ */ new Date();
33210
- d2.setDate(d2.getDate() - parseInt(dayMatch[1]));
33211
- return d2.toISOString().split("T")[0];
33212
- }
33400
+ if (dayMatch) return shiftDays(parseInt(dayMatch[1]));
33213
33401
  if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
33214
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
33215
- return today;
33402
+ const key = trimmed.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, " ").trim();
33403
+ if (key === "hoy" || key === "today") return iso(/* @__PURE__ */ new Date());
33404
+ if (key === "ayer" || key === "yesterday") return shiftDays(1);
33405
+ if (/^(la |el )?semana pasada$/.test(key) || key === "last week") return shiftDays(7);
33406
+ if (/^(la |el )?mes pasada?$/.test(key) || key === "last month") return shiftDays(30);
33407
+ const natural = key.match(/^(?:hace|last|ultimos?|past)\s+(\d+)\s*(dia|dias|day|days|semana|semanas|week|weeks|mes|meses|month|months)\b/);
33408
+ if (natural) {
33409
+ const n = parseInt(natural[1]);
33410
+ const unit = natural[2];
33411
+ if (/^(dia|dias|day|days)$/.test(unit)) return shiftDays(n);
33412
+ if (/^(semana|semanas|week|weeks)$/.test(unit)) return shiftDays(n * 7);
33413
+ return shiftDays(n * 30);
33414
+ }
33415
+ return iso(/* @__PURE__ */ new Date());
33216
33416
  }
33217
33417
 
33218
33418
  // src/mcp/scoring.ts
@@ -33220,8 +33420,8 @@ init_utils();
33220
33420
  function entryScore(dateStr, accessed) {
33221
33421
  return importance({ date: dateStr, accessed });
33222
33422
  }
33223
- function entryScoreForLine(line) {
33224
- const parts = parseToonLine(line);
33423
+ function entryScoreForLine(line2) {
33424
+ const parts = parseToonLine(line2);
33225
33425
  const date5 = parts[6] || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
33226
33426
  const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0;
33227
33427
  return entryScore(date5, accessed);
@@ -33230,8 +33430,8 @@ function findRelatedEntries(text, excludeKey = "", limit = 3) {
33230
33430
  const data = readMemory();
33231
33431
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
33232
33432
  const queryTokens = normalize(text).split(" ").filter(Boolean);
33233
- const scored = lines.map((line) => {
33234
- const trimmed = line.trim();
33433
+ const scored = lines.map((line2) => {
33434
+ const trimmed = line2.trim();
33235
33435
  const parts = parseToonLine(trimmed);
33236
33436
  if (parts.length < 7) return null;
33237
33437
  const [id2, cat, key, content, file2, tags, date5] = parts;
@@ -33255,10 +33455,10 @@ function bumpAccessed(ids) {
33255
33455
  if (headerIdx === -1) return;
33256
33456
  const now = (/* @__PURE__ */ new Date()).toISOString();
33257
33457
  for (let i = headerIdx + 1; i < lines.length; i++) {
33258
- const line = lines[i];
33259
- if (!line.startsWith(" ") || !line.includes("|")) continue;
33260
- if (line.startsWith(" summaries:")) break;
33261
- const parts = parseToonLine(line);
33458
+ const line2 = lines[i];
33459
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
33460
+ if (line2.startsWith(" summaries:")) break;
33461
+ const parts = parseToonLine(line2);
33262
33462
  if (idSet.has(parts[0])) {
33263
33463
  const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1;
33264
33464
  parts[8] = String(accessed);
@@ -33270,15 +33470,90 @@ function bumpAccessed(ids) {
33270
33470
  writeMemory(lines.join("\n"));
33271
33471
  }
33272
33472
 
33273
- // src/mcp/observations.ts
33274
- import { readFileSync as readFileSync3, existsSync as existsSync3, writeFileSync as writeFileSync3 } from "fs";
33473
+ // src/mcp/session-store.ts
33474
+ import { readFileSync as readFileSync3, existsSync as existsSync3 } from "fs";
33475
+ import { join as join2 } from "path";
33275
33476
  init_utils();
33276
- function readObservations() {
33277
- if (!existsSync3(OBSERVATIONS_FILE)) return [];
33278
- return readFileSync3(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
33477
+ function readSessionEntries(sessionId) {
33478
+ const filePath = getSessionFile();
33479
+ if (!existsSync3(filePath)) return [];
33480
+ const entries = readFileSync3(filePath, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
33279
33481
  const p2 = parseToonLine(l);
33280
- return { ts: p2[0] || "", session: p2[1] || "", agent: p2[2] || "", branch: p2[3] || "", tool: p2[4] || "", file: p2[6] || "", summary: p2[7] || "" };
33482
+ return {
33483
+ ts: p2[0] || "",
33484
+ session: p2[1] || "",
33485
+ agent: p2[2] || "",
33486
+ branch: p2[3] || "",
33487
+ tool: p2[4] || "",
33488
+ file: p2[6] || "",
33489
+ summary: p2[7] || "",
33490
+ accessed: p2.length > 8 ? parseInt(p2[8]) || 0 : 0,
33491
+ lastAccessed: p2.length > 9 ? p2[9] || "" : ""
33492
+ };
33281
33493
  });
33494
+ if (sessionId) {
33495
+ return entries.filter((e) => e.session === sessionId);
33496
+ }
33497
+ return entries;
33498
+ }
33499
+ function getSessionFile() {
33500
+ const sessionFile = join2(MEMORY_DIR, "session.toon");
33501
+ if (existsSync3(sessionFile)) return sessionFile;
33502
+ if (existsSync3(OBSERVATIONS_FILE)) {
33503
+ migrateObservationsToSession();
33504
+ return sessionFile;
33505
+ }
33506
+ return sessionFile;
33507
+ }
33508
+ function migrateObservationsToSession() {
33509
+ const data = readFileSync3(OBSERVATIONS_FILE, "utf-8");
33510
+ const lines = data.split("\n");
33511
+ const headerIdx = lines.findIndex((l) => l.startsWith("observations["));
33512
+ if (headerIdx === -1) return;
33513
+ const newLines = [`session[0|]{ts|session|agent|branch|tool||file|summary|accessed|lastAccessed}:`];
33514
+ for (const line2 of lines.slice(headerIdx + 1)) {
33515
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
33516
+ const parts = parseToonLine(line2);
33517
+ while (parts.length < 8) parts.push("");
33518
+ parts.push("0", "");
33519
+ newLines.push(toToonLine(parts));
33520
+ }
33521
+ const sessionFile = join2(MEMORY_DIR, "session.toon");
33522
+ atomicWrite(sessionFile, newLines.join("\n"));
33523
+ }
33524
+ var readObservations = readSessionEntries;
33525
+
33526
+ // src/mcp/args.ts
33527
+ var toNumber = (v3) => {
33528
+ if (typeof v3 === "string" && v3.trim() !== "" && Number.isFinite(Number(v3))) return Number(v3);
33529
+ return v3;
33530
+ };
33531
+ function positiveInt(fallback, max = 500) {
33532
+ return external_exports.preprocess(toNumber, external_exports.number().int().min(1).max(max).optional().default(fallback));
33533
+ }
33534
+ function optionalPositiveInt(max = 500) {
33535
+ return external_exports.preprocess(toNumber, external_exports.number().int().min(1).max(max).optional());
33536
+ }
33537
+ function requiredText(label, max = 4e3) {
33538
+ return external_exports.string().trim().min(1, `${label} must not be empty`).max(max);
33539
+ }
33540
+ function splitIds(value) {
33541
+ if (!value) return [];
33542
+ let raw = value;
33543
+ if (value.trim().startsWith("[")) {
33544
+ try {
33545
+ const parsed = JSON.parse(value);
33546
+ if (Array.isArray(parsed)) raw = parsed.map(String).join(" ");
33547
+ } catch {
33548
+ }
33549
+ }
33550
+ return raw.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean);
33551
+ }
33552
+ function noMatches(query) {
33553
+ return {
33554
+ content: [{ type: "text", text: `No matching memories for "${query}". Try a shorter query, or save one first with memory_remember. A transient empty result is not an error.` }],
33555
+ structuredContent: { found: false, count: 0 }
33556
+ };
33282
33557
  }
33283
33558
 
33284
33559
  // src/mcp/archive.ts
@@ -33287,8 +33562,8 @@ init_utils();
33287
33562
  function findHeaderIdx(lines) {
33288
33563
  return lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
33289
33564
  }
33290
- function bumpHeaderCount(line, count) {
33291
- return line.replace(/^([a-z]+)?\[(\d+)\|/, (_m2, pre) => `${pre || ""}[${count}|`);
33565
+ function bumpHeaderCount(line2, count) {
33566
+ return line2.replace(/^([a-z]+)?\[(\d+)\|/, (_m2, pre) => `${pre || ""}[${count}|`);
33292
33567
  }
33293
33568
  function archiveOldEntries(opts = {}) {
33294
33569
  const data = readMemory();
@@ -33301,8 +33576,8 @@ function archiveOldEntries(opts = {}) {
33301
33576
  const cutoffStr = cutoff.toISOString().split("T")[0];
33302
33577
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
33303
33578
  const toArchive = /* @__PURE__ */ new Set();
33304
- entryLines2.forEach((line, idx) => {
33305
- const parts = parseToonLine(line);
33579
+ entryLines2.forEach((line2, idx) => {
33580
+ const parts = parseToonLine(line2);
33306
33581
  if (parts.length < 7) return;
33307
33582
  const date5 = parts[6];
33308
33583
  const ttl = parts[7] || "";
@@ -33313,7 +33588,7 @@ function archiveOldEntries(opts = {}) {
33313
33588
  const maxEntries = getMaxEntries();
33314
33589
  if (remaining > maxEntries) {
33315
33590
  const need = remaining - maxEntries;
33316
- const candidates = entryLines2.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c2) => !toArchive.has(c2.idx)).sort((a, b2) => a.score - b2.score);
33591
+ const candidates = entryLines2.map((line2, idx) => ({ idx, score: entryScoreForLine(line2) })).filter((c2) => !toArchive.has(c2.idx)).sort((a, b2) => a.score - b2.score);
33317
33592
  for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx);
33318
33593
  }
33319
33594
  }
@@ -33409,8 +33684,8 @@ function consolidateEntries() {
33409
33684
  const keyOrder = [];
33410
33685
  const mergedAway = [];
33411
33686
  for (let i = 0; i < entryLines2.length; i++) {
33412
- const line = entryLines2[i].trim();
33413
- const parts = parseToonLine(line);
33687
+ const line2 = entryLines2[i].trim();
33688
+ const parts = parseToonLine(line2);
33414
33689
  if (parts.length < 3) continue;
33415
33690
  const key = parts[2];
33416
33691
  const existingIdx = keyOrder.findIndex((idx) => {
@@ -33418,11 +33693,11 @@ function consolidateEntries() {
33418
33693
  return ep2[2] === key;
33419
33694
  });
33420
33695
  if (existingIdx !== -1) {
33421
- const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx]), line);
33696
+ const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx]), line2);
33422
33697
  byKey.set(keyOrder[existingIdx], mergedLine);
33423
33698
  mergedAway.push(i);
33424
33699
  } else {
33425
- byKey.set(i, line);
33700
+ byKey.set(i, line2);
33426
33701
  keyOrder.push(i);
33427
33702
  }
33428
33703
  }
@@ -33430,10 +33705,10 @@ function consolidateEntries() {
33430
33705
  const order = [];
33431
33706
  const duplicates = [];
33432
33707
  for (const idx of keyOrder) {
33433
- const line = byKey.get(idx);
33434
- const parts = parseToonLine(line);
33708
+ const line2 = byKey.get(idx);
33709
+ const parts = parseToonLine(line2);
33435
33710
  if (parts.length < 3) {
33436
- order.push(line);
33711
+ order.push(line2);
33437
33712
  continue;
33438
33713
  }
33439
33714
  const content = parts[3] || "";
@@ -33448,7 +33723,7 @@ function consolidateEntries() {
33448
33723
  if (existingParts[1] !== parts[1]) continue;
33449
33724
  const sim = contentSimilarity(content, existingParts[3] || "");
33450
33725
  if (sim >= NEAR_DUP_THRESHOLD) {
33451
- const mergedLine = mergeEntries(existing.line, line);
33726
+ const mergedLine = mergeEntries(existing.line, line2);
33452
33727
  contentSeen.set(seenNorm, { line: mergedLine, idx: existing.idx });
33453
33728
  const orderIdx = order.findIndex((l) => l === existing.line);
33454
33729
  if (orderIdx !== -1) order[orderIdx] = mergedLine;
@@ -33458,8 +33733,8 @@ function consolidateEntries() {
33458
33733
  }
33459
33734
  }
33460
33735
  if (!merged) {
33461
- contentSeen.set(normalized, { line, idx: order.length });
33462
- order.push(line);
33736
+ contentSeen.set(normalized, { line: line2, idx: order.length });
33737
+ order.push(line2);
33463
33738
  }
33464
33739
  }
33465
33740
  const totalRemoved = mergedAway.length + duplicates.length;
@@ -33487,22 +33762,22 @@ function mergeMemoryFiles(localData, incomingData) {
33487
33762
  summaries = body.filter((l) => !isEntry(l));
33488
33763
  }
33489
33764
  const merged = /* @__PURE__ */ new Map();
33490
- for (const line of localEntryLines) {
33491
- const parts = parseToonLine(line);
33492
- if (parts.length >= 3) merged.set(parts[2], line.trim());
33765
+ for (const line2 of localEntryLines) {
33766
+ const parts = parseToonLine(line2);
33767
+ if (parts.length >= 3) merged.set(parts[2], line2.trim());
33493
33768
  }
33494
33769
  let added = 0;
33495
33770
  let updated = 0;
33496
- for (const line of incomingData.split("\n").filter(isEntry)) {
33497
- const parts = parseToonLine(line);
33771
+ for (const line2 of incomingData.split("\n").filter(isEntry)) {
33772
+ const parts = parseToonLine(line2);
33498
33773
  if (parts.length < 3) continue;
33499
33774
  const key = parts[2];
33500
33775
  const existing = merged.get(key);
33501
33776
  if (existing === void 0) {
33502
- merged.set(key, line.trim());
33777
+ merged.set(key, line2.trim());
33503
33778
  added++;
33504
33779
  } else {
33505
- merged.set(key, mergeEntries(existing, line.trim()));
33780
+ merged.set(key, mergeEntries(existing, line2.trim()));
33506
33781
  updated++;
33507
33782
  }
33508
33783
  }
@@ -33530,10 +33805,10 @@ function consolidateVersions(dryRun) {
33530
33805
  if (headerIdx === -1) return { removed: 0, proposals: [], groups: [] };
33531
33806
  const candidates = [];
33532
33807
  for (let i = headerIdx + 1; i < lines.length; i++) {
33533
- const line = lines[i];
33534
- if (!line.startsWith(" ") || !line.includes("|")) continue;
33535
- if (line.startsWith(" summaries:")) break;
33536
- const parts = parseToonLine(line);
33808
+ const line2 = lines[i];
33809
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
33810
+ if (line2.startsWith(" summaries:")) break;
33811
+ const parts = parseToonLine(line2);
33537
33812
  if (parts.length < 7) continue;
33538
33813
  const [id2, category, key, content] = parts;
33539
33814
  const hit = extractVersion(`${key} ${content}`.toLowerCase());
@@ -33609,9 +33884,9 @@ function writeVault(content) {
33609
33884
  }
33610
33885
  function vaultEntries(content) {
33611
33886
  const out = [];
33612
- for (const line of content.split("\n")) {
33613
- if (!line.startsWith(" ") || !line.includes("|")) continue;
33614
- const parts = parseToonLine(line);
33887
+ for (const line2 of content.split("\n")) {
33888
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
33889
+ const parts = parseToonLine(line2);
33615
33890
  if (parts.length < 7) continue;
33616
33891
  out.push({ id: parts[0], key: parts[2], value: parts[3] || "", file: parts[4] || "", tags: parts[5] || "", date: parts[6] || "", ttl: parts[7] || "" });
33617
33892
  }
@@ -33704,40 +33979,40 @@ init_utils();
33704
33979
  init_synonyms();
33705
33980
  init_fuzzy();
33706
33981
  import { existsSync as existsSync11 } from "fs";
33707
- import { join as join6 } from "path";
33982
+ import { join as join7 } from "path";
33708
33983
  init_sessions();
33709
33984
 
33710
33985
  // src/lib/git.ts
33711
33986
  init_sessions();
33712
33987
  import { existsSync as existsSync8, readFileSync as readFileSync6, statSync as statSync3 } from "fs";
33713
- import { join as join3 } from "path";
33988
+ import { join as join4 } from "path";
33714
33989
  import { inflateSync } from "zlib";
33715
33990
  function gitDir(cwd) {
33716
- const dotgit = join3(cwd || process.cwd(), ".git");
33991
+ const dotgit = join4(cwd || process.cwd(), ".git");
33717
33992
  if (!existsSync8(dotgit)) return null;
33718
33993
  if (statSync3(dotgit).isDirectory()) return dotgit;
33719
33994
  const pointer = readFileSync6(dotgit, "utf-8").trim();
33720
33995
  if (pointer.startsWith("gitdir:")) {
33721
33996
  const target = pointer.slice(7).trim();
33722
- return target.startsWith("/") ? target : join3(process.cwd(), target);
33997
+ return target.startsWith("/") ? target : join4(process.cwd(), target);
33723
33998
  }
33724
33999
  return null;
33725
34000
  }
33726
34001
  function resolveHead(cwd) {
33727
34002
  const dir = gitDir(cwd);
33728
34003
  if (!dir) return null;
33729
- const headPath = join3(dir, "HEAD");
34004
+ const headPath = join4(dir, "HEAD");
33730
34005
  if (!existsSync8(headPath)) return null;
33731
34006
  const head = readFileSync6(headPath, "utf-8").trim();
33732
34007
  if (head.startsWith("ref:")) {
33733
- const refPath = join3(dir, head.slice(4).trim());
34008
+ const refPath = join4(dir, head.slice(4).trim());
33734
34009
  if (!existsSync8(refPath)) return null;
33735
34010
  return readFileSync6(refPath, "utf-8").trim();
33736
34011
  }
33737
34012
  return head || null;
33738
34013
  }
33739
34014
  function parseIndex(dir) {
33740
- const indexPath = join3(dir, "index");
34015
+ const indexPath = join4(dir, "index");
33741
34016
  if (!existsSync8(indexPath)) return [];
33742
34017
  const buf = readFileSync6(indexPath);
33743
34018
  if (buf.length < 12) return [];
@@ -33799,7 +34074,7 @@ function fileMtimes(cwd) {
33799
34074
  function readObject(sha, cwd) {
33800
34075
  const dir = gitDir(cwd);
33801
34076
  if (!dir) return null;
33802
- const objPath = join3(dir, "objects", sha.slice(0, 2), sha.slice(2));
34077
+ const objPath = join4(dir, "objects", sha.slice(0, 2), sha.slice(2));
33803
34078
  if (!existsSync8(objPath)) return null;
33804
34079
  try {
33805
34080
  const compressed = readFileSync6(objPath);
@@ -33831,21 +34106,21 @@ function readRecentCommits(count = 10, cwd) {
33831
34106
  let date5 = "";
33832
34107
  let parent = null;
33833
34108
  let pastHeaders = false;
33834
- for (const line of lines) {
33835
- if (line.startsWith("author ")) {
33836
- const match = line.match(/^author\s+(.+?)\s+<[^>]+>\s+(\d+)/);
34109
+ for (const line2 of lines) {
34110
+ if (line2.startsWith("author ")) {
34111
+ const match = line2.match(/^author\s+(.+?)\s+<[^>]+>\s+(\d+)/);
33837
34112
  if (match) {
33838
34113
  author = match[1];
33839
34114
  const ts2 = parseInt(match[2]);
33840
34115
  date5 = new Date(ts2 * 1e3).toISOString().split("T")[0];
33841
34116
  }
33842
- } else if (line.startsWith("parent ")) {
33843
- parent = line.slice(7).trim();
33844
- } else if (line.startsWith("tree ")) {
33845
- } else if (line.startsWith("committer ")) {
34117
+ } else if (line2.startsWith("parent ")) {
34118
+ parent = line2.slice(7).trim();
34119
+ } else if (line2.startsWith("tree ")) {
34120
+ } else if (line2.startsWith("committer ")) {
33846
34121
  pastHeaders = true;
33847
- } else if (pastHeaders && !subject && line.trim()) {
33848
- subject = line.trim();
34122
+ } else if (pastHeaders && !subject && line2.trim()) {
34123
+ subject = line2.trim();
33849
34124
  }
33850
34125
  }
33851
34126
  commits.push({
@@ -33864,13 +34139,13 @@ function gitStatusSummary(cwd) {
33864
34139
  const head = resolveHead(cwd);
33865
34140
  const trackedFiles = readGitIndex(cwd).length;
33866
34141
  const recentCommits = readRecentCommits(5, cwd);
33867
- const hasGitignore = existsSync8(join3(cwd || process.cwd(), ".gitignore"));
34142
+ const hasGitignore = existsSync8(join4(cwd || process.cwd(), ".gitignore"));
33868
34143
  return { branch, head, trackedFiles, recentCommits, hasGitignore };
33869
34144
  }
33870
34145
 
33871
34146
  // src/lib/project-scan.ts
33872
34147
  import { existsSync as existsSync9, readFileSync as readFileSync7, readdirSync as readdirSync3, statSync as statSync4 } from "fs";
33873
- import { join as join4, extname } from "path";
34148
+ import { join as join5, extname } from "path";
33874
34149
  var SKIP_DIRS = /* @__PURE__ */ new Set([
33875
34150
  "node_modules",
33876
34151
  ".git",
@@ -33901,7 +34176,7 @@ function scanProjectStructure(root, maxDepth = 2) {
33901
34176
  }
33902
34177
  for (const entry of entries) {
33903
34178
  if (entry.startsWith(".") && depth === 0 && entry !== ".env.example" && entry !== ".env.template") continue;
33904
- const fullPath = join4(dir, entry);
34179
+ const fullPath = join5(dir, entry);
33905
34180
  let isDir;
33906
34181
  try {
33907
34182
  isDir = statSync4(fullPath).isDirectory();
@@ -33926,7 +34201,7 @@ function scanProjectStructure(root, maxDepth = 2) {
33926
34201
  function readEnvExample(root) {
33927
34202
  const candidates = [".env.example", ".env.template", ".env.sample"];
33928
34203
  for (const name of candidates) {
33929
- const p2 = join4(root, name);
34204
+ const p2 = join5(root, name);
33930
34205
  if (existsSync9(p2)) {
33931
34206
  try {
33932
34207
  const content = readFileSync7(p2, "utf-8");
@@ -33941,12 +34216,12 @@ function readEnvExample(root) {
33941
34216
  function parseEnvContent(content) {
33942
34217
  const vars = [];
33943
34218
  for (const raw of content.split("\n")) {
33944
- const line = raw.trim();
33945
- if (!line || line.startsWith("#")) continue;
33946
- const eqIdx = line.indexOf("=");
34219
+ const line2 = raw.trim();
34220
+ if (!line2 || line2.startsWith("#")) continue;
34221
+ const eqIdx = line2.indexOf("=");
33947
34222
  if (eqIdx < 0) continue;
33948
- const name = line.slice(0, eqIdx).trim();
33949
- const rest = line.slice(eqIdx + 1);
34223
+ const name = line2.slice(0, eqIdx).trim();
34224
+ const rest = line2.slice(eqIdx + 1);
33950
34225
  const hashIdx = rest.indexOf("#");
33951
34226
  const defaultVal = (hashIdx >= 0 ? rest.slice(0, hashIdx) : rest).trim();
33952
34227
  const comment = hashIdx >= 0 ? rest.slice(hashIdx + 1).trim() : "";
@@ -33955,7 +34230,7 @@ function parseEnvContent(content) {
33955
34230
  return vars;
33956
34231
  }
33957
34232
  function readManifest(root) {
33958
- const pkgPath = join4(root, "package.json");
34233
+ const pkgPath = join5(root, "package.json");
33959
34234
  if (existsSync9(pkgPath)) {
33960
34235
  try {
33961
34236
  const pkg = JSON.parse(readFileSync7(pkgPath, "utf-8"));
@@ -33971,7 +34246,7 @@ function readManifest(root) {
33971
34246
  } catch {
33972
34247
  }
33973
34248
  }
33974
- const cargoPath = join4(root, "Cargo.toml");
34249
+ const cargoPath = join5(root, "Cargo.toml");
33975
34250
  if (existsSync9(cargoPath)) {
33976
34251
  try {
33977
34252
  const txt = readFileSync7(cargoPath, "utf-8");
@@ -33991,7 +34266,7 @@ function readManifest(root) {
33991
34266
  } catch {
33992
34267
  }
33993
34268
  }
33994
- const pyPath = join4(root, "pyproject.toml");
34269
+ const pyPath = join5(root, "pyproject.toml");
33995
34270
  if (existsSync9(pyPath)) {
33996
34271
  try {
33997
34272
  const txt = readFileSync7(pyPath, "utf-8");
@@ -34009,7 +34284,7 @@ function readManifest(root) {
34009
34284
  } catch {
34010
34285
  }
34011
34286
  }
34012
- const goPath = join4(root, "go.mod");
34287
+ const goPath = join5(root, "go.mod");
34013
34288
  if (existsSync9(goPath)) {
34014
34289
  try {
34015
34290
  const txt = readFileSync7(goPath, "utf-8");
@@ -34032,7 +34307,7 @@ function readManifest(root) {
34032
34307
 
34033
34308
  // src/lib/code-search.ts
34034
34309
  import { readFileSync as readFileSync8, readdirSync as readdirSync4, statSync as statSync5 } from "fs";
34035
- import { join as join5, extname as extname2, relative } from "path";
34310
+ import { join as join6, extname as extname2, relative } from "path";
34036
34311
  var SOURCE_EXTS = /* @__PURE__ */ new Set([
34037
34312
  ".ts",
34038
34313
  ".tsx",
@@ -34083,7 +34358,7 @@ function findFilesByPattern(root, pattern) {
34083
34358
  }
34084
34359
  for (const entry of entries) {
34085
34360
  if (SKIP_DIRS2.has(entry)) continue;
34086
- const fullPath = join5(dir, entry);
34361
+ const fullPath = join6(dir, entry);
34087
34362
  let isDir;
34088
34363
  try {
34089
34364
  isDir = statSync5(fullPath).isDirectory();
@@ -34116,7 +34391,7 @@ function findCallers(root, symbol2) {
34116
34391
  for (const entry of entries) {
34117
34392
  if (results.length >= maxResults) return;
34118
34393
  if (SKIP_DIRS2.has(entry)) continue;
34119
- const fullPath = join5(dir, entry);
34394
+ const fullPath = join6(dir, entry);
34120
34395
  let isDir;
34121
34396
  try {
34122
34397
  isDir = statSync5(fullPath).isDirectory();
@@ -34449,8 +34724,8 @@ function generateContextHealth(data, root) {
34449
34724
  const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
34450
34725
  const TTL_RE = /^\d{4}(?:-\d{2}-\d{2})?$/;
34451
34726
  const malformed = [];
34452
- for (const line of entryLines(data)) {
34453
- const parts2 = parseToonLine(line);
34727
+ for (const line2 of entryLines(data)) {
34728
+ const parts2 = parseToonLine(line2);
34454
34729
  if (parts2.length < 7) {
34455
34730
  malformed.push(`too few fields (${parts2.length})`);
34456
34731
  continue;
@@ -34504,7 +34779,7 @@ function generateContextHealth(data, root) {
34504
34779
  for (const e of entries) {
34505
34780
  if (e.file) {
34506
34781
  const filePath = e.file.split(":")[0];
34507
- if (filePath && !existsSync11(join6(root, filePath))) {
34782
+ if (filePath && !existsSync11(join7(root, filePath))) {
34508
34783
  brokenFiles.push(`${e.key}: ${e.file}`);
34509
34784
  }
34510
34785
  }
@@ -34653,7 +34928,572 @@ init_sessions();
34653
34928
  init_utils();
34654
34929
  init_evidence();
34655
34930
  init_synonyms();
34931
+
34932
+ // src/lib/handoff.ts
34933
+ init_graph();
34934
+ init_utils();
34935
+ import { basename } from "path";
34936
+ function projectSlug(root) {
34937
+ return root.replace(/^[\\/]+/, "").replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase();
34938
+ }
34939
+ function entryAgeDays(date5, today) {
34940
+ if (!date5) return 0;
34941
+ const then = Date.parse(`${date5}T00:00:00`);
34942
+ const now = Date.parse(`${today}T00:00:00`);
34943
+ if (!Number.isFinite(then) || !Number.isFinite(now)) return 0;
34944
+ return Math.max(0, Math.round((now - then) / 864e5));
34945
+ }
34946
+ function claim(e, maxChars = 130) {
34947
+ const text = e.content.replace(/\s+/g, " ").trim();
34948
+ if (!text) return e.key;
34949
+ const sentence = text.match(/^[^.!?]+[.!?]?/)?.[0] || text;
34950
+ if (sentence.length <= maxChars) return sentence.trim();
34951
+ const cut = sentence.slice(0, maxChars).replace(/\s+\S*$/, "");
34952
+ return `${cut} \xB7 ver ${e.key}`;
34953
+ }
34954
+ function matches(e, task) {
34955
+ const q2 = task.toLowerCase();
34956
+ if (!q2) return false;
34957
+ const text = `${e.key} ${e.content} ${e.tags.join(" ")} ${e.file}`.toLowerCase();
34958
+ return q2.split(/\s+/).filter((t) => t.length > 3).some((t) => text.includes(t));
34959
+ }
34960
+ function buildHandoffBrief(data, root, opts = {}) {
34961
+ const today = opts.today || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
34962
+ const maxTokens = opts.maxTokens ?? 420;
34963
+ const task = opts.task || "";
34964
+ const usable = parseEntries(data).filter(
34965
+ (e) => e.status !== "obsolete" && e.status !== "draft" && !isPrivate(e) && !(e.ttl && isExpiredLocal(e.ttl, today))
34966
+ );
34967
+ const newest = usable.reduce((acc, e) => e.date > acc ? e.date : acc, "");
34968
+ const age = entryAgeDays(newest, today);
34969
+ const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh";
34970
+ const head = [
34971
+ `<memory project="${basename(root) || root}" as_of="${today}" freshness="${freshness}">`,
34972
+ `identity: mcp_project=${projectSlug(root)} | root=${root}`
34973
+ ];
34974
+ const used = /* @__PURE__ */ new Set();
34975
+ const take = (list) => {
34976
+ const out2 = [];
34977
+ for (const e of list) {
34978
+ if (used.has(e.key)) continue;
34979
+ used.add(e.key);
34980
+ out2.push(e);
34981
+ }
34982
+ return out2;
34983
+ };
34984
+ const byDate = (a, b2) => b2.date.localeCompare(a.date);
34985
+ const line2 = (section, e) => {
34986
+ const stale = entryAgeDays(e.date, today) > 30 ? ` [stale ${entryAgeDays(e.date, today)}d]` : "";
34987
+ const file2 = e.file ? ` @ ${e.file}` : "";
34988
+ return `${section} [${e.category}] ${e.key}: ${claim(e)}${file2}${stale}`;
34989
+ };
34990
+ const traps = take(
34991
+ usable.filter(
34992
+ (e) => e.category === "warning" || e.tags.some((t) => ["trap", "gotcha", "risk", "warning"].includes(t.toLowerCase()))
34993
+ ).sort(byDate).slice(0, 2)
34994
+ );
34995
+ const directives = take(
34996
+ usable.filter((e) => e.origin === "human" || e.importance === "critical").sort((a, b2) => b2.priority - a.priority || byDate(a, b2)).slice(0, 2)
34997
+ );
34998
+ const open = take(usable.filter((e) => e.category === "decision").sort(byDate).slice(0, 3));
34999
+ const recent = take(
35000
+ [...usable].sort((a, b2) => {
35001
+ const tm2 = Number(matches(b2, task)) - Number(matches(a, task));
35002
+ return tm2 || byDate(a, b2);
35003
+ }).slice(0, 3)
35004
+ );
35005
+ const files = usable.filter((e) => e.file).sort(byDate).slice(0, 3);
35006
+ const sections = [];
35007
+ const push = (title, rows) => {
35008
+ if (rows.length > 0) sections.push(`${title}
35009
+ ${rows.join("\n")}`);
35010
+ };
35011
+ push("directives:", directives.map((e) => line2("-", e)));
35012
+ push("traps:", traps.map((e) => line2("-", e)));
35013
+ push("open:", open.map((e) => line2("-", e)));
35014
+ push("recent:", recent.map((e) => line2("-", e)));
35015
+ if (files.length > 0) {
35016
+ push("files:", files.map((e) => `- ${e.file}${e.key ? ` \u2190 ${e.key}` : ""}`));
35017
+ }
35018
+ const out = [...head];
35019
+ for (const section of sections) {
35020
+ if (estimateTokens(out.join("\n") + "\n" + section) > maxTokens) break;
35021
+ out.push(section);
35022
+ }
35023
+ if (out.length === 2) out.push("(no stable memories yet)");
35024
+ out.push("</memory>");
35025
+ return out.join("\n");
35026
+ }
35027
+
35028
+ // src/lib/compiler.ts
35029
+ init_graph();
35030
+ init_utils();
35031
+ import { basename as basename2 } from "path";
35032
+ function claim2(e, maxChars = 120) {
35033
+ const text = e.content.replace(/\s+/g, " ").trim();
35034
+ if (!text) return e.key;
35035
+ const sentence = text.match(/^[^.!?]+[.!?]?/)?.[0] || text;
35036
+ if (sentence.length <= maxChars) return sentence.trim();
35037
+ return `${sentence.slice(0, maxChars).replace(/\s+\S*$/, "")} \xB7 ${e.key}`;
35038
+ }
35039
+ function line(e, today) {
35040
+ const age = entryAgeDays(e.date, today);
35041
+ const stale = age > 30 ? ` [stale ${age}d]` : "";
35042
+ const file2 = e.file ? ` @ ${e.file}` : "";
35043
+ return `- [${e.category}] ${e.key}: ${claim2(e)}${file2}${stale}`;
35044
+ }
35045
+ function compileContext(data, task, opts = {}) {
35046
+ const today = opts.today || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
35047
+ const root = opts.root || process.cwd();
35048
+ const maxTokens = opts.maxTokens ?? 900;
35049
+ const usable = parseEntries(data).filter(
35050
+ (e) => e.status !== "obsolete" && e.status !== "draft" && !isPrivate(e) && !(e.ttl && isExpiredLocal(e.ttl, today))
35051
+ );
35052
+ const newest = usable.reduce((acc, e) => e.date > acc ? e.date : acc, "");
35053
+ const age = entryAgeDays(newest, today);
35054
+ const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh";
35055
+ const graphRanked = graphRecallDetailed(data, task, {
35056
+ limit: 12,
35057
+ utility: opts.utility,
35058
+ edges: opts.edges,
35059
+ activation: opts.activation,
35060
+ dense: opts.dense
35061
+ }).entries;
35062
+ const utilitySeeds = [...opts.utility?.entries() || []].filter(([, value]) => value > 0).sort((a, b2) => b2[1] - a[1]).map(([key]) => key);
35063
+ const utilityEntries = utilitySeeds.map((key) => usable.find((e) => e.key === key)).filter((e) => Boolean(e));
35064
+ const ranked = [...utilityEntries, ...graphRanked.filter((e) => !utilitySeeds.includes(e.key))];
35065
+ const seen = /* @__PURE__ */ new Set();
35066
+ const take = (list) => {
35067
+ const out = [];
35068
+ for (const e of list) {
35069
+ if (seen.has(e.key)) continue;
35070
+ seen.add(e.key);
35071
+ out.push(e);
35072
+ }
35073
+ return out;
35074
+ };
35075
+ const byDate = (a, b2) => b2.date.localeCompare(a.date);
35076
+ const directives = take(
35077
+ usable.filter(
35078
+ (e) => (e.origin === "human" || e.importance === "critical" || e.priority > 0) && e.category !== "warning" && e.evidence !== "conflict"
35079
+ ).sort((a, b2) => b2.priority - a.priority || byDate(a, b2)).slice(0, 3)
35080
+ );
35081
+ const constraints = take(
35082
+ usable.filter(
35083
+ (e) => e.category === "warning" || e.evidence === "conflict" || e.tags.some((t) => ["trap", "gotcha", "risk", "warning", "outdated"].includes(t.toLowerCase()))
35084
+ ).sort(byDate).slice(0, 2)
35085
+ );
35086
+ const memory = take(ranked.slice(0, 5));
35087
+ const decisions = take(ranked.filter((e) => e.category === "decision").slice(0, 2));
35088
+ const tokens = tokenize(task).slice(0, 4);
35089
+ const queries = [];
35090
+ if (task.trim()) queries.push(task.trim().slice(0, 140));
35091
+ if (tokens.length >= 2) queries.push(`${tokens[0]} ${tokens[1]}`);
35092
+ if (memory.length > 0 && tokens.length > 0) queries.push(`${memory[0].key} ${tokens[0]}`);
35093
+ const queriesOut = [...new Set(queries)].slice(0, 3);
35094
+ const hydrate = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.key))].slice(0, 8);
35095
+ const files = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.file).filter(Boolean))].slice(0, 4);
35096
+ const sessionLines = (opts.sessions || []).slice(0, 2).map((s2) => `- ${s2}`);
35097
+ const sections = [
35098
+ { title: "Directives", lines: directives.map((e) => line(e, today)) },
35099
+ { title: "Constraints", lines: constraints.map((e) => line(e, today)) },
35100
+ { title: "Memory", lines: memory.map((e) => line(e, today)) },
35101
+ { title: "Decisions", lines: decisions.map((e) => line(e, today)) },
35102
+ { title: "Retrieval", lines: queriesOut.map((q2) => `- query: ${q2}`) },
35103
+ { title: "Hydrate", lines: hydrate.length ? hydrate.map((k3) => `- ${k3}`) : ["- (none)"] },
35104
+ { title: "Files", lines: files.map((f3) => `- ${f3}`) },
35105
+ { title: "Sessions", lines: sessionLines.length ? sessionLines : ["- (none)"] }
35106
+ ].filter((s2) => s2.lines.length > 0);
35107
+ const pkg = {
35108
+ task,
35109
+ asOf: today,
35110
+ freshness,
35111
+ project: basename2(root) || root,
35112
+ slug: projectSlug(root),
35113
+ root,
35114
+ sections: [],
35115
+ queries: queriesOut,
35116
+ hydrate,
35117
+ usedTokens: 0
35118
+ };
35119
+ let used = estimateTokens(
35120
+ `<memory project="${pkg.project}" as_of="${today}" freshness="${freshness}">
35121
+ identity: mcp_project=${pkg.slug} | root=${root}
35122
+ </memory>`
35123
+ );
35124
+ for (const section of sections) {
35125
+ const block = `${section.title}
35126
+ ${section.lines.join("\n")}`;
35127
+ const cost = estimateTokens(`
35128
+ ${block}`);
35129
+ if (used + cost > maxTokens) continue;
35130
+ used += cost;
35131
+ pkg.sections.push(section);
35132
+ }
35133
+ pkg.usedTokens = used;
35134
+ return pkg;
35135
+ }
35136
+ function renderContextPackage(pkg) {
35137
+ const task = pkg.task.replace(/"/g, "&quot;").slice(0, 140);
35138
+ const out = [
35139
+ `<memory project="${pkg.project}" as_of="${pkg.asOf}" freshness="${pkg.freshness}" task="${task}">`,
35140
+ `identity: mcp_project=${pkg.slug} | root=${pkg.root}`
35141
+ ];
35142
+ for (const section of pkg.sections) out.push(`${section.title}
35143
+ ${section.lines.join("\n")}`);
35144
+ if (pkg.sections.length === 0) out.push("(no stable memories yet)");
35145
+ out.push("</memory>");
35146
+ return out.join("\n");
35147
+ }
35148
+
35149
+ // src/mcp/feedback.ts
35150
+ import { existsSync as existsSync12, mkdirSync as mkdirSync3, readFileSync as readFileSync10 } from "fs";
35151
+ import { dirname } from "path";
35152
+ import { randomBytes as randomBytes3 } from "crypto";
35153
+ init_utils();
35154
+ var HEADER = "version: 1\nfeedback[0|]{id|key|signal|source|ts|session|task}:";
35155
+ var MAX_EVENTS = 1e3;
35156
+ var SIGNAL_WEIGHT = {
35157
+ useful: 1,
35158
+ irrelevant: -1,
35159
+ outdated: -1.5,
35160
+ wrong: -2
35161
+ };
35162
+ function readFeedback() {
35163
+ if (!existsSync12(FEEDBACK_FILE)) return [];
35164
+ let data = "";
35165
+ try {
35166
+ data = readFileSync10(FEEDBACK_FILE, "utf-8");
35167
+ } catch {
35168
+ return [];
35169
+ }
35170
+ const lines = data.split("\n");
35171
+ const headerIdx = lines.findIndex((l) => l.startsWith("feedback[") || /^\[\d+\|]/.test(l));
35172
+ if (headerIdx === -1) return [];
35173
+ const out = [];
35174
+ for (const line2 of lines.slice(headerIdx + 1)) {
35175
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35176
+ const p2 = parseToonLine(line2.trim());
35177
+ if (p2.length < 5) continue;
35178
+ const signal = p2[2];
35179
+ if (!(signal in SIGNAL_WEIGHT)) continue;
35180
+ out.push({
35181
+ id: p2[0],
35182
+ key: p2[1],
35183
+ signal,
35184
+ source: p2[3] === "implicit" ? "implicit" : "explicit",
35185
+ ts: p2[4],
35186
+ session: p2[5] || "",
35187
+ task: p2[6] || ""
35188
+ });
35189
+ }
35190
+ return out;
35191
+ }
35192
+ function appendFeedback(event) {
35193
+ const full = {
35194
+ id: event.id || `fb-${randomBytes3(4).toString("hex")}`,
35195
+ key: event.key,
35196
+ signal: event.signal,
35197
+ source: event.source,
35198
+ ts: event.ts || (/* @__PURE__ */ new Date()).toISOString(),
35199
+ session: event.session || "",
35200
+ task: event.task || ""
35201
+ };
35202
+ const dir = dirname(FEEDBACK_FILE);
35203
+ if (!existsSync12(dir)) mkdirSync3(dir, { recursive: true });
35204
+ withLockSync(FEEDBACK_FILE, () => {
35205
+ const data = existsSync12(FEEDBACK_FILE) ? readFileSync10(FEEDBACK_FILE, "utf-8") : HEADER;
35206
+ const lines = data.split("\n");
35207
+ let headerIdx = lines.findIndex((l) => l.startsWith("feedback[") || /^\[\d+\|]/.test(l));
35208
+ if (headerIdx === -1) {
35209
+ lines.unshift(HEADER.split("\n")[1]);
35210
+ headerIdx = 0;
35211
+ }
35212
+ const rows = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && l.startsWith(" "));
35213
+ const row = toToonLine([
35214
+ full.id,
35215
+ full.key,
35216
+ full.signal,
35217
+ full.source,
35218
+ full.ts,
35219
+ full.session,
35220
+ full.task.slice(0, 2e3)
35221
+ ]);
35222
+ const kept = [row, ...rows].slice(0, MAX_EVENTS);
35223
+ const countMatch = lines[headerIdx].match(/\[(\d+)\|/);
35224
+ const count = countMatch ? parseInt(countMatch[1], 10) : 0;
35225
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
35226
+ lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...kept);
35227
+ atomicWrite(FEEDBACK_FILE, lines.join("\n"));
35228
+ });
35229
+ return full;
35230
+ }
35231
+ function utilityMap(today) {
35232
+ const ref = today || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
35233
+ const refTime = Date.parse(`${ref}T00:00:00Z`);
35234
+ const out = /* @__PURE__ */ new Map();
35235
+ for (const e of readFeedback()) {
35236
+ const days = Number.isNaN(refTime) ? 0 : Math.max(0, (refTime - Date.parse(e.ts)) / 864e5);
35237
+ const decay = Math.pow(0.9, days);
35238
+ const delta = SIGNAL_WEIGHT[e.signal] * decay;
35239
+ out.set(e.key, Math.max(-3, Math.min(3, Number(((out.get(e.key) || 0) + delta).toFixed(3)))));
35240
+ }
35241
+ return out;
35242
+ }
35243
+ function markWrong(key) {
35244
+ const data = readMemory();
35245
+ const lines = data.split("\n");
35246
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35247
+ if (headerIdx === -1) return false;
35248
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35249
+ const line2 = lines[i];
35250
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35251
+ if (line2.startsWith(" summaries:")) break;
35252
+ const parts = parseToonLine(line2);
35253
+ if (parts[0] !== key && parts[2] !== key) continue;
35254
+ while (parts.length < 20) parts.push("");
35255
+ parts[19] = "conflict";
35256
+ lines[i] = toToonLine(parts);
35257
+ writeMemory(lines.join("\n"));
35258
+ return true;
35259
+ }
35260
+ return false;
35261
+ }
35262
+
35263
+ // src/mcp/edges.ts
35264
+ import { existsSync as existsSync13, mkdirSync as mkdirSync4, readFileSync as readFileSync11 } from "fs";
35265
+ import { dirname as dirname2 } from "path";
35266
+ init_graph();
35267
+ init_utils();
35268
+ var EDGE_TYPES = ["related", "supports", "contradicts", "supersedes", "depends_on", "derived_from", "used_in"];
35269
+ var MAX_EDGES = 2e3;
35270
+ function normalizeType(type) {
35271
+ const t = type.toLowerCase();
35272
+ return EDGE_TYPES.includes(t) ? t : "related";
35273
+ }
35274
+ function readEdges() {
35275
+ if (!existsSync13(EDGES_FILE)) return [];
35276
+ try {
35277
+ const lines = readFileSync11(EDGES_FILE, "utf-8").split("\n");
35278
+ const start = lines.findIndex((l) => l.startsWith("edges[") || /^\[\d+\|]/.test(l));
35279
+ if (start === -1) return [];
35280
+ const out = [];
35281
+ for (const line2 of lines.slice(start + 1)) {
35282
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35283
+ const p2 = parseToonLine(line2);
35284
+ if (p2.length < 5) continue;
35285
+ const weight = Number(p2[3]);
35286
+ if (!p2[0] || !p2[1] || !Number.isFinite(weight)) continue;
35287
+ out.push({ from: p2[0], to: p2[1], type: normalizeType(p2[2]), weight, ts: p2[4] || "" });
35288
+ }
35289
+ return out;
35290
+ } catch {
35291
+ return [];
35292
+ }
35293
+ }
35294
+ function writeEdges(edges) {
35295
+ const dir = dirname2(EDGES_FILE);
35296
+ if (!existsSync13(dir)) mkdirSync4(dir, { recursive: true });
35297
+ const sorted = [...edges].filter((e) => e.from && e.to && e.from !== e.to).sort((a, b2) => a.from.localeCompare(b2.from) || a.to.localeCompare(b2.to) || a.type.localeCompare(b2.type)).slice(0, MAX_EDGES);
35298
+ const header = `version: 1
35299
+ edges[${sorted.length}|]{from|to|type|weight|ts}:`;
35300
+ const lines = [header, ...sorted.map((e) => toToonLine([e.from, e.to, e.type, String(e.weight), e.ts]))];
35301
+ withLockSync(EDGES_FILE, () => atomicWrite(EDGES_FILE, lines.join("\n")));
35302
+ }
35303
+ function deriveEdges(data, feedback = []) {
35304
+ const entries = parseEntries(data);
35305
+ const keys = new Set(entries.map((e) => e.key));
35306
+ const map2 = /* @__PURE__ */ new Map();
35307
+ const add = (from, to2, type, weight, ts2) => {
35308
+ if (!keys.has(from) || !keys.has(to2) || from === to2) return;
35309
+ const id2 = `${from}|${to2}|${type}`;
35310
+ const prev = map2.get(id2);
35311
+ if (prev) prev.weight = Math.max(prev.weight, weight);
35312
+ else map2.set(id2, { from, to: to2, type, weight, ts: ts2 });
35313
+ };
35314
+ for (const e of entries) {
35315
+ for (const link of e.links) {
35316
+ const { type, key } = parseLinkToken(link);
35317
+ add(e.key, key, normalizeType(type), 1, e.date);
35318
+ }
35319
+ }
35320
+ for (const event of feedback) {
35321
+ if (!event.task) continue;
35322
+ const haystack = event.task.toLowerCase();
35323
+ const type = event.signal === "wrong" || event.signal === "outdated" ? "contradicts" : "used_in";
35324
+ const weight = event.signal === "useful" ? 1 : 0.5;
35325
+ for (const key of keys) {
35326
+ if (key === event.key) continue;
35327
+ if (!haystack.includes(key.toLowerCase())) continue;
35328
+ add(event.key, key, type, weight, event.ts.slice(0, 10));
35329
+ }
35330
+ }
35331
+ return [...map2.values()];
35332
+ }
35333
+ function rebuildEdges(data, feedback = []) {
35334
+ const edges = deriveEdges(data, feedback);
35335
+ writeEdges(edges);
35336
+ return edges.length;
35337
+ }
35338
+
35339
+ // src/lib/dense.ts
35340
+ init_graph();
35341
+ import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync5 } from "fs";
35342
+ import { dirname as dirname3 } from "path";
35343
+ async function loadDenseModule() {
35344
+ const spec = process.env.TOON_MEMORY_DENSE_MODULE || "toon-memory-dense";
35345
+ try {
35346
+ const mod = await import(spec);
35347
+ const embed = mod?.embed || mod?.default?.embed || mod?.default;
35348
+ return typeof embed === "function" ? { embed } : null;
35349
+ } catch {
35350
+ return null;
35351
+ }
35352
+ }
35353
+ function cosine(a, b2) {
35354
+ const n = Math.min(a.length, b2.length);
35355
+ if (n === 0) return 0;
35356
+ let dot = 0;
35357
+ let na2 = 0;
35358
+ let nb2 = 0;
35359
+ for (let i = 0; i < n; i++) {
35360
+ dot += a[i] * b2[i];
35361
+ na2 += a[i] * a[i];
35362
+ nb2 += b2[i] * b2[i];
35363
+ }
35364
+ if (na2 === 0 || nb2 === 0) return 0;
35365
+ const value = dot / (Math.sqrt(na2) * Math.sqrt(nb2));
35366
+ return Number.isFinite(value) ? value : 0;
35367
+ }
35368
+ function readVectors() {
35369
+ const empty = { dim: 0, vectors: /* @__PURE__ */ new Map() };
35370
+ if (!existsSync14(VECTORS_FILE)) return empty;
35371
+ try {
35372
+ const buf = readFileSync12(VECTORS_FILE);
35373
+ const newline = buf.indexOf(10);
35374
+ if (newline === -1) return empty;
35375
+ const match = buf.subarray(0, newline).toString("utf-8").match(/^TMVEC1 (\d+)$/);
35376
+ if (!match) return empty;
35377
+ const dim = Number(match[1]);
35378
+ if (!Number.isFinite(dim) || dim <= 0) return empty;
35379
+ let offset = newline + 1;
35380
+ const vectors = /* @__PURE__ */ new Map();
35381
+ while (offset + 2 <= buf.length) {
35382
+ const len = buf.readUInt16BE(offset);
35383
+ offset += 2;
35384
+ if (offset + len + dim * 4 > buf.length) break;
35385
+ const key = buf.subarray(offset, offset + len).toString("utf-8");
35386
+ offset += len;
35387
+ const vec = [];
35388
+ for (let i = 0; i < dim; i++) vec.push(buf.readFloatLE(offset + i * 4));
35389
+ offset += dim * 4;
35390
+ vectors.set(key, vec);
35391
+ }
35392
+ return { dim, vectors };
35393
+ } catch {
35394
+ return empty;
35395
+ }
35396
+ }
35397
+ function writeVectors(vectors, dim) {
35398
+ const dir = dirname3(VECTORS_FILE);
35399
+ if (!existsSync14(dir)) mkdirSync5(dir, { recursive: true });
35400
+ const chunks = [Buffer.from(`TMVEC1 ${dim}
35401
+ `, "utf-8")];
35402
+ let written = 0;
35403
+ for (const [key, vec] of vectors) {
35404
+ if (vec.length !== dim) continue;
35405
+ const keyBuf = Buffer.from(key, "utf-8");
35406
+ const lenBuf = Buffer.alloc(2);
35407
+ lenBuf.writeUInt16BE(keyBuf.length);
35408
+ const vecBuf = Buffer.alloc(dim * 4);
35409
+ for (let i = 0; i < dim; i++) vecBuf.writeFloatLE(vec[i], i * 4);
35410
+ chunks.push(lenBuf, keyBuf, vecBuf);
35411
+ written++;
35412
+ }
35413
+ const out = Buffer.concat(chunks);
35414
+ withLockSync(VECTORS_FILE, () => writeFileSync5(VECTORS_FILE, out));
35415
+ return written;
35416
+ }
35417
+ async function buildVectors(data, module, model) {
35418
+ const entries = parseEntries(data).filter((e) => e.status !== "obsolete" && e.status !== "draft");
35419
+ if (entries.length === 0) return 0;
35420
+ const embedded = await module.embed(entries.map((e) => `${e.key} ${e.content}`), model);
35421
+ const dim = embedded[0]?.length || loadConfig().dense?.dim || 0;
35422
+ if (!dim) return 0;
35423
+ const vectors = /* @__PURE__ */ new Map();
35424
+ entries.forEach((e, i) => {
35425
+ if (embedded[i]?.length === dim) vectors.set(e.key, embedded[i]);
35426
+ });
35427
+ return writeVectors(vectors, dim);
35428
+ }
35429
+ async function denseScores(query, data) {
35430
+ const config2 = loadConfig();
35431
+ if (!config2.dense?.enabled || !query.trim()) return /* @__PURE__ */ new Map();
35432
+ try {
35433
+ const module = await loadDenseModule();
35434
+ if (!module) return /* @__PURE__ */ new Map();
35435
+ if (readVectors().vectors.size === 0) await buildVectors(data, module, config2.dense.model);
35436
+ const stored = readVectors();
35437
+ if (stored.vectors.size === 0) return /* @__PURE__ */ new Map();
35438
+ const [queryVec] = await module.embed([query], config2.dense.model);
35439
+ if (!queryVec) return /* @__PURE__ */ new Map();
35440
+ const out = /* @__PURE__ */ new Map();
35441
+ for (const [key, vec] of stored.vectors) out.set(key, cosine(queryVec, vec));
35442
+ return out;
35443
+ } catch {
35444
+ return /* @__PURE__ */ new Map();
35445
+ }
35446
+ }
35447
+
35448
+ // src/mcp/tools.ts
34656
35449
  function registerTools(server2) {
35450
+ const EXPERT_TOOLS = /* @__PURE__ */ new Set([
35451
+ "memory_stats",
35452
+ "memory_diff",
35453
+ "memory_suggest",
35454
+ "memory_primer",
35455
+ "memory_reflect",
35456
+ "memory_visualize",
35457
+ "memory_graph_path",
35458
+ "memory_sessions",
35459
+ "memory_merge_sessions",
35460
+ "memory_compress",
35461
+ "memory_consolidate",
35462
+ "memory_archive",
35463
+ "memory_backup",
35464
+ "memory_encrypt",
35465
+ "memory_decrypt",
35466
+ "memory_secret",
35467
+ "memory_tag",
35468
+ "memory_pin",
35469
+ "memory_unpin",
35470
+ "memory_edges",
35471
+ "context_generate",
35472
+ "context_diff",
35473
+ "context_focus",
35474
+ "context_health",
35475
+ "context_export",
35476
+ "memory_export_gist",
35477
+ "memory_import_gist",
35478
+ "memory_export_global",
35479
+ "memory_import_global"
35480
+ ]);
35481
+ const expertMode = process.env.TOON_MEMORY_EXPERT_TOOLS === "1";
35482
+ const sdk = server2;
35483
+ const register = (name, config2, cb2) => {
35484
+ if (!expertMode && EXPERT_TOOLS.has(name)) return;
35485
+ sdk.registerTool(name, config2, cb2);
35486
+ };
35487
+ const recallExtras = async (query = "") => {
35488
+ const config2 = loadConfig();
35489
+ const edges = config2.graph?.activation ? readEdges() : void 0;
35490
+ const dense = config2.dense?.enabled ? await denseScores(query, readMemory()) : /* @__PURE__ */ new Map();
35491
+ return {
35492
+ utility: utilityMap(),
35493
+ ...edges && edges.length ? { edges, activation: true } : {},
35494
+ ...dense.size ? { dense } : {}
35495
+ };
35496
+ };
34657
35497
  function softDelete(key) {
34658
35498
  const data = readMemory();
34659
35499
  const lines = data.split("\n");
@@ -34663,10 +35503,10 @@ function registerTools(server2) {
34663
35503
  }
34664
35504
  let found = false;
34665
35505
  for (let i = headerIdx + 1; i < lines.length; i++) {
34666
- const line = lines[i];
34667
- if (!line.startsWith(" ") || !line.includes("|")) continue;
34668
- if (line.startsWith(" summaries:")) break;
34669
- const parts = parseToonLine(line);
35506
+ const line2 = lines[i];
35507
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35508
+ if (line2.startsWith(" summaries:")) break;
35509
+ const parts = parseToonLine(line2);
34670
35510
  if (parts[0] === key || parts[2] === key) {
34671
35511
  while (parts.length < 17) parts.push("");
34672
35512
  parts[16] = "obsolete";
@@ -34714,10 +35554,10 @@ function registerTools(server2) {
34714
35554
  let found = false;
34715
35555
  let wasObsolete = false;
34716
35556
  for (let i = headerIdx + 1; i < lines.length; i++) {
34717
- const line = lines[i];
34718
- if (!line.startsWith(" ") || !line.includes("|")) continue;
34719
- if (line.startsWith(" summaries:")) break;
34720
- const parts = parseToonLine(line);
35557
+ const line2 = lines[i];
35558
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35559
+ if (line2.startsWith(" summaries:")) break;
35560
+ const parts = parseToonLine(line2);
34721
35561
  if (parts[0] === key || parts[2] === key) {
34722
35562
  while (parts.length < 17) parts.push("");
34723
35563
  wasObsolete = parts[16] === "obsolete";
@@ -34744,10 +35584,10 @@ function registerTools(server2) {
34744
35584
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
34745
35585
  let oldIdx = -1;
34746
35586
  for (let i = headerIdx + 1; i < lines.length; i++) {
34747
- const line = lines[i];
34748
- if (!line.startsWith(" ") || !line.includes("|")) continue;
34749
- if (line.startsWith(" summaries:")) break;
34750
- const parts = parseToonLine(line);
35587
+ const line2 = lines[i];
35588
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35589
+ if (line2.startsWith(" summaries:")) break;
35590
+ const parts = parseToonLine(line2);
34751
35591
  if (parts[0] === old_key || parts[2] === old_key) {
34752
35592
  oldIdx = i;
34753
35593
  break;
@@ -34760,10 +35600,10 @@ function registerTools(server2) {
34760
35600
  let newKey = "";
34761
35601
  if (new_key) {
34762
35602
  for (let i = headerIdx + 1; i < lines.length; i++) {
34763
- const line = lines[i];
34764
- if (!line.startsWith(" ") || !line.includes("|")) continue;
34765
- if (line.startsWith(" summaries:")) break;
34766
- const parts = parseToonLine(line);
35603
+ const line2 = lines[i];
35604
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35605
+ if (line2.startsWith(" summaries:")) break;
35606
+ const parts = parseToonLine(line2);
34767
35607
  if (parts[0] === new_key || parts[2] === new_key) {
34768
35608
  newIdx = i;
34769
35609
  newKey = parts[2];
@@ -34870,14 +35710,14 @@ ${result.proposals.map((p2) => ` \u2022 ${p2}`).join("\n")}`
34870
35710
  }
34871
35711
  const parsed = [];
34872
35712
  for (let i = headerIdx + 1; i < lines.length; i++) {
34873
- const line = lines[i];
34874
- if (!line.startsWith(" ") || !line.includes("|")) continue;
34875
- if (line.startsWith(" summaries:")) break;
34876
- const parts = parseToonLine(line);
35713
+ const line2 = lines[i];
35714
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35715
+ if (line2.startsWith(" summaries:")) break;
35716
+ const parts = parseToonLine(line2);
34877
35717
  if (parts.length < 7) continue;
34878
35718
  const [id2, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
34879
35719
  const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean));
34880
- parsed.push({ lineIdx: i, id: id2, cat, key, content, file: file2, tags, date: date5, ttl, accessed: parseInt(accessedRaw) || 0, words, line });
35720
+ parsed.push({ lineIdx: i, id: id2, cat, key, content, file: file2, tags, date: date5, ttl, accessed: parseInt(accessedRaw) || 0, words, line: line2 });
34881
35721
  }
34882
35722
  if (parsed.length < 2) {
34883
35723
  return { content: [{ type: "text", text: "\u2705 Not enough entries to compress." }] };
@@ -34968,8 +35808,8 @@ ${mergeActions.join("\n")}`
34968
35808
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34969
35809
  const candidates = [];
34970
35810
  for (let i = 0; i < entryLines2.length; i++) {
34971
- const line = entryLines2[i].trim();
34972
- const parts = parseToonLine(line);
35811
+ const line2 = entryLines2[i].trim();
35812
+ const parts = parseToonLine(line2);
34973
35813
  if (parts.length < 11) continue;
34974
35814
  const quality = parseFloat(parts[10]) || 0;
34975
35815
  const tags = parts[5] || "";
@@ -34977,7 +35817,7 @@ ${mergeActions.join("\n")}`
34977
35817
  const content = parts[3] || "";
34978
35818
  const isCandidate = quality < minQuality || !tags || content.length < 20;
34979
35819
  if (isCandidate) {
34980
- candidates.push({ idx: i, line, quality, key });
35820
+ candidates.push({ idx: i, line: line2, quality, key });
34981
35821
  }
34982
35822
  }
34983
35823
  if (candidates.length === 0) {
@@ -35028,15 +35868,15 @@ ${mergeActions.join("\n")}`
35028
35868
  sections.push("\u{1F4A1} Use memory_compress to merge related entries before removing them.");
35029
35869
  return { content: [{ type: "text", text: sections.join("\n") }] };
35030
35870
  }
35031
- server2.registerTool(
35871
+ register(
35032
35872
  "memory_remember",
35033
35873
  {
35034
35874
  title: "Save to Memory",
35035
35875
  description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions. Tags: 'private' excludes from context injection; 'superseded' marks as obsolete.",
35036
35876
  inputSchema: {
35037
- category: external_exports.enum(["decision", "pattern", "bug", "knowledge", "warning"]).describe("Category of the fact. 'warning' = negative memory ('NO hacer esto, rompe X') \u2014 recalled with a boost so past mistakes surface first."),
35038
- key: external_exports.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
35039
- content: external_exports.string().describe("Detailed content of the fact"),
35877
+ category: external_exports.enum(["decision", "pattern", "bug", "knowledge", "warning", "architecture"]).describe("Category of the fact. 'warning' = negative memory ('NO hacer esto, rompe X') \u2014 recalled with a boost so past mistakes surface first."),
35878
+ key: requiredText("key", 120).describe("Short title in kebab-case (e.g. risk-engine-priority)"),
35879
+ content: requiredText("content").describe("Detailed content of the fact"),
35040
35880
  file: external_exports.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
35041
35881
  tags: external_exports.string().optional().default("").describe("Semicolon-separated tags (e.g. risk;spec)"),
35042
35882
  ttl: external_exports.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
@@ -35060,10 +35900,10 @@ ${mergeActions.join("\n")}`
35060
35900
  let existingIdx = -1;
35061
35901
  let existingId = newId;
35062
35902
  for (let i = headerIdx + 1; i < lines.length; i++) {
35063
- const line = lines[i];
35064
- if (!line.startsWith(" ") || !line.includes("|")) continue;
35065
- if (line.startsWith(" summaries:")) break;
35066
- const parts = parseToonLine(line);
35903
+ const line2 = lines[i];
35904
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
35905
+ if (line2.startsWith(" summaries:")) break;
35906
+ const parts = parseToonLine(line2);
35067
35907
  if (parts[2] === key) {
35068
35908
  existingIdx = i;
35069
35909
  existingId = parts[0];
@@ -35147,7 +35987,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${evidenceMsg}${confli
35147
35987
  };
35148
35988
  }
35149
35989
  );
35150
- server2.registerTool(
35990
+ register(
35151
35991
  "memory_recall",
35152
35992
  {
35153
35993
  title: "Search Memory",
@@ -35155,32 +35995,37 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${evidenceMsg}${confli
35155
35995
  inputSchema: {
35156
35996
  query: external_exports.string().optional().default("").describe("Text to search for (optional when mode:'index' or ids is given)"),
35157
35997
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
35158
- from_date: external_exports.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
35998
+ from_date: external_exports.string().optional().default("").describe("Start date filter (YYYY-MM-DD or relative like 'ayer', 'la semana pasada', '7d')"),
35999
+ since: external_exports.string().optional().default("").describe("Alias of from_date with natural-language dates."),
35159
36000
  to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
35160
36001
  mode: external_exports.enum(["flat", "graph", "index"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens). 'index' = one line per entry (key, id, category, date, relevance %) with no content \u2014 browse then fetch full entries with `ids`."),
35161
36002
  ids: external_exports.string().optional().default("").describe("Batch fetch: comma/space/;-separated entry ids or keys, rendered in the given order (unknown entries skipped). Complements mode:'index' \u2014 layer 2 of progressive disclosure. Overrides mode."),
35162
- hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
35163
- limit: external_exports.number().optional().describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
35164
- compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
35165
- budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
35166
- budget_tokens: external_exports.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
36003
+ hops: positiveInt(1, 3).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
36004
+ limit: optionalPositiveInt(200).describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
36005
+ compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags). Does not mutate .toon file."),
36006
+ budget: external_exports.enum(["tiny", "normal", "deep"]).optional().describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
36007
+ budget_tokens: optionalPositiveInt(2e4).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit)."),
35167
36008
  explain: external_exports.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM \u2014 pure heuristics."),
35168
36009
  bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
35169
36010
  path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
35170
36011
  rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
35171
- as_of: external_exports.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date. Superseded entries still appear if they were active then.")
36012
+ as_of: external_exports.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date. Superseded entries still appear if they were active then."),
36013
+ today: external_exports.string().optional().default("").describe("Alias of as_of (documented in older changelogs)."),
36014
+ sessionBias: external_exports.boolean().optional().default(false).describe("Alias of bias:'session' (documented in older READMEs).")
35172
36015
  },
35173
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
36016
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
35174
36017
  },
35175
- async ({ query, category, from_date, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
36018
+ async ({ query, category, from_date, since, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of, today, sessionBias }) => {
35176
36019
  const data = readMemory();
35177
36020
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
35178
- const resolvedAsOf = as_of || void 0;
36021
+ const resolvedAsOf = as_of || today || void 0;
36022
+ const resolvedBias = sessionBias && bias === "none" ? "session" : bias;
36023
+ const resolvedFrom = from_date || since ? parseRelativeDate(from_date || since) : "";
35179
36024
  if (ids && ids.trim()) {
35180
- const tokens = ids.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean);
36025
+ const tokens = splitIds(ids);
35181
36026
  const entries = fetchEntriesByIds(data, tokens, { asOf: resolvedAsOf });
35182
36027
  if (entries.length === 0) {
35183
- return { content: [{ type: "text", text: `No entries found for ids: ${ids}` }] };
36028
+ return noMatches(ids);
35184
36029
  }
35185
36030
  bumpAccessed(entries.map((e) => e.id));
35186
36031
  const label = entries.length === 1 ? "entry" : "entries";
@@ -35209,13 +36054,11 @@ ${formatted3}` }] };
35209
36054
 
35210
36055
  ${formatted2}` }] };
35211
36056
  }
35212
- const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
36057
+ const sessionFiles = resolvedBias === "session" ? getCurrentSessionFiles() : void 0;
35213
36058
  const limit = limitParam ?? (mode === "index" ? 15 : 6);
35214
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, limit, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: resolvedAsOf });
36059
+ const detail = graphRecallDetailed(data, query, { category, from_date: resolvedFrom, to_date, hops, limit, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: resolvedAsOf, ...await recallExtras(query) });
35215
36060
  if (mode === "index") {
35216
- if (detail.entries.length === 0) {
35217
- return { content: [{ type: "text", text: `No results found for "${query}"` }] };
35218
- }
36061
+ if (detail.entries.length === 0) return noMatches(query);
35219
36062
  const formatted2 = renderIndex(detail.entries, { scores: detail.scores });
35220
36063
  return {
35221
36064
  content: [{
@@ -35228,9 +36071,7 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35228
36071
  }]
35229
36072
  };
35230
36073
  }
35231
- if (detail.entries.length === 0) {
35232
- return { content: [{ type: "text", text: `No results found for "${query}"` }] };
35233
- }
36074
+ if (detail.entries.length === 0) return noMatches(query);
35234
36075
  bumpAccessed(detail.entries.map((e) => e.id));
35235
36076
  const reasons = explain ? detail.reasons : void 0;
35236
36077
  if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
@@ -35272,13 +36113,13 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35272
36113
  return { content: [{ type: "text", text: formatted }] };
35273
36114
  }
35274
36115
  );
35275
- server2.registerTool(
36116
+ register(
35276
36117
  "memory_forget",
35277
36118
  {
35278
36119
  title: "Forget from Memory",
35279
36120
  description: "Lifecycle operations for a memory entry: soft (default) marks it obsolete and hides it from recalls, hard permanently removes it, restore brings it back to active, supersede retires it with a typed superseded_by edge to a newer entry.",
35280
36121
  inputSchema: {
35281
- key: external_exports.string().describe("Key or id of the entry"),
36122
+ key: requiredText("key", 200).describe("Key or id of the entry"),
35282
36123
  action: external_exports.enum(["soft", "hard", "restore", "supersede"]).optional().default("soft").describe("soft: mark obsolete (default). hard: permanently remove. restore: bring an obsolete entry back to active. supersede: mark obsolete with a superseded_by link to new_key."),
35283
36124
  new_key: external_exports.string().optional().default("").describe("Replacement entry key or id (only used with action: supersede)."),
35284
36125
  reason: external_exports.string().optional().default("").describe("Optional note appended to the old entry (only used with action: supersede).")
@@ -35298,7 +36139,7 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35298
36139
  }
35299
36140
  }
35300
36141
  );
35301
- server2.registerTool(
36142
+ register(
35302
36143
  "memory_stats",
35303
36144
  {
35304
36145
  title: "Memory Stats",
@@ -35343,9 +36184,18 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35343
36184
  const dupPct = entries.length > 0 ? (dupCount / entries.length * 100).toFixed(0) : "0";
35344
36185
  const deadCount = byStatus["obsolete"] || 0;
35345
36186
  const deadPct = entries.length > 0 ? (deadCount / entries.length * 100).toFixed(0) : "0";
36187
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
36188
+ const newest = fullParts.map((p2) => p2[6] || "").filter(Boolean).sort().at(-1) || "";
36189
+ const age = newest ? entryAgeDays(newest, today) : 0;
36190
+ const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh";
36191
+ const staleCount = fullParts.filter((p2) => p2[6] && entryAgeDays(p2[6], today) > 30 && p2[16] !== "obsolete").length;
36192
+ const trapCount = fullParts.filter(
36193
+ (p2) => p2[1] === "warning" || /(^|;)(trap|gotcha|risk)(;|$)/i.test(p2[5] || "")
36194
+ ).length;
35346
36195
  const stats = [
35347
36196
  `Total entries: ${entries.length}`,
35348
36197
  `File summaries: ${summaryLines.length}`,
36198
+ `Freshness: ${freshness} | stale: ${staleCount} | traps: ${trapCount} | catalog: ${expertMode ? "expert" : "core"}`,
35349
36199
  "",
35350
36200
  "By category:",
35351
36201
  ...Object.entries(byCategory).map(([k3, v3]) => ` ${k3}: ${v3}`),
@@ -35414,13 +36264,13 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35414
36264
  return { content: [{ type: "text", text: stats.join("\n") }] };
35415
36265
  }
35416
36266
  );
35417
- server2.registerTool(
36267
+ register(
35418
36268
  "memory_diff",
35419
36269
  {
35420
36270
  title: "Memory Diff",
35421
36271
  description: "Show what changed in memory since a date. Useful for seeing what was learned since the last session.",
35422
36272
  inputSchema: {
35423
- since: external_exports.string().describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
36273
+ since: requiredText("since", 80).describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
35424
36274
  type: external_exports.enum(["all", "created", "updated"]).optional().default("all").describe("Filter by change type")
35425
36275
  },
35426
36276
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
@@ -35430,8 +36280,8 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35430
36280
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
35431
36281
  const data = readMemory();
35432
36282
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
35433
- const results = lines.map((line) => {
35434
- const trimmed = line.trim();
36283
+ const results = lines.map((line2) => {
36284
+ const trimmed = line2.trim();
35435
36285
  const parts = parseToonLine(trimmed);
35436
36286
  if (parts.length < 7) return null;
35437
36287
  const [id2, cat, key, content, file2, tags, date5] = parts;
@@ -35464,14 +36314,14 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35464
36314
  return { content: [{ type: "text", text: sections.join("\n") }] };
35465
36315
  }
35466
36316
  );
35467
- server2.registerTool(
36317
+ register(
35468
36318
  "memory_suggest",
35469
36319
  {
35470
36320
  title: "Suggest Related Memories",
35471
36321
  description: "Suggest memory entries related to a given context. Useful for gathering context before a task.",
35472
36322
  inputSchema: {
35473
- context: external_exports.string().describe("Text or context to search for suggestions"),
35474
- limit: external_exports.number().optional().default(5).describe("Maximum suggestions")
36323
+ context: requiredText("context", 500).describe("Text or context to search for suggestions"),
36324
+ limit: positiveInt(5, 20).describe("Maximum suggestions")
35475
36325
  },
35476
36326
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
35477
36327
  },
@@ -35488,18 +36338,18 @@ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"fla
35488
36338
  ${formatted}` }] };
35489
36339
  }
35490
36340
  );
35491
- server2.registerTool(
36341
+ register(
35492
36342
  "memory_smart_recall",
35493
36343
  {
35494
36344
  title: "Smart Recall (Unified)",
35495
36345
  description: "Unified retrieval: combines BM25 + graph + decay + quality in a single call. Use at the START of each task to get all relevant memory context. Then use context_diff for recent changes, context_focus for deep dives.",
35496
36346
  inputSchema: {
35497
- intent: external_exports.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
35498
- limit: external_exports.number().optional().default(8).describe("Maximum entries to return"),
36347
+ intent: requiredText("intent", 500).describe("Describe what you need to know (e.g. 'database schema for backend')"),
36348
+ limit: positiveInt(8, 50).describe("Maximum entries to return"),
35499
36349
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
35500
36350
  bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
35501
36351
  rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
35502
- budget_tokens: external_exports.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
36352
+ budget_tokens: optionalPositiveInt(2e4).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit)."),
35503
36353
  explain: external_exports.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM \u2014 pure heuristics.")
35504
36354
  },
35505
36355
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
@@ -35508,18 +36358,18 @@ ${formatted}` }] };
35508
36358
  const data = readMemory();
35509
36359
  const mtimes = fileMtimes();
35510
36360
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
35511
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || void 0, explain });
36361
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || void 0, explain, ...await recallExtras(intent) });
35512
36362
  return { content: [{ type: "text", text: result }] };
35513
36363
  }
35514
36364
  );
35515
- server2.registerTool(
36365
+ register(
35516
36366
  "memory_summary",
35517
36367
  {
35518
36368
  title: "File Summary",
35519
36369
  description: "Save or retrieve a summary of a large file to save tokens.",
35520
36370
  inputSchema: {
35521
36371
  action: external_exports.enum(["get", "set"]).describe("get to read, set to save"),
35522
- file: external_exports.string().describe("File path"),
36372
+ file: requiredText("file", 500).describe("File path"),
35523
36373
  summary: external_exports.string().optional().default("").describe("File summary (only for set)")
35524
36374
  },
35525
36375
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
@@ -35560,7 +36410,7 @@ ${formatted}` }] };
35560
36410
  };
35561
36411
  }
35562
36412
  );
35563
- server2.registerTool(
36413
+ register(
35564
36414
  "memory_archive",
35565
36415
  {
35566
36416
  title: "Archive Old Entries",
@@ -35582,7 +36432,7 @@ ${formatted}` }] };
35582
36432
  };
35583
36433
  }
35584
36434
  );
35585
- server2.registerTool(
36435
+ register(
35586
36436
  "memory_encrypt",
35587
36437
  {
35588
36438
  title: "Enable Encryption",
@@ -35608,13 +36458,13 @@ ${formatted}` }] };
35608
36458
  };
35609
36459
  }
35610
36460
  );
35611
- server2.registerTool(
36461
+ register(
35612
36462
  "memory_decrypt",
35613
36463
  {
35614
36464
  title: "Disable Encryption",
35615
36465
  description: "Disable encryption and decode memory.",
35616
36466
  inputSchema: {
35617
- key: external_exports.string().describe("Encryption key")
36467
+ key: external_exports.string().optional().default("").describe("Encryption key. If omitted, TOON_MEMORY_KEY is used.")
35618
36468
  },
35619
36469
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
35620
36470
  },
@@ -35640,7 +36490,7 @@ ${formatted}` }] };
35640
36490
  }
35641
36491
  }
35642
36492
  );
35643
- server2.registerTool(
36493
+ register(
35644
36494
  "memory_secret",
35645
36495
  {
35646
36496
  title: "Encrypted Secrets Vault",
@@ -35708,13 +36558,13 @@ Get a value with memory_secret(action: "get", key: "<key>")` }]
35708
36558
  }
35709
36559
  }
35710
36560
  );
35711
- server2.registerTool(
36561
+ register(
35712
36562
  "memory_captured",
35713
36563
  {
35714
36564
  title: "List Captured Activity",
35715
36565
  description: "Show activity log captured automatically by hooks (only if capture is enabled). Useful for promoting observations to memory with memory_remember.",
35716
36566
  inputSchema: {
35717
- limit: external_exports.number().optional().default(20).describe("Maximum observations to show"),
36567
+ limit: positiveInt(20, 100).describe("Maximum observations to show"),
35718
36568
  tool: external_exports.string().optional().default("").describe("Filter by tool name"),
35719
36569
  file: external_exports.string().optional().default("").describe("Filter by file"),
35720
36570
  clear: external_exports.boolean().optional().default(false).describe("If true, clears the capture log")
@@ -35723,8 +36573,8 @@ Get a value with memory_secret(action: "get", key: "<key>")` }]
35723
36573
  },
35724
36574
  async ({ limit, tool, file: file2, clear }) => {
35725
36575
  if (clear) {
35726
- if (existsSync12(OBSERVATIONS_FILE)) {
35727
- writeFileSync5(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n");
36576
+ if (existsSync15(OBSERVATIONS_FILE)) {
36577
+ writeFileSync6(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n");
35728
36578
  }
35729
36579
  return { content: [{ type: "text", text: "\u{1F9F9} Capture log cleared" }] };
35730
36580
  }
@@ -35747,14 +36597,14 @@ Get a value with memory_secret(action: "get", key: "<key>")` }]
35747
36597
  ${formatted}` }] };
35748
36598
  }
35749
36599
  );
35750
- server2.registerTool(
36600
+ register(
35751
36601
  "memory_consolidate",
35752
36602
  {
35753
36603
  title: "Consolidate Memory",
35754
36604
  description: "Cleanup operations, all deterministic (no LLM): identical removes duplicate entries (keeps the first), similar merges entries with >50% word overlap (keeps longer content, combines tags), low-quality removes entries below minQuality or without tags, versions marks entries describing the same subject with older versions obsolete in favor of the newest.",
35755
36605
  inputSchema: {
35756
36606
  mode: external_exports.enum(["identical", "similar", "low-quality", "versions"]).optional().default("identical").describe("identical: dedupe entries with identical content (default). similar: merge entries with >50% word overlap. low-quality: remove entries below minQuality or without tags. versions: detect version supersession ('Use React 18' vs 'React 19') and obsolete the older ones."),
35757
- minQuality: external_exports.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
36607
+ minQuality: external_exports.coerce.number().min(0).max(1).optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
35758
36608
  dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would change without writing.")
35759
36609
  },
35760
36610
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
@@ -35772,7 +36622,7 @@ ${formatted}` }] };
35772
36622
  }
35773
36623
  }
35774
36624
  );
35775
- server2.registerTool(
36625
+ register(
35776
36626
  "memory_sessions",
35777
36627
  {
35778
36628
  title: "Active Sessions & Conflicts",
@@ -35838,24 +36688,76 @@ ${files}` : "";
35838
36688
  return { content: [{ type: "text", text: parts.join("\n") }] };
35839
36689
  }
35840
36690
  );
35841
- server2.registerTool(
36691
+ register(
35842
36692
  "context_brief",
35843
36693
  {
35844
36694
  title: "Context Briefing",
35845
36695
  description: "Generate a compact context briefing: relevant memory + active sessions + project health. Single call instead of 5-6 separate calls. Zero LLM, pure deterministic logic.",
35846
36696
  inputSchema: {
35847
36697
  task: external_exports.string().optional().default("").describe("Current agent task. If provided, entries are ranked by relevance to this task. If empty, shows top entries by importance."),
35848
- limit: external_exports.number().optional().default(6).describe("Maximum relevant entries to show")
36698
+ limit: positiveInt(6, 50).describe("Maximum relevant entries to show"),
36699
+ handoff: external_exports.boolean().optional().default(true).describe("Prepend the compact handoff packet with identity, freshness, directives, traps and file pointers."),
36700
+ budget: positiveInt(1200, 4e3).describe("Token ceiling for the handoff packet when handoff=true.")
35849
36701
  },
35850
36702
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
35851
36703
  },
35852
- async ({ task, limit }) => {
36704
+ async ({ task, limit, handoff, budget }) => {
35853
36705
  const data = readMemory();
36706
+ if (task && handoff) {
36707
+ const sessions = readObservations().slice(-2).map((e) => `${e.session || "cli"}: ${e.summary.slice(0, 80)}`);
36708
+ const compiled = compileContext(data, task, { maxTokens: budget, ...await recallExtras(task), sessions });
36709
+ return { content: [{ type: "text", text: renderContextPackage(compiled) }] };
36710
+ }
35854
36711
  const brief = generateContextBrief(data, { task: task || void 0, limit });
35855
- return { content: [{ type: "text", text: brief }] };
36712
+ if (!handoff) return { content: [{ type: "text", text: brief }] };
36713
+ const packet = buildHandoffBrief(data, process.cwd(), { task: task || void 0, maxTokens: budget });
36714
+ return { content: [{ type: "text", text: `${packet}
36715
+
36716
+ ${brief}` }] };
36717
+ }
36718
+ );
36719
+ register(
36720
+ "context_compile",
36721
+ {
36722
+ title: "Compile Task Context",
36723
+ description: "Compile a task into a tiny context packet: directives, constraints, relevant memory, decisions, retrieval queries, hydrate keys, files and sessions. Deterministic, zero LLM, feedback-aware. Prefer this over context_brief when a task is known.",
36724
+ inputSchema: {
36725
+ task: requiredText("task", 1e3).describe("Current agent task or question"),
36726
+ budget: positiveInt(200, 6e3).describe("Token ceiling for the compiled packet")
36727
+ },
36728
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
36729
+ },
36730
+ async ({ task, budget }) => {
36731
+ const data = readMemory();
36732
+ const sessions = readObservations().slice(-2).map((e) => `${e.session || "cli"}: ${e.summary.slice(0, 80)}`);
36733
+ const compiled = compileContext(data, task, { maxTokens: budget, ...await recallExtras(task), sessions });
36734
+ return { content: [{ type: "text", text: renderContextPackage(compiled) }] };
36735
+ }
36736
+ );
36737
+ register(
36738
+ "context_hydrate",
36739
+ {
36740
+ title: "Hydrate Compressed Context",
36741
+ description: "Expand hydrate keys emitted by context_compile into full memory entries. Layer 2 of progressive disclosure.",
36742
+ inputSchema: {
36743
+ keys: external_exports.array(requiredText("key", 200)).min(1).max(20).describe("Keys or ids from context_compile's Hydrate section")
36744
+ },
36745
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
36746
+ },
36747
+ async ({ keys }) => {
36748
+ const data = readMemory();
36749
+ const entries = fetchEntriesByIds(data, splitIds(keys.join(",")));
36750
+ if (entries.length === 0) return noMatches(keys.join(","));
36751
+ bumpAccessed(entries.map((e) => e.id));
36752
+ const formatted = entries.map((e) => `[${e.category}] ${e.key} (${e.id})
36753
+ ${e.content}
36754
+ File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}`).join("\n\n");
36755
+ return { content: [{ type: "text", text: `Hydrated ${entries.length} ${entries.length === 1 ? "entry" : "entries"}:
36756
+
36757
+ ${formatted}` }] };
35856
36758
  }
35857
36759
  );
35858
- server2.registerTool(
36760
+ register(
35859
36761
  "context_generate",
35860
36762
  {
35861
36763
  title: "Generate Full Context",
@@ -35872,7 +36774,7 @@ ${files}` : "";
35872
36774
  return { content: [{ type: "text", text: brief }] };
35873
36775
  }
35874
36776
  );
35875
- server2.registerTool(
36777
+ register(
35876
36778
  "context_diff",
35877
36779
  {
35878
36780
  title: "Context Diff",
@@ -35889,14 +36791,14 @@ ${files}` : "";
35889
36791
  return { content: [{ type: "text", text: diff }] };
35890
36792
  }
35891
36793
  );
35892
- server2.registerTool(
36794
+ register(
35893
36795
  "context_focus",
35894
36796
  {
35895
36797
  title: "Focus Context for Task",
35896
36798
  description: "Hyper-focused context for a specific task: relevant entries + related files + code referencing the symbol + existing tests. Zero LLM.",
35897
36799
  inputSchema: {
35898
- task: external_exports.string().describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
35899
- limit: external_exports.number().optional().default(6).describe("Maximum memory entries to include")
36800
+ task: requiredText("task", 500).describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
36801
+ limit: positiveInt(6, 50).describe("Maximum memory entries to include")
35900
36802
  },
35901
36803
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
35902
36804
  },
@@ -35907,7 +36809,7 @@ ${files}` : "";
35907
36809
  return { content: [{ type: "text", text: focused }] };
35908
36810
  }
35909
36811
  );
35910
- server2.registerTool(
36812
+ register(
35911
36813
  "context_health",
35912
36814
  {
35913
36815
  title: "Memory Health Audit",
@@ -35922,7 +36824,7 @@ ${files}` : "";
35922
36824
  return { content: [{ type: "text", text: markdown }] };
35923
36825
  }
35924
36826
  );
35925
- server2.registerTool(
36827
+ register(
35926
36828
  "context_export",
35927
36829
  {
35928
36830
  title: "Export Memory as Markdown",
@@ -35938,7 +36840,7 @@ ${files}` : "";
35938
36840
  return { content: [{ type: "text", text: exported }] };
35939
36841
  }
35940
36842
  );
35941
- server2.registerTool(
36843
+ register(
35942
36844
  "memory_backup",
35943
36845
  {
35944
36846
  title: "Backup Memory",
@@ -35947,17 +36849,17 @@ ${files}` : "";
35947
36849
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
35948
36850
  },
35949
36851
  async () => {
35950
- if (!existsSync12(MEMORY_FILE)) {
36852
+ if (!existsSync15(MEMORY_FILE)) {
35951
36853
  return { content: [{ type: "text", text: "No memory file to backup" }] };
35952
36854
  }
35953
- const backupDir = join7(MEMORY_DIR, "backups");
35954
- if (!existsSync12(backupDir)) mkdirSync3(backupDir, { recursive: true });
36855
+ const backupDir = join8(MEMORY_DIR, "backups");
36856
+ if (!existsSync15(backupDir)) mkdirSync6(backupDir, { recursive: true });
35955
36857
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
35956
- const backupFile = join7(backupDir, `memory-${timestamp}.toon`);
36858
+ const backupFile = join8(backupDir, `memory-${timestamp}.toon`);
35957
36859
  copyFileSync(MEMORY_FILE, backupFile);
35958
36860
  let archiveBackup = "";
35959
- if (existsSync12(ARCHIVE_FILE)) {
35960
- const archiveBackupFile = join7(backupDir, `archive-${timestamp}.toon`);
36861
+ if (existsSync15(ARCHIVE_FILE)) {
36862
+ const archiveBackupFile = join8(backupDir, `archive-${timestamp}.toon`);
35961
36863
  copyFileSync(ARCHIVE_FILE, archiveBackupFile);
35962
36864
  archiveBackup = `
35963
36865
  \u{1F4E6} Archive backed up`;
@@ -35966,20 +36868,20 @@ ${files}` : "";
35966
36868
  for (const old of backups.slice(10)) {
35967
36869
  try {
35968
36870
  const { unlinkSync: unlinkSync3 } = __require("fs");
35969
- unlinkSync3(join7(backupDir, old));
36871
+ unlinkSync3(join8(backupDir, old));
35970
36872
  } catch {
35971
36873
  }
35972
36874
  }
35973
36875
  return {
35974
36876
  content: [{
35975
36877
  type: "text",
35976
- text: `\u{1F4BE} Memory backed up to ${basename(backupFile)}${archiveBackup}
36878
+ text: `\u{1F4BE} Memory backed up to ${basename3(backupFile)}${archiveBackup}
35977
36879
  \u{1F4E6} ${backups.length} backup(s) retained`
35978
36880
  }]
35979
36881
  };
35980
36882
  }
35981
36883
  );
35982
- server2.registerTool(
36884
+ register(
35983
36885
  "memory_primer",
35984
36886
  {
35985
36887
  title: "System Primer",
@@ -35994,14 +36896,14 @@ ${files}` : "";
35994
36896
  return { content: [{ type: "text", text: primer }] };
35995
36897
  }
35996
36898
  );
35997
- server2.registerTool(
36899
+ register(
35998
36900
  "memory_compress",
35999
36901
  {
36000
36902
  title: "Compress Memory Entries",
36001
36903
  description: "LLM-powered compression: select entries to compress into one concise entry. The agent (YOU) reads the entries, writes a compressed summary, then calls memory_remember to save it. Two-step dance: this tool provides context, you provide intelligence.",
36002
36904
  inputSchema: {
36003
36905
  query: external_exports.string().optional().default("").describe("Search query to find entries to compress (e.g. 'auth bug fixes'). Empty = show lowest-quality entries."),
36004
- count: external_exports.number().optional().default(3).describe("Number of entries to compress (2-10). Default: 3."),
36906
+ count: positiveInt(3, 10).describe("Number of entries to compress (2-10). Default: 3."),
36005
36907
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all).")
36006
36908
  },
36007
36909
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
@@ -36066,7 +36968,7 @@ ${files}` : "";
36066
36968
  return { content: [{ type: "text", text: prompt }] };
36067
36969
  }
36068
36970
  );
36069
- server2.registerTool(
36971
+ register(
36070
36972
  "memory_export_gist",
36071
36973
  {
36072
36974
  title: "Export to GitHub Gist",
@@ -36086,10 +36988,10 @@ ${files}` : "";
36086
36988
  }]
36087
36989
  };
36088
36990
  }
36089
- if (!existsSync12(MEMORY_FILE)) {
36991
+ if (!existsSync15(MEMORY_FILE)) {
36090
36992
  return { content: [{ type: "text", text: "No memory file to export." }] };
36091
36993
  }
36092
- const data = readFileSync10(MEMORY_FILE, "utf-8");
36994
+ const data = readFileSync13(MEMORY_FILE, "utf-8");
36093
36995
  const desc = description || `toon-memory backup ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`;
36094
36996
  try {
36095
36997
  const resp = await fetch("https://api.github.com/gists", {
@@ -36127,13 +37029,13 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
36127
37029
  }
36128
37030
  }
36129
37031
  );
36130
- server2.registerTool(
37032
+ register(
36131
37033
  "memory_import_gist",
36132
37034
  {
36133
37035
  title: "Import from GitHub Gist",
36134
37036
  description: "Import memory from a GitHub Gist. Merges entries (keeps newer dates, combines tags). Requires GITHUB_TOKEN env var.",
36135
37037
  inputSchema: {
36136
- gist_id: external_exports.string().describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
37038
+ gist_id: requiredText("gist_id", 300).describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
36137
37039
  merge: external_exports.boolean().optional().default(true).describe("If true, merge with existing memory. If false, replace entirely.")
36138
37040
  },
36139
37041
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
@@ -36177,7 +37079,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
36177
37079
  }]
36178
37080
  };
36179
37081
  }
36180
- const localData = existsSync12(MEMORY_FILE) ? readFileSync10(MEMORY_FILE, "utf-8") : "version: 1\nentries[0|]\n";
37082
+ const localData = existsSync15(MEMORY_FILE) ? readFileSync13(MEMORY_FILE, "utf-8") : "version: 1\nentries[0|]\n";
36181
37083
  const localEntries = parseEntries(localData);
36182
37084
  const remoteEntries = parseEntries(remoteData);
36183
37085
  const localByKey = new Map(localEntries.map((e) => [e.key, e]));
@@ -36229,7 +37131,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
36229
37131
  }
36230
37132
  }
36231
37133
  );
36232
- server2.registerTool(
37134
+ register(
36233
37135
  "memory_export_global",
36234
37136
  {
36235
37137
  title: "Export to Global Memory",
@@ -36242,7 +37144,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
36242
37144
  async ({ target }) => {
36243
37145
  const dest = target || GLOBAL_FILE;
36244
37146
  const data = readMemory();
36245
- mkdirSync3(dirname(dest), { recursive: true });
37147
+ mkdirSync6(dirname4(dest), { recursive: true });
36246
37148
  safeWrite(dest, data);
36247
37149
  const count = parseEntries(data).length;
36248
37150
  return {
@@ -36253,7 +37155,7 @@ Import them elsewhere with memory_import_global.` }]
36253
37155
  };
36254
37156
  }
36255
37157
  );
36256
- server2.registerTool(
37158
+ register(
36257
37159
  "memory_import_global",
36258
37160
  {
36259
37161
  title: "Import Global Memory",
@@ -36266,7 +37168,7 @@ Import them elsewhere with memory_import_global.` }]
36266
37168
  },
36267
37169
  async ({ merge: merge2, source }) => {
36268
37170
  const src = source || GLOBAL_FILE;
36269
- if (!existsSync12(src)) {
37171
+ if (!existsSync15(src)) {
36270
37172
  return {
36271
37173
  content: [{ type: "text", text: `\u274C No global memory at:
36272
37174
  ${src}
@@ -36274,7 +37176,7 @@ Import them elsewhere with memory_import_global.` }]
36274
37176
  Export from another project with memory_export_global, or create the file with a few memory entries first.` }]
36275
37177
  };
36276
37178
  }
36277
- const globalData = readFileSync10(src, "utf-8");
37179
+ const globalData = readFileSync13(src, "utf-8");
36278
37180
  if (!merge2) {
36279
37181
  safeWrite(MEMORY_FILE, globalData);
36280
37182
  const count = parseEntries(globalData).length;
@@ -36294,7 +37196,7 @@ Export from another project with memory_export_global, or create the file with a
36294
37196
  };
36295
37197
  }
36296
37198
  );
36297
- server2.registerTool(
37199
+ register(
36298
37200
  "memory_merge_sessions",
36299
37201
  {
36300
37202
  title: "Merge Session Observations",
@@ -36324,8 +37226,8 @@ Export from another project with memory_export_global, or create the file with a
36324
37226
  }
36325
37227
  const sharedFiles = [...allFiles.entries()].filter(([_2, sessions2]) => sessions2.length >= 2).sort((a, b2) => b2[1].length - a[1].length);
36326
37228
  let observations = [];
36327
- if (existsSync12(OBSERVATIONS_FILE)) {
36328
- const data = readFileSync10(OBSERVATIONS_FILE, "utf-8");
37229
+ if (existsSync15(OBSERVATIONS_FILE)) {
37230
+ const data = readFileSync13(OBSERVATIONS_FILE, "utf-8");
36329
37231
  const sessionIds = new Set(recentSessions.map((s2) => s2.id));
36330
37232
  observations = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
36331
37233
  const p2 = parseToonLine(l);
@@ -36398,14 +37300,14 @@ Export from another project with memory_export_global, or create the file with a
36398
37300
  return { content: [{ type: "text", text: sections.join("\n") }] };
36399
37301
  }
36400
37302
  );
36401
- server2.registerTool(
37303
+ register(
36402
37304
  "memory_graph_path",
36403
37305
  {
36404
37306
  title: "Find Graph Path",
36405
37307
  description: "Find the shortest path between two memory entries in the knowledge graph. Shows how two concepts are connected through related entries.",
36406
37308
  inputSchema: {
36407
- from: external_exports.string().describe("Starting entry key"),
36408
- to: external_exports.string().describe("Target entry key")
37309
+ from: requiredText("from", 200).describe("Starting entry key"),
37310
+ to: requiredText("to", 200).describe("Target entry key")
36409
37311
  },
36410
37312
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
36411
37313
  },
@@ -36463,7 +37365,7 @@ Export from another project with memory_export_global, or create the file with a
36463
37365
  };
36464
37366
  }
36465
37367
  );
36466
- server2.registerTool(
37368
+ register(
36467
37369
  "memory_checkpoint",
36468
37370
  {
36469
37371
  title: "Session Checkpoint",
@@ -36500,10 +37402,10 @@ Branch: ${branch}${fileList}`;
36500
37402
  let existingIdx = -1;
36501
37403
  let existingId = "";
36502
37404
  for (let i = headerIdx + 1; i < lines.length; i++) {
36503
- const line = lines[i];
36504
- if (!line.startsWith(" ") || !line.includes("|")) continue;
36505
- if (line.startsWith(" summaries:")) break;
36506
- const parts = parseToonLine(line);
37405
+ const line2 = lines[i];
37406
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
37407
+ if (line2.startsWith(" summaries:")) break;
37408
+ const parts = parseToonLine(line2);
36507
37409
  if (parts[2] === key) {
36508
37410
  existingIdx = i;
36509
37411
  existingId = parts[0];
@@ -36545,14 +37447,14 @@ ${note}` : ""}`
36545
37447
  };
36546
37448
  }
36547
37449
  );
36548
- server2.registerTool(
37450
+ register(
36549
37451
  "memory_pin",
36550
37452
  {
36551
37453
  title: "Pin Entry",
36552
37454
  description: "Pin a memory entry with priority level (1-5). Higher priority entries appear first in recalls. Default: 1. Useful for critical decisions, project rules, or frequently-needed context.",
36553
37455
  inputSchema: {
36554
- key: external_exports.string().describe("Key or id of the entry to pin"),
36555
- priority: external_exports.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1.")
37456
+ key: requiredText("key", 200).describe("Key or id of the entry to pin"),
37457
+ priority: positiveInt(1, 5).describe("Priority level 1-5 (5 = highest). Default: 1.")
36556
37458
  },
36557
37459
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
36558
37460
  },
@@ -36566,10 +37468,10 @@ ${note}` : ""}`
36566
37468
  const clampedPriority = Math.max(1, Math.min(5, Math.round(priority)));
36567
37469
  let found = false;
36568
37470
  for (let i = headerIdx + 1; i < lines.length; i++) {
36569
- const line = lines[i];
36570
- if (!line.startsWith(" ") || !line.includes("|")) continue;
36571
- if (line.startsWith(" summaries:")) break;
36572
- const parts = parseToonLine(line);
37471
+ const line2 = lines[i];
37472
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
37473
+ if (line2.startsWith(" summaries:")) break;
37474
+ const parts = parseToonLine(line2);
36573
37475
  if (parts[0] === key || parts[2] === key) {
36574
37476
  while (parts.length < 14) parts.push("");
36575
37477
  parts[13] = String(clampedPriority);
@@ -36585,13 +37487,13 @@ ${note}` : ""}`
36585
37487
  return { content: [{ type: "text", text: `\u{1F4CC}${clampedPriority > 1 ? clampedPriority : ""} Pinned "${key}" at priority ${clampedPriority}. It will now appear first in recalls.` }] };
36586
37488
  }
36587
37489
  );
36588
- server2.registerTool(
37490
+ register(
36589
37491
  "memory_unpin",
36590
37492
  {
36591
37493
  title: "Unpin Entry",
36592
37494
  description: "Remove the pin from a memory entry so it returns to normal ranking.",
36593
37495
  inputSchema: {
36594
- key: external_exports.string().describe("Key or id of the entry to unpin")
37496
+ key: requiredText("key", 200).describe("Key or id of the entry to unpin")
36595
37497
  },
36596
37498
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
36597
37499
  },
@@ -36604,10 +37506,10 @@ ${note}` : ""}`
36604
37506
  }
36605
37507
  let found = false;
36606
37508
  for (let i = headerIdx + 1; i < lines.length; i++) {
36607
- const line = lines[i];
36608
- if (!line.startsWith(" ") || !line.includes("|")) continue;
36609
- if (line.startsWith(" summaries:")) break;
36610
- const parts = parseToonLine(line);
37509
+ const line2 = lines[i];
37510
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
37511
+ if (line2.startsWith(" summaries:")) break;
37512
+ const parts = parseToonLine(line2);
36611
37513
  if (parts[0] === key || parts[2] === key) {
36612
37514
  if (parts.length > 13) {
36613
37515
  parts[13] = "0";
@@ -36624,20 +37526,74 @@ ${note}` : ""}`
36624
37526
  return { content: [{ type: "text", text: `Unpinned "${key}". It will now use normal ranking.` }] };
36625
37527
  }
36626
37528
  );
36627
- server2.registerTool(
37529
+ register(
37530
+ "memory_feedback",
37531
+ {
37532
+ title: "Feedback on recalled memory",
37533
+ description: "Tell toon-memory whether a recalled entry was useful, irrelevant, outdated or wrong. Explicit feedback adjusts learned utility; 'wrong' also flags evidence as conflict. Use this after acting on a recalled memory.",
37534
+ inputSchema: {
37535
+ key: requiredText("key", 200).describe("Key or id of the entry you used"),
37536
+ signal: external_exports.enum(["useful", "irrelevant", "outdated", "wrong"]).describe("useful | irrelevant | outdated | wrong"),
37537
+ task: external_exports.string().trim().max(500).optional().describe("Short description of the task where the memory was used")
37538
+ },
37539
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
37540
+ },
37541
+ async ({ key, signal, task }) => {
37542
+ const data = readMemory();
37543
+ const entry = parseEntries(data).find((e) => e.key === key || e.id === key);
37544
+ if (!entry) {
37545
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
37546
+ }
37547
+ appendFeedback({ key: entry.key, signal, source: "explicit", task: task || "" });
37548
+ if (signal === "wrong") markWrong(entry.key);
37549
+ const utility = utilityMap().get(entry.key) || 0;
37550
+ return {
37551
+ content: [{
37552
+ type: "text",
37553
+ text: `\u{1F4E3} Feedback recorded: ${entry.key} \u2192 ${signal}. Learned utility: ${utility.toFixed(2)}${signal === "wrong" ? " (evidence flagged as conflict)" : ""}.`
37554
+ }]
37555
+ };
37556
+ }
37557
+ );
37558
+ register(
37559
+ "memory_edges",
37560
+ {
37561
+ title: "Typed memory edges",
37562
+ description: "List or rebuild typed edges in edges.toon. Edges are derived from explicit links and feedback; spread activation is opt-in via config.graph.activation.",
37563
+ inputSchema: {
37564
+ action: external_exports.enum(["list", "rebuild"]).optional().default("list").describe("list shows current edges; rebuild derives them from data.toon and feedback.toon"),
37565
+ limit: positiveInt(20, 200).describe("Maximum edges to list")
37566
+ },
37567
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
37568
+ },
37569
+ async ({ action, limit }) => {
37570
+ if (action === "rebuild") {
37571
+ const count = rebuildEdges(readMemory(), readFeedback());
37572
+ return { content: [{ type: "text", text: `Rebuilt ${count} typed edge(s) in edges.toon.` }] };
37573
+ }
37574
+ const edges = readEdges().slice(0, limit);
37575
+ if (edges.length === 0) {
37576
+ return { content: [{ type: "text", text: 'No typed edges yet. Run memory_edges(action="rebuild").' }] };
37577
+ }
37578
+ const text = edges.map((e) => `${e.from} -[${e.type} ${e.weight.toFixed(2)}]-> ${e.to} (${e.ts || "unknown"})`).join("\n");
37579
+ return { content: [{ type: "text", text: `${edges.length} typed edge(s):
37580
+ ${text}` }] };
37581
+ }
37582
+ );
37583
+ register(
36628
37584
  "memory_search",
36629
37585
  {
36630
37586
  title: "Unified Search",
36631
37587
  description: "Search memory with combined filters: text query, category, tags, and date range. Returns ranked results.",
36632
37588
  inputSchema: {
36633
- query: external_exports.string().describe("Text to search for"),
37589
+ query: requiredText("query", 500).describe("Text to search for"),
36634
37590
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
36635
37591
  tags: external_exports.string().optional().default("").describe("Semicolon-separated tags; entry must have ALL specified tags"),
36636
37592
  from_date: external_exports.string().optional().default("").describe("Start date filter (YYYY-MM-DD or relative like 7d)"),
36637
37593
  to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
36638
- limit: external_exports.number().optional().default(6).describe("Maximum entries to return"),
37594
+ limit: positiveInt(6, 200).describe("Maximum entries to return"),
36639
37595
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
36640
- hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
37596
+ hops: positiveInt(1, 3).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
36641
37597
  compact: external_exports.boolean().optional().default(false).describe("Token-efficient output"),
36642
37598
  budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
36643
37599
  bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
@@ -36645,7 +37601,7 @@ ${note}` : ""}`
36645
37601
  rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
36646
37602
  as_of: external_exports.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date.")
36647
37603
  },
36648
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
37604
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
36649
37605
  },
36650
37606
  async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
36651
37607
  const data = readMemory();
@@ -36662,11 +37618,10 @@ ${note}` : ""}`
36662
37618
  sessionFiles,
36663
37619
  path_scope: path_scope || void 0,
36664
37620
  rrf,
37621
+ ...await recallExtras(query),
36665
37622
  asOf: as_of || void 0
36666
37623
  });
36667
- if (detail.entries.length === 0) {
36668
- return { content: [{ type: "text", text: `No results found for "${query}"` }] };
36669
- }
37624
+ if (detail.entries.length === 0) return noMatches(query);
36670
37625
  bumpAccessed(detail.entries.map((e) => e.id));
36671
37626
  if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
36672
37627
  const formatted2 = renderCompact(detail.entries, {
@@ -36703,15 +37658,15 @@ ${formatted}` }]
36703
37658
  };
36704
37659
  }
36705
37660
  );
36706
- server2.registerTool(
37661
+ register(
36707
37662
  "memory_tag",
36708
37663
  {
36709
37664
  title: "Batch Tag Operations",
36710
37665
  description: "Batch add, remove, or set tags on one or more memory entries by key or id.",
36711
37666
  inputSchema: {
36712
37667
  action: external_exports.enum(["add", "remove", "set"]).describe("'add': merge tags (union). 'remove': remove specified tags. 'set': replace all tags."),
36713
- tags: external_exports.string().describe("Semicolon-separated tags to apply"),
36714
- ids: external_exports.string().describe("Comma or space-separated entry keys or IDs to modify")
37668
+ tags: requiredText("tags", 300).describe("Semicolon-separated tags to apply"),
37669
+ ids: requiredText("ids", 1e3).describe("Comma, semicolon or space-separated entry keys or IDs to modify")
36715
37670
  },
36716
37671
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
36717
37672
  },
@@ -36722,7 +37677,7 @@ ${formatted}` }]
36722
37677
  if (headerIdx === -1) {
36723
37678
  return { content: [{ type: "text", text: "No entries in memory." }] };
36724
37679
  }
36725
- const targetIds = ids.split(/[\s,]+/).filter(Boolean);
37680
+ const targetIds = splitIds(ids);
36726
37681
  const targetSet = new Set(targetIds);
36727
37682
  const tagsToApply = tags.split(";").map((t) => t.trim()).filter(Boolean);
36728
37683
  if (tagsToApply.length === 0) {
@@ -36731,10 +37686,10 @@ ${formatted}` }]
36731
37686
  let modified = 0;
36732
37687
  const modifiedKeys = [];
36733
37688
  for (let i = headerIdx + 1; i < lines.length; i++) {
36734
- const line = lines[i];
36735
- if (!line.startsWith(" ") || !line.includes("|")) continue;
36736
- if (line.startsWith(" summaries:")) break;
36737
- const parts = parseToonLine(line);
37689
+ const line2 = lines[i];
37690
+ if (!line2.startsWith(" ") || !line2.includes("|")) continue;
37691
+ if (line2.startsWith(" summaries:")) break;
37692
+ const parts = parseToonLine(line2);
36738
37693
  const entryId = parts[0];
36739
37694
  const entryKey = parts[2];
36740
37695
  if (!targetSet.has(entryId) && !targetSet.has(entryKey)) continue;
@@ -36767,14 +37722,14 @@ ${formatted}` }]
36767
37722
  };
36768
37723
  }
36769
37724
  );
36770
- server2.registerTool(
37725
+ register(
36771
37726
  "memory_reflect",
36772
37727
  {
36773
37728
  title: "Reflect on Memory",
36774
37729
  description: "Deterministic memory audit (no LLM): tag co-occurrence themes, hub/orphan entries, near-duplicates, contradiction candidates, stale entries, and superseded-but-active entries. Signals what to link, merge, or retire.",
36775
37730
  inputSchema: {
36776
37731
  category: external_exports.string().optional().default("").describe("Restrict analysis to one category (empty = all)."),
36777
- limit: external_exports.number().optional().default(5).describe("Max items per section.")
37732
+ limit: positiveInt(5, 20).describe("Max items per section.")
36778
37733
  },
36779
37734
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
36780
37735
  },
@@ -36899,16 +37854,16 @@ ${formatted}` }]
36899
37854
  return { content: [{ type: "text", text: sections.join("\n") }] };
36900
37855
  }
36901
37856
  );
36902
- server2.registerTool(
37857
+ register(
36903
37858
  "memory_promote",
36904
37859
  {
36905
37860
  title: "Promote Observations",
36906
37861
  description: "Heuristic auto-promote from the capture log (no LLM). Each observation gets a deterministic confidence score; high-confidence ones promote as active entries, low-confidence (\u2264 minConfidence) become reviewable drafts. Opt-in: run with dryRun: true first.",
36907
37862
  inputSchema: {
36908
37863
  dryRun: external_exports.boolean().optional().default(true).describe("If true, only preview what would be promoted (no writes)."),
36909
- minConfidence: external_exports.number().optional().default(0.65).describe("Observations at or below this confidence become drafts; above it become active entries."),
36910
- max: external_exports.number().optional().default(5).describe("Maximum observations to promote."),
36911
- days: external_exports.number().optional().default(7).describe("Only consider observations from the last N days.")
37864
+ minConfidence: external_exports.coerce.number().min(0).max(1).optional().default(0.65).describe("Observations at or below this confidence become drafts; above it become active entries."),
37865
+ max: positiveInt(5, 50).describe("Maximum observations to promote."),
37866
+ days: positiveInt(7, 365).describe("Only consider observations from the last N days.")
36912
37867
  },
36913
37868
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
36914
37869
  },
@@ -37018,7 +37973,7 @@ Drafts are hidden from recalls until promoted \u2014 use memory_forget(key, acti
37018
37973
  };
37019
37974
  }
37020
37975
  );
37021
- K3(
37976
+ if (expertMode) K3(
37022
37977
  server2,
37023
37978
  "memory_visualize",
37024
37979
  {
@@ -47702,11 +48657,11 @@ function buildViewerData() {
47702
48657
  }
47703
48658
 
47704
48659
  // src/viewer/html.ts
47705
- import { readFileSync as readFileSync11 } from "fs";
47706
- import { resolve, dirname as dirname2 } from "path";
48660
+ import { readFileSync as readFileSync14 } from "fs";
48661
+ import { resolve, dirname as dirname5 } from "path";
47707
48662
  import { fileURLToPath } from "url";
47708
48663
  function readViewerAsset(name) {
47709
- const dir = dirname2(fileURLToPath(import.meta.url));
48664
+ const dir = dirname5(fileURLToPath(import.meta.url));
47710
48665
  const candidates = [
47711
48666
  resolve(dir, `../src/viewer/${name}`),
47712
48667
  resolve(dir, `../../src/viewer/${name}`),
@@ -47714,7 +48669,7 @@ function readViewerAsset(name) {
47714
48669
  ];
47715
48670
  for (const p2 of candidates) {
47716
48671
  try {
47717
- return readFileSync11(p2, "utf-8");
48672
+ return readFileSync14(p2, "utf-8");
47718
48673
  } catch {
47719
48674
  }
47720
48675
  }
@@ -48708,25 +49663,82 @@ function registerResources(server2) {
48708
49663
  return { contents: [{ uri: uri.href, text: primer }] };
48709
49664
  }
48710
49665
  );
48711
- const viewerResource = Lk({
48712
- uri: "ui://viewer",
48713
- content: { type: "rawHtml", htmlString: generateHtml(buildViewerData()) },
48714
- encoding: "text",
48715
- adapters: { mcpApps: { enabled: true } }
48716
- });
48717
49666
  N3(
48718
49667
  server2,
48719
49668
  "Memory Graph Viewer",
48720
- viewerResource.resource.uri,
49669
+ "ui://viewer",
48721
49670
  { description: "Interactive memory graph viewer (D3.js force-directed graph with stats, timeline, detail panel)" },
48722
- async () => ({ contents: [viewerResource.resource] })
49671
+ async (uri) => {
49672
+ const viewerResource = Lk({
49673
+ uri: "ui://viewer",
49674
+ content: { type: "rawHtml", htmlString: generateHtml(buildViewerData()) },
49675
+ encoding: "text",
49676
+ adapters: { mcpApps: { enabled: true } }
49677
+ });
49678
+ return { contents: [{ ...viewerResource.resource, uri: uri.href }] };
49679
+ }
49680
+ );
49681
+ }
49682
+
49683
+ // src/mcp/prompts.ts
49684
+ init_graph();
49685
+ function registerPrompts(server2) {
49686
+ server2.registerPrompt(
49687
+ "summarize_project_context",
49688
+ {
49689
+ title: "Summarize Project Context",
49690
+ description: "Analyze the current TOON memory state and generate a compact summary of project knowledge.",
49691
+ argsSchema: { intent: external_exports.string().optional().describe("Optional focus area (e.g. 'auth', 'database')") }
49692
+ },
49693
+ ({ intent }) => {
49694
+ const data = readMemory();
49695
+ const entries = parseEntries(data);
49696
+ const byCategory = {};
49697
+ for (const e of entries) {
49698
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1;
49699
+ }
49700
+ const total = entries.length;
49701
+ let summary = `This project has ${total} memory entr${total === 1 ? "y" : "ies"}`;
49702
+ if (byCategory.decision) summary += `, ${byCategory.decision} decision${byCategory.decision === 1 ? "" : "s"}`;
49703
+ if (byCategory.pattern) summary += `, ${byCategory.pattern} pattern${byCategory.pattern === 1 ? "" : "s"}`;
49704
+ if (byCategory.bug) summary += `, ${byCategory.bug} bug${byCategory.bug === 1 ? "" : "s"}`;
49705
+ if (byCategory.knowledge) summary += `, ${byCategory.knowledge} knowledge entr${byCategory.knowledge === 1 ? "y" : "ies"}`;
49706
+ if (byCategory.architecture) summary += `, ${byCategory.architecture} architecture note${byCategory.architecture === 1 ? "" : "s"}`;
49707
+ summary += ".";
49708
+ let filtered = entries;
49709
+ if (intent) {
49710
+ const q2 = intent.toLowerCase();
49711
+ filtered = entries.filter(
49712
+ (e) => e.key.toLowerCase().includes(q2) || e.content.toLowerCase().includes(q2) || e.tags.some((t) => t.toLowerCase().includes(q2))
49713
+ );
49714
+ }
49715
+ const recent = [...filtered].sort((a, b2) => b2.date.localeCompare(a.date)).slice(0, 5);
49716
+ let detail = recent.length > 0 ? "\n\nMost relevant entries:\n" + recent.map(
49717
+ (e) => ` [${e.category}] ${e.key}: ${e.content.slice(0, 100)}`
49718
+ ).join("\n") : "";
49719
+ return {
49720
+ messages: [{
49721
+ role: "user",
49722
+ content: { type: "text", text: summary + detail }
49723
+ }]
49724
+ };
49725
+ }
48723
49726
  );
48724
49727
  }
48725
49728
 
48726
49729
  // src/mcp/server.ts
49730
+ var INSTRUCTIONS = [
49731
+ "toon-memory: at task start call context_compile(task=...) and hydrate only the keys you need.",
49732
+ "Before reading files, call memory_recall(query=<path or concept>).",
49733
+ "When recalled memory was useful or wrong, call memory_feedback(key=..., signal=...).",
49734
+ "Save decisions, directives and resolved bugs with memory_remember."
49735
+ ].join(" ");
48727
49736
  var server = new McpServer(
48728
- { name: "toon-memory", version: "4.3.5" },
48729
- { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
49737
+ { name: "toon-memory", version: "4.4.0" },
49738
+ {
49739
+ instructions: INSTRUCTIONS,
49740
+ capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } }
49741
+ }
48730
49742
  );
48731
49743
  var s = server.server;
48732
49744
  s.setRequestHandler(InitializeRequestSchema, async (request) => {
@@ -48737,12 +49749,13 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
48737
49749
  return {
48738
49750
  protocolVersion,
48739
49751
  capabilities: s.getCapabilities(),
48740
- serverInfo: { name: "toon-memory", version: "4.3.5" },
49752
+ serverInfo: { name: "toon-memory", version: "4.4.0" },
48741
49753
  ...s._instructions && { instructions: s._instructions }
48742
49754
  };
48743
49755
  });
48744
49756
  registerResources(server);
48745
49757
  registerTools(server);
49758
+ registerPrompts(server);
48746
49759
  try {
48747
49760
  pruneExpiredEntries();
48748
49761
  } catch {