toon-memory 2.4.5 → 2.5.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 +192 -41
- package/bin/toon-memory.js +17 -14
- package/dist/cli/setup.js +83 -125
- package/mcp/server.js +226 -33
- package/package.json +8 -2
- package/src/bin/toon-memory.ts +17 -14
- package/src/cli/setup.ts +93 -145
- package/src/lib/quality.ts +221 -0
- package/src/mcp/server.ts +98 -31
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.0",
|
|
4
4
|
"description": "MCP server giving AI coding agents offline, token-efficient persistent memory — recall decisions, patterns, and bugs across sessions with 68.5% fewer tokens than re-reading context. No LLM, no server; works with 15+ agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -20,16 +20,22 @@
|
|
|
20
20
|
"build": "npm run build:bin && npm run build:mcp && npm run build:cli",
|
|
21
21
|
"build:bin": "esbuild src/bin/toon-memory.ts --platform=node --format=esm --outfile=bin/toon-memory.js",
|
|
22
22
|
"build:mcp": "esbuild src/mcp/server.ts --bundle --platform=node --format=esm --outfile=mcp/server.js",
|
|
23
|
-
"build:cli": "esbuild src/cli/setup.ts --bundle --platform=node --format=esm --outfile=dist/cli/setup.js && esbuild src/cli/toon-memory.ts --bundle --platform=node --format=esm --outfile=dist/cli/toon-memory.js && esbuild src/cli/capture.ts --bundle --platform=node --format=esm --outfile=dist/cli/capture.js && esbuild src/cli/session-start.ts --bundle --platform=node --format=esm --outfile=dist/cli/session-start.js",
|
|
23
|
+
"build:cli": "esbuild src/cli/setup.ts --bundle --platform=node --format=esm --packages=external --outfile=dist/cli/setup.js && esbuild src/cli/toon-memory.ts --bundle --platform=node --format=esm --outfile=dist/cli/toon-memory.js && esbuild src/cli/capture.ts --bundle --platform=node --format=esm --outfile=dist/cli/capture.js && esbuild src/cli/session-start.ts --bundle --platform=node --format=esm --outfile=dist/cli/session-start.js",
|
|
24
24
|
"test": "vitest run",
|
|
25
25
|
"test:watch": "vitest",
|
|
26
26
|
"bench": "node scripts/benchmark-toon.mjs",
|
|
27
27
|
"bench:impact": "node scripts/benchmark-impact.mjs",
|
|
28
|
+
"inspect": "npm run build && npx @modelcontextprotocol/inspector node bin/toon-memory.js mcp",
|
|
28
29
|
"prepublishOnly": "npm run build && npm test"
|
|
29
30
|
},
|
|
30
31
|
"dependencies": {
|
|
32
|
+
"@ffmpeg-installer/ffmpeg": "^1.1.0",
|
|
33
|
+
"@inquirer/prompts": "^8.5.2",
|
|
31
34
|
"@modelcontextprotocol/server": "^2.0.0-beta.3",
|
|
32
35
|
"@toon-format/toon": "^2.3.0",
|
|
36
|
+
"ffmpeg-static": "^5.3.0",
|
|
37
|
+
"hyperframes": "^0.7.59",
|
|
38
|
+
"yauzl": "^3.4.0",
|
|
33
39
|
"zod": "^4.4.3"
|
|
34
40
|
},
|
|
35
41
|
"devDependencies": {
|
package/src/bin/toon-memory.ts
CHANGED
|
@@ -18,26 +18,29 @@ function getVersion(): string {
|
|
|
18
18
|
const HELP = `toon-memory — MCP memory server for AI coding agents
|
|
19
19
|
|
|
20
20
|
Usage:
|
|
21
|
-
toon-memory <command> [
|
|
21
|
+
toon-memory <command> [options]
|
|
22
22
|
|
|
23
23
|
Commands:
|
|
24
|
-
init [local|global]
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
24
|
+
init [--agent <name>...] [--scope local|global]
|
|
25
|
+
Install memory tools + hooks
|
|
26
|
+
Without --agent: interactive agent selection
|
|
27
|
+
With --agent: non-interactive (default scope: local)
|
|
28
|
+
status Show version, memory count, and agent config status
|
|
29
|
+
stats Show memory statistics
|
|
30
|
+
dump Print memory as injectable markdown (auto-load)
|
|
31
|
+
export [file] Export memory to a TOON/JSON file
|
|
32
|
+
import <file> Import memory from a TOON/JSON file
|
|
33
|
+
watch Watch memory file and re-render on change
|
|
34
|
+
uninstall Remove toon-memory from all agents
|
|
35
|
+
capture <on|off> Enable/disable activity capture hooks
|
|
36
|
+
upgrade Upgrade to the latest version
|
|
34
37
|
|
|
35
38
|
Options:
|
|
36
|
-
-v, --version
|
|
37
|
-
-h, --help
|
|
39
|
+
-v, --version Show version
|
|
40
|
+
-h, --help Show this help
|
|
38
41
|
|
|
39
42
|
MCP mode:
|
|
40
|
-
toon-memory mcp
|
|
43
|
+
toon-memory mcp Run as an MCP server (stdio)
|
|
41
44
|
`
|
|
42
45
|
|
|
43
46
|
if (args[0] === "-v" || args[0] === "--version") {
|
package/src/cli/setup.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, cpSync, unlinkSync, readdirSync, statSync, chmodSync, rmSync } from "fs"
|
|
2
2
|
import { basename, dirname, join } from "path"
|
|
3
3
|
import { fileURLToPath } from "url"
|
|
4
|
-
import {
|
|
4
|
+
import { checkbox, select, confirm } from "@inquirer/prompts"
|
|
5
5
|
import { gzipSync, gunzipSync } from "zlib"
|
|
6
6
|
import { extractProjectDeps } from "../lib/vocab"
|
|
7
7
|
|
|
@@ -791,12 +791,28 @@ function updateMemoryConfig(patch: Record<string, any>): void {
|
|
|
791
791
|
}
|
|
792
792
|
|
|
793
793
|
/**
|
|
794
|
-
*
|
|
794
|
+
* Interactive multi-select for agents using @inquirer/prompts.
|
|
795
|
+
* Returns the selected Agent array.
|
|
796
|
+
*/
|
|
797
|
+
async function promptAgentSelection(agents: Agent[]): Promise<Agent[]> {
|
|
798
|
+
return checkbox({
|
|
799
|
+
message: "¿Qué agentes quieres configurar?",
|
|
800
|
+
choices: agents.map((a) => ({
|
|
801
|
+
name: `${a.name} (${a.format === "none" ? "instrucciones" : a.global ? "local/global" : "solo local"})`,
|
|
802
|
+
value: a,
|
|
803
|
+
checked: true
|
|
804
|
+
}))
|
|
805
|
+
})
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Initialize toon-memory. Behaviour depends on flags and TTY:
|
|
795
810
|
*
|
|
796
|
-
*
|
|
797
|
-
*
|
|
811
|
+
* - `--agent` flag → non-interactive install for the listed agents
|
|
812
|
+
* - No `--agent`, TTY present → interactive checkbox + scope prompt
|
|
813
|
+
* - No `--agent`, no TTY → install for ALL agents (CI fallback)
|
|
798
814
|
*/
|
|
799
|
-
function init(scope
|
|
815
|
+
async function init(scope?: string, agentFilter?: string[]): Promise<void> {
|
|
800
816
|
console.log("\n🧠 toon-memory init\n")
|
|
801
817
|
|
|
802
818
|
installMemoryDir()
|
|
@@ -810,8 +826,43 @@ function init(scope: string = "local"): void {
|
|
|
810
826
|
}
|
|
811
827
|
|
|
812
828
|
const agents = detectAgents()
|
|
813
|
-
|
|
814
|
-
|
|
829
|
+
let selected: Agent[]
|
|
830
|
+
let finalScope = scope || "local"
|
|
831
|
+
|
|
832
|
+
if (agentFilter && agentFilter.length > 0) {
|
|
833
|
+
selected = agents.filter((a) => agentFilter.includes(a.name.toLowerCase()))
|
|
834
|
+
if (selected.length === 0) {
|
|
835
|
+
console.log(`Agentes no encontrados: ${agentFilter.join(", ")}`)
|
|
836
|
+
console.log(`Disponibles: ${agents.map((a) => a.name).join(", ")}`)
|
|
837
|
+
process.exit(1)
|
|
838
|
+
}
|
|
839
|
+
} else if (process.stdin.isTTY) {
|
|
840
|
+
selected = await promptAgentSelection(agents)
|
|
841
|
+
if (selected.length === 0) {
|
|
842
|
+
console.log("\nNo se seleccionaron agentes. Nada instalado.\n")
|
|
843
|
+
return
|
|
844
|
+
}
|
|
845
|
+
finalScope = await select({
|
|
846
|
+
message: "Alcance:",
|
|
847
|
+
choices: [
|
|
848
|
+
{ name: "Local (proyecto)", value: "local" },
|
|
849
|
+
{ name: "Global (~home)", value: "global" }
|
|
850
|
+
],
|
|
851
|
+
default: finalScope as "local" | "global"
|
|
852
|
+
})
|
|
853
|
+
const ok = await confirm({ message: "¿Proceder?", default: true })
|
|
854
|
+
if (!ok) {
|
|
855
|
+
console.log("\nInstalación cancelada.\n")
|
|
856
|
+
return
|
|
857
|
+
}
|
|
858
|
+
} else {
|
|
859
|
+
selected = agents
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
console.log(`\nInstalando (${finalScope}) — ${selected.map((a) => a.name).join(", ")}...\n`)
|
|
863
|
+
|
|
864
|
+
for (const agent of selected) {
|
|
865
|
+
installForAgent(agent, finalScope)
|
|
815
866
|
console.log("")
|
|
816
867
|
}
|
|
817
868
|
|
|
@@ -1503,7 +1554,25 @@ if (args[0] === "uninstall") {
|
|
|
1503
1554
|
}
|
|
1504
1555
|
|
|
1505
1556
|
if (args[0] === "init") {
|
|
1506
|
-
|
|
1557
|
+
const rest = args.slice(1)
|
|
1558
|
+
const agentNames: string[] = []
|
|
1559
|
+
let scope: string | undefined
|
|
1560
|
+
let i = 0
|
|
1561
|
+
while (i < rest.length) {
|
|
1562
|
+
if (rest[i] === "--agent" && rest[i + 1]) {
|
|
1563
|
+
agentNames.push(rest[i + 1].toLowerCase())
|
|
1564
|
+
i += 2
|
|
1565
|
+
} else if (rest[i] === "--scope" && rest[i + 1]) {
|
|
1566
|
+
scope = rest[i + 1]
|
|
1567
|
+
i += 2
|
|
1568
|
+
} else if (rest[i] !== "--agent" && rest[i] !== "--scope") {
|
|
1569
|
+
scope = rest[i]
|
|
1570
|
+
i++
|
|
1571
|
+
} else {
|
|
1572
|
+
i++
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
await init(scope, agentNames.length > 0 ? agentNames : undefined)
|
|
1507
1576
|
process.exit(0)
|
|
1508
1577
|
}
|
|
1509
1578
|
|
|
@@ -1554,17 +1623,15 @@ process.exit(1)
|
|
|
1554
1623
|
|
|
1555
1624
|
/** Minimal usage string for unknown commands (full help lives in the entry point). */
|
|
1556
1625
|
function printUsage(): void {
|
|
1557
|
-
console.log(`Uso: toon-memory <comando> [
|
|
1626
|
+
console.log(`Uso: toon-memory <comando> [opciones]
|
|
1558
1627
|
Comandos: init, status, stats, export, import, watch, uninstall, capture, upgrade, mcp
|
|
1628
|
+
Init: toon-memory init [--agent <nombre> --agent <nombre>...] [--scope local|global]
|
|
1629
|
+
Sin --agent: selector interactivo de agentes y scope.
|
|
1630
|
+
Con --agent: instalación no interactiva (default: scope local).
|
|
1559
1631
|
Opciones: -v/--version, -h/--help
|
|
1560
1632
|
Sin argumentos inicia el instalador interactivo.`)
|
|
1561
1633
|
}
|
|
1562
1634
|
|
|
1563
|
-
/** Promise wrapper around readline question. */
|
|
1564
|
-
function ask(rl: ReturnType<typeof createInterface>, prompt: string): Promise<string> {
|
|
1565
|
-
return new Promise((resolve) => rl.question(prompt, resolve))
|
|
1566
|
-
}
|
|
1567
|
-
|
|
1568
1635
|
/**
|
|
1569
1636
|
* Guided interactive installer: pick agents, choose local vs global scope,
|
|
1570
1637
|
* confirm, then install. Requires a TTY; otherwise prints a non-interactive hint.
|
|
@@ -1572,62 +1639,32 @@ function ask(rl: ReturnType<typeof createInterface>, prompt: string): Promise<st
|
|
|
1572
1639
|
async function interactiveInstall(): Promise<void> {
|
|
1573
1640
|
if (!process.stdin.isTTY) {
|
|
1574
1641
|
console.log("\n🧠 toon-memory — la instalación interactiva requiere una terminal.")
|
|
1575
|
-
console.log("Ejecuta 'toon-memory init [
|
|
1642
|
+
console.log("Ejecuta 'toon-memory init [--agent <nombre>]' para instalación no interactiva.\n")
|
|
1576
1643
|
return
|
|
1577
1644
|
}
|
|
1578
1645
|
|
|
1579
1646
|
const agents = detectAgents()
|
|
1580
|
-
const selected = await
|
|
1581
|
-
if (selected === null) {
|
|
1582
|
-
console.log("\nInstalación cancelada.\n")
|
|
1583
|
-
return
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1647
|
+
const selected = await promptAgentSelection(agents)
|
|
1586
1648
|
if (selected.length === 0) {
|
|
1587
1649
|
console.log("\nNo se seleccionaron agentes. Nada instalado.\n")
|
|
1588
1650
|
return
|
|
1589
1651
|
}
|
|
1590
1652
|
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
const scopeAnswer = (await ask(rl, "Alcance — (1) Local (proyecto) o (2) Global (~home)? [1/2]: ")).trim()
|
|
1599
|
-
if (scopeAnswer === "" || scopeAnswer === "1") {
|
|
1600
|
-
scope = "local"
|
|
1601
|
-
break
|
|
1602
|
-
}
|
|
1603
|
-
if (scopeAnswer === "2") {
|
|
1604
|
-
scope = "global"
|
|
1605
|
-
break
|
|
1606
|
-
}
|
|
1607
|
-
console.log("Escribe 1 (local) o 2 (global).\n")
|
|
1608
|
-
}
|
|
1609
|
-
|
|
1610
|
-
// 3) Confirmation summary
|
|
1611
|
-
console.log("\nSe instalará:")
|
|
1612
|
-
for (const a of selected) {
|
|
1613
|
-
const resolved = scope === "global" && a.global ? "global" : "local"
|
|
1614
|
-
const parts: string[] = []
|
|
1615
|
-
if (a.format !== "none") parts.push("MCP")
|
|
1616
|
-
if (a.needsPlugin) parts.push("plugin")
|
|
1617
|
-
else if (a.needsHooks) parts.push("hooks")
|
|
1618
|
-
if (a.needsInstructions) parts.push("instrucciones")
|
|
1619
|
-
const target = resolved === "global" && a.global ? a.global : a.local || "(instrucciones)"
|
|
1620
|
-
console.log(` • ${a.name} [${resolved}] → ${target}${parts.length ? ` (${parts.join(", ")})` : ""}`)
|
|
1621
|
-
}
|
|
1653
|
+
const scope = await select({
|
|
1654
|
+
message: "Alcance:",
|
|
1655
|
+
choices: [
|
|
1656
|
+
{ name: "Local (proyecto)", value: "local" },
|
|
1657
|
+
{ name: "Global (~home)", value: "global" }
|
|
1658
|
+
]
|
|
1659
|
+
})
|
|
1622
1660
|
|
|
1623
|
-
const
|
|
1624
|
-
if (
|
|
1661
|
+
const ok = await confirm({ message: "¿Proceder?", default: true })
|
|
1662
|
+
if (!ok) {
|
|
1625
1663
|
console.log("\nInstalación cancelada.\n")
|
|
1626
|
-
rl.close()
|
|
1627
1664
|
return
|
|
1628
1665
|
}
|
|
1629
1666
|
|
|
1630
|
-
console.log(`\nInstalando (${scope})...\n`)
|
|
1667
|
+
console.log(`\nInstalando (${scope}) — ${selected.map((a) => a.name).join(", ")}...\n`)
|
|
1631
1668
|
installMemoryDir()
|
|
1632
1669
|
|
|
1633
1670
|
const deps = extractProjectDeps(projectRoot)
|
|
@@ -1645,93 +1682,4 @@ async function interactiveInstall(): Promise<void> {
|
|
|
1645
1682
|
|
|
1646
1683
|
console.log("Done! Restart your agent to use memory tools.")
|
|
1647
1684
|
console.log("Run 'npx toon-memory uninstall' to remove.\n")
|
|
1648
|
-
rl.close()
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
/**
|
|
1652
|
-
* Navigable multi-select checklist rendered in the terminal (no dependencies).
|
|
1653
|
-
* ↑/↓ (or k/j) move the cursor, space toggles a selection, 'a' toggles all,
|
|
1654
|
-
* Enter confirms, 'q'/'c'/Ctrl-C aborts. Requires a TTY.
|
|
1655
|
-
*/
|
|
1656
|
-
async function runAgentChecklist(agents: Agent[]): Promise<Agent[] | null> {
|
|
1657
|
-
const n = agents.length
|
|
1658
|
-
let cursor = 0
|
|
1659
|
-
const selected = new Set<number>()
|
|
1660
|
-
let prevLines = 0
|
|
1661
|
-
|
|
1662
|
-
const render = (): void => {
|
|
1663
|
-
let out = ""
|
|
1664
|
-
if (prevLines > 0) out += `\x1b[${prevLines}A\x1b[J`
|
|
1665
|
-
const lines: string[] = []
|
|
1666
|
-
lines.push("\n🧠 toon-memory installer")
|
|
1667
|
-
lines.push("")
|
|
1668
|
-
lines.push("Agentes detectados:")
|
|
1669
|
-
agents.forEach((a: Agent, i: number) => {
|
|
1670
|
-
const isCursor = i === cursor
|
|
1671
|
-
const isSel = selected.has(i)
|
|
1672
|
-
const box = isSel ? "[x]" : "[ ]"
|
|
1673
|
-
const cur = isCursor ? ">" : " "
|
|
1674
|
-
const hasConfig = a.format !== "none" && ((a.local && existsSync(a.local)) || (a.global && existsSync(a.global)))
|
|
1675
|
-
const indicator = hasConfig ? "✓" : "·"
|
|
1676
|
-
const scopeNote = a.format === "none" ? "(instrucciones)" : a.global ? "(local/global)" : "(solo local)"
|
|
1677
|
-
lines.push(` ${cur} ${box} ${indicator} ${i + 1}. ${a.name} ${scopeNote}`)
|
|
1678
|
-
})
|
|
1679
|
-
lines.push("")
|
|
1680
|
-
lines.push(" ↑/↓ mover · espacio marcar · 'a' todos · Enter confirmar · 'q' salir")
|
|
1681
|
-
process.stdout.write(out + lines.join("\n") + "\n")
|
|
1682
|
-
prevLines = lines.length
|
|
1683
|
-
}
|
|
1684
|
-
|
|
1685
|
-
return new Promise<Agent[] | null>((resolve) => {
|
|
1686
|
-
emitKeypressEvents(process.stdin)
|
|
1687
|
-
process.stdin.setRawMode(true)
|
|
1688
|
-
process.stdin.resume()
|
|
1689
|
-
|
|
1690
|
-
const finish = (result: Agent[] | null): void => {
|
|
1691
|
-
process.stdin.setRawMode(false)
|
|
1692
|
-
process.stdin.removeListener("keypress", onKey)
|
|
1693
|
-
process.stdout.write("\n")
|
|
1694
|
-
resolve(result)
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
|
-
const onKey = (_str: string, key: Key | undefined): void => {
|
|
1698
|
-
if (!key) return
|
|
1699
|
-
if (key.ctrl && key.name === "c") {
|
|
1700
|
-
finish(null)
|
|
1701
|
-
return
|
|
1702
|
-
}
|
|
1703
|
-
switch (key.name) {
|
|
1704
|
-
case "up":
|
|
1705
|
-
case "k":
|
|
1706
|
-
cursor = (cursor - 1 + n) % n
|
|
1707
|
-
break
|
|
1708
|
-
case "down":
|
|
1709
|
-
case "j":
|
|
1710
|
-
cursor = (cursor + 1) % n
|
|
1711
|
-
break
|
|
1712
|
-
case "space":
|
|
1713
|
-
if (selected.has(cursor)) selected.delete(cursor)
|
|
1714
|
-
else selected.add(cursor)
|
|
1715
|
-
break
|
|
1716
|
-
case "a":
|
|
1717
|
-
if (selected.size === n) selected.clear()
|
|
1718
|
-
else for (let i = 0; i < n; i++) selected.add(i)
|
|
1719
|
-
break
|
|
1720
|
-
case "return":
|
|
1721
|
-
finish(agents.filter((_: Agent, i: number) => selected.has(i)))
|
|
1722
|
-
return
|
|
1723
|
-
case "q":
|
|
1724
|
-
case "c":
|
|
1725
|
-
finish(null)
|
|
1726
|
-
return
|
|
1727
|
-
default:
|
|
1728
|
-
render()
|
|
1729
|
-
return
|
|
1730
|
-
}
|
|
1731
|
-
render()
|
|
1732
|
-
}
|
|
1733
|
-
|
|
1734
|
-
process.stdin.on("keypress", onKey)
|
|
1735
|
-
render()
|
|
1736
|
-
})
|
|
1737
1685
|
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quality scoring, merge-dedup, smart recall, and system primer utilities.
|
|
3
|
+
*
|
|
4
|
+
* Pure heuristics — no LLM, no network, no embeddings. These functions
|
|
5
|
+
* power the enhanced memory features: quality-based ranking, automatic
|
|
6
|
+
* deduplication with attribute merging, unified recall, and the system
|
|
7
|
+
* primer (auto-generated knowledge map).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
|
|
11
|
+
|
|
12
|
+
const normalize = (s: string): string =>
|
|
13
|
+
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
14
|
+
|
|
15
|
+
const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
|
16
|
+
|
|
17
|
+
const isExpiredLocal = (ttl: string): boolean => {
|
|
18
|
+
if (!ttl) return false
|
|
19
|
+
const today = new Date().toISOString().split("T")[0]
|
|
20
|
+
return ttl <= today
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const importance = (e: GraphEntry): number => {
|
|
24
|
+
const today = new Date().toISOString().split("T")[0]
|
|
25
|
+
const days =
|
|
26
|
+
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
27
|
+
const recency = Math.max(0, 30 - days) / 30
|
|
28
|
+
const freq = Math.min(1, e.accessed / 5)
|
|
29
|
+
return recency * 0.6 + freq * 0.4
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Quality score for an entry (0..1). Pure heuristics, no LLM.
|
|
34
|
+
* Measures how well-structured and useful a memory entry is.
|
|
35
|
+
*/
|
|
36
|
+
export function qualityScore(tags: string, links: string, content: string, date: string): number {
|
|
37
|
+
let score = 0
|
|
38
|
+
if (tags) {
|
|
39
|
+
const count = tags.split(";").filter(Boolean).length
|
|
40
|
+
score += Math.min(0.3, count * 0.1)
|
|
41
|
+
}
|
|
42
|
+
if (links) {
|
|
43
|
+
const count = links.split(/[\s;]+/).filter(Boolean).length
|
|
44
|
+
score += Math.min(0.2, count * 0.1)
|
|
45
|
+
}
|
|
46
|
+
const len = content.length
|
|
47
|
+
if (len > 20) score += 0.1
|
|
48
|
+
if (len > 60) score += 0.1
|
|
49
|
+
if (len > 150) score += 0.1
|
|
50
|
+
// Recency bonus
|
|
51
|
+
if (date) {
|
|
52
|
+
const days = (Date.now() - new Date(`${date}T00:00:00`).getTime()) / 86400000
|
|
53
|
+
if (days < 7) score += 0.1
|
|
54
|
+
else if (days < 30) score += 0.05
|
|
55
|
+
}
|
|
56
|
+
// Specificity: more unique words → higher score
|
|
57
|
+
const words = content.toLowerCase().split(/\s+/).filter(Boolean)
|
|
58
|
+
const unique = new Set(words)
|
|
59
|
+
const specificity = words.length > 0 ? unique.size / words.length : 0
|
|
60
|
+
score += specificity * 0.1
|
|
61
|
+
return Math.min(1, score)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Merge two entry lines with the same key. Combines tags (union), takes
|
|
66
|
+
* max confidence, updates date if newer, merges links, and recalculates
|
|
67
|
+
* quality. Returns the merged TOON entry line.
|
|
68
|
+
*/
|
|
69
|
+
export function mergeEntries(existingLine: string, newLine: string): string {
|
|
70
|
+
const ep = existingLine.trim().split("|")
|
|
71
|
+
const np = newLine.trim().split("|")
|
|
72
|
+
if (ep.length < 7 || np.length < 7) return newLine
|
|
73
|
+
|
|
74
|
+
const id = ep[0]
|
|
75
|
+
const category = np[1] || ep[1]
|
|
76
|
+
const key = ep[2]
|
|
77
|
+
const content = np[3] || ep[3]
|
|
78
|
+
const file = np[4] || ep[4]
|
|
79
|
+
|
|
80
|
+
// Merge tags (union)
|
|
81
|
+
const existingTags = (ep[5] || "").split(";").map((t) => t.trim()).filter(Boolean)
|
|
82
|
+
const newTags = (np[5] || "").split(";").map((t) => t.trim()).filter(Boolean)
|
|
83
|
+
const mergedTags = [...new Set([...existingTags, ...newTags])].join(";")
|
|
84
|
+
|
|
85
|
+
// Take newer date
|
|
86
|
+
const existingDate = ep[6] || ""
|
|
87
|
+
const newDate = np[6] || ""
|
|
88
|
+
const date = newDate > existingDate ? newDate : existingDate
|
|
89
|
+
|
|
90
|
+
// Take new TTL if provided, otherwise keep existing
|
|
91
|
+
const existingTtl = ep[7] || ""
|
|
92
|
+
const newTtl = np[7] || ""
|
|
93
|
+
const ttl = newTtl || existingTtl
|
|
94
|
+
|
|
95
|
+
// Take max confidence
|
|
96
|
+
const existingConf = ep.length > 11 ? parseFloat(ep[11]) || 0 : 0
|
|
97
|
+
const newConf = np.length > 11 ? parseFloat(np[11]) || 0 : 0
|
|
98
|
+
const confidence = Math.max(existingConf, newConf)
|
|
99
|
+
|
|
100
|
+
// Merge links (union)
|
|
101
|
+
const existingLinks = (ep[9] || "").split(/[\s;]+/).filter(Boolean)
|
|
102
|
+
const newLinks = (np[9] || "").split(/[\s;]+/).filter(Boolean)
|
|
103
|
+
const mergedLinks = [...new Set([...existingLinks, ...newLinks])].join(" ")
|
|
104
|
+
|
|
105
|
+
const quality = qualityScore(mergedTags, mergedLinks, content, date)
|
|
106
|
+
|
|
107
|
+
return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|0|${mergedLinks}|${quality.toFixed(2)}|${confidence}`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Unified recall: BM25 + graph traversal + quality + decay in one call.
|
|
112
|
+
* The LLM calls this at the start of a task to get everything it needs.
|
|
113
|
+
*/
|
|
114
|
+
export function generateSmartRecall(
|
|
115
|
+
data: string,
|
|
116
|
+
intent: string,
|
|
117
|
+
opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void } = {}
|
|
118
|
+
): string {
|
|
119
|
+
const entries = parseEntries(data)
|
|
120
|
+
if (entries.length === 0) return "Memoria vacía."
|
|
121
|
+
|
|
122
|
+
const { adjacency } = buildGraph(entries)
|
|
123
|
+
const bm25 = bm25Scores(entries, intent)
|
|
124
|
+
const cent = centrality(adjacency)
|
|
125
|
+
const limit = opts.limit ?? 8
|
|
126
|
+
const category = opts.category || ""
|
|
127
|
+
|
|
128
|
+
const qTokens = tokenize(intent)
|
|
129
|
+
|
|
130
|
+
const scored = entries
|
|
131
|
+
.filter((e) => {
|
|
132
|
+
if (category && e.category !== category) return false
|
|
133
|
+
if (e.ttl && isExpiredLocal(e.ttl)) return false
|
|
134
|
+
return true
|
|
135
|
+
})
|
|
136
|
+
.map((e) => {
|
|
137
|
+
const text = normalize(
|
|
138
|
+
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
139
|
+
)
|
|
140
|
+
const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t))
|
|
141
|
+
const bm25Score = bm25.get(e.key) || 0
|
|
142
|
+
const centScore = cent.get(e.key) || 0
|
|
143
|
+
const impScore = importance(e)
|
|
144
|
+
const combined =
|
|
145
|
+
bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0)
|
|
146
|
+
return { entry: e, score: combined, matchesQuery }
|
|
147
|
+
})
|
|
148
|
+
.filter((x) => x.score > 0 || x.matchesQuery)
|
|
149
|
+
.sort((a, b) => b.score - a.score)
|
|
150
|
+
.slice(0, limit)
|
|
151
|
+
|
|
152
|
+
if (scored.length === 0) {
|
|
153
|
+
const top = entries
|
|
154
|
+
.filter((e) => !category || e.category === category)
|
|
155
|
+
.sort((a, b) => importance(b) - importance(a))
|
|
156
|
+
.slice(0, limit)
|
|
157
|
+
if (top.length === 0) return "No hay entradas en memoria."
|
|
158
|
+
return renderCompact(top)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (opts.bumpAccess) opts.bumpAccess(scored.map((x) => x.entry.id))
|
|
162
|
+
return renderCompact(scored.map((x) => x.entry))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Generate a system primer: a concise, always-current knowledge map.
|
|
167
|
+
* Regenerates when called (lightweight — no LLM, pure heuristics).
|
|
168
|
+
*/
|
|
169
|
+
export function generateSystemPrimer(data: string): string {
|
|
170
|
+
const entries = parseEntries(data)
|
|
171
|
+
if (entries.length === 0) return "Memoria vacía. No hay entradas guardadas."
|
|
172
|
+
|
|
173
|
+
const byCategory: Record<string, GraphEntry[]> = {}
|
|
174
|
+
for (const e of entries) {
|
|
175
|
+
if (!byCategory[e.category]) byCategory[e.category] = []
|
|
176
|
+
byCategory[e.category].push(e)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const lines: string[] = [
|
|
180
|
+
"=== System Primer ===",
|
|
181
|
+
`Entradas: ${entries.length}`,
|
|
182
|
+
"",
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
// Top entries by importance (global)
|
|
186
|
+
const top = [...entries]
|
|
187
|
+
.sort((a, b) => importance(b) - importance(a))
|
|
188
|
+
.slice(0, 5)
|
|
189
|
+
lines.push("Top memorias:")
|
|
190
|
+
for (const e of top) {
|
|
191
|
+
const quality = qualityScore(
|
|
192
|
+
e.tags.join(";"),
|
|
193
|
+
e.links.join(" "),
|
|
194
|
+
e.content,
|
|
195
|
+
e.date
|
|
196
|
+
)
|
|
197
|
+
const conf = quality >= 0.5 ? "alta" : quality >= 0.3 ? "media" : "baja"
|
|
198
|
+
lines.push(
|
|
199
|
+
` [${e.category}] ${e.key} — ${e.content.slice(0, 80)} (calidad: ${conf})`
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
lines.push("")
|
|
203
|
+
|
|
204
|
+
// Categories
|
|
205
|
+
lines.push("Categorías:")
|
|
206
|
+
for (const [cat, items] of Object.entries(byCategory)) {
|
|
207
|
+
lines.push(` ${cat}: ${items.length}`)
|
|
208
|
+
}
|
|
209
|
+
lines.push("")
|
|
210
|
+
|
|
211
|
+
// Rules (mandatory patterns)
|
|
212
|
+
const patterns = entries.filter((e) => e.category === "pattern")
|
|
213
|
+
if (patterns.length > 0) {
|
|
214
|
+
lines.push("Patrones establecidos:")
|
|
215
|
+
for (const p of patterns.slice(0, 5)) {
|
|
216
|
+
lines.push(` • ${p.key}: ${p.content.slice(0, 100)}`)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return lines.join("\n")
|
|
221
|
+
}
|