toon-memory 4.3.0 → 4.3.1
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.de.md +2 -2
- package/README.es.md +2 -2
- package/README.fr.md +2 -2
- package/README.ja.md +2 -2
- package/README.ko.md +2 -2
- package/README.md +2 -2
- package/README.pt-br.md +2 -2
- package/README.zh.md +2 -2
- package/bin/toon-memory.js +18 -7
- package/dist/cli/setup.js +104 -49
- package/dist/cli/toon-memory.js +12 -3
- package/install.ps1 +25 -15
- package/mcp/server.js +97 -7
- package/package.json +3 -3
- package/src/bin/toon-memory.ts +3 -2
- package/src/cli/config-writer.ts +34 -23
- package/src/cli/entry.ts +11 -0
- package/src/cli/hooks.ts +33 -11
- package/src/cli/opencode-plugin.ts +57 -18
- package/src/cli/toon-memory.ts +4 -3
- package/src/lib/graph.ts +66 -0
- package/src/mcp/tools.ts +56 -7
package/README.de.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
>
|
|
5
|
+
> Die Kontinuitätsebene für KI-Agenten — KI-Agenten sollten dein Projekt nicht jede Sitzung neu lernen müssen.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
|
|
42
42
|
Kannst du dich an diesen Moment erinnern, in dem dein KI-Agent alles aus der Sitzung von gestern vergessen hat? Du erklärst zum dritten Mal dieselbe Architekturentscheidung, und er schlägt immer noch den Ansatz vor, den du bereits abgelehnt hast?
|
|
43
43
|
|
|
44
|
-
**toon-memory löst dieses Problem.** Es
|
|
44
|
+
**toon-memory löst dieses Problem.** Es ist die Kontinuitätsebene für KI-Agenten — ein leichtes System, das das Wissen, die Entscheidungen und die Konventionen deines Projekts zwischen den Sitzungen bewahrt, damit jede Sitzung dort beginnt, wo die letzte endete. 100% lokal und privat, über MCP — kein Cloud, kein Server.
|
|
45
45
|
|
|
46
46
|
📖 **[Dokumentation lesen](https://luiggival08.github.io/toon-memory/)**
|
|
47
47
|
|
package/README.es.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
>
|
|
5
|
+
> La capa de continuidad para agentes de IA — los agentes de IA no deberían tener que reaprender tu proyecto en cada sesión.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
|
|
42
42
|
¿Alguna vez has tenido esa sensación donde tu agente de IA olvida todo de la sesión de ayer? Explicas la misma decisión de arquitectura por tercera vez, y aún así sugiere el enfoque que ya rechazaste?
|
|
43
43
|
|
|
44
|
-
**toon-memory soluciona esto.**
|
|
44
|
+
**toon-memory soluciona esto.** Es la capa de continuidad para agentes de IA — un sistema ligero que conserva el conocimiento, las decisiones y las convenciones de tu proyecto entre sesiones, para que cada sesión empiece donde terminó la anterior. 100% local y privado, vía MCP — sin nube, sin servidor.
|
|
45
45
|
|
|
46
46
|
📖 **[Lee la documentación](https://luiggival08.github.io/toon-memory/)**
|
|
47
47
|
|
package/README.fr.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
>
|
|
5
|
+
> La couche de continuité pour les agents IA — les agents IA ne devraient pas avoir à réapprendre votre projet à chaque session.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
|
|
41
41
|
Vous avez déjà vécu cette situation où votre agent IA oublie tout de la session d'hier ? Vous lui réexpliquez la même décision d'architecture pour la troisième fois, et il propose encore l'approche que vous avez déjà rejetée ?
|
|
42
42
|
|
|
43
|
-
**toon-memory résout ce problème.**
|
|
43
|
+
**toon-memory résout ce problème.** C'est la couche de continuité pour les agents IA — un système léger qui préserve le savoir, les décisions et les conventions de votre projet entre les sessions, pour que chaque session commence là où la précédente s'est arrêtée. 100% local et privé, via MCP — sans cloud, sans serveur.
|
|
44
44
|
|
|
45
45
|
📖 **[Lire la documentation](https://luiggival08.github.io/toon-memory/)**
|
|
46
46
|
|
package/README.ja.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
> AI
|
|
5
|
+
> AIエージェントのための継続性レイヤー — AIエージェントは毎セッションでプロジェクトを学び直すべきではありません。
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
AIエージェントが昨日のセッションの内容を全て忘れてしまう経験はありますか?同じアーキテクチャの意思決定を3回目の説明しても、すでに却下したアプローチを再び提案されてしまう……
|
|
41
41
|
|
|
42
|
-
**toon-memoryはこの問題を解決します。**
|
|
42
|
+
**toon-memoryはこの問題を解決します。** AIエージェントのための継続性レイヤー — セッションをまたいでプロジェクトの知識・決定・規約を保存する軽量システムで、各セッションが前回の終わりから始まります。100% ローカルでプライベート、MCP 経由 — クラウドもサーバーも不要。
|
|
43
43
|
|
|
44
44
|
📖 **[ドキュメントを読む](https://luiggival08.github.io/toon-memory/)**
|
|
45
45
|
|
package/README.ko.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
>
|
|
5
|
+
> AI 에이전트를 위한 연속성 레이어 — AI 에이전트는 매 세션마다 프로젝트를 다시 배우지 않아야 합니다.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
|
|
42
42
|
어제 세션에서 AI 에이전트가 모든 것을 잊어버린 경험 있으신가요? 같은 아키텍처 결정을 세 번째로 설명하는데, 이미 거절한 접근법을 또 제안하나요?
|
|
43
43
|
|
|
44
|
-
**toon-memory는 이 문제를 해결합니다.** AI
|
|
44
|
+
**toon-memory는 이 문제를 해결합니다.** AI 에이전트를 위한 연속성 레이어 — 세션 간에 프로젝트의 지식, 결정, 관례를 보존하는 가벼운 시스템으로, 모든 세션이 이전 세션이 끝난 곳에서 시작됩니다. 100% 로컬 및 프라이빗, MCP 기반 — 클라우드도 서버도 필요 없습니다.
|
|
45
45
|
|
|
46
46
|
📖 **[문서 읽기](https://luiggival08.github.io/toon-memory/)**
|
|
47
47
|
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
>
|
|
5
|
+
> The Continuity Layer for AI Agents — AI agents shouldn't have to relearn your project every session.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
|
|
41
41
|
Ever had that feeling where your AI agent forgets everything from yesterday's session? You explain the same architecture decision for the third time, and it still suggests the approach you already rejected?
|
|
42
42
|
|
|
43
|
-
**toon-memory fixes this.** It
|
|
43
|
+
**toon-memory fixes this.** It's the Continuity Layer for AI Agents — a lightweight system that preserves your project's knowledge, decisions, and conventions across sessions, so every session starts where the last one ended. Fully local and private, over MCP — no cloud, no server.
|
|
44
44
|
|
|
45
45
|
📖 **[Read the documentation](https://luiggival08.github.io/toon-memory/)**
|
|
46
46
|
|
package/README.pt-br.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
>
|
|
5
|
+
> A camada de continuidade para agentes de IA — agentes de IA não deveriam ter que reaprender seu projeto a cada sessão.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
Já teve aquela sensação de que seu agente de IA esquece tudo da sessão de ontem? Você explica a mesma decisão de arquitetura pela terceira vez e ele ainda sugere a abordagem que você já rejeitou?
|
|
41
41
|
|
|
42
|
-
**toon-memory resolve isso.**
|
|
42
|
+
**toon-memory resolve isso.** É a camada de continuidade para agentes de IA — um sistema leve que preserva o conhecimento, as decisões e as convenções do seu projeto entre sessões, para que cada sessão comece onde a anterior terminou. 100% local e privado, via MCP — sem nuvem, sem servidor.
|
|
43
43
|
|
|
44
44
|
📖 **[Leia a documentação](https://luiggival08.github.io/toon-memory/)**
|
|
45
45
|
|
package/README.zh.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# toon-memory
|
|
4
4
|
|
|
5
|
-
>
|
|
5
|
+
> AI 代理的连续性层 — AI 代理不应在每个会话中重新学习你的项目。
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/toon-memory)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
|
|
41
41
|
你是否有过这样的经历:AI 助手完全忘记了昨天会话中的内容?你不得不第三次解释同一个架构决策,而它仍然建议你已经否决的方案?
|
|
42
42
|
|
|
43
|
-
**toon-memory 解决了这个问题。**
|
|
43
|
+
**toon-memory 解决了这个问题。** 它是 AI 代理的连续性层 — 一个轻量系统,在会话之间保存你项目的知识、决策和约定,让每个会话都从上次结束的地方开始。100% 本地且私密,通过 MCP — 无需云、无需服务器。
|
|
44
44
|
|
|
45
45
|
📖 **[阅读文档](https://luiggival08.github.io/toon-memory/)**
|
|
46
46
|
|
package/bin/toon-memory.js
CHANGED
|
@@ -1,18 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
|
|
3
|
+
// src/bin/toon-memory.ts
|
|
4
|
+
import { dirname, join as join2 } from "path";
|
|
3
5
|
import { readFileSync } from "fs";
|
|
4
6
|
import { fileURLToPath } from "url";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
|
|
8
|
+
// src/cli/entry.ts
|
|
9
|
+
import { join } from "path";
|
|
10
|
+
import { pathToFileURL } from "url";
|
|
11
|
+
function fileImportURL(dirname2, ...parts) {
|
|
12
|
+
return pathToFileURL(join(dirname2, ...parts)).href;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/bin/toon-memory.ts
|
|
16
|
+
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
var args = process.argv.slice(2);
|
|
7
18
|
function getVersion() {
|
|
8
19
|
try {
|
|
9
|
-
const pkg = JSON.parse(readFileSync(
|
|
20
|
+
const pkg = JSON.parse(readFileSync(join2(__dirname, "..", "package.json"), "utf-8"));
|
|
10
21
|
return pkg.version || "unknown";
|
|
11
22
|
} catch {
|
|
12
23
|
return "unknown";
|
|
13
24
|
}
|
|
14
25
|
}
|
|
15
|
-
|
|
26
|
+
var HELP = `toon-memory \u2014 MCP memory server for AI coding agents
|
|
16
27
|
|
|
17
28
|
Usage:
|
|
18
29
|
toon-memory <command> [options]
|
|
@@ -49,8 +60,8 @@ if (args[0] === "-h" || args[0] === "--help") {
|
|
|
49
60
|
process.exit(0);
|
|
50
61
|
}
|
|
51
62
|
if (args[0] === "mcp") {
|
|
52
|
-
await import(
|
|
63
|
+
await import(fileImportURL(__dirname, "..", "mcp", "server.js"));
|
|
53
64
|
} else {
|
|
54
65
|
process.argv = ["node", "toon-memory", ...args];
|
|
55
|
-
await import(
|
|
66
|
+
await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"));
|
|
56
67
|
}
|
package/dist/cli/setup.js
CHANGED
|
@@ -421,6 +421,14 @@ function dumpMemoryMarkdown() {
|
|
|
421
421
|
// src/cli/config-writer.ts
|
|
422
422
|
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
423
423
|
import { dirname as dirname3 } from "path";
|
|
424
|
+
function loadJSON(file) {
|
|
425
|
+
if (!existsSync5(file)) return {};
|
|
426
|
+
try {
|
|
427
|
+
return JSON.parse(readFileSync5(file, "utf-8"));
|
|
428
|
+
} catch {
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
424
432
|
function installJSONConfig(agent, scope) {
|
|
425
433
|
const configPath = scope === "global" ? agent.global : agent.local;
|
|
426
434
|
if (!configPath) {
|
|
@@ -429,13 +437,10 @@ function installJSONConfig(agent, scope) {
|
|
|
429
437
|
}
|
|
430
438
|
const configDir = dirname3(configPath);
|
|
431
439
|
if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
|
|
432
|
-
|
|
433
|
-
if (
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
} catch {
|
|
437
|
-
config = {};
|
|
438
|
-
}
|
|
440
|
+
const config = loadJSON(configPath);
|
|
441
|
+
if (config === null) {
|
|
442
|
+
console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
|
|
443
|
+
return;
|
|
439
444
|
}
|
|
440
445
|
const mcpKey = agent.mcpKey || "mcpServers";
|
|
441
446
|
if (!config[mcpKey]) config[mcpKey] = {};
|
|
@@ -483,9 +488,13 @@ function installZedConfig(agent) {
|
|
|
483
488
|
const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
|
484
489
|
config = JSON.parse(stripped);
|
|
485
490
|
} catch {
|
|
486
|
-
config =
|
|
491
|
+
config = null;
|
|
487
492
|
}
|
|
488
493
|
}
|
|
494
|
+
if (config === null) {
|
|
495
|
+
console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
489
498
|
if (!config.context_servers) config.context_servers = {};
|
|
490
499
|
config.context_servers["toon-memory"] = {
|
|
491
500
|
command: "npx",
|
|
@@ -500,13 +509,10 @@ function installContinueConfig(agent) {
|
|
|
500
509
|
if (!configPath) return;
|
|
501
510
|
const configDir = dirname3(configPath);
|
|
502
511
|
if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
|
|
503
|
-
|
|
504
|
-
if (
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
} catch {
|
|
508
|
-
config = {};
|
|
509
|
-
}
|
|
512
|
+
const config = loadJSON(configPath);
|
|
513
|
+
if (config === null) {
|
|
514
|
+
console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
|
|
515
|
+
return;
|
|
510
516
|
}
|
|
511
517
|
if (!config.experimental) config.experimental = {};
|
|
512
518
|
if (!config.experimental.modelContextProtocolServers) {
|
|
@@ -534,13 +540,10 @@ function installOpenClawConfig(agent) {
|
|
|
534
540
|
if (!configPath) return;
|
|
535
541
|
const configDir = dirname3(configPath);
|
|
536
542
|
if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
|
|
537
|
-
|
|
538
|
-
if (
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
} catch {
|
|
542
|
-
config = {};
|
|
543
|
-
}
|
|
543
|
+
const config = loadJSON(configPath);
|
|
544
|
+
if (config === null) {
|
|
545
|
+
console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
|
|
546
|
+
return;
|
|
544
547
|
}
|
|
545
548
|
if (!config.mcp) config.mcp = {};
|
|
546
549
|
if (!config.mcp.servers) config.mcp.servers = {};
|
|
@@ -611,6 +614,14 @@ ${content}`);
|
|
|
611
614
|
// src/cli/hooks.ts
|
|
612
615
|
import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync5, chmodSync } from "fs";
|
|
613
616
|
import { dirname as dirname5, join as join5 } from "path";
|
|
617
|
+
function readJSON(file) {
|
|
618
|
+
if (!existsSync7(file)) return {};
|
|
619
|
+
try {
|
|
620
|
+
return JSON.parse(readFileSync7(file, "utf-8"));
|
|
621
|
+
} catch {
|
|
622
|
+
return null;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
614
625
|
function sessionStartHookContent(agentName) {
|
|
615
626
|
return `#!/bin/bash
|
|
616
627
|
# toon-memory session-start hook for ${agentName}
|
|
@@ -665,13 +676,10 @@ function registerCaptureHookJSON(agent, scriptPath) {
|
|
|
665
676
|
if (!configPath) return;
|
|
666
677
|
const configDir = dirname5(configPath);
|
|
667
678
|
if (!existsSync7(configDir)) mkdirSync5(configDir, { recursive: true });
|
|
668
|
-
|
|
669
|
-
if (
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
} catch {
|
|
673
|
-
config = {};
|
|
674
|
-
}
|
|
679
|
+
const config = readJSON(configPath);
|
|
680
|
+
if (config === null) {
|
|
681
|
+
console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
|
|
682
|
+
return;
|
|
675
683
|
}
|
|
676
684
|
if (!config.hooks) config.hooks = {};
|
|
677
685
|
for (const event of agent.captureJson || []) {
|
|
@@ -730,9 +738,13 @@ function registerHookJSON(agent, hookPath) {
|
|
|
730
738
|
config = JSON.parse(readFileSync7(configPath, "utf-8"));
|
|
731
739
|
}
|
|
732
740
|
} catch {
|
|
733
|
-
config =
|
|
741
|
+
config = null;
|
|
734
742
|
}
|
|
735
743
|
}
|
|
744
|
+
if (config === null) {
|
|
745
|
+
console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
736
748
|
if (agent.name === "claude" || agent.name === "gemini") {
|
|
737
749
|
if (!config.hooks) config.hooks = {};
|
|
738
750
|
if (!config.hooks.SessionStart) config.hooks.SessionStart = [];
|
|
@@ -763,9 +775,13 @@ function registerAntigravityHooks(agent) {
|
|
|
763
775
|
try {
|
|
764
776
|
cfg = JSON.parse(readFileSync7(hooksFile, "utf-8"));
|
|
765
777
|
} catch {
|
|
766
|
-
cfg =
|
|
778
|
+
cfg = null;
|
|
767
779
|
}
|
|
768
780
|
}
|
|
781
|
+
if (cfg === null) {
|
|
782
|
+
console.log(` \u26A0\uFE0F Skipping ${hooksFile}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
769
785
|
cfg[ANTIGRAVITY_HOOK_NAME] = {
|
|
770
786
|
PreInvocation: [{ type: "command", command: sessionPath }],
|
|
771
787
|
PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: capPath }] }],
|
|
@@ -794,6 +810,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
794
810
|
const recall = async (query, opts = {}) => {
|
|
795
811
|
try {
|
|
796
812
|
const args = { query, mode: "flat", budget: opts.budget || "tiny", path_scope: opts.path_scope || "" }
|
|
813
|
+
if (opts.category) args.category = opts.category
|
|
797
814
|
const result = await $\`npx -y toon-memory mcp\`.cwd(root)
|
|
798
815
|
.stdin(JSON.stringify({
|
|
799
816
|
jsonrpc: "2.0",
|
|
@@ -807,11 +824,44 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
807
824
|
} catch { return "" }
|
|
808
825
|
}
|
|
809
826
|
|
|
827
|
+
// Pre-edit risk surfacing: warning-category entries scoped to a file path.
|
|
828
|
+
// Injected as a distinct block so the agent sees known risks before it edits.
|
|
829
|
+
const risks = async (filePath) => {
|
|
830
|
+
return await recall(filePath, { budget: "tiny", path_scope: filePath, category: "warning" })
|
|
831
|
+
}
|
|
832
|
+
|
|
810
833
|
const write = (text) => {
|
|
811
834
|
fs.mkdirSync(INS, { recursive: true })
|
|
812
835
|
fs.writeFileSync(OUT, text)
|
|
813
836
|
}
|
|
814
837
|
|
|
838
|
+
const pickPath = (args) => {
|
|
839
|
+
if (!args) return ""
|
|
840
|
+
if (args.file) return args.file
|
|
841
|
+
if (args.path) return args.path
|
|
842
|
+
if (args.filePath) return args.filePath
|
|
843
|
+
if (args.target) return args.target
|
|
844
|
+
return ""
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
const buildQuery = (filePath) => {
|
|
848
|
+
const basename = path.basename(filePath, path.extname(filePath))
|
|
849
|
+
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
850
|
+
return [basename, ...dirParts.slice(-2)].join(" ")
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
const inject = (ctx, key, text) => {
|
|
854
|
+
if (!text || text.includes("(empty)") || text.includes("No results")) return
|
|
855
|
+
if (typeof ctx?.setContext === "function") ctx.setContext(key, text)
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// Edit/write-ish tools are where known risks matter most.
|
|
859
|
+
const isEditTool = (name) => {
|
|
860
|
+
if (!name) return false
|
|
861
|
+
return name === "edit" || name === "write" || name === "apply-patch" ||
|
|
862
|
+
name.includes("edit") || name.includes("write") || name.includes("patch")
|
|
863
|
+
}
|
|
864
|
+
|
|
815
865
|
return {
|
|
816
866
|
"session.created": async () => {
|
|
817
867
|
try {
|
|
@@ -825,6 +875,19 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
825
875
|
if (Array.isArray(output?.context)) output.context.push(out)
|
|
826
876
|
} catch {}
|
|
827
877
|
},
|
|
878
|
+
"tool.execute.before": async (input, output) => {
|
|
879
|
+
// Pre-edit risk surfacing: for edit/write tools, surface known
|
|
880
|
+
// warning entries for the target file BEFORE the tool runs.
|
|
881
|
+
try {
|
|
882
|
+
const toolName = input?.tool || ""
|
|
883
|
+
if (!isEditTool(toolName)) return
|
|
884
|
+
const args = output?.args || input?.args || {}
|
|
885
|
+
const filePath = pickPath(args)
|
|
886
|
+
if (!filePath) return
|
|
887
|
+
const text = await risks(filePath)
|
|
888
|
+
inject(input, "toon-memory:risks:" + filePath, "\u26A0 KNOWN RISKS for " + filePath + ":\\n" + text)
|
|
889
|
+
} catch {}
|
|
890
|
+
},
|
|
828
891
|
"tool.execute.after": async (input) => {
|
|
829
892
|
// Intelligent auto-loading: extract file path from tool result,
|
|
830
893
|
// recall only memory relevant to that file, inject as context.
|
|
@@ -834,11 +897,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
834
897
|
const args = input?.args || {}
|
|
835
898
|
|
|
836
899
|
// Extract file path from tool arguments or output
|
|
837
|
-
let filePath =
|
|
838
|
-
if (args.file) filePath = args.file
|
|
839
|
-
else if (args.path) filePath = args.path
|
|
840
|
-
else if (args.filePath) filePath = args.filePath
|
|
841
|
-
else if (args.target) filePath = args.target
|
|
900
|
+
let filePath = pickPath(args)
|
|
842
901
|
|
|
843
902
|
// Also try to extract from tool output text
|
|
844
903
|
if (!filePath && input?.output) {
|
|
@@ -849,15 +908,15 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
849
908
|
|
|
850
909
|
if (filePath) {
|
|
851
910
|
// Build recall query from file path components
|
|
852
|
-
const
|
|
853
|
-
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
854
|
-
const query = [basename, ...dirParts.slice(-2)].join(" ")
|
|
855
|
-
|
|
911
|
+
const query = buildQuery(filePath)
|
|
856
912
|
const text = await recall(query, { budget: "tiny", path_scope: filePath })
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
913
|
+
inject(input, "toon-memory:" + filePath, text)
|
|
914
|
+
|
|
915
|
+
// Pre-edit risk block for edit/write tools (same key as the before
|
|
916
|
+
// hook \u2014 setContext overwrites, so no duplication when both fire).
|
|
917
|
+
if (isEditTool(toolName)) {
|
|
918
|
+
const riskText = await risks(filePath)
|
|
919
|
+
inject(input, "toon-memory:risks:" + filePath, "\u26A0 KNOWN RISKS for " + filePath + ":\\n" + riskText)
|
|
861
920
|
}
|
|
862
921
|
}
|
|
863
922
|
|
|
@@ -875,11 +934,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
875
934
|
|
|
876
935
|
if (toolKeywords.length > 3) {
|
|
877
936
|
const text = await recall(toolKeywords, { budget: "tiny" })
|
|
878
|
-
|
|
879
|
-
if (typeof input?.setContext === "function") {
|
|
880
|
-
input.setContext("toon-memory:" + toolName, text)
|
|
881
|
-
}
|
|
882
|
-
}
|
|
937
|
+
inject(input, "toon-memory:" + toolName, text)
|
|
883
938
|
}
|
|
884
939
|
}
|
|
885
940
|
} catch {}
|
package/dist/cli/toon-memory.js
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
1
|
// src/cli/toon-memory.ts
|
|
2
|
-
import { dirname
|
|
2
|
+
import { dirname } from "path";
|
|
3
3
|
import { fileURLToPath } from "url";
|
|
4
|
+
|
|
5
|
+
// src/cli/entry.ts
|
|
6
|
+
import { join } from "path";
|
|
7
|
+
import { pathToFileURL } from "url";
|
|
8
|
+
function fileImportURL(dirname2, ...parts) {
|
|
9
|
+
return pathToFileURL(join(dirname2, ...parts)).href;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// src/cli/toon-memory.ts
|
|
4
13
|
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
5
14
|
var args = process.argv.slice(2);
|
|
6
15
|
if (args[0] === "mcp") {
|
|
7
|
-
await import(
|
|
16
|
+
await import(fileImportURL(__dirname, "..", "mcp", "server.js"));
|
|
8
17
|
} else {
|
|
9
18
|
process.argv = ["node", "toon-memory", ...args];
|
|
10
|
-
await import(
|
|
19
|
+
await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"));
|
|
11
20
|
}
|
package/install.ps1
CHANGED
|
@@ -1,18 +1,24 @@
|
|
|
1
1
|
# toon-memory installer for Windows (PowerShell)
|
|
2
2
|
# Usage: irm https://raw.githubusercontent.com/LuiggiVal08/toon-memory/main/install.ps1 | iex
|
|
3
3
|
|
|
4
|
-
$TOON_VERSION = "1.0.9"
|
|
5
|
-
# SHA-256 checksum of the tarball. Update on each release.
|
|
6
|
-
# Generate with: certutil -hashfile toon-memory-$TOON_VERSION.tgz SHA256
|
|
7
|
-
$TOON_CHECKSUM = "d5b2a8cbe0f3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9"
|
|
8
|
-
|
|
9
4
|
Write-Host "🧠 toon-memory installer" -ForegroundColor Cyan
|
|
10
5
|
Write-Host ""
|
|
11
6
|
|
|
7
|
+
# Resolve the latest version + integrity from the npm registry (mirrors install.sh)
|
|
8
|
+
try {
|
|
9
|
+
$meta = Invoke-RestMethod -Uri "https://registry.npmjs.org/toon-memory/latest" -ErrorAction Stop
|
|
10
|
+
$TOON_VERSION = $meta.version
|
|
11
|
+
$integrity = $meta.dist.integrity
|
|
12
|
+
} catch {
|
|
13
|
+
Write-Host "Error: Could not determine latest toon-memory version." -ForegroundColor Red
|
|
14
|
+
Write-Host "You can install manually: npm install -g toon-memory"
|
|
15
|
+
exit 1
|
|
16
|
+
}
|
|
17
|
+
|
|
12
18
|
# Check if npm is available
|
|
13
19
|
if (Get-Command npm -ErrorAction SilentlyContinue) {
|
|
14
|
-
Write-Host "Installing toon-memory via npm..."
|
|
15
|
-
npm install -g toon-memory@$TOON_VERSION
|
|
20
|
+
Write-Host "Installing toon-memory v$TOON_VERSION via npm..."
|
|
21
|
+
npm install -g "toon-memory@$TOON_VERSION"
|
|
16
22
|
Write-Host ""
|
|
17
23
|
Write-Host "✅ toon-memory installed!" -ForegroundColor Green
|
|
18
24
|
Write-Host ""
|
|
@@ -35,15 +41,19 @@ if (Get-Command npm -ErrorAction SilentlyContinue) {
|
|
|
35
41
|
$tgzPath = "$INSTALL_DIR\toon-memory.tgz"
|
|
36
42
|
Invoke-WebRequest -Uri $url -OutFile $tgzPath
|
|
37
43
|
|
|
38
|
-
# Verify integrity
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
44
|
+
# Verify integrity (npm dist.integrity is "sha512-<base64>"; compare against SHA512 hex)
|
|
45
|
+
if ($integrity -and $integrity.StartsWith("sha512-")) {
|
|
46
|
+
$expectedHex = -join ([Convert]::FromBase64String($integrity.Substring(7)) | ForEach-Object { $_.ToString("x2") })
|
|
47
|
+
$actualHash = (Get-FileHash -Path $tgzPath -Algorithm SHA512).Hash.ToLower()
|
|
48
|
+
if ($actualHash -ne $expectedHex.ToLower()) {
|
|
49
|
+
Write-Host "❌ Integrity check failed! The downloaded file may be corrupted or tampered with." -ForegroundColor Red
|
|
50
|
+
Remove-Item -Path $tgzPath -Force
|
|
51
|
+
exit 1
|
|
52
|
+
}
|
|
53
|
+
Write-Host "✅ Integrity verified" -ForegroundColor Green
|
|
54
|
+
} else {
|
|
55
|
+
Write-Host "⚠️ No sha512 integrity available from the registry; skipping verification" -ForegroundColor Yellow
|
|
45
56
|
}
|
|
46
|
-
Write-Host "✅ Integrity verified" -ForegroundColor Green
|
|
47
57
|
|
|
48
58
|
# Extract
|
|
49
59
|
cd $INSTALL_DIR
|
package/mcp/server.js
CHANGED
|
@@ -22614,6 +22614,25 @@ function graphRecallDetailed(data, query, opts = {}) {
|
|
|
22614
22614
|
}
|
|
22615
22615
|
return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons };
|
|
22616
22616
|
}
|
|
22617
|
+
function fetchEntriesByIds(data, tokens, opts = {}) {
|
|
22618
|
+
const byId = /* @__PURE__ */ new Map();
|
|
22619
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
22620
|
+
const asOf = opts.asOf || "";
|
|
22621
|
+
for (const e of parseEntries(data)) {
|
|
22622
|
+
const visible = e.status === "active" || e.status === "resolved" || asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf;
|
|
22623
|
+
if (!visible) continue;
|
|
22624
|
+
if (asOf && e.date && e.date > asOf) continue;
|
|
22625
|
+
if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue;
|
|
22626
|
+
if (!byId.has(e.id)) byId.set(e.id, e);
|
|
22627
|
+
if (!byKey.has(e.key)) byKey.set(e.key, e);
|
|
22628
|
+
}
|
|
22629
|
+
const out = [];
|
|
22630
|
+
for (const t of tokens) {
|
|
22631
|
+
const e = byKey.get(t) || byId.get(t);
|
|
22632
|
+
if (e && !out.includes(e)) out.push(e);
|
|
22633
|
+
}
|
|
22634
|
+
return out;
|
|
22635
|
+
}
|
|
22617
22636
|
function globMatch(pattern, target) {
|
|
22618
22637
|
if (!pattern) return true;
|
|
22619
22638
|
if (pattern.startsWith("/")) pattern = pattern.slice(1);
|
|
@@ -22686,6 +22705,24 @@ function renderCompact(entries, opts = {}) {
|
|
|
22686
22705
|
}
|
|
22687
22706
|
return rendered.join("\n\n");
|
|
22688
22707
|
}
|
|
22708
|
+
function renderIndex(entries, opts = {}) {
|
|
22709
|
+
let max = 0;
|
|
22710
|
+
if (opts.scores) {
|
|
22711
|
+
for (const v3 of opts.scores.values()) if (v3 > max) max = v3;
|
|
22712
|
+
}
|
|
22713
|
+
const lines = [];
|
|
22714
|
+
for (let i = 0; i < entries.length; i++) {
|
|
22715
|
+
const e = entries[i];
|
|
22716
|
+
const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
|
|
22717
|
+
let score = "";
|
|
22718
|
+
if (opts.scores && max > 0) {
|
|
22719
|
+
const s2 = opts.scores.get(e.key);
|
|
22720
|
+
if (s2 !== void 0) score = ` \xB7 ${Math.round(s2 / max * 100)}%`;
|
|
22721
|
+
}
|
|
22722
|
+
lines.push(`[${i + 1}] ${e.key} (${e.id})${pin} \xB7 ${e.category} \xB7 ${e.date}${score}`);
|
|
22723
|
+
}
|
|
22724
|
+
return lines.join("\n");
|
|
22725
|
+
}
|
|
22689
22726
|
var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
|
|
22690
22727
|
var init_graph = __esm({
|
|
22691
22728
|
"src/lib/graph.ts"() {
|
|
@@ -34866,12 +34903,14 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
|
|
|
34866
34903
|
title: "Search Memory",
|
|
34867
34904
|
description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files. Pattern: recall \u2192 context_diff for recent changes \u2192 capture to save observations.",
|
|
34868
34905
|
inputSchema: {
|
|
34869
|
-
query: external_exports.string().describe("Text to search for"),
|
|
34906
|
+
query: external_exports.string().optional().default("").describe("Text to search for (optional when mode:'index' or ids is given)"),
|
|
34870
34907
|
category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
|
|
34871
34908
|
from_date: external_exports.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
|
|
34872
34909
|
to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
|
|
34873
|
-
mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
|
|
34910
|
+
mode: external_exports.enum(["flat", "graph", "index"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens). 'index' = one line per entry (key, id, category, date, relevance %) with no content \u2014 browse then fetch full entries with `ids`."),
|
|
34911
|
+
ids: external_exports.string().optional().default("").describe("Batch fetch: comma/space/;-separated entry ids or keys, rendered in the given order (unknown entries skipped). Complements mode:'index' \u2014 layer 2 of progressive disclosure. Overrides mode."),
|
|
34874
34912
|
hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
|
|
34913
|
+
limit: external_exports.number().optional().describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
|
|
34875
34914
|
compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
|
|
34876
34915
|
budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
|
|
34877
34916
|
budget_tokens: external_exports.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
|
|
@@ -34883,11 +34922,62 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
|
|
|
34883
34922
|
},
|
|
34884
34923
|
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
|
|
34885
34924
|
},
|
|
34886
|
-
async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
|
|
34925
|
+
async ({ query, category, from_date, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
|
|
34887
34926
|
const data = readMemory();
|
|
34888
|
-
const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
|
|
34889
34927
|
const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
|
|
34890
|
-
const
|
|
34928
|
+
const resolvedAsOf = as_of || void 0;
|
|
34929
|
+
if (ids && ids.trim()) {
|
|
34930
|
+
const tokens = ids.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean);
|
|
34931
|
+
const entries = fetchEntriesByIds(data, tokens, { asOf: resolvedAsOf });
|
|
34932
|
+
if (entries.length === 0) {
|
|
34933
|
+
return { content: [{ type: "text", text: `No entries found for ids: ${ids}` }] };
|
|
34934
|
+
}
|
|
34935
|
+
bumpAccessed(entries.map((e) => e.id));
|
|
34936
|
+
const label = entries.length === 1 ? "entry" : "entries";
|
|
34937
|
+
if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
|
|
34938
|
+
const formatted3 = renderCompact(entries, {
|
|
34939
|
+
budget: resolvedBudget,
|
|
34940
|
+
budgetTokens: budget_tokens || void 0
|
|
34941
|
+
});
|
|
34942
|
+
return { content: [{ type: "text", text: `Fetched ${entries.length} ${label}:
|
|
34943
|
+
|
|
34944
|
+
${formatted3}` }] };
|
|
34945
|
+
}
|
|
34946
|
+
const formatted2 = entries.map((r2) => {
|
|
34947
|
+
const links = r2.links.length ? `
|
|
34948
|
+
links: ${r2.links.join(", ")}` : "";
|
|
34949
|
+
const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
|
|
34950
|
+
const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
|
|
34951
|
+
const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
|
|
34952
|
+
const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
|
|
34953
|
+
const supersededInfo = r2.supersededOn ? ` | superseded: ${r2.supersededOn}` : "";
|
|
34954
|
+
return `[${r2.category}] ${r2.key}${pin} (${r2.id})
|
|
34955
|
+
${r2.content}
|
|
34956
|
+
File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`;
|
|
34957
|
+
}).join("\n\n");
|
|
34958
|
+
return { content: [{ type: "text", text: `Fetched ${entries.length} ${label}:
|
|
34959
|
+
|
|
34960
|
+
${formatted2}` }] };
|
|
34961
|
+
}
|
|
34962
|
+
const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
|
|
34963
|
+
const limit = limitParam ?? (mode === "index" ? 15 : 6);
|
|
34964
|
+
const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, limit, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: resolvedAsOf });
|
|
34965
|
+
if (mode === "index") {
|
|
34966
|
+
if (detail.entries.length === 0) {
|
|
34967
|
+
return { content: [{ type: "text", text: `No results found for "${query}"` }] };
|
|
34968
|
+
}
|
|
34969
|
+
const formatted2 = renderIndex(detail.entries, { scores: detail.scores });
|
|
34970
|
+
return {
|
|
34971
|
+
content: [{
|
|
34972
|
+
type: "text",
|
|
34973
|
+
text: `\u{1F4C7} Memory index (${detail.entries.length} entries):
|
|
34974
|
+
|
|
34975
|
+
${formatted2}
|
|
34976
|
+
|
|
34977
|
+
Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"flat".`
|
|
34978
|
+
}]
|
|
34979
|
+
};
|
|
34980
|
+
}
|
|
34891
34981
|
if (detail.entries.length === 0) {
|
|
34892
34982
|
return { content: [{ type: "text", text: `No results found for "${query}"` }] };
|
|
34893
34983
|
}
|
|
@@ -48210,7 +48300,7 @@ function registerResources(server2) {
|
|
|
48210
48300
|
|
|
48211
48301
|
// src/mcp/server.ts
|
|
48212
48302
|
var server = new McpServer(
|
|
48213
|
-
{ name: "toon-memory", version: "4.3.
|
|
48303
|
+
{ name: "toon-memory", version: "4.3.1" },
|
|
48214
48304
|
{ capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
|
|
48215
48305
|
);
|
|
48216
48306
|
var s = server.server;
|
|
@@ -48222,7 +48312,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
|
|
|
48222
48312
|
return {
|
|
48223
48313
|
protocolVersion,
|
|
48224
48314
|
capabilities: s.getCapabilities(),
|
|
48225
|
-
serverInfo: { name: "toon-memory", version: "4.3.
|
|
48315
|
+
serverInfo: { name: "toon-memory", version: "4.3.1" },
|
|
48226
48316
|
...s._instructions && { instructions: s._instructions }
|
|
48227
48317
|
};
|
|
48228
48318
|
});
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
3
|
"mcpName": "io.github.LuiggiVal08/toon-memory",
|
|
4
|
-
"version": "4.3.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "4.3.1",
|
|
5
|
+
"description": "The Continuity Layer for AI Agents — an MCP memory server that preserves project knowledge, decisions, and conventions across sessions so every session starts where the last one ended. Offline, token-efficient, no LLM, no server; works with 15+ agents.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"toon-memory": "./bin/toon-memory.js"
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
],
|
|
20
20
|
"scripts": {
|
|
21
21
|
"build": "npm run build:bin && npm run build:mcp && npm run build:cli",
|
|
22
|
-
"build:bin": "esbuild src/bin/toon-memory.ts --platform=node --format=esm --outfile=bin/toon-memory.js",
|
|
22
|
+
"build:bin": "esbuild src/bin/toon-memory.ts --bundle --platform=node --format=esm --outfile=bin/toon-memory.js",
|
|
23
23
|
"build:mcp": "node -e \"const{version}=require('./package.json');const esbuild=require('esbuild');esbuild.build({entryPoints:['src/mcp/server.ts'],bundle:true,platform:'node',format:'esm',outfile:'mcp/server.js',define:{TOON_VERSION:JSON.stringify(version)}})\"",
|
|
24
24
|
"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",
|
|
25
25
|
"test": "vitest run",
|
package/src/bin/toon-memory.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { dirname, join } from "path"
|
|
3
3
|
import { readFileSync } from "fs"
|
|
4
4
|
import { fileURLToPath } from "url"
|
|
5
|
+
import { fileImportURL } from "../cli/entry"
|
|
5
6
|
|
|
6
7
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
7
8
|
const args = process.argv.slice(2)
|
|
@@ -55,8 +56,8 @@ if (args[0] === "-h" || args[0] === "--help") {
|
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
if (args[0] === "mcp") {
|
|
58
|
-
await import(
|
|
59
|
+
await import(fileImportURL(__dirname, "..", "mcp", "server.js"))
|
|
59
60
|
} else {
|
|
60
61
|
process.argv = ["node", "toon-memory", ...args]
|
|
61
|
-
await import(
|
|
62
|
+
await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"))
|
|
62
63
|
}
|
package/src/cli/config-writer.ts
CHANGED
|
@@ -3,6 +3,21 @@ import { dirname } from "path"
|
|
|
3
3
|
import type { Agent } from "./types"
|
|
4
4
|
import { MEMORY_DIR, CAPTURE_CONFIG } from "./constants"
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Read an existing JSON config file.
|
|
8
|
+
* Returns {} when the file is missing, or null when it exists but cannot be
|
|
9
|
+
* parsed — callers MUST skip (never overwrite) on null to avoid wiping the
|
|
10
|
+
* user's other settings.
|
|
11
|
+
*/
|
|
12
|
+
function loadJSON(file: string): Record<string, any> | null {
|
|
13
|
+
if (!existsSync(file)) return {}
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(file, "utf-8"))
|
|
16
|
+
} catch {
|
|
17
|
+
return null
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
6
21
|
/**
|
|
7
22
|
* Install MCP server configuration for a JSON-format agent.
|
|
8
23
|
*/
|
|
@@ -17,13 +32,10 @@ export function installJSONConfig(agent: Agent, scope: string): void {
|
|
|
17
32
|
const configDir = dirname(configPath)
|
|
18
33
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
19
34
|
|
|
20
|
-
|
|
21
|
-
if (
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
} catch {
|
|
25
|
-
config = {}
|
|
26
|
-
}
|
|
35
|
+
const config = loadJSON(configPath)
|
|
36
|
+
if (config === null) {
|
|
37
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
38
|
+
return
|
|
27
39
|
}
|
|
28
40
|
|
|
29
41
|
const mcpKey = agent.mcpKey || "mcpServers"
|
|
@@ -80,17 +92,22 @@ export function installZedConfig(agent: Agent): void {
|
|
|
80
92
|
const configDir = dirname(configPath)
|
|
81
93
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
82
94
|
|
|
83
|
-
let config: Record<string, any> = {}
|
|
95
|
+
let config: Record<string, any> | null = {}
|
|
84
96
|
if (existsSync(configPath)) {
|
|
85
97
|
try {
|
|
86
98
|
const raw = readFileSync(configPath, "utf-8")
|
|
87
99
|
const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
|
|
88
100
|
config = JSON.parse(stripped)
|
|
89
101
|
} catch {
|
|
90
|
-
config =
|
|
102
|
+
config = null
|
|
91
103
|
}
|
|
92
104
|
}
|
|
93
105
|
|
|
106
|
+
if (config === null) {
|
|
107
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
|
|
94
111
|
if (!config.context_servers) config.context_servers = {}
|
|
95
112
|
|
|
96
113
|
config.context_servers["toon-memory"] = {
|
|
@@ -114,13 +131,10 @@ export function installContinueConfig(agent: Agent): void {
|
|
|
114
131
|
const configDir = dirname(configPath)
|
|
115
132
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
116
133
|
|
|
117
|
-
|
|
118
|
-
if (
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
} catch {
|
|
122
|
-
config = {}
|
|
123
|
-
}
|
|
134
|
+
const config = loadJSON(configPath)
|
|
135
|
+
if (config === null) {
|
|
136
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
137
|
+
return
|
|
124
138
|
}
|
|
125
139
|
|
|
126
140
|
if (!config.experimental) config.experimental = {}
|
|
@@ -158,13 +172,10 @@ export function installOpenClawConfig(agent: Agent): void {
|
|
|
158
172
|
const configDir = dirname(configPath)
|
|
159
173
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
160
174
|
|
|
161
|
-
|
|
162
|
-
if (
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
} catch {
|
|
166
|
-
config = {}
|
|
167
|
-
}
|
|
175
|
+
const config = loadJSON(configPath)
|
|
176
|
+
if (config === null) {
|
|
177
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
178
|
+
return
|
|
168
179
|
}
|
|
169
180
|
|
|
170
181
|
if (!config.mcp) config.mcp = {}
|
package/src/cli/entry.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { join } from "path"
|
|
2
|
+
import { pathToFileURL } from "url"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Build a file:// URL for a dynamic import relative to the running module.
|
|
6
|
+
* pathToFileURL is required on Windows: `import("C:\\...")` is parsed as a
|
|
7
|
+
* URL with scheme "c:" and throws ERR_UNSUPPORTED_ESM_URL_SCHEME.
|
|
8
|
+
*/
|
|
9
|
+
export function fileImportURL(dirname: string, ...parts: string[]): string {
|
|
10
|
+
return pathToFileURL(join(dirname, ...parts)).href
|
|
11
|
+
}
|
package/src/cli/hooks.ts
CHANGED
|
@@ -3,6 +3,21 @@ import { dirname, join } from "path"
|
|
|
3
3
|
import type { Agent } from "./types"
|
|
4
4
|
import { projectRoot, CAPTURE_JS, SESSION_START_JS, CAPTURE_CONFIG, ANTIGRAVITY_HOOK_NAME } from "./constants"
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Read an existing JSON config file.
|
|
8
|
+
* Returns {} when the file is missing, or null when it exists but cannot be
|
|
9
|
+
* parsed — callers MUST skip (never overwrite) on null to avoid wiping the
|
|
10
|
+
* user's other settings.
|
|
11
|
+
*/
|
|
12
|
+
function readJSON(file: string): Record<string, any> | null {
|
|
13
|
+
if (!existsSync(file)) return {}
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(file, "utf-8"))
|
|
16
|
+
} catch {
|
|
17
|
+
return null
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
6
21
|
/** Hook script content for SessionStart reminder */
|
|
7
22
|
export function sessionStartHookContent(agentName: string): string {
|
|
8
23
|
return `#!/bin/bash
|
|
@@ -76,13 +91,10 @@ export function registerCaptureHookJSON(agent: Agent, scriptPath: string): void
|
|
|
76
91
|
const configDir = dirname(configPath)
|
|
77
92
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
78
93
|
|
|
79
|
-
|
|
80
|
-
if (
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
} catch {
|
|
84
|
-
config = {}
|
|
85
|
-
}
|
|
94
|
+
const config = readJSON(configPath)
|
|
95
|
+
if (config === null) {
|
|
96
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
97
|
+
return
|
|
86
98
|
}
|
|
87
99
|
|
|
88
100
|
if (!config.hooks) config.hooks = {}
|
|
@@ -136,7 +148,7 @@ export function registerHookJSON(agent: Agent, hookPath: string): void {
|
|
|
136
148
|
const configDir = dirname(configPath)
|
|
137
149
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
138
150
|
|
|
139
|
-
let config: Record<string, any> = {}
|
|
151
|
+
let config: Record<string, any> | null = {}
|
|
140
152
|
if (existsSync(configPath)) {
|
|
141
153
|
try {
|
|
142
154
|
if (agent.format === "jsonc") {
|
|
@@ -147,10 +159,15 @@ export function registerHookJSON(agent: Agent, hookPath: string): void {
|
|
|
147
159
|
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
148
160
|
}
|
|
149
161
|
} catch {
|
|
150
|
-
config =
|
|
162
|
+
config = null
|
|
151
163
|
}
|
|
152
164
|
}
|
|
153
165
|
|
|
166
|
+
if (config === null) {
|
|
167
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
|
|
154
171
|
if (agent.name === "claude" || agent.name === "gemini") {
|
|
155
172
|
if (!config.hooks) config.hooks = {}
|
|
156
173
|
if (!config.hooks.SessionStart) config.hooks.SessionStart = []
|
|
@@ -186,15 +203,20 @@ export function registerAntigravityHooks(agent: Agent): void {
|
|
|
186
203
|
const hooksFile = join(base, "hooks.json")
|
|
187
204
|
mkdirSync(base, { recursive: true })
|
|
188
205
|
|
|
189
|
-
let cfg: Record<string, any> = {}
|
|
206
|
+
let cfg: Record<string, any> | null = {}
|
|
190
207
|
if (existsSync(hooksFile)) {
|
|
191
208
|
try {
|
|
192
209
|
cfg = JSON.parse(readFileSync(hooksFile, "utf-8"))
|
|
193
210
|
} catch {
|
|
194
|
-
cfg =
|
|
211
|
+
cfg = null
|
|
195
212
|
}
|
|
196
213
|
}
|
|
197
214
|
|
|
215
|
+
if (cfg === null) {
|
|
216
|
+
console.log(` ⚠️ Skipping ${hooksFile}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
|
|
198
220
|
cfg[ANTIGRAVITY_HOOK_NAME] = {
|
|
199
221
|
PreInvocation: [{ type: "command", command: sessionPath }],
|
|
200
222
|
PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: capPath }] }],
|
|
@@ -29,6 +29,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
29
29
|
const recall = async (query, opts = {}) => {
|
|
30
30
|
try {
|
|
31
31
|
const args = { query, mode: "flat", budget: opts.budget || "tiny", path_scope: opts.path_scope || "" }
|
|
32
|
+
if (opts.category) args.category = opts.category
|
|
32
33
|
const result = await $\`npx -y toon-memory mcp\`.cwd(root)
|
|
33
34
|
.stdin(JSON.stringify({
|
|
34
35
|
jsonrpc: "2.0",
|
|
@@ -42,11 +43,44 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
42
43
|
} catch { return "" }
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
// Pre-edit risk surfacing: warning-category entries scoped to a file path.
|
|
47
|
+
// Injected as a distinct block so the agent sees known risks before it edits.
|
|
48
|
+
const risks = async (filePath) => {
|
|
49
|
+
return await recall(filePath, { budget: "tiny", path_scope: filePath, category: "warning" })
|
|
50
|
+
}
|
|
51
|
+
|
|
45
52
|
const write = (text) => {
|
|
46
53
|
fs.mkdirSync(INS, { recursive: true })
|
|
47
54
|
fs.writeFileSync(OUT, text)
|
|
48
55
|
}
|
|
49
56
|
|
|
57
|
+
const pickPath = (args) => {
|
|
58
|
+
if (!args) return ""
|
|
59
|
+
if (args.file) return args.file
|
|
60
|
+
if (args.path) return args.path
|
|
61
|
+
if (args.filePath) return args.filePath
|
|
62
|
+
if (args.target) return args.target
|
|
63
|
+
return ""
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const buildQuery = (filePath) => {
|
|
67
|
+
const basename = path.basename(filePath, path.extname(filePath))
|
|
68
|
+
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
69
|
+
return [basename, ...dirParts.slice(-2)].join(" ")
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const inject = (ctx, key, text) => {
|
|
73
|
+
if (!text || text.includes("(empty)") || text.includes("No results")) return
|
|
74
|
+
if (typeof ctx?.setContext === "function") ctx.setContext(key, text)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Edit/write-ish tools are where known risks matter most.
|
|
78
|
+
const isEditTool = (name) => {
|
|
79
|
+
if (!name) return false
|
|
80
|
+
return name === "edit" || name === "write" || name === "apply-patch" ||
|
|
81
|
+
name.includes("edit") || name.includes("write") || name.includes("patch")
|
|
82
|
+
}
|
|
83
|
+
|
|
50
84
|
return {
|
|
51
85
|
"session.created": async () => {
|
|
52
86
|
try {
|
|
@@ -60,6 +94,19 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
60
94
|
if (Array.isArray(output?.context)) output.context.push(out)
|
|
61
95
|
} catch {}
|
|
62
96
|
},
|
|
97
|
+
"tool.execute.before": async (input, output) => {
|
|
98
|
+
// Pre-edit risk surfacing: for edit/write tools, surface known
|
|
99
|
+
// warning entries for the target file BEFORE the tool runs.
|
|
100
|
+
try {
|
|
101
|
+
const toolName = input?.tool || ""
|
|
102
|
+
if (!isEditTool(toolName)) return
|
|
103
|
+
const args = output?.args || input?.args || {}
|
|
104
|
+
const filePath = pickPath(args)
|
|
105
|
+
if (!filePath) return
|
|
106
|
+
const text = await risks(filePath)
|
|
107
|
+
inject(input, "toon-memory:risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + text)
|
|
108
|
+
} catch {}
|
|
109
|
+
},
|
|
63
110
|
"tool.execute.after": async (input) => {
|
|
64
111
|
// Intelligent auto-loading: extract file path from tool result,
|
|
65
112
|
// recall only memory relevant to that file, inject as context.
|
|
@@ -69,11 +116,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
69
116
|
const args = input?.args || {}
|
|
70
117
|
|
|
71
118
|
// Extract file path from tool arguments or output
|
|
72
|
-
let filePath =
|
|
73
|
-
if (args.file) filePath = args.file
|
|
74
|
-
else if (args.path) filePath = args.path
|
|
75
|
-
else if (args.filePath) filePath = args.filePath
|
|
76
|
-
else if (args.target) filePath = args.target
|
|
119
|
+
let filePath = pickPath(args)
|
|
77
120
|
|
|
78
121
|
// Also try to extract from tool output text
|
|
79
122
|
if (!filePath && input?.output) {
|
|
@@ -84,15 +127,15 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
84
127
|
|
|
85
128
|
if (filePath) {
|
|
86
129
|
// Build recall query from file path components
|
|
87
|
-
const
|
|
88
|
-
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
89
|
-
const query = [basename, ...dirParts.slice(-2)].join(" ")
|
|
90
|
-
|
|
130
|
+
const query = buildQuery(filePath)
|
|
91
131
|
const text = await recall(query, { budget: "tiny", path_scope: filePath })
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
132
|
+
inject(input, "toon-memory:" + filePath, text)
|
|
133
|
+
|
|
134
|
+
// Pre-edit risk block for edit/write tools (same key as the before
|
|
135
|
+
// hook — setContext overwrites, so no duplication when both fire).
|
|
136
|
+
if (isEditTool(toolName)) {
|
|
137
|
+
const riskText = await risks(filePath)
|
|
138
|
+
inject(input, "toon-memory:risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + riskText)
|
|
96
139
|
}
|
|
97
140
|
}
|
|
98
141
|
|
|
@@ -110,11 +153,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
110
153
|
|
|
111
154
|
if (toolKeywords.length > 3) {
|
|
112
155
|
const text = await recall(toolKeywords, { budget: "tiny" })
|
|
113
|
-
|
|
114
|
-
if (typeof input?.setContext === "function") {
|
|
115
|
-
input.setContext("toon-memory:" + toolName, text)
|
|
116
|
-
}
|
|
117
|
-
}
|
|
156
|
+
inject(input, "toon-memory:" + toolName, text)
|
|
118
157
|
}
|
|
119
158
|
}
|
|
120
159
|
} catch {}
|
package/src/cli/toon-memory.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { dirname
|
|
1
|
+
import { dirname } from "path"
|
|
2
2
|
import { fileURLToPath } from "url"
|
|
3
|
+
import { fileImportURL } from "./entry"
|
|
3
4
|
|
|
4
5
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
5
6
|
const args = process.argv.slice(2)
|
|
6
7
|
|
|
7
8
|
if (args[0] === "mcp") {
|
|
8
|
-
await import(
|
|
9
|
+
await import(fileImportURL(__dirname, "..", "mcp", "server.js"))
|
|
9
10
|
} else {
|
|
10
11
|
process.argv = ["node", "toon-memory", ...args]
|
|
11
|
-
await import(
|
|
12
|
+
await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"))
|
|
12
13
|
}
|
package/src/lib/graph.ts
CHANGED
|
@@ -612,6 +612,42 @@ export function graphRecall(
|
|
|
612
612
|
return graphRecallDetailed(data, query, opts).entries
|
|
613
613
|
}
|
|
614
614
|
|
|
615
|
+
export interface FetchByIdsOpts {
|
|
616
|
+
/** Temporal view: include superseded entries still valid on that date. */
|
|
617
|
+
asOf?: string
|
|
618
|
+
/** Reference date for TTL expiry checks. Defaults to the wall clock. */
|
|
619
|
+
today?: string
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Resolve ids or keys (comma/space/`;`-separated tokens) to entries, preserving
|
|
624
|
+
* input order. Skips unknown tokens and entries that are obsolete/draft (unless
|
|
625
|
+
* they were still valid under `asOf`). Used by `memory_recall`'s batch fetch —
|
|
626
|
+
* the "second layer" of progressive disclosure after browsing the index.
|
|
627
|
+
*/
|
|
628
|
+
export function fetchEntriesByIds(data: string, tokens: string[], opts: FetchByIdsOpts = {}): GraphEntry[] {
|
|
629
|
+
const byId = new Map<string, GraphEntry>()
|
|
630
|
+
const byKey = new Map<string, GraphEntry>()
|
|
631
|
+
const asOf = opts.asOf || ""
|
|
632
|
+
for (const e of parseEntries(data)) {
|
|
633
|
+
const visible =
|
|
634
|
+
e.status === "active" ||
|
|
635
|
+
e.status === "resolved" ||
|
|
636
|
+
(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)
|
|
637
|
+
if (!visible) continue
|
|
638
|
+
if (asOf && e.date && e.date > asOf) continue
|
|
639
|
+
if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue
|
|
640
|
+
if (!byId.has(e.id)) byId.set(e.id, e)
|
|
641
|
+
if (!byKey.has(e.key)) byKey.set(e.key, e)
|
|
642
|
+
}
|
|
643
|
+
const out: GraphEntry[] = []
|
|
644
|
+
for (const t of tokens) {
|
|
645
|
+
const e = byKey.get(t) || byId.get(t)
|
|
646
|
+
if (e && !out.includes(e)) out.push(e)
|
|
647
|
+
}
|
|
648
|
+
return out
|
|
649
|
+
}
|
|
650
|
+
|
|
615
651
|
export interface RenderCompactOpts {
|
|
616
652
|
/** Restricted adjacency for numeric edge rendering (graph mode). */
|
|
617
653
|
adjacency?: Map<string, string[]>
|
|
@@ -729,3 +765,33 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
|
|
|
729
765
|
|
|
730
766
|
return rendered.join("\n\n")
|
|
731
767
|
}
|
|
768
|
+
|
|
769
|
+
export interface RenderIndexOpts {
|
|
770
|
+
/** Final combined score per key. Normalized to the best result and shown as %. */
|
|
771
|
+
scores?: Map<string, number>
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Token-cheapest listing of recall results — the "first layer" of progressive
|
|
776
|
+
* disclosure. One line per entry: index, key, id, category, date, optional
|
|
777
|
+
* relative relevance %. No content. The agent picks ids from here, then does a
|
|
778
|
+
* full fetch with `memory_recall`'s `ids` parameter. Deterministic, no LLM.
|
|
779
|
+
*/
|
|
780
|
+
export function renderIndex(entries: GraphEntry[], opts: RenderIndexOpts = {}): string {
|
|
781
|
+
let max = 0
|
|
782
|
+
if (opts.scores) {
|
|
783
|
+
for (const v of opts.scores.values()) if (v > max) max = v
|
|
784
|
+
}
|
|
785
|
+
const lines: string[] = []
|
|
786
|
+
for (let i = 0; i < entries.length; i++) {
|
|
787
|
+
const e = entries[i]
|
|
788
|
+
const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
|
|
789
|
+
let score = ""
|
|
790
|
+
if (opts.scores && max > 0) {
|
|
791
|
+
const s = opts.scores.get(e.key)
|
|
792
|
+
if (s !== undefined) score = ` · ${Math.round((s / max) * 100)}%`
|
|
793
|
+
}
|
|
794
|
+
lines.push(`[${i + 1}] ${e.key} (${e.id})${pin} · ${e.category} · ${e.date}${score}`)
|
|
795
|
+
}
|
|
796
|
+
return lines.join("\n")
|
|
797
|
+
}
|
package/src/mcp/tools.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { archiveOldEntries } from "./archive"
|
|
|
12
12
|
import { consolidateEntries, consolidateVersions } from "./consolidation"
|
|
13
13
|
import { readUnderLock } from "../lib/lock"
|
|
14
14
|
import { encrypt, decrypt } from "./crypto"
|
|
15
|
-
import { graphRecallDetailed, renderCompact, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
|
|
15
|
+
import { graphRecallDetailed, renderCompact, renderIndex, fetchEntriesByIds, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
|
|
16
16
|
import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
|
|
17
17
|
import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
|
|
18
18
|
import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS, getCurrentSessionFiles } from "../lib/sessions"
|
|
@@ -563,12 +563,14 @@ server.registerTool(
|
|
|
563
563
|
title: "Search Memory",
|
|
564
564
|
description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files. Pattern: recall → context_diff for recent changes → capture to save observations.",
|
|
565
565
|
inputSchema: {
|
|
566
|
-
query: z.string().describe("Text to search for"),
|
|
566
|
+
query: z.string().optional().default("").describe("Text to search for (optional when mode:'index' or ids is given)"),
|
|
567
567
|
category: z.string().optional().default("").describe("Filter by category (empty = all)"),
|
|
568
568
|
from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
|
|
569
569
|
to_date: z.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
|
|
570
|
-
mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
|
|
570
|
+
mode: z.enum(["flat", "graph", "index"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens). 'index' = one line per entry (key, id, category, date, relevance %) with no content — browse then fetch full entries with `ids`."),
|
|
571
|
+
ids: z.string().optional().default("").describe("Batch fetch: comma/space/;-separated entry ids or keys, rendered in the given order (unknown entries skipped). Complements mode:'index' — layer 2 of progressive disclosure. Overrides mode."),
|
|
571
572
|
hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
|
|
573
|
+
limit: z.number().optional().describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
|
|
572
574
|
compact: z.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
|
|
573
575
|
budget: z.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
|
|
574
576
|
budget_tokens: z.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
|
|
@@ -580,14 +582,61 @@ server.registerTool(
|
|
|
580
582
|
},
|
|
581
583
|
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
|
|
582
584
|
},
|
|
583
|
-
async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
|
|
585
|
+
async ({ query, category, from_date, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
|
|
584
586
|
const data = readMemory()
|
|
587
|
+
const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
|
|
588
|
+
const resolvedAsOf = as_of || undefined
|
|
589
|
+
|
|
590
|
+
// ── Batch fetch by ids/keys (layer 2 of progressive disclosure) ──────
|
|
591
|
+
if (ids && ids.trim()) {
|
|
592
|
+
const tokens = ids.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean)
|
|
593
|
+
const entries = fetchEntriesByIds(data, tokens, { asOf: resolvedAsOf })
|
|
594
|
+
if (entries.length === 0) {
|
|
595
|
+
return { content: [{ type: "text" as const, text: `No entries found for ids: ${ids}` }] }
|
|
596
|
+
}
|
|
597
|
+
bumpAccessed(entries.map((e) => e.id))
|
|
598
|
+
const label = entries.length === 1 ? "entry" : "entries"
|
|
599
|
+
if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
|
|
600
|
+
const formatted = renderCompact(entries, {
|
|
601
|
+
budget: resolvedBudget,
|
|
602
|
+
budgetTokens: budget_tokens || undefined,
|
|
603
|
+
})
|
|
604
|
+
return { content: [{ type: "text" as const, text: `Fetched ${entries.length} ${label}:\n\n${formatted}` }] }
|
|
605
|
+
}
|
|
606
|
+
const formatted = entries
|
|
607
|
+
.map((r) => {
|
|
608
|
+
const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
|
|
609
|
+
const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
|
|
610
|
+
const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
|
|
611
|
+
const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
|
|
612
|
+
const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
|
|
613
|
+
const supersededInfo = r.supersededOn ? ` | superseded: ${r.supersededOn}` : ""
|
|
614
|
+
return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`
|
|
615
|
+
})
|
|
616
|
+
.join("\n\n")
|
|
617
|
+
return { content: [{ type: "text" as const, text: `Fetched ${entries.length} ${label}:\n\n${formatted}` }] }
|
|
618
|
+
}
|
|
585
619
|
|
|
586
|
-
// Delegate to graphRecallDetailed for
|
|
620
|
+
// Delegate to graphRecallDetailed for flat / graph / index modes
|
|
587
621
|
// This avoids duplicating BM25 + ranking logic
|
|
588
622
|
const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
|
|
589
|
-
const
|
|
590
|
-
const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || undefined, rrf, asOf:
|
|
623
|
+
const limit = limitParam ?? (mode === "index" ? 15 : 6)
|
|
624
|
+
const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, limit, sessionFiles, path_scope: path_scope || undefined, rrf, asOf: resolvedAsOf })
|
|
625
|
+
|
|
626
|
+
// ── Index mode: one line per entry, no content ───────────────────────
|
|
627
|
+
if (mode === "index") {
|
|
628
|
+
if (detail.entries.length === 0) {
|
|
629
|
+
return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
|
|
630
|
+
}
|
|
631
|
+
const formatted = renderIndex(detail.entries, { scores: detail.scores })
|
|
632
|
+
return {
|
|
633
|
+
content: [{
|
|
634
|
+
type: "text" as const,
|
|
635
|
+
text: `📇 Memory index (${detail.entries.length} entries):\n\n${formatted}\n\nFetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"flat".`,
|
|
636
|
+
}],
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
591
640
|
if (detail.entries.length === 0) {
|
|
592
641
|
return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
|
|
593
642
|
}
|