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