Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(recall): preserve saved memories across retrieval and token budgets (#1519)

Rohit Ghumare9d70369f015b
diff --git a/AGENTS.md b/AGENTS.md
index 1d41c57c..6cb59ff1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -101,7 +101,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
## Testing
-- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (2,600+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests.
+- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (2,700+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests.
- Before any npm publish: `npm run release:gate` must pass. It installs the packed tarballs into a clean home and runs capture, recovery, restart, export/import, MCP and status checks against the installed CLI (see CONTRIBUTING.md, Release process)
- Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list`
- Test files go in `test/` with `.test.ts` extension
@@ -114,4 +114,4 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 17 skills
- 312+ iii functions
-- 2,600+ tests
+- 2,700+ tests
diff --git a/README.md b/README.md
index 0b664aa0..0c7ad885 100644
--- a/README.md
+++ b/README.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tools.svg"><img src="assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-hooks.svg"><img src="assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-deps.svg"><img src="assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tests.svg"><img src="assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tests.svg"><img src="assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom plugin systems | `iii worker add <name>` |
-**220 source files · ~52,000 LOC · 2,600+ tests · 312 functions · 60 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself.
+**223 source files · ~53,000 LOC · 2,700+ tests · 312 functions · 60 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself.
---
@@ -1873,7 +1873,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ar-SA.md b/READMEs/README.ar-SA.md
index 6c8e718e..d56c7779 100644
--- a/READMEs/README.ar-SA.md
+++ b/READMEs/README.ar-SA.md
@@ -73,7 +73,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1439,7 +1439,7 @@ fi
| Prometheus / Grafana | OTEL في iii + مراقب الحالة الصحية |
| أنظمة إضافات مخصصة | `iii worker add <name>` |
-**220 ملف مصدري · ~52,000 سطر برمجي · 2,600+ اختبار · 312 دالة · 60 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه.
+**223 ملف مصدري · ~53,000 سطر برمجي · 2,700+ اختبار · 312 دالة · 60 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه.
---
@@ -1863,7 +1863,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.bn-BD.md b/READMEs/README.bn-BD.md
index eb0a3f27..6b69b8a3 100644
--- a/READMEs/README.bn-BD.md
+++ b/READMEs/README.bn-BD.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP টুল" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 অটো হুক" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 এক্সটার্নাল ডিবি" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ টেস্ট পাস" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ টেস্ট পাস" height="38" /></picture>
</p>
<p align="center">
@@ -1437,7 +1437,7 @@ fi
| Prometheus / Grafana | iii OTEL + হেলথ মনিটর |
| কাস্টম প্লাগইন সিস্টেম | `iii worker add <name>` |
-**220 সোর্স ফাইল · ~52,000 LOC · 2,600+ টেস্ট · 312 ফাংশন · 60 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে।
+**223 সোর্স ফাইল · ~53,000 LOC · 2,700+ টেস্ট · 312 ফাংশন · 60 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে।
---
@@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.cs-CZ.md b/READMEs/README.cs-CZ.md
index 14e56293..a57e3cfc 100644
--- a/READMEs/README.cs-CZ.md
+++ b/READMEs/README.cs-CZ.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP nástrojů" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 automatických hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 externích databází" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ testů úspěšně proběhlo" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ testů úspěšně proběhlo" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Vlastní systémy pluginů | `iii worker add <name>` |
-**220 zdrojových souborů · ~52,000 řádků kódu · 2,600+ testů · 312 funkcí · 60 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii.
+**223 zdrojových souborů · ~53,000 řádků kódu · 2,700+ testů · 312 funkcí · 60 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.da-DK.md b/READMEs/README.da-DK.md
index 7b442c18..14098e09 100644
--- a/READMEs/README.da-DK.md
+++ b/READMEs/README.da-DK.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP-værktøjer" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 automatiske hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 eksterne databaser" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ beståede tests" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ beståede tests" height="38" /></picture>
</p>
<p align="center">
@@ -1436,7 +1436,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom plugin-systemer | `iii worker add <name>` |
-**220 kildefiler · ~52,000 LOC · 2,600+ tests · 312 funktioner · 60 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv.
+**223 kildefiler · ~53,000 LOC · 2,700+ tests · 312 funktioner · 60 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv.
---
@@ -1860,7 +1860,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md
index 32906825..d3a21162 100644
--- a/READMEs/README.de-DE.md
+++ b/READMEs/README.de-DE.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP-Tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 Auto-Hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 externe DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ bestandene Tests" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ bestandene Tests" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + Health-Monitor |
| Eigene Plugin-Systeme | `iii worker add <name>` |
-**220 Quelldateien · ~52,000 LOC · 2,600+ Tests · 312 Funktionen · 60 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst.
+**223 Quelldateien · ~53,000 LOC · 2,700+ Tests · 312 Funktionen · 60 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.el-GR.md b/READMEs/README.el-GR.md
index a7ae202c..57226dee 100644
--- a/READMEs/README.el-GR.md
+++ b/READMEs/README.el-GR.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 εργαλεία MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 αυτόματα hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 εξωτερικές βάσεις δεδομένων" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ επιτυχημένες δοκιμές" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ επιτυχημένες δοκιμές" height="38" /></picture>
</p>
<p align="center">
@@ -1438,7 +1438,7 @@ fi
| Prometheus / Grafana | iii OTEL + monitor υγείας |
| Προσαρμοσμένα συστήματα plugin | `iii worker add <name>` |
-**220 αρχεία πηγαίου κώδικα · ~52,000 LOC · 2,600+ δοκιμές · 312 functions · 60 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii.
+**223 αρχεία πηγαίου κώδικα · ~53,000 LOC · 2,700+ δοκιμές · 312 functions · 60 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii.
---
@@ -1862,7 +1862,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md
index 00e1aa7a..2abc256c 100644
--- a/READMEs/README.es-ES.md
+++ b/READMEs/README.es-ES.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 tools MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 hooks automáticos" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 bases de datos externas" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests superados" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests superados" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + monitor de salud |
| Sistemas de plugins propios | `iii worker add <name>` |
-**220 ficheros de código · ~52,000 LOC · 2,600+ tests · 312 funciones · 60 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo.
+**223 ficheros de código · ~53,000 LOC · 2,700+ tests · 312 funciones · 60 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.fi-FI.md b/READMEs/README.fi-FI.md
index 9de4a8bd..bdcdebc1 100644
--- a/READMEs/README.fi-FI.md
+++ b/READMEs/README.fi-FI.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP-työkalua" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 automaattista hookia" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 ulkoista tietokantaa" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ testiä läpäisty" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ testiä läpäisty" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + terveysmonitori |
| Mukautetut plugin-järjestelmät | `iii worker add <name>` |
-**220 lähdetiedostoa · ~52,000 LOC · 2,600+ testiä · 312 funktiota · 60 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse.
+**223 lähdetiedostoa · ~53,000 LOC · 2,700+ testiä · 312 funktiota · 60 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md
index c56106d0..2e7baa1e 100644
--- a/READMEs/README.fr-FR.md
+++ b/READMEs/README.fr-FR.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1448,7 +1448,7 @@ fi
| Prometheus / Grafana | iii OTEL + moniteur de santé |
| Systèmes de plugins custom | `iii worker add <name>` |
-**220 fichiers sources · ~52,000 LOC · 2,600+ tests · 312 fonctions · 60 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même.
+**223 fichiers sources · ~53,000 LOC · 2,700+ tests · 312 fonctions · 60 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même.
---
@@ -1872,7 +1872,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.he-IL.md b/READMEs/README.he-IL.md
index e63951b5..598907af 100644
--- a/READMEs/README.he-IL.md
+++ b/READMEs/README.he-IL.md
@@ -73,7 +73,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 כלי MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 hooks אוטומטיים" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 מסדי נתונים חיצוניים" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ בדיקות עוברות" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ בדיקות עוברות" height="38" /></picture>
</p>
<p align="center">
@@ -1439,7 +1439,7 @@ fi
| Prometheus / Grafana | iii OTEL + מוניטור health |
| מערכות plugin מותאמות אישית | `iii worker add <name>` |
-**220 קבצי מקור · ~52,000 LOC · 2,600+ בדיקות · 312 פונקציות · 60 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו.
+**223 קבצי מקור · ~53,000 LOC · 2,700+ בדיקות · 312 פונקציות · 60 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו.
---
@@ -1863,7 +1863,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md
index ea4b48e9..936158b0 100644
--- a/READMEs/README.hi-IN.md
+++ b/READMEs/README.hi-IN.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1449,7 +1449,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom plugin systems | `iii worker add <name>` |
-**220 source files · ~52,000 LOC · 2,600+ tests · 312 functions · 60 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है।
+**223 source files · ~53,000 LOC · 2,700+ tests · 312 functions · 60 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है।
---
@@ -1873,7 +1873,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.hu-HU.md b/READMEs/README.hu-HU.md
index 95bd5e77..dce76e6d 100644
--- a/READMEs/README.hu-HU.md
+++ b/READMEs/README.hu-HU.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP eszköz" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 automatikus hook" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 külső adatbázis" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ sikeres teszt" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ sikeres teszt" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ A `/agentmemory/export` emellett elfogadja a `?maxSessions=`-t és a `?offset=`-
| Prometheus / Grafana | iii OTEL + egészségfigyelő |
| Egyéni plugin-rendszerek | `iii worker add <name>` |
-**220 forrásfájl · ~52,000 LOC · 2,600+ teszt · 312 funkció · 60 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii.
+**223 forrásfájl · ~53,000 LOC · 2,700+ teszt · 312 funkció · 60 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.id-ID.md b/READMEs/README.id-ID.md
index 0d7c985d..52fd8a99 100644
--- a/READMEs/README.id-ID.md
+++ b/READMEs/README.id-ID.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 tool MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 hook otomatis" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 DB eksternal" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ pengujian lolos" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ pengujian lolos" height="38" /></picture>
</p>
<p align="center">
@@ -1447,7 +1447,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Sistem plugin custom | `iii worker add <name>` |
-**220 file sumber · ~52,000 LOC · 2,600+ pengujian · 312 fungsi · 60 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri.
+**223 file sumber · ~53,000 LOC · 2,700+ pengujian · 312 fungsi · 60 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri.
---
@@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.it-IT.md b/READMEs/README.it-IT.md
index fd0a2d12..770b3dd0 100644
--- a/READMEs/README.it-IT.md
+++ b/READMEs/README.it-IT.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + monitor di salute |
| Sistemi di plugin personalizzati | `iii worker add <name>` |
-**220 file sorgente · ~52,000 righe di codice · 2,600+ test · 312 funzioni · 60 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso.
+**223 file sorgente · ~53,000 righe di codice · 2,700+ test · 312 funzioni · 60 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md
index 7f080a19..fedf3758 100644
--- a/READMEs/README.ja-JP.md
+++ b/READMEs/README.ja-JP.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP ツール" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 自動 hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="外部 DB 0 個" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ 件のテストが成功" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ 件のテストが成功" height="38" /></picture>
</p>
<p align="center">
@@ -1445,7 +1445,7 @@ fi
| Prometheus / Grafana | iii OTEL + ヘルスモニタ |
| カスタムプラグインシステム | `iii worker add <name>` |
-**220 ソースファイル · ~52,000 LOC · 2,600+ テスト · 312 functions · 60 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。
+**223 ソースファイル · ~53,000 LOC · 2,700+ テスト · 312 functions · 60 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。
---
@@ -1869,7 +1869,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md
index 94bcd342..b164c32a 100644
--- a/READMEs/README.ko-KR.md
+++ b/READMEs/README.ko-KR.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + health 모니터 |
| 커스텀 플러그인 시스템 | `iii worker add <name>` |
-**소스 파일 220개 · LOC ~52,000줄 · 테스트 2,600+개 · 함수 312개 · KV 스코프 60개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다.
+**소스 파일 223개 · LOC ~53,000줄 · 테스트 2,700+개 · 함수 312개 · KV 스코프 60개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.nb-NO.md b/READMEs/README.nb-NO.md
index 7875e502..2e10f52f 100644
--- a/READMEs/README.nb-NO.md
+++ b/READMEs/README.nb-NO.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1447,7 +1447,7 @@ fi
| Prometheus / Grafana | iii OTEL + helseovervåker |
| Egendefinerte plugin-systemer | `iii worker add <name>` |
-**220 kildefiler · ~52,000 LOC · 2,600+ tester · 312 funksjoner · 60 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv.
+**223 kildefiler · ~53,000 LOC · 2,700+ tester · 312 funksjoner · 60 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv.
---
@@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.nl-NL.md b/READMEs/README.nl-NL.md
index 5b2fa0b2..749663b7 100644
--- a/READMEs/README.nl-NL.md
+++ b/READMEs/README.nl-NL.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom plugin-systemen | `iii worker add <name>` |
-**220 bronbestanden · ~52,000 LOC · 2,600+ tests · 312 functies · 60 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf.
+**223 bronbestanden · ~53,000 LOC · 2,700+ tests · 312 functies · 60 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pl-PL.md b/READMEs/README.pl-PL.md
index d9f046d5..453f1b72 100644
--- a/READMEs/README.pl-PL.md
+++ b/READMEs/README.pl-PL.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 narzędzia MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 automatycznych hooków" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 zewnętrznych baz danych" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ zaliczonych testów" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ zaliczonych testów" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + monitor stanu |
| Niestandardowe systemy pluginów | `iii worker add <name>` |
-**220 plików źródłowych · ~52,000 LOC · 2,600+ testów · 312 funkcji · 60 zakresów KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii.
+**223 plików źródłowych · ~53,000 LOC · 2,700+ testów · 312 funkcji · 60 zakresów KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md
index a21e6bd7..306ef159 100644
--- a/READMEs/README.pt-BR.md
+++ b/READMEs/README.pt-BR.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1447,7 +1447,7 @@ fi
| Prometheus / Grafana | iii OTEL + monitor de saúde |
| Sistemas de plugin customizados | `iii worker add <name>` |
-**220 arquivos de código · ~52,000 LOC · 2,600+ testes · 312 funções · 60 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.
+**223 arquivos de código · ~53,000 LOC · 2,700+ testes · 312 funções · 60 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.
---
@@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pt-PT.md b/READMEs/README.pt-PT.md
index bb0a0c0b..97146fc4 100644
--- a/READMEs/README.pt-PT.md
+++ b/READMEs/README.pt-PT.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 ferramentas MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 hooks automáticos" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 bases de dados externas" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ testes aprovados" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ testes aprovados" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ O `/agentmemory/export` também aceita `?maxSessions=` e `?offset=` para dividir
| Prometheus / Grafana | iii OTEL + monitor de saúde |
| Sistemas de plugins personalizados | `iii worker add <name>` |
-**220 ficheiros de código-fonte · ~52,000 LOC · 2,600+ testes · 312 funções · 60 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.
+**223 ficheiros de código-fonte · ~53,000 LOC · 2,700+ testes · 312 funções · 60 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ro-RO.md b/READMEs/README.ro-RO.md
index ac4349c1..ddbac809 100644
--- a/READMEs/README.ro-RO.md
+++ b/READMEs/README.ro-RO.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 de instrumente MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 hook-uri automate" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 baze de date externe" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ teste trecute" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ teste trecute" height="38" /></picture>
</p>
<p align="center">
@@ -1430,7 +1430,7 @@ fi
| Prometheus / Grafana | iii OTEL + monitor de sănătate |
| Sisteme de plugin-uri personalizate | `iii worker add <name>` |
-**220 fișiere sursă · ~52,000 LOC · 2,600+ teste · 312 funcții · 60 domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii.
+**223 fișiere sursă · ~53,000 LOC · 2,700+ teste · 312 funcții · 60 domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii.
---
@@ -1854,7 +1854,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md
index 3546d60c..5159f1cd 100644
--- a/READMEs/README.ru-RU.md
+++ b/READMEs/README.ru-RU.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ fi
| Prometheus / Grafana | iii OTEL + монитор состояния |
| Самописные плагинные системы | `iii worker add <name>` |
-**220 исходных файлов · ~52,000 LOC · 2,600+ тестов · 312 функция · 60 KV-scope'ов**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii.
+**223 исходных файлов · ~53,000 LOC · 2,700+ тестов · 312 функция · 60 KV-scope'ов**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.sv-SE.md b/READMEs/README.sv-SE.md
index 8b56965d..5d2e43e6 100644
--- a/READMEs/README.sv-SE.md
+++ b/READMEs/README.sv-SE.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP-verktyg" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 automatiska hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 externa databaser" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ godkända tester" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ godkända tester" height="38" /></picture>
</p>
<p align="center">
@@ -1437,7 +1437,7 @@ fi
| Prometheus / Grafana | iii OTEL + hälsoövervakare |
| Anpassade pluginsystem | `iii worker add <name>` |
-**220 källkodsfiler · ~52,000 LOC · 2,600+ tester · 312 funktioner · 60 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt.
+**223 källkodsfiler · ~53,000 LOC · 2,700+ tester · 312 funktioner · 60 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt.
---
@@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.th-TH.md b/READMEs/README.th-TH.md
index a453c441..21f84656 100644
--- a/READMEs/README.th-TH.md
+++ b/READMEs/README.th-TH.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 เครื่องมือ MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 hook อัตโนมัติ" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="ไม่ต้องพึ่ง external DB เลย" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="ผ่านการทดสอบ 2,600+ รายการ" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="ผ่านการทดสอบ 2,700+ รายการ" height="38" /></picture>
</p>
<p align="center">
@@ -1444,7 +1444,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom plugin systems | `iii worker add <name>` |
-**220 source file · ~52,000 LOC · 2,600+ การทดสอบ · 312 function · 60 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ
+**223 source file · ~53,000 LOC · 2,700+ การทดสอบ · 312 function · 60 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ
---
@@ -1868,7 +1868,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.tl-PH.md b/READMEs/README.tl-PH.md
index b99e89d1..e5576d32 100644
--- a/READMEs/README.tl-PH.md
+++ b/READMEs/README.tl-PH.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tool" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 awtomatikong hook" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 panlabas na DB" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ pumapasang test" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ pumapasang test" height="38" /></picture>
</p>
<p align="center">
@@ -1446,7 +1446,7 @@ Tinatanggap din ng `/agentmemory/export` ang `?maxSessions=` at `?offset=` para
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom na plugin system | `iii worker add <name>` |
-**220 na source file · ~52,000 LOC · 2,600+ na test · 312 na function · 60 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii.
+**223 na source file · ~53,000 LOC · 2,700+ na test · 312 na function · 60 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii.
---
@@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md
index 04f6e194..558838ee 100644
--- a/READMEs/README.tr-TR.md
+++ b/READMEs/README.tr-TR.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1437,7 +1437,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom eklenti sistemleri | `iii worker add <name>` |
-**220 kaynak dosya · ~52,000 LOC · 2,600+ test · 312 fonksiyon · 60 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir.
+**223 kaynak dosya · ~53,000 LOC · 2,700+ test · 312 fonksiyon · 60 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir.
---
@@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.uk-UA.md b/READMEs/README.uk-UA.md
index 73bee280..3ee2bb63 100644
--- a/READMEs/README.uk-UA.md
+++ b/READMEs/README.uk-UA.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 інструменти MCP" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 автоматичних хуків" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 зовнішніх БД" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ тестів пройдено" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ тестів пройдено" height="38" /></picture>
</p>
<p align="center">
@@ -1447,7 +1447,7 @@ fi
| Prometheus / Grafana | iii OTEL + монітор стану здоров'я |
| Власні системи плагінів | `iii worker add <name>` |
-**220 вихідних файлів · ~52,000 LOC · 2,600+ тестів · 312 функцій · 60 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii.
+**223 вихідних файлів · ~53,000 LOC · 2,700+ тестів · 312 функцій · 60 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii.
---
@@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ur-PK.md b/READMEs/README.ur-PK.md
index 5a6f6599..ddff308c 100644
--- a/READMEs/README.ur-PK.md
+++ b/READMEs/README.ur-PK.md
@@ -73,7 +73,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP ٹولز" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 خودکار ہکس" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 خارجی ڈیٹابیسز" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ ٹیسٹس پاس ہو رہے ہیں" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ ٹیسٹس پاس ہو رہے ہیں" height="38" /></picture>
</p>
<p align="center">
@@ -1432,7 +1432,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| کسٹم plugin سسٹمز | `iii worker add <name>` |
-**220 سورس فائلز · ~52,000 لائنز کوڈ · 2,600+ ٹیسٹس · 312 فنکشنز · 60 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔
+**223 سورس فائلز · ~53,000 لائنز کوڈ · 2,700+ ٹیسٹس · 312 فنکشنز · 60 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔
---
@@ -1854,7 +1854,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.vi-VN.md b/READMEs/README.vi-VN.md
index 7cb76258..1dec686e 100644
--- a/READMEs/README.vi-VN.md
+++ b/READMEs/README.vi-VN.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ tests passing" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ tests passing" height="38" /></picture>
</p>
<p align="center">
@@ -1437,7 +1437,7 @@ fi
| Prometheus / Grafana | iii OTEL + health monitor |
| Hệ thống plugin tùy chỉnh | `iii worker add <name>` |
-**220 file source · ~52,000 LOC · 2,600+ test · 312 function · 60 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii.
+**223 file source · ~53,000 LOC · 2,700+ test · 312 function · 60 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii.
---
@@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md
index 3cd9d255..51250d3b 100644
--- a/READMEs/README.zh-CN.md
+++ b/READMEs/README.zh-CN.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 个 MCP 工具" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 个自动 hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 个外部数据库" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ 项测试通过" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ 项测试通过" height="38" /></picture>
</p>
<p align="center">
@@ -1444,7 +1444,7 @@ fi
| Prometheus / Grafana | iii OTEL + 健康监控 |
| Custom plugin systems | `iii worker add <name>` |
-**220 个源文件 · ~52,000 行代码 · 2,600+ 个测试 · 312 个函数 · 60 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。
+**223 个源文件 · ~53,000 行代码 · 2,700+ 个测试 · 312 个函数 · 60 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。
---
@@ -1868,7 +1868,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md
index 57a1c78d..d8f7704f 100644
--- a/READMEs/README.zh-TW.md
+++ b/READMEs/README.zh-TW.md
@@ -71,7 +71,7 @@
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tools.svg"><img src="../assets/tags/stat-tools.svg" alt="54 個 MCP 工具" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-hooks.svg"><img src="../assets/tags/stat-hooks.svg" alt="12 個自動 hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-deps.svg"><img src="../assets/tags/stat-deps.svg" alt="0 個外部資料庫" height="38" /></picture>
- <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,600+ 測試通過" height="38" /></picture>
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../assets/tags/light/stat-tests.svg"><img src="../assets/tags/stat-tests.svg" alt="2,700+ 測試通過" height="38" /></picture>
</p>
<p align="center">
@@ -1430,7 +1430,7 @@ fi
| Prometheus / Grafana | iii OTEL + 健康監控 |
| 自訂外掛系統 | `iii worker add <name>` |
-**220 個原始檔 · ~52,000 行程式碼 · 2,600+ 測試 · 312 個函式 · 60 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。
+**223 個原始檔 · ~53,000 行程式碼 · 2,700+ 測試 · 312 個函式 · 60 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。
---
@@ -1854,7 +1854,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 2,600+ tests
+npm test # 2,700+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/assets/tags/light/stat-tests.svg b/assets/tags/light/stat-tests.svg
index 4dfe9de3..a6acf266 100644
--- a/assets/tags/light/stat-tests.svg
+++ b/assets/tags/light/stat-tests.svg
@@ -1,5 +1,5 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 2600+">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 2700+">
<rect x="0" y="0" width="140" height="48" rx="10" fill="#FFFFFF" stroke="#E5E7EB" stroke-width="1"/>
- <text x="70" y="24" fill="#16A34A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">2600+</text>
+ <text x="70" y="24" fill="#16A34A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">2700+</text>
<text x="70" y="38" fill="#64748B" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="9" font-weight="600" text-anchor="middle" letter-spacing="1.5">TESTS PASSING</text>
</svg>
diff --git a/assets/tags/stat-tests.svg b/assets/tags/stat-tests.svg
index b704fbe7..25a0b0c8 100644
--- a/assets/tags/stat-tests.svg
+++ b/assets/tags/stat-tests.svg
@@ -1,5 +1,5 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 2600+">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 2700+">
<rect x="0" y="0" width="140" height="48" rx="10" fill="#1A1A1A" stroke="#2A2A2A" stroke-width="1"/>
- <text x="70" y="24" fill="#00D26A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">2600+</text>
+ <text x="70" y="24" fill="#00D26A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">2700+</text>
<text x="70" y="38" fill="#9CA3AF" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="9" font-weight="600" text-anchor="middle" letter-spacing="1.5">TESTS PASSING</text>
</svg>
diff --git a/docs/recall.md b/docs/recall.md
new file mode 100644
index 00000000..434dc5bf
--- /dev/null
+++ b/docs/recall.md
@@ -0,0 +1,88 @@
+# Retrieving saved knowledge
+
+Use `targetLayer: "memory"` when you want records created by `memory_save`,
+including their latest versions. Captured tool activity remains available through
+`targetLayer: "observation"`. Omitting the option, or passing `"all"`, keeps mixed
+search. Both `memory_recall` and `memory_smart_search` accept the option.
+
+```json
+{
+ "query": "authentication deployment decision",
+ "project": "my-project",
+ "targetLayer": "memory",
+ "format": "narrative",
+ "token_budget": 900
+}
+```
+
+Send these arguments to `memory_recall`, or POST them to
+`/agentmemory/search`. The layer filter runs before keyword and vector candidate
+limits and graph ranking, so a large observation history cannot consume the
+saved-memory candidate slots. Search results include a `layer` field. Layer
+selection does not change the default mixed ranking or delete captured activity.
+
+`memory_smart_search` uses the same layer selection at `/agentmemory/smart-search`.
+Its optional lesson list accompanies mixed search only. Use `memory_lesson_recall`
+for lessons and `memory_insight_list` for insights. Layer selection is separate
+from `project` and `agentId`; preserve scope filters when expanding results.
+
+## Budgeted recall
+
+All three `memory_recall` formats (`full`, `compact`, `narrative`) return structured
+JSON through both REST and MCP. Narrative output includes its readable `text`
+field alongside results and budget metadata. Clients that previously consumed
+raw narrative MCP text should parse the JSON and read `text`.
+
+- `matched_count` counts scoped, ranked matches within the requested `limit`.
+ It is not a corpus-wide count.
+- `content_truncated: true` on a result marks a shortened preview. Its ID remains
+ intact. Full previews can omit facts, concepts, files, and optional fields to
+ fit the budget; available agent identity, confidence, and origin channel/time
+ are retained. The stored record remains unchanged.
+- `excluded_by_budget` counts matched records that were not returned.
+- `excluded_results` contains up to ten recovery references with IDs, session
+ IDs, and short titles. `excluded_results_truncated` indicates more omissions.
+- `minimum_budget` appears when the budget cannot fit even the top result's
+ smallest identity-bearing preview. Increase the budget or expand the reference.
+- `truncated` covers either shortened content or omitted results.
+
+The highest-ranked match is kept first, with a preview when necessary. Packing
+preserves rank order; it does not replace a long top match with smaller,
+lower-ranked records. `matched_count: 0` means no selected matches. Empty results
+with a positive `matched_count` mean the budget prevented a preview.
+
+`tokens_used` is a heuristic: the sum of each returned result's serialized JSON
+length divided by three, rounded up. `token_budget` caps that estimate. It is not
+an exact model-token count or a cap on the whole response. The JSON envelope,
+recovery metadata, and narrative `text` copy add overhead outside that estimate.
+Use compact recall followed by selective expansion when response size matters.
+
+## Recover full content
+
+Call `memory_smart_search` with a clipped result ID or an ID from
+`excluded_results`. A query is not required for expansion:
+
+```json
+{
+ "expandIds": "mem_example",
+ "project": "my-project",
+ "targetLayer": "memory"
+}
+```
+
+Use a comma-separated string for MCP and an array of IDs for REST.
+The response contains complete stored content for up to 20 accessible matching
+records. The server examines at most 100 requested IDs per call and sets
+`truncated` when a cap leaves requests unprocessed. Keep any `agentId` filter
+from the original search.
+
+The reduced local MCP fallback stores saved memories only. Memory-only recall
+works there; observation-only recall returns no rows. It uses the same recall
+budget response contract as the full server.
+
+## Local regression evaluation
+
+Run `npm run build` followed by `npm run eval:recall`. The evaluation creates a
+fresh local iii instance, imports synthetic tool observations and saved memories,
+and checks recall through REST and MCP without model calls or personal data.
+See [evaluation setup](../eval/README.md) for engine and sandbox requirements.
diff --git a/eval/README.md b/eval/README.md
index 72f94a49..73aae2c8 100644
--- a/eval/README.md
+++ b/eval/README.md
@@ -12,6 +12,7 @@ npm run eval:coding-life -- --adapters grep,bm25
npm run build
npm run eval:coding-life -- --adapters grep,bm25,agentmemory
npm run eval:lifecycle
+npm run eval:recall
```
The defaults are local and require no model API keys. The HTTP adapter and lifecycle suite require an installed **iii 0.22.1** binary. Set `AGENTMEMORY_EVAL_III` to its absolute path, or use the binary installed by AgentMemory at `~/.agentmemory/bin/iii`.
@@ -90,6 +91,17 @@ The reader is a deterministic command selector over returned text. The fixture c
## Methodology and publication
+`eval:recall` runs a synthetic saved-memory regression against the built CLI and
+iii. Each of five queries has one long saved memory and 360 short tool observations;
+a separate-project memory tests scope preservation. It checks filtering before
+retrieval limits, all recall formats over REST and MCP, tiny-budget disclosure,
+full-content expansion, observation-only search, and restart persistence. Reports
+include mixed and memory-only result IDs, source fingerprints, and every check.
+The distractors exceed both keyword and hybrid candidate windows, and the mixed
+search control must miss the saved record before filtered recall is tested.
+These checks measure the response contract on a development fixture, not general
+answer accuracy or competitor performance.
+
Useful methods were adapted from [gbrain-evals](https://github.com/garrytan/gbrain-evals) (strict evidence and lifecycle controls), [Mem0 memory-benchmarks](https://github.com/mem0ai/memory-benchmarks) (long-history coverage), [DolphinBench](https://github.com/mem0ai/dolphinbench) (memory-to-action checks), and [Supermemory MemoryBench](https://github.com/supermemoryai/memorybench) (provider separation and per-case reporting). This is an independent implementation, not an official run of those suites.
A public competitive claim requires the same dataset revision and split, ingestion semantics, context budget, reader model/prompt, judge/rubric, retries and failure accounting across systems. Publish full per-case receipts, operational failure rates, phase costs and paired uncertainty estimates. Keep development tuning separate from held-out evaluation; freeze configuration before the held-out run. A tie or a small selected slice does not establish leadership. Vendor headline answer scores cannot be compared with these retrieval scores.
diff --git a/eval/runner/recall-quality.ts b/eval/runner/recall-quality.ts
new file mode 100644
index 00000000..265e2579
--- /dev/null
+++ b/eval/runner/recall-quality.ts
@@ -0,0 +1,147 @@
+import assert from "node:assert/strict";
+import { appendFileSync, existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { parseArgs } from "node:util";
+import type { CompressedObservation, Memory, Session } from "../../src/types.js";
+import { VERSION } from "../../src/version.js";
+import { fingerprint } from "./fingerprint.js";
+import { startSandbox, type LocalSandbox } from "./sandbox.js";
+
+type Hit = { obsId?: string; observation?: CompressedObservation; layer?: string; content_truncated?: boolean };
+interface Recall {
+ results: Hit[];
+ matched_count: number;
+ excluded_by_budget: number;
+ excluded_results: Array<{ obsId: string }>;
+ minimum_budget?: number;
+ tokens_used: number;
+ truncated: boolean;
+}
+interface Check { name: string; status: "pass" | "fail"; receipt?: unknown; error?: string }
+
+const project = "recall-eval-orbit";
+const timestamp = "2026-01-01T00:00:00Z";
+const queries = ["quasar routing", "cedar deployment", "marble authentication", "cobalt storage", "saffron tracing"];
+const sessions: Session[] = queries.map((_, i) => ({ id: `ses_recall_${i}`, project, cwd: "/synthetic/orbit",
+ startedAt: timestamp, status: "completed", observationCount: 360 }));
+const observations: Record<string, CompressedObservation[]> = Object.fromEntries(sessions.map((session, i) => [
+ session.id, Array.from({ length: 360 }, (_, n) => ({ id: `obs_recall_${i}_${n}`, sessionId: session.id,
+ timestamp, type: "command_run" as const, title: "Bash", narrative: `${queries[i]} command output ${n}`,
+ facts: [], concepts: [], files: [], importance: 5, confidence: 0.3 })),
+]));
+const memories: Memory[] = queries.map((query, i) => ({ id: `mem_recall_${i}`, createdAt: timestamp,
+ updatedAt: timestamp, type: "architecture", title: `${query} decision savedpolicy${i}`,
+ content: `${query}: keep the approved policy. ` + "The design records explicit assumptions, operational constraints, and the rollback procedure. ".repeat(90),
+ concepts: [], files: [], sessionIds: [], strength: 8, version: 1, isLatest: true, project }));
+const privateMemory: Memory = { ...memories[0], id: "mem_recall_private", project: "recall-eval-other",
+ title: "Private quasar routing policy savedpolicy0", content: "quasar routing private policy" };
+const id = (hit: Hit): string | undefined => hit.obsId ?? hit.observation?.id;
+
+async function main(): Promise<void> {
+ const { values } = parseArgs({ options: { out: { type: "string",
+ default: "eval/reports/recall-" + new Date().toISOString().replace(/[:.]/g, "-") } } });
+ const out = resolve(values.out);
+ if (existsSync(out) && readdirSync(out).length) throw new Error("Output directory is not empty: " + out);
+ mkdirSync(out, { recursive: true });
+ writeFileSync(join(out, "manifest.json"), JSON.stringify({ benchmark: "saved-memory-recall-v1", source: fingerprint(true),
+ fixture: { observations: 1800, savedMemories: 5, privateControl: 1, observationsPerSavedMemory: 360, queries },
+ scope: "Synthetic retrieval and budget regression; noop provider, no embeddings or model calls" }, null, 2) + "\n");
+ const checks: Check[] = [];
+ async function check(name: string, run: () => Promise<unknown>): Promise<void> {
+ let result: Check;
+ try { result = { name, status: "pass", receipt: await run() }; }
+ catch (error) { result = { name, status: "fail", error: error instanceof Error ? error.message : String(error) }; }
+ checks.push(result);
+ appendFileSync(join(out, "checks.ndjson"), JSON.stringify(result) + "\n");
+ console.log(result.status + " " + name);
+ }
+ let sandbox: LocalSandbox | undefined;
+ const planned = queries.length * 2 + 9;
+ try {
+ sandbox = await startSandbox();
+ const store = sandbox;
+ await store.request("/import", { exportData: { version: VERSION, exportedAt: timestamp,
+ sessions, observations, memories: [...memories, privateMemory], summaries: [] } });
+ for (const [i, query] of queries.entries()) {
+ for (const path of ["/search", "/smart-search"]) {
+ await check(path.slice(1) + "-saved-memory-" + i, async () => {
+ const mixed = await store.request<Recall>(path, { query, project, limit: 5 });
+ assert.ok(!mixed.results.some((hit) => id(hit) === memories[i].id), "noise control must crowd out the saved memory");
+ const filtered = await store.request<Recall>(path, { query, project, limit: 5, targetLayer: "memory" });
+ assert.ok(filtered.results.some((hit) => id(hit) === memories[i].id));
+ assert.ok(filtered.results.every((hit) => hit.layer === "memory"));
+ assert.ok(filtered.results.every((hit) => id(hit) !== privateMemory.id));
+ return { mixedIds: mixed.results.map(id), memoryIds: filtered.results.map(id), expected: memories[i].id };
+ });
+ }
+ }
+ for (const format of ["full", "compact", "narrative"]) {
+ await check("budget-and-mcp-" + format, async () => {
+ const args = { query: "savedpolicy0", project, targetLayer: "memory", format, token_budget: 900 };
+ const response = await store.request<Recall>("/search", args);
+ assert.equal(id(response.results[0]), memories[0].id);
+ assert.equal(response.matched_count, 1);
+ assert.ok(response.tokens_used <= 900);
+ if (format !== "compact") assert.equal(response.results[0].content_truncated, true);
+ const mcp = await store.request<{ content: Array<{ text: string }> }>("/mcp/call", { name: "memory_recall", arguments: args });
+ const wire = JSON.parse(mcp.content[0].text) as Recall;
+ assert.equal(id(wire.results[0]), memories[0].id);
+ assert.equal(wire.matched_count, 1);
+ assert.deepEqual(wire, response);
+ return { id: id(wire.results[0]), tokens: wire.tokens_used, clipped: wire.results[0].content_truncated ?? false };
+ });
+ }
+ await check("tiny-budget-has-scoped-recovery-reference", async () => {
+ const result = await store.request<Recall>("/search", { query: "savedpolicy0", project, targetLayer: "memory", token_budget: 1 });
+ assert.deepEqual(result.results, []);
+ assert.equal(result.matched_count, 1);
+ assert.equal(result.excluded_by_budget, 1);
+ assert.ok((result.minimum_budget ?? 0) > 1);
+ assert.deepEqual(result.excluded_results.map((hit) => hit.obsId), [memories[0].id]);
+ const mcp = await store.request<{ content: Array<{ text: string }> }>("/mcp/call", {
+ name: "memory_recall", arguments: { query: "savedpolicy0", project, targetLayer: "memory", token_budget: 1 },
+ });
+ assert.deepEqual(JSON.parse(mcp.content[0].text), result);
+ return result;
+ });
+ await check("mcp-expansion-recovers-complete-memory", async () => {
+ const response = await store.request<{ content: Array<{ text: string }> }>("/mcp/call", {
+ name: "memory_smart_search", arguments: { expandIds: memories[0].id, targetLayer: "memory", project },
+ });
+ const expanded = JSON.parse(response.content[0].text) as Recall;
+ assert.equal(expanded.results[0]?.observation?.narrative, memories[0].content);
+ return { id: id(expanded.results[0]), recoveredCharacters: memories[0].content.length };
+ });
+ await check("empty-query-match-is-distinct-from-budget-exclusion", async () => {
+ const response = await store.request<Recall>("/search", { query: "nonexistentuniquelexeme", targetLayer: "memory", token_budget: 1 });
+ assert.deepEqual(response.results, []);
+ assert.equal(response.matched_count, 0);
+ assert.equal(response.excluded_by_budget, 0);
+ assert.equal(response.truncated, false);
+ return response;
+ });
+ await check("observation-layer-remains-searchable", async () => {
+ const response = await store.request<Recall>("/smart-search", { query: queries[0], project, targetLayer: "observation", limit: 5 });
+ assert.equal(response.results.length, 5);
+ assert.ok(response.results.every((hit) => hit.layer === "observation"));
+ return { ids: response.results.map(id) };
+ });
+ await check("restart-preserves-memory-filter-and-content", async () => {
+ await store.restart();
+ const response = await store.request<Recall>("/search", { query: queries[0], project, targetLayer: "memory" });
+ assert.equal(response.results[0]?.observation?.narrative, memories[0].content);
+ return { ids: response.results.map(id) };
+ });
+ } catch (error) {
+ await check("setup-or-infrastructure", async () => { throw error; });
+ } finally {
+ await check("sandbox-cleanup", async () => { await sandbox?.close(); return { stopped: true }; });
+ const failed = checks.filter((entry) => entry.status === "fail").length;
+ const summary = { planned, executed: checks.length, passed: checks.length - failed, failed,
+ complete: checks.length === planned, claim: "Synthetic regression fixture, not a competitor or answer-quality benchmark" };
+ writeFileSync(join(out, "summary.json"), JSON.stringify(summary, null, 2) + "\n");
+ if (failed || !summary.complete) process.exitCode = 1;
+ }
+}
+
+main().catch((error) => { console.error(error); process.exitCode = 1; });
diff --git a/package.json b/package.json
index a9af87d4..0893be3a 100644
--- a/package.json
+++ b/package.json
@@ -39,6 +39,7 @@
"eval:longmemeval": "node --import tsx eval/runner/longmemeval.ts",
"eval:coding-life": "node --import tsx eval/runner/coding-life.ts",
"eval:lifecycle": "node --import tsx eval/runner/lifecycle.ts",
+ "eval:recall": "node --import tsx eval/runner/recall-quality.ts",
"eval:check": "tsc --noEmit --project tsconfig.eval.json && vitest run test/eval-adapters.test.ts test/eval-integrity.test.ts"
},
"keywords": [
diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
index fc01a8dd..c1b7b6c1 100644
--- a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
+++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
@@ -36,7 +36,7 @@ agentmemory exposes 54 MCP tools. 8 are in the lean core set (`--tools core` or
| `memory_obsidian_export` | | `vaultDir`: string, `types`: string | Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view. |
| `memory_patterns` | | `project`: string, `limit`: integer | Detect recurring patterns across sessions. |
| `memory_profile` | | `project`*: string, `refresh`: string | User/project profile with top concepts and file patterns. |
-| `memory_recall` | yes | `query`*: string, `limit`: number, `format`: string, `token_budget`: number | Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before. |
+| `memory_recall` | yes | `query`*: string, `limit`: number, `format`: string, `token_budget`: number, `targetLayer`: string, `project`: string, `cwd`: string, `agentId`: string | Search stored memories and session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before. |
| `memory_reflect` | yes | `project`: string, `maxClusters`: number | Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights. |
| `memory_relations` | | `memoryId`*: string, `maxHops`: number, `minConfidence`: number | Query the memory relationship graph. |
| `memory_routine_run` | | `routineId`*: string, `project`: string, `initiatedBy`: string | Instantiate a frozen workflow routine, creating actions for each step with proper dependencies. |
@@ -54,7 +54,7 @@ agentmemory exposes 54 MCP tools. 8 are in the lean core set (`--tools core` or
| `memory_slot_get` | | `label`*: string | Read a single slot by label. |
| `memory_slot_list` | | none | List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions. |
| `memory_slot_replace` | | `label`*: string, `content`*: string | Replace slot content in place. Fails if content exceeds sizeLimit. |
-| `memory_smart_search` | yes | `query`*: string, `expandIds`: string, `limit`: number | Hybrid semantic+keyword search with progressive disclosure. |
+| `memory_smart_search` | yes | `query`: string, `expandIds`: string, `limit`: number, `targetLayer`: string, `project`: string, `agentId`: string, `includeLessons`: boolean | Hybrid semantic+keyword search with progressive disclosure. Pass query to search, or expandIds to recover full results. |
| `memory_snapshot_create` | | `message`: string | Create a git-versioned snapshot of current memory state. |
| `memory_team_feed` | | `limit`: number | Get recent shared items from all team members. |
| `memory_team_share` | | `itemId`*: string, `itemType`*: string | Share a memory or observation with team members. |
diff --git a/plugin/skills/agentmemory-mcp-tools/SKILL.md b/plugin/skills/agentmemory-mcp-tools/SKILL.md
index 00445ef3..9ab2a03c 100644
--- a/plugin/skills/agentmemory-mcp-tools/SKILL.md
+++ b/plugin/skills/agentmemory-mcp-tools/SKILL.md
@@ -11,7 +11,7 @@ agentmemory exposes its full capability set as MCP tools. This skill is the inde
Save then recall:
1. `memory_save` with `content` (the insight), `concepts` (comma-separated keywords), `files` (comma-separated paths).
-2. `memory_smart_search` with `query` and `limit` to retrieve it later. This runs hybrid BM25 plus vector plus graph-expanded search.
+2. `memory_smart_search` with `query`, `limit`, and `targetLayer: "memory"` to retrieve saved knowledge later. Omit `targetLayer` to also search captured observations. This runs hybrid BM25 plus vector plus graph-expanded search.
## Tool families
@@ -27,6 +27,9 @@ Save then recall:
1. Pick the narrowest tool for the task. Prefer `memory_smart_search` for open recall, `memory_recall` when you already have a focused query, `memory_sessions` for session listings.
2. Look up exact parameter names and which are required in REFERENCE.md before calling.
3. Pass only documented fields. REST handlers whitelist fields and drop unknown ones.
+4. For budgeted `memory_recall`, distinguish `matched_count: 0` from
+ `excluded_by_budget > 0`. Expand clipped or omitted IDs with
+ `memory_smart_search` and `expandIds`, preserving the same scope filters.
## See also
diff --git a/plugin/skills/recall/SKILL.md b/plugin/skills/recall/SKILL.md
index 830130c6..42943706 100644
--- a/plugin/skills/recall/SKILL.md
+++ b/plugin/skills/recall/SKILL.md
@@ -30,12 +30,19 @@ id, or an importance score. If nothing comes back, say so.
1. Call `memory_smart_search` with the user's text as `query` and `limit: 10`.
Pass `project` when the user scopes to a specific repo.
+ Use `targetLayer: "memory"` for explicitly saved knowledge, or
+ `targetLayer: "observation"` for captured activity. Omit it for mixed search.
2. Group results by session. Records carry a provenance channel (`user`, `agent`,
`tool`, `import`, `shared`); when results conflict, prefer `user` over `agent`
inference, and flag `shared` records as another teammate's write.
3. For each observation show its type, title, and narrative.
4. Lead with the high-signal observations (importance >= 7).
-5. If zero results, suggest 2-3 alternative search terms and stop. Do not guess.
+5. With `memory_recall`, inspect `matched_count`, `excluded_by_budget`, and
+ `content_truncated` before treating an empty or shortened response as absent
+ knowledge. Recover full content with `memory_smart_search` using `expandIds`
+ and the same project, agent, and layer filters. `minimum_budget` reports the
+ estimated budget needed for a minimal preview when the budget is too small.
+6. If there are no matches, suggest 2-3 alternative search terms and stop. Do not guess.
## Anti-patterns
diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json
index 075517cb..2e1b5e92 100644
--- a/scripts/docs-sync.state.json
+++ b/scripts/docs-sync.state.json
@@ -20,16 +20,16 @@
"12"
],
"tests": [
- "2600+"
+ "2700+"
],
"functions": [
"312"
],
"sourceFiles": [
- "220"
+ "223"
],
"loc": [
- "52000"
+ "53000"
],
"kvScopes": [
"60"
diff --git a/src/functions/graph-retrieval.ts b/src/functions/graph-retrieval.ts
index dbe37bbc..b12a9d8a 100644
--- a/src/functions/graph-retrieval.ts
+++ b/src/functions/graph-retrieval.ts
@@ -2,6 +2,7 @@ import type {
GraphNode,
GraphEdge,
} from "../types.js";
+import { matchesSearchLayer, type SearchLayer, type SearchLayerResolver } from "../state/search-layer.js";
import { KV } from "../state/schema.js";
import type { StateKV } from "../state/kv.js";
@@ -39,12 +40,13 @@ function buildGraphContext(
}
export class GraphRetrieval {
- constructor(private kv: StateKV) {}
+ constructor(private kv: StateKV, private resolveLayer?: SearchLayerResolver) {}
async searchByEntities(
entityNames: string[],
maxDepth = 2,
maxResults = 20,
+ targetLayer: SearchLayer = "all",
): Promise<GraphRetrievalResult[]> {
const allNodes = (await this.kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);
const allEdges = (await this.kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);
@@ -74,7 +76,7 @@ export class GraphRetrieval {
for (const path of paths) {
const lastNode = path[path.length - 1].node;
for (const obsId of lastNode.sourceObservationIds) {
- if (visitedObs.has(obsId)) continue;
+ if (visitedObs.has(obsId) || !matchesSearchLayer(obsId, "", targetLayer, this.resolveLayer?.(obsId, ""))) continue;
visitedObs.add(obsId);
const pathLength = path.length;
@@ -98,7 +100,7 @@ export class GraphRetrieval {
}
for (const obsId of startNode.sourceObservationIds) {
- if (visitedObs.has(obsId)) continue;
+ if (visitedObs.has(obsId) || !matchesSearchLayer(obsId, "", targetLayer, this.resolveLayer?.(obsId, ""))) continue;
visitedObs.add(obsId);
results.push({
obsId,
@@ -118,6 +120,7 @@ export class GraphRetrieval {
obsIds: string[],
maxDepth = 1,
maxResults = 10,
+ targetLayer: SearchLayer = "all",
): Promise<GraphRetrievalResult[]> {
const allNodes = (await this.kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);
const allEdges = (await this.kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);
@@ -134,7 +137,7 @@ export class GraphRetrieval {
for (const path of paths) {
const lastNode = path[path.length - 1].node;
for (const obsId of lastNode.sourceObservationIds) {
- if (visitedObs.has(obsId)) continue;
+ if (visitedObs.has(obsId) || !matchesSearchLayer(obsId, "", targetLayer, this.resolveLayer?.(obsId, ""))) continue;
visitedObs.add(obsId);
const pathLength = path.length;
diff --git a/src/functions/lessons.ts b/src/functions/lessons.ts
index cc238a9f..cc724fe7 100644
--- a/src/functions/lessons.ts
+++ b/src/functions/lessons.ts
@@ -39,7 +39,7 @@ async function ensureLessonIndex(kv: StateKV): Promise<SearchIndex> {
if (generation !== lessonIndexGeneration) return;
for (const l of all) {
if (!l.deleted) {
- idx.add(lessonToObservation(l));
+ idx.add(lessonToObservation(l), "lesson");
lessonRecords.set(l.id, l);
}
}
@@ -119,7 +119,7 @@ export function registerLessonsFunctions(sdk: IIIClient, kv: StateKV): void {
lessonRecords.set(existing.id, existing);
if (indexedTextChanged && lessonIndex) {
lessonIndex.remove(existing.id);
- lessonIndex.add(lessonToObservation(existing));
+ lessonIndex.add(lessonToObservation(existing), "lesson");
}
noteLessonMutation();
@@ -161,7 +161,7 @@ export function registerLessonsFunctions(sdk: IIIClient, kv: StateKV): void {
await kv.set(KV.lessons, lesson.id, lesson);
lessonRecords.set(lesson.id, lesson);
- if (lessonIndex) lessonIndex.add(lessonToObservation(lesson));
+ if (lessonIndex) lessonIndex.add(lessonToObservation(lesson), "lesson");
noteLessonMutation();
try {
diff --git a/src/functions/recall-response.ts b/src/functions/recall-response.ts
new file mode 100644
index 00000000..dadd6559
--- /dev/null
+++ b/src/functions/recall-response.ts
@@ -0,0 +1,198 @@
+import type { CompactSearchResult, SearchResult } from "../types.js";
+
+export type RecallFormat = "full" | "compact" | "narrative";
+
+type ClippedResult = { content_truncated?: true };
+type FullResult = SearchResult & ClippedResult;
+type CompactResult = CompactSearchResult & ClippedResult;
+type NarrativeResult = Omit<CompactResult, "type"> & { narrative: string };
+type RecallResult = FullResult | CompactResult | NarrativeResult;
+
+interface RecallMetadata {
+ tokens_used: number;
+ tokens_budget?: number;
+ truncated: boolean;
+ matched_count: number;
+ excluded_by_budget: number;
+ excluded_results: Array<{ obsId: string; sessionId: string; title: string }>;
+ excluded_results_truncated: boolean;
+ minimum_budget?: number;
+}
+
+export type RecallResponse = RecallMetadata & (
+ | { format: "full"; results: FullResult[] }
+ | { format: "compact"; results: CompactResult[] }
+ | { format: "narrative"; results: NarrativeResult[]; text: string }
+);
+
+function estimateTokens(value: unknown): number {
+ return Math.max(1, Math.ceil(JSON.stringify(value).length / 3));
+}
+
+function prefix(text: string, length: number): string {
+ let end = Math.min(length, text.length);
+ if (end > 0 && end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1])) end--;
+ return text.slice(0, end);
+}
+
+function fitText<T>(text: string, budget: number, makeResult: (text: string) => T): T {
+ let low = 0;
+ let high = text.length;
+ while (low < high) {
+ const middle = Math.ceil((low + high) / 2);
+ if (estimateTokens(makeResult(prefix(text, middle))) <= budget) low = middle;
+ else high = middle - 1;
+ }
+ return makeResult(prefix(text, low));
+}
+
+function formatResult(result: SearchResult, format: RecallFormat): RecallResult {
+ if (format === "full") return result;
+ const observation = result.observation;
+ const compact: CompactResult = {
+ obsId: observation.id,
+ sessionId: result.sessionId,
+ title: observation.title,
+ type: observation.type,
+ score: result.score,
+ timestamp: observation.timestamp,
+ ...(result.layer !== undefined && { layer: result.layer }),
+ };
+ if (format === "compact") return compact;
+ const { type: _type, ...narrative } = compact;
+ return { ...narrative, narrative: observation.narrative };
+}
+
+function clipResult(
+ result: SearchResult,
+ format: RecallFormat,
+ budget: number,
+): { result?: RecallResult; minimum: number } {
+ const observation = result.observation;
+ const layer = result.layer !== undefined ? { layer: result.layer } : {};
+ if (format === "compact") {
+ const base: CompactResult = {
+ obsId: observation.id,
+ sessionId: result.sessionId,
+ title: "",
+ type: observation.type,
+ score: result.score,
+ timestamp: observation.timestamp,
+ ...layer,
+ content_truncated: true,
+ };
+ const minimum = estimateTokens(base);
+ if (minimum > budget) return { minimum };
+ return {
+ result: fitText(observation.title, budget, (title) => ({ ...base, title })),
+ minimum,
+ };
+ }
+
+ const makeResult = (title: string, narrative: string): FullResult | NarrativeResult => {
+ if (format === "narrative") {
+ return {
+ obsId: observation.id,
+ sessionId: result.sessionId,
+ title,
+ narrative,
+ score: result.score,
+ timestamp: observation.timestamp,
+ ...layer,
+ content_truncated: true,
+ };
+ }
+ return {
+ observation: {
+ id: observation.id,
+ sessionId: observation.sessionId,
+ timestamp: observation.timestamp,
+ type: observation.type,
+ title,
+ facts: [],
+ narrative,
+ concepts: [],
+ files: [],
+ importance: observation.importance,
+ ...(observation.confidence !== undefined && { confidence: observation.confidence }),
+ ...(observation.agentId !== undefined && { agentId: observation.agentId }),
+ ...(observation.origin && {
+ origin: { channel: observation.origin.channel, capturedAt: observation.origin.capturedAt },
+ }),
+ },
+ score: result.score,
+ sessionId: result.sessionId,
+ ...layer,
+ content_truncated: true,
+ };
+ };
+ const minimum = estimateTokens(makeResult("", ""));
+ if (minimum > budget) return { minimum };
+
+ const titleResult = fitText(prefix(observation.title, 120), budget, (title) => makeResult(title, ""));
+ const title = "observation" in titleResult ? titleResult.observation.title : titleResult.title;
+ const narrative = observation.narrative || observation.facts.join("\n");
+ return {
+ result: fitText(narrative, budget, (text) => makeResult(title, text)),
+ minimum,
+ };
+}
+
+export function buildRecallResponse(
+ results: SearchResult[],
+ format: RecallFormat,
+ tokenBudget?: number,
+): RecallResponse {
+ const selected: RecallResult[] = [];
+ let used = 0;
+ let clipped = false;
+ let minimumBudget: number | undefined;
+ for (const result of results) {
+ const formatted = formatResult(result, format);
+ const tokens = estimateTokens(formatted);
+ if (tokenBudget === undefined || used + tokens <= tokenBudget) {
+ selected.push(formatted);
+ used += tokens;
+ continue;
+ }
+ if (selected.length === 0) {
+ const preview = clipResult(result, format, tokenBudget);
+ if (preview.result) {
+ selected.push(preview.result);
+ used = estimateTokens(preview.result);
+ clipped = true;
+ continue;
+ } else {
+ minimumBudget = Math.min(preview.minimum, tokens);
+ }
+ }
+ break;
+ }
+
+ const excluded = results.slice(selected.length);
+ const metadata: RecallMetadata = {
+ tokens_used: used,
+ tokens_budget: tokenBudget,
+ truncated: clipped || excluded.length > 0,
+ matched_count: results.length,
+ excluded_by_budget: excluded.length,
+ excluded_results: excluded.slice(0, 10).map((result) => ({
+ obsId: result.observation.id,
+ sessionId: result.sessionId,
+ title: prefix(result.observation.title, 120),
+ })),
+ excluded_results_truncated: excluded.length > 10,
+ ...(minimumBudget !== undefined && { minimum_budget: minimumBudget }),
+ };
+ if (format === "narrative") {
+ const narrativeResults = selected as NarrativeResult[];
+ return {
+ ...metadata,
+ format,
+ results: narrativeResults,
+ text: narrativeResults.map((result, index) => `${index + 1}. ${result.title}\n${result.narrative}`).join("\n\n"),
+ };
+ }
+ if (format === "compact") return { ...metadata, format, results: selected as CompactResult[] };
+ return { ...metadata, format, results: selected as FullResult[] };
+}
diff --git a/src/functions/relations.ts b/src/functions/relations.ts
index 505697bd..5f9b02c2 100644
--- a/src/functions/relations.ts
+++ b/src/functions/relations.ts
@@ -214,7 +214,7 @@ export function registerRelationsFunction(sdk: IIIClient, kv: StateKV): void {
await kv.set(KV.memories, evolved.id, evolved);
try {
- getSearchIndex().add(memoryToObservation(evolved));
+ getSearchIndex().add(memoryToObservation(evolved), "memory");
scheduleIndexSave();
} catch (err) {
logger.warn("Failed to index evolved memory into BM25", {
diff --git a/src/functions/remember.ts b/src/functions/remember.ts
index 8d891637..b6720742 100644
--- a/src/functions/remember.ts
+++ b/src/functions/remember.ts
@@ -198,7 +198,7 @@ export function registerRememberFunction(sdk: IIIClient, kv: StateKV): void {
await kv.set(KV.memories, memory.id, memory);
try {
- getSearchIndex().add(memoryToObservation(memory));
+ getSearchIndex().add(memoryToObservation(memory), "memory");
scheduleIndexSave();
} catch (err) {
logger.warn("Failed to index saved memory into BM25", {
diff --git a/src/functions/search.ts b/src/functions/search.ts
index d157a6b4..8223f2e2 100644
--- a/src/functions/search.ts
+++ b/src/functions/search.ts
@@ -1,12 +1,14 @@
import type { IIIClient } from 'iii-sdk'
import type { IndexPersistenceStatus } from "../state/index-persistence.js";
-import type { CompactSearchResult, CompressedObservation, Memory, SearchResult, Session } from '../types.js'
+import type { CompressedObservation, Memory, SearchResult, Session } from '../types.js'
import { KV } from '../state/schema.js'
import { StateKV } from '../state/kv.js'
+import { getSearchResultLayer, isSearchLayer, matchesSearchLayer, type SearchLayer, type SearchResultLayer } from "../state/search-layer.js";
import { SearchIndex } from '../state/search-index.js'
import { VectorIndex } from '../state/vector-index.js'
import type { EmbeddingProvider } from '../types.js'
import { memoryToObservation } from '../state/memory-utils.js'
+import { buildRecallResponse, type RecallFormat } from "./recall-response.js";
import { recordAccessBatch } from './access-tracker.js'
import { logger } from "../logger.js";
import { withoutObservationSource } from "./observation-source.js";
@@ -30,7 +32,8 @@ let currentEmbeddingProvider: EmbeddingProvider | null = null
type HybridRanker = (
query: string,
limit: number,
-) => Promise<Array<{ observation: CompressedObservation; sessionId: string; combinedScore: number }>>
+ targetLayer?: SearchLayer,
+) => Promise<Array<{ observation: CompressedObservation; sessionId: string; combinedScore: number; layer?: SearchResultLayer }>>
let hybridRanker: HybridRanker | null = null
export function setHybridRanker(fn: HybridRanker | null): void {
@@ -106,7 +109,6 @@ export function getEmbeddingProvider(): EmbeddingProvider | null {
return currentEmbeddingProvider
}
-const MEMORY_ID_PREFIX = "mem_"
const RANK_FUSION_K = 60
export async function rankMemoryIds(
@@ -115,15 +117,13 @@ export async function rankMemoryIds(
): Promise<{ ids: string[]; mode: "hybrid" | "keyword" }> {
const fetchLimit = Math.max(limit * 4, 50)
const keyword = getSearchIndex()
- .search(query, fetchLimit)
- .filter((hit) => hit.obsId.startsWith(MEMORY_ID_PREFIX))
+ .search(query, fetchLimit, "memory")
let semantic: Array<{ obsId: string }> = []
if (vectorIndex && vectorIndex.size > 0 && currentEmbeddingProvider) {
try {
const embedding = await currentEmbeddingProvider.embed(query)
semantic = vectorIndex
- .search(embedding, fetchLimit)
- .filter((hit) => hit.obsId.startsWith(MEMORY_ID_PREFIX))
+ .search(embedding, fetchLimit, "memory", (id) => getSearchIndex().layerOf(id))
} catch (err) {
logger.warn("memory vector ranking failed, using keyword ranking", {
error: err instanceof Error ? err.message : String(err),
@@ -380,7 +380,7 @@ export async function indexRecords(
for (const memory of memories) {
if (memory.isLatest === false) continue
if (!memory.title || !memory.content) continue
- idx.add(memoryToObservation(memory))
+ idx.add(memoryToObservation(memory), "memory")
await enqueue({
id: memory.id,
sessionId: memory.sessionIds?.[0] ?? 'memory',
@@ -580,7 +580,7 @@ async function runKeywordRebuild(
for (const memory of memories) {
if (memory.isLatest === false) continue
if (!memory.title || !memory.content) continue
- idx.add(memoryToObservation(memory))
+ idx.add(memoryToObservation(memory), "memory")
consider(memory.id, memory.sessionIds?.[0] ?? 'memory', memory.title + ' ' + memory.content, memory.createdAt, "memory")
documents++
}
@@ -695,6 +695,7 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {
cwd?: string
format?: string
token_budget?: number
+ targetLayer?: SearchLayer
agentId?: string
}) => {
const idx = getSearchIndex()
@@ -704,6 +705,10 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {
throw new Error('mem::search: query must be a non-empty string')
}
const query = data.query.trim()
+ if (data.targetLayer !== undefined && !isSearchLayer(data.targetLayer)) {
+ throw new Error("mem::search: targetLayer must be one of 'all', 'memory', or 'observation'")
+ }
+ const targetLayer = data.targetLayer ?? 'all'
const MAX_LIMIT = 100
let effectiveLimit = 20
if (data.limit !== undefined) {
@@ -788,24 +793,26 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {
sessionId: string
score: number
observation?: CompressedObservation
+ layer?: SearchResultLayer
}>
if (hybridRanker && vectorIndex && vectorIndex.size > 0) {
try {
- const hybrid = await hybridRanker(query, fetchLimit)
+ const hybrid = await hybridRanker(query, fetchLimit, targetLayer)
results = hybrid.map((r) => ({
obsId: r.observation.id,
sessionId: r.sessionId,
score: r.combinedScore,
observation: r.observation,
+ layer: r.layer,
}))
} catch (err) {
logger.warn("hybrid ranking failed, falling back to keyword search", {
error: err instanceof Error ? err.message : String(err),
})
- results = idx.search(query, fetchLimit)
+ results = idx.search(query, fetchLimit, targetLayer)
}
} else {
- results = idx.search(query, fetchLimit)
+ results = idx.search(query, fetchLimit, targetLayer)
}
// Resolve session -> project/cwd once per sessionId we touch.
@@ -817,15 +824,10 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {
return s ?? null
}
- // Cache for memory project lookups. Memories indexed via mem::remember
- // use a synthetic sessionId ('memory' or the first real sessionId) that
- // either has no KV.sessions entry or belongs to a different project.
- // When loadSession returns null we fall through to a KV.memories probe
- // so project-filtered search can include or exclude them correctly.
const memoryProjectCache = new Map<string, string | null>()
const loadMemoryProject = async (obsId: string): Promise<string | null> => {
if (memoryProjectCache.has(obsId)) return memoryProjectCache.get(obsId)!
- const mem = await kv.get<Memory>(KV.memories, obsId).catch(() => null)
+ const mem = await kv.get<Memory>(KV.memories, obsId)
const proj = mem?.project ?? null
memoryProjectCache.set(obsId, proj)
return proj
@@ -844,31 +846,17 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {
const candidates: typeof results = []
for (const r of results) {
if (candidates.length >= earlyCap) break
+ const layer = r.layer ?? idx.layerOf(r.obsId) ?? getSearchResultLayer(r.obsId, r.sessionId)
+ if (!matchesSearchLayer(r.obsId, r.sessionId, targetLayer, layer)) continue
if (filtering) {
- const s = await loadSession(r.sessionId)
- if (s) {
- if (projectFilter && s.project !== projectFilter) continue
- if (cwdFilter && s.cwd !== cwdFilter) continue
- } else {
- // Session not found. Two cases arrive here:
- // 1. Synthetic sessionId — memories indexed via mem::remember use
- // sessionIds[0] ?? 'memory'. The string 'memory' has no session
- // entry; neither does a real sessionId when sessionIds[0] happens
- // to be a session from a different lifecycle. Probe KV.memories
- // directly to get the memory's own project field.
- // 2. Deleted session — the session existed when the entry was indexed
- // but was since evicted. The KV.memories probe returns null for
- // these (they are observations, not memories), so memProject is
- // null and the entry passes through as unscoped. This is the safe
- // fallback: we lose the ability to filter but never incorrectly
- // block a result whose session we can no longer verify.
- // In both cases, a null memProject means "project unknown — treat as
- // unscoped and let it through" to preserve backward-compatibility.
- if (projectFilter) {
- const memProject = await loadMemoryProject(r.obsId)
- if (memProject !== null && memProject !== projectFilter) continue
- }
- // cwd filter does not apply to unbound entries.
+ const memoryProject = projectFilter && layer === "memory"
+ ? await loadMemoryProject(r.obsId)
+ : null
+ if (projectFilter && memoryProject !== null && memoryProject !== projectFilter) continue
+ const session = await loadSession(r.sessionId)
+ if (session) {
+ if (projectFilter && memoryProject === null && session.project !== projectFilter) continue
+ if (cwdFilter && session.cwd !== cwdFilter) continue
}
}
candidates.push(r)
@@ -876,115 +864,46 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {
const obsResults = await Promise.all(
candidates.map(async (r) => {
- if (r.observation) return r.observation
+ if (r.observation) return { observation: r.observation, layer: r.layer ?? idx.layerOf(r.obsId) ?? getSearchResultLayer(r.obsId, r.sessionId) }
const obs = await kv
.get<CompressedObservation>(KV.observations(r.sessionId), r.obsId)
.catch(() => null)
- if (obs) return obs
+ if (obs) return { observation: obs, layer: "observation" as const }
const mem = await kv
.get<Memory>(KV.memories, r.obsId)
.catch(() => null)
- return mem ? memoryToObservation(mem) : null
+ return mem ? { observation: memoryToObservation(mem), layer: "memory" as const } : null
})
)
const enriched: SearchResult[] = []
for (let i = 0; i < candidates.length; i++) {
- const obs = obsResults[i]
- if (!obs) continue
+ const resolved = obsResults[i]
+ if (!resolved) continue
+ const obs = resolved.observation
+ if (!matchesSearchLayer(obs.id, obs.sessionId, targetLayer, resolved.layer)) continue
if (filterAgentId !== undefined && obs.agentId !== filterAgentId) continue
if (enriched.length >= effectiveLimit) break
enriched.push({
observation: withoutObservationSource(obs),
+ layer: resolved.layer,
score: candidates[i].score,
sessionId: candidates[i].sessionId,
})
}
+ const response = buildRecallResponse(enriched, format as RecallFormat, tokenBudget)
void recordAccessBatch(
kv,
- enriched.map((r) => r.observation.id),
+ enriched.slice(0, response.results.length).map((result) => result.observation.id),
)
- const estimateTokens = (value: unknown): number =>
- Math.max(1, Math.ceil(JSON.stringify(value).length / 3))
-
- const applyTokenBudget = <T>(items: T[]): {
- items: T[]
- used: number
- truncated: boolean
- } => {
- if (!tokenBudget) return { items, used: items.reduce((sum, item) => sum + estimateTokens(item), 0), truncated: false }
- const selected: T[] = []
- let used = 0
- for (const item of items) {
- const itemTokens = estimateTokens(item)
- if (used + itemTokens > tokenBudget) {
- return { items: selected, used, truncated: selected.length < items.length }
- }
- selected.push(item)
- used += itemTokens
- }
- return { items: selected, used, truncated: false }
- }
-
- if (format === 'compact') {
- const compactResults: CompactSearchResult[] = enriched.map((r) => ({
- obsId: r.observation.id,
- sessionId: r.sessionId,
- title: r.observation.title,
- type: r.observation.type,
- score: r.score,
- timestamp: r.observation.timestamp,
- }))
- const packed = applyTokenBudget(compactResults)
- return {
- format,
- results: packed.items,
- tokens_used: packed.used,
- tokens_budget: tokenBudget,
- truncated: packed.truncated,
- }
- }
-
- if (format === 'narrative') {
- const narrativeResults = enriched.map((r) => ({
- obsId: r.observation.id,
- sessionId: r.sessionId,
- title: r.observation.title,
- narrative: r.observation.narrative,
- score: r.score,
- timestamp: r.observation.timestamp,
- }))
- const packed = applyTokenBudget(narrativeResults)
- const text = packed.items
- .map((r, index) => `${index + 1}. ${r.title}\n${r.narrative}`)
- .join('\n\n')
- return {
- format,
- results: packed.items,
- text,
- tokens_used: packed.used,
- tokens_budget: tokenBudget,
- truncated: packed.truncated,
- }
- }
-
- const packed = applyTokenBudget(enriched)
-
- // Avoid logging raw cwd/project (host paths). Log only that filters were active.
logger.info('Search completed', {
query,
- results: packed.items.length,
+ results: response.results.length,
hasProjectFilter: !!projectFilter,
hasCwdFilter: !!cwdFilter,
})
- return {
- format,
- results: packed.items,
- tokens_used: packed.used,
- tokens_budget: tokenBudget,
- truncated: packed.truncated,
- }
+ return response
}
)
}
diff --git a/src/functions/smart-search.ts b/src/functions/smart-search.ts
index a442363b..f2d4352d 100644
--- a/src/functions/smart-search.ts
+++ b/src/functions/smart-search.ts
@@ -7,6 +7,7 @@ import type {
Lesson,
Memory,
} from "../types.js";
+import { getSearchResultLayer, isSearchLayer, matchesSearchLayer, type SearchLayer, type SearchResultLayer } from "../state/search-layer.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
@@ -24,6 +25,7 @@ import { logger } from "../logger.js";
import { withoutObservationSource } from "./observation-source.js";
import { getCounters } from "../telemetry/setup.js";
import { memoryToObservation } from "../state/memory-utils.js";
+import { getSearchIndex } from "./search.js";
export interface RecentSearch {
sessionId: string;
@@ -77,7 +79,7 @@ const LESSON_CONTENT_PREVIEW_CHARS = 240;
export function registerSmartSearchFunction(
sdk: IIIClient,
kv: StateKV,
- searchFn: (query: string, limit: number) => Promise<HybridSearchResult[]>,
+ searchFn: (query: string, limit: number, targetLayer?: SearchLayer) => Promise<HybridSearchResult[]>,
): void {
sdk.registerFunction("mem::smart-search",
async (data: {
@@ -86,6 +88,7 @@ export function registerSmartSearchFunction(
limit?: number;
project?: string;
includeLessons?: boolean;
+ targetLayer?: SearchLayer;
// optional per-call agent filter for runtimes routing many
// roles through one server. "*" opts out of the env-default
// scope and returns hits from every agent.
@@ -94,6 +97,10 @@ export function registerSmartSearchFunction(
source?: string;
}) => {
+ if (data.targetLayer !== undefined && !isSearchLayer(data.targetLayer)) {
+ throw new Error("mem::smart-search: targetLayer must be one of 'all', 'memory', or 'observation'");
+ }
+ const targetLayer = data.targetLayer ?? "all";
const isolated = isAgentScopeIsolated();
const explicitAgentId =
typeof data.agentId === "string" && data.agentId.trim().length > 0
@@ -125,11 +132,11 @@ export function registerSmartSearchFunction(
const matchesProject = project ? makeProjectMatcher(kv, project) : undefined;
if (data.expandIds && data.expandIds.length > 0) {
- const raw = data.expandIds.slice(0, 20);
+ const raw = data.expandIds.slice(0, 100);
const items = raw.map((entry) => {
if (typeof entry === "string") return { obsId: entry, sessionId: undefined as string | undefined };
- if (entry && typeof entry === "object" && typeof (entry as any).obsId === "string") {
- return { obsId: (entry as any).obsId, sessionId: (entry as any).sessionId as string | undefined };
+ if (entry && typeof entry === "object" && typeof entry.obsId === "string") {
+ return { obsId: entry.obsId, sessionId: typeof entry.sessionId === "string" ? entry.sessionId : undefined };
}
return null;
}).filter((item): item is NonNullable<typeof item> => item !== null);
@@ -138,37 +145,40 @@ export function registerSmartSearchFunction(
obsId: string;
sessionId: string;
observation: CompressedObservation;
+ layer: SearchResultLayer;
}> = [];
- const results = await Promise.all(
- items.map(({ obsId, sessionId }) =>
- findObservation(kv, obsId, sessionId).then((obs) =>
- obs ? { obsId, sessionId: obs.sessionId, observation: withoutObservationSource(obs) } : null,
- ),
- ),
- );
- for (const r of results) {
- if (r) expanded.push(r);
+ let attempted = 0;
+ for (let offset = 0; offset < items.length && expanded.length < 20; offset += 10) {
+ const batch = items.slice(offset, offset + 10);
+ const results = await Promise.all(batch.map(({ obsId, sessionId }) => findObservation(kv, obsId, sessionId)));
+ attempted += batch.length;
+ for (const result of results) {
+ if (!result) continue;
+ const { observation, layer } = result;
+ if (!matchesSearchLayer(observation.id, observation.sessionId, targetLayer, layer)) continue;
+ if (filterAgentId && observation.agentId !== filterAgentId) continue;
+ if (matchesProject && !await matchesProject(observation.id, observation.sessionId)) continue;
+ expanded.push({
+ obsId: observation.id,
+ sessionId: observation.sessionId,
+ observation: withoutObservationSource(observation),
+ layer,
+ });
+ }
}
-
- const projectScoped = matchesProject
- ? await filterProjectResults(expanded, (entry) => matchesProject(entry.obsId, entry.sessionId))
- : expanded;
- const scoped = filterAgentId
- ? projectScoped.filter((e) => e.observation.agentId === filterAgentId)
- : projectScoped;
+ const scoped = expanded.slice(0, 20);
void recordAccessBatch(
kv,
scoped.map((e) => e.observation.id),
);
- const truncated = data.expandIds.length > raw.length;
+ const truncated = data.expandIds.length > raw.length || attempted < items.length || expanded.length > scoped.length;
logger.info("Smart search expanded", {
requested: data.expandIds.length,
- attempted: raw.length,
+ attempted,
returned: scoped.length,
- filteredOutOfScope: expanded.length - scoped.length,
truncated,
});
return { mode: "expanded", results: scoped, truncated };
@@ -182,21 +192,27 @@ export function registerSmartSearchFunction(
// Lesson recall stays capped: lessons are denser than raw
// observations so 10 covers most recall flows.
const lessonLimit = Math.min(limit, 10);
- const includeLessons = data.includeLessons !== false;
+ const includeLessons = targetLayer === "all" && data.includeLessons !== false;
const overFetchLimit = filterAgentId || project
? Math.max(Math.min(limit * 10, 300), 100)
: limit;
const [hybridResults, lessons] = await Promise.all([
- searchFn(data.query, overFetchLimit),
+ searchFn(data.query, overFetchLimit, targetLayer),
includeLessons
? recallLessons(sdk, data.query, lessonLimit, project)
: Promise.resolve([]),
]);
+ const layerResults = hybridResults.filter((result) => matchesSearchLayer(
+ result.observation.id,
+ result.sessionId,
+ targetLayer,
+ result.layer ?? getSearchIndex().layerOf(result.observation.id),
+ ));
const projectResults = matchesProject
- ? await filterProjectResults(hybridResults, (result) => matchesProject(result.observation.id, result.sessionId))
- : hybridResults;
+ ? await filterProjectResults(layerResults, (result) => matchesProject(result.observation.id, result.sessionId))
+ : layerResults;
const filteredHybrid = filterAgentId
? projectResults
@@ -206,6 +222,7 @@ export function registerSmartSearchFunction(
const compact: CompactSearchResult[] = filteredHybrid.map((r) => ({
obsId: r.observation.id,
+ layer: r.layer ?? getSearchIndex().layerOf(r.observation.id) ?? getSearchResultLayer(r.observation.id, r.sessionId),
sessionId: r.sessionId,
title: r.observation.title,
type: r.observation.type,
@@ -351,15 +368,15 @@ async function findObservation(
kv: StateKV,
obsId: string,
sessionIdHint?: string,
-): Promise<CompressedObservation | null> {
- const memory = await kv.get<Memory>(KV.memories, obsId).catch(() => null);
- if (memory) return memoryToObservation(memory);
+): Promise<{ observation: CompressedObservation; layer: SearchResultLayer } | null> {
+ const memory = await kv.get<Memory>(KV.memories, obsId);
+ if (memory) return { observation: memoryToObservation(memory), layer: "memory" };
if (sessionIdHint) {
const obs = await kv
.get<CompressedObservation>(KV.observations(sessionIdHint), obsId)
.catch(() => null);
- if (obs) return obs;
+ if (obs) return { observation: obs, layer: "observation" };
}
const indexedSessionId = await lookupObservationSession(kv, obsId);
@@ -367,7 +384,7 @@ async function findObservation(
const obs = await kv
.get<CompressedObservation>(KV.observations(indexedSessionId), obsId)
.catch(() => null);
- if (obs) return obs;
+ if (obs) return { observation: obs, layer: "observation" };
}
const sessions = await kv.list<{ id: string }>(KV.sessions);
@@ -384,7 +401,7 @@ async function findObservation(
await indexObservationSession(kv, obsId, batch[foundIndex].id).catch(
() => {},
);
- return found;
+ return { observation: found, layer: "observation" };
}
}
return null;
diff --git a/src/index.ts b/src/index.ts
index 0137ca99..08dbb3a0 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -30,6 +30,7 @@ import {
} from "./providers/index.js";
import { StateKV } from "./state/kv.js";
import { VectorIndex } from "./state/vector-index.js";
+import type { SearchLayer } from "./state/search-layer.js";
import { HybridSearch } from "./state/hybrid-search.js";
import { IndexPersistence } from "./state/index-persistence.js";
import { SHUTDOWN_FLUSH_TIMEOUT_MS, SHUTDOWN_HARD_EXIT_MS, settleWithin } from "./shutdown.js";
@@ -432,8 +433,8 @@ async function main() {
graphWeight,
);
- const hybridRanker = (query: string, limit: number) =>
- hybridSearch.search(query, limit);
+ const hybridRanker = (query: string, limit: number, targetLayer?: SearchLayer) =>
+ hybridSearch.search(query, limit, targetLayer);
registerSmartSearchFunction(sdk, kv, hybridRanker);
setHybridRanker(hybridRanker);
registerRecentSearchesSweepFunction(sdk, kv);
diff --git a/src/mcp/search-arguments.ts b/src/mcp/search-arguments.ts
new file mode 100644
index 00000000..659fb552
--- /dev/null
+++ b/src/mcp/search-arguments.ts
@@ -0,0 +1,13 @@
+export type SearchExpansionId = string | { obsId: string; sessionId: string };
+
+export function parseSearchExpansionIds(value: unknown): SearchExpansionId[] {
+ const entries = typeof value === "string" ? value.split(",") : Array.isArray(value) ? value : [];
+ return entries.flatMap((entry): SearchExpansionId[] => {
+ if (typeof entry === "string") return entry.trim() ? [entry.trim()] : [];
+ if (!entry || typeof entry !== "object" || typeof entry.obsId !== "string" || !entry.obsId.trim()) return [];
+ const obsId = entry.obsId.trim();
+ return typeof entry.sessionId === "string" && entry.sessionId.trim()
+ ? [{ obsId, sessionId: entry.sessionId.trim() }]
+ : [obsId];
+ });
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index be5ad365..8ea5b80d 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -10,6 +10,8 @@ import type {
GraphEdge,
} from "../types.js";
import { getVisibleTools } from "./tools-registry.js";
+import { parseSearchExpansionIds } from "./search-arguments.js";
+import { isSearchLayer } from "../state/search-layer.js";
import { checkAuth } from "../triggers/api.js";
import { getAgentId, isAgentScopeIsolated } from "../config.js";
@@ -75,6 +77,14 @@ export function registerMcpEndpoints(
try {
switch (name) {
case "memory_recall": {
+ if (args.targetLayer !== undefined && !isSearchLayer(args.targetLayer)) {
+ return { status_code: 400, body: { error: "targetLayer must be one of: all, memory, observation" } };
+ }
+ for (const field of ["project", "cwd", "agentId"] as const) {
+ if (args[field] !== undefined && typeof args[field] !== "string") {
+ return { status_code: 400, body: { error: `${field} must be a string` } };
+ }
+ }
if (typeof args.query !== "string" || !args.query.trim()) {
return {
status_code: 400,
@@ -111,15 +121,11 @@ export function registerMcpEndpoints(
format,
token_budget: tokenBudget,
agentId: recallAgentId,
+ project: asNonEmptyString(args.project),
+ cwd: asNonEmptyString(args.cwd),
+ targetLayer: args.targetLayer ?? "all",
} });
- const text =
- format === "narrative" &&
- result &&
- typeof result === "object" &&
- "text" in (result as Record<string, unknown>) &&
- typeof (result as { text?: unknown }).text === "string"
- ? (result as { text: string }).text
- : JSON.stringify(result, null, 2);
+ const text = JSON.stringify(result, null, 2);
return {
status_code: 200,
body: {
@@ -255,20 +261,34 @@ export function registerMcpEndpoints(
}
case "memory_smart_search": {
- if (typeof args.query !== "string" || !args.query.trim()) {
+ if (args.targetLayer !== undefined && !isSearchLayer(args.targetLayer)) {
+ return { status_code: 400, body: { error: "targetLayer must be one of: all, memory, observation" } };
+ }
+ for (const field of ["project", "agentId", "sessionId", "source"] as const) {
+ if (args[field] !== undefined && typeof args[field] !== "string") {
+ return { status_code: 400, body: { error: `${field} must be a string` } };
+ }
+ }
+ const expandIds = parseSearchExpansionIds(args.expandIds);
+ if ((typeof args.query !== "string" || !args.query.trim()) && expandIds.length === 0) {
return {
status_code: 400,
- body: { error: "query is required for memory_smart_search" },
+ body: { error: "query or expandIds is required for memory_smart_search" },
};
}
- const expandIds = parseCsvList(args.expandIds).slice(0, 20);
const limit = Math.max(1, Math.min(100, asNumber(args.limit, 10) ?? 10));
const result = await sdk.trigger({
function_id: "mem::smart-search",
payload: {
- query: args.query,
+ query: asNonEmptyString(args.query),
expandIds,
limit,
+ project: asNonEmptyString(args.project),
+ agentId: asNonEmptyString(args.agentId),
+ sessionId: asNonEmptyString(args.sessionId),
+ source: asNonEmptyString(args.source),
+ includeLessons: typeof args.includeLessons === "boolean" ? args.includeLessons : undefined,
+ targetLayer: args.targetLayer ?? "all",
},
});
return {
diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts
index b173934a..c0e90366 100644
--- a/src/mcp/standalone.ts
+++ b/src/mcp/standalone.ts
@@ -3,7 +3,12 @@
import { InMemoryKV } from "./in-memory-kv.js";
import { createStdioTransport } from "./transport.js";
import { getAllTools } from "./tools-registry.js";
-import { getStandalonePersistPath } from "../config.js";
+import { getAgentId, getStandalonePersistPath, isAgentScopeIsolated } from "../config.js";
+import { isSearchLayer, type SearchLayer } from "../state/search-layer.js";
+import { memoryToObservation } from "../state/memory-utils.js";
+import { buildRecallResponse } from "../functions/recall-response.js";
+import { parseSearchExpansionIds, type SearchExpansionId } from "./search-arguments.js";
+import type { Memory, SearchResult, Session } from "../types.js";
import { VERSION } from "../version.js";
import { generateId } from "../state/schema.js";
import { queryAudit } from "../functions/audit.js";
@@ -111,8 +116,14 @@ interface Validated {
agentId?: string;
query?: string;
limit?: number;
- format?: string;
+ format?: "full" | "compact" | "narrative";
tokenBudget?: number;
+ targetLayer?: SearchLayer;
+ cwd?: string;
+ expandIds?: SearchExpansionId[];
+ sessionId?: string;
+ source?: string;
+ includeLessons?: boolean;
memoryIds?: string[];
reason?: string;
}
@@ -145,22 +156,40 @@ function validate(toolName: string, args: Record<string, unknown>): Validated {
}
case "memory_recall":
case "memory_smart_search": {
+ if (args.targetLayer !== undefined && !isSearchLayer(args.targetLayer)) {
+ throw new Error("targetLayer must be one of: all, memory, observation");
+ }
+ v.targetLayer = args.targetLayer ?? "all";
+ for (const field of ["project", "cwd", "agentId", "sessionId", "source"] as const) {
+ if (args[field] !== undefined && typeof args[field] !== "string") {
+ throw new Error(`${field} must be a string`);
+ }
+ if (typeof args[field] === "string" && args[field].trim()) v[field] = args[field].trim();
+ }
+ if (toolName === "memory_smart_search") {
+ v.expandIds = parseSearchExpansionIds(args.expandIds);
+ if (typeof args.includeLessons === "boolean") v.includeLessons = args.includeLessons;
+ }
const query = args["query"];
if (typeof query !== "string" || !query.trim()) {
- throw new Error("query is required");
+ if (!v.expandIds?.length) throw new Error("query is required unless expandIds is provided");
+ } else {
+ v.query = query.trim();
}
- v.query = query.trim();
v.limit = parseLimit(args["limit"]);
- const fmt = args["format"];
- if (typeof fmt === "string" && fmt.trim()) {
- v.format = fmt.trim().toLowerCase();
- }
- const budget = args["token_budget"];
- if (typeof budget === "number" && Number.isFinite(budget) && budget > 0) {
- v.tokenBudget = Math.floor(budget);
- } else if (typeof budget === "string" && budget.trim()) {
- const n = Number(budget);
- if (Number.isFinite(n) && n > 0) v.tokenBudget = Math.floor(n);
+ if (toolName === "memory_recall") {
+ const format = typeof args.format === "string" ? args.format.trim().toLowerCase() : args.format ?? "full";
+ if (format !== "full" && format !== "compact" && format !== "narrative") {
+ throw new Error("format must be one of: full, compact, narrative");
+ }
+ v.format = format;
+ if (args.token_budget !== undefined) {
+ const budget = typeof args.token_budget === "string" ? Number(args.token_budget) : args.token_budget;
+ if (typeof budget !== "number" || !Number.isInteger(budget) || budget < 1) {
+ throw new Error("token_budget must be a positive integer");
+ }
+ v.tokenBudget = budget;
+ }
}
return v;
}
@@ -210,6 +239,10 @@ async function handleProxy(
query: v.query,
limit: v.limit,
format: v.format ?? "full",
+ targetLayer: v.targetLayer,
+ project: v.project,
+ cwd: v.cwd,
+ agentId: v.agentId,
};
if (v.tokenBudget != null) body["token_budget"] = v.tokenBudget;
const result = await handle.call("/agentmemory/search", {
@@ -219,9 +252,17 @@ async function handleProxy(
return textResponse(result, true);
}
case "memory_smart_search": {
- const body: Record<string, unknown> = { query: v.query, limit: v.limit };
- if (v.format != null) body["format"] = v.format;
- if (v.tokenBudget != null) body["token_budget"] = v.tokenBudget;
+ const body: Record<string, unknown> = {
+ query: v.query,
+ limit: v.limit,
+ targetLayer: v.targetLayer,
+ project: v.project,
+ agentId: v.agentId,
+ expandIds: v.expandIds,
+ sessionId: v.sessionId,
+ source: v.source,
+ includeLessons: v.includeLessons,
+ };
const result = await handle.call("/agentmemory/smart-search", {
method: "POST",
body: JSON.stringify(body),
@@ -291,6 +332,8 @@ async function handleLocal(
version: 1,
isLatest: true,
sessionIds: [],
+ ...(v.project !== undefined && { project: v.project }),
+ ...((v.agentId ?? getAgentId()) !== undefined && { agentId: v.agentId ?? getAgentId() }),
});
kvInstance.persist();
return textResponse({ saved: id });
@@ -298,26 +341,48 @@ async function handleLocal(
case "memory_recall":
case "memory_smart_search": {
+ const isolated = isAgentScopeIsolated();
+ const agentId = v.agentId === "*" ? undefined : v.agentId ?? (isolated ? getAgentId() : undefined);
+ if (isolated && v.agentId !== "*" && !agentId) {
+ throw new Error("AGENTMEMORY_AGENT_SCOPE=isolated requires an agentId; pass '*' to read across agents");
+ }
const query = (v.query || "").toLowerCase();
const limit = v.limit ?? DEFAULT_LIMIT;
- const all =
- await kvInstance.list<Record<string, unknown>>("mem:memories");
- const results = all
- .filter((m) => {
- const text = [
- typeof m["title"] === "string" ? m["title"] : "",
- typeof m["content"] === "string" ? m["content"] : "",
- Array.isArray(m["files"]) ? m["files"].join(" ") : "",
- Array.isArray(m["concepts"]) ? m["concepts"].join(" ") : "",
- Array.isArray(m["sessionIds"]) ? m["sessionIds"].join(" ") : "",
- typeof m["id"] === "string" ? m["id"] : "",
- ]
- .join(" ")
- .toLowerCase();
- return query.split(/\s+/).every((word) => text.includes(word));
- })
- .slice(0, limit);
- return textResponse({ mode: "compact", results }, true);
+ const all = v.targetLayer === "observation" ? [] : await kvInstance.list<Memory>("mem:memories");
+ const sessions = v.project || v.cwd ? await kvInstance.list<Session>("mem:sessions") : [];
+ const sessionsById = new Map(sessions.map((session) => [session.id, session]));
+ const scoped = all.filter((memory) => {
+ if (memory.isLatest === false || (agentId && memory.agentId !== agentId)) return false;
+ const linkedSessions = (memory.sessionIds ?? []).map((id) => sessionsById.get(id));
+ if (v.project && (memory.project ? memory.project !== v.project : !linkedSessions.some((session) => session?.project === v.project))) return false;
+ if (v.cwd && !linkedSessions.some((session) => session?.cwd === v.cwd)) return false;
+ return true;
+ });
+ if (v.tool === "memory_smart_search" && v.expandIds?.length) {
+ const ids = v.expandIds.map((entry) => typeof entry === "string" ? entry : entry.obsId);
+ const byId = new Map(scoped.map((memory) => [memory.id, memory]));
+ const eligible = ids.filter((id) => byId.has(id));
+ const results = eligible.slice(0, 20).map((id) => {
+ const observation = memoryToObservation(byId.get(id)!);
+ return { obsId: id, sessionId: observation.sessionId, observation, layer: "memory" };
+ });
+ return textResponse({ mode: "expanded", results, truncated: eligible.length > 20 }, true);
+ }
+ const results = scoped.filter((memory) => {
+ const text = [memory.title, memory.content, ...(memory.files ?? []), ...(memory.concepts ?? []), ...(memory.sessionIds ?? []), memory.id]
+ .join(" ").toLowerCase();
+ return query.split(/\s+/).every((word) => text.includes(word));
+ }).slice(0, limit);
+ if (v.tool === "memory_recall") {
+ const matches: SearchResult[] = results.map((memory) => {
+ const observation = memoryToObservation(memory);
+ return { sessionId: observation.sessionId, observation, score: 1, layer: "memory" };
+ });
+ return textResponse(buildRecallResponse(matches, v.format ?? "full", v.tokenBudget), true);
+ }
+ return textResponse({ mode: "compact", results: results.map((memory) => ({
+ ...memory, obsId: memory.id, sessionId: memory.sessionIds?.[0] ?? "memory", layer: "memory",
+ })) }, true);
}
case "memory_sessions": {
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index 17b658de..ad66d15e 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -3,7 +3,7 @@ export type McpToolDef = {
description: string;
inputSchema: {
type: "object";
- properties: Record<string, { type: string; description: string }>;
+ properties: Record<string, { type: string; description: string; enum?: string[] }>;
required?: string[];
};
};
@@ -12,7 +12,7 @@ export const CORE_TOOLS: McpToolDef[] = [
{
name: "memory_recall",
description:
- "Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.",
+ "Search stored memories and session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.",
inputSchema: {
type: "object",
properties: {
@@ -30,8 +30,16 @@ export const CORE_TOOLS: McpToolDef[] = [
},
token_budget: {
type: "number",
- description: "Optional token budget to trim returned results",
+ description: "Optional estimated content token budget; response includes truncation and recovery metadata",
},
+ targetLayer: {
+ type: "string",
+ enum: ["all", "memory", "observation"],
+ description: "Search all indexed layers (default), durable memories, or raw observations before ranking",
+ },
+ project: { type: "string", description: "Filter by project path" },
+ cwd: { type: "string", description: "Filter by session working directory" },
+ agentId: { type: "string", description: "Filter by owning agent; '*' reads across agents" },
},
required: ["query"],
},
@@ -131,18 +139,25 @@ export const CORE_TOOLS: McpToolDef[] = [
},
{
name: "memory_smart_search",
- description: "Hybrid semantic+keyword search with progressive disclosure.",
+ description: "Hybrid semantic+keyword search with progressive disclosure. Pass query to search, or expandIds to recover full results.",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Search query" },
expandIds: {
type: "string",
- description: "Comma-separated observation IDs to expand",
+ description: "Comma-separated memory or observation IDs to expand; query is optional when provided",
},
limit: { type: "number", description: "Max results (default 10)" },
+ targetLayer: {
+ type: "string",
+ enum: ["all", "memory", "observation"],
+ description: "Search all indexed layers (default), durable memories, or raw observations before ranking",
+ },
+ project: { type: "string", description: "Filter by project path" },
+ agentId: { type: "string", description: "Filter by owning agent; '*' reads across agents" },
+ includeLessons: { type: "boolean", description: "Include lesson matches when targetLayer is all (default true)" },
},
- required: ["query"],
},
},
{
diff --git a/src/state/hybrid-search.ts b/src/state/hybrid-search.ts
index 158522a6..47b11ce2 100644
--- a/src/state/hybrid-search.ts
+++ b/src/state/hybrid-search.ts
@@ -1,4 +1,5 @@
import { SearchIndex } from "./search-index.js";
+import type { SearchLayer } from "./search-layer.js";
import { VectorIndex } from "./vector-index.js";
import type {
EmbeddingProvider,
@@ -32,17 +33,18 @@ export class HybridSearch {
private graphWeight = 0.3,
private rerankEnabled = process.env.RERANK_ENABLED === "true",
) {
- this.graphRetrieval = new GraphRetrieval(kv);
+ this.graphRetrieval = new GraphRetrieval(kv, (id) => this.bm25.layerOf(id));
}
- async search(query: string, limit = 20): Promise<HybridSearchResult[]> {
- return this.tripleStreamSearch(query, limit);
+ async search(query: string, limit = 20, targetLayer: SearchLayer = "all"): Promise<HybridSearchResult[]> {
+ return this.tripleStreamSearch(query, limit, targetLayer);
}
async searchWithExpansion(
query: string,
limit: number,
expansion: QueryExpansion,
+ targetLayer: SearchLayer = "all",
): Promise<HybridSearchResult[]> {
const allQueries = [
query,
@@ -56,7 +58,7 @@ export class HybridSearch {
];
const resultSets = await Promise.all(
- allQueries.map((q) => this.tripleStreamSearch(q, limit, allEntities)),
+ allQueries.map((q) => this.tripleStreamSearch(q, limit, targetLayer, allEntities)),
);
const merged = new Map<string, HybridSearchResult>();
@@ -73,7 +75,7 @@ export class HybridSearch {
.sort(
(a, b) =>
b.combinedScore - a.combinedScore ||
- (a.obsId < b.obsId ? -1 : a.obsId > b.obsId ? 1 : 0),
+ (a.observation.id < b.observation.id ? -1 : a.observation.id > b.observation.id ? 1 : 0),
)
.slice(0, limit);
}
@@ -81,9 +83,10 @@ export class HybridSearch {
private async tripleStreamSearch(
query: string,
limit: number,
+ targetLayer: SearchLayer,
entityHints?: string[],
): Promise<HybridSearchResult[]> {
- const bm25Results = this.bm25.search(query, limit * 2);
+ const bm25Results = this.bm25.search(query, limit * 2, targetLayer);
let vectorResults: Array<{
obsId: string;
@@ -95,7 +98,7 @@ export class HybridSearch {
if (this.vector && this.embeddingProvider && this.vector.size > 0) {
try {
queryEmbedding = await this.embeddingProvider.embed(query);
- vectorResults = this.vector.search(queryEmbedding, limit * 2);
+ vectorResults = this.vector.search(queryEmbedding, limit * 2, targetLayer, (id) => this.bm25.layerOf(id));
} catch {
// fall through to BM25-only
}
@@ -115,6 +118,7 @@ export class HybridSearch {
entities,
2,
limit,
+ targetLayer,
);
} catch {
// graph search is best-effort
@@ -125,7 +129,7 @@ export class HybridSearch {
if (graphEnabled && topVectorObs.length > 0) {
try {
const expansionResults =
- await this.graphRetrieval.expandFromChunks(topVectorObs, 1, 5);
+ await this.graphRetrieval.expandFromChunks(topVectorObs, 1, 5, targetLayer);
graphResults = [...graphResults, ...expansionResults];
} catch {
// expansion is best-effort
@@ -315,7 +319,7 @@ export class HybridSearch {
const obs = await this.kv
.get<CompressedObservation>(KV.observations(r.sessionId), r.obsId)
.catch(() => null);
- if (obs) return obs;
+ if (obs) return { observation: obs, layer: "observation" as const };
// Fallback: indexed entry may originate from mem::remember, which
// writes to KV.memories with a synthetic sessionId ("memory" or the
// memory's first associated session). Coerce the Memory record into
@@ -323,15 +327,16 @@ export class HybridSearch {
const mem = await this.kv
.get<Memory>(KV.memories, r.obsId)
.catch(() => null);
- return mem ? memoryToObservation(mem) : null;
+ return mem ? { observation: memoryToObservation(mem), layer: "memory" as const } : null;
}),
);
const enriched: HybridSearchResult[] = [];
for (let i = 0; i < sliced.length; i++) {
- const obs = observations[i];
- if (obs) {
+ const resolved = observations[i];
+ if (resolved) {
enriched.push({
- observation: obs,
+ observation: resolved.observation,
+ layer: resolved.layer,
bm25Score: sliced[i].bm25Score,
vectorScore: sliced[i].vectorScore,
graphScore: sliced[i].graphScore,
diff --git a/src/state/search-index.ts b/src/state/search-index.ts
index cd0bc4bb..895f66ef 100644
--- a/src/state/search-index.ts
+++ b/src/state/search-index.ts
@@ -1,4 +1,5 @@
import type { CompressedObservation } from "../types.js";
+import { getSearchResultLayer, isSearchResultLayer, matchesSearchLayer, type SearchLayer, type SearchResultLayer } from "./search-layer.js";
import { stem } from "./stemmer.js";
import { getSynonyms } from "./synonyms.js";
import { segmentCjk, hasCjk } from "./cjk-segmenter.js";
@@ -7,6 +8,7 @@ interface IndexEntry {
obsId: string;
sessionId: string;
termCount: number;
+ layer: SearchResultLayer;
}
export class SearchIndex {
@@ -19,7 +21,7 @@ export class SearchIndex {
private readonly k1 = 1.2;
private readonly b = 0.75;
- add(obs: CompressedObservation): void {
+ add(obs: CompressedObservation, layer: SearchResultLayer = "observation"): void {
if (this.entries.has(obs.id)) this.remove(obs.id);
const terms = this.extractTerms(obs);
const termFreq = new Map<string, number>();
@@ -34,6 +36,7 @@ export class SearchIndex {
obsId: obs.id,
sessionId: obs.sessionId,
termCount,
+ layer,
});
this.docTermCounts.set(obs.id, termFreq);
this.totalDocLength += termCount;
@@ -56,10 +59,14 @@ export class SearchIndex {
return this.entries.get(id)?.sessionId;
}
+ layerOf(id: string): SearchResultLayer | undefined {
+ return this.entries.get(id)?.layer;
+ }
+
observationCountsBySession(): Map<string, number> {
const counts = new Map<string, number>();
for (const entry of this.entries.values()) {
- if (entry.obsId.startsWith("mem_")) continue;
+ if (entry.layer !== "observation") continue;
counts.set(entry.sessionId, (counts.get(entry.sessionId) ?? 0) + 1);
}
return counts;
@@ -69,8 +76,8 @@ export class SearchIndex {
let memories = 0;
let lessons = 0;
for (const entry of this.entries.values()) {
- if (entry.obsId.startsWith("mem_")) memories++;
- else if (entry.sessionId === "lesson") lessons++;
+ if (entry.layer === "memory") memories++;
+ else if (entry.layer === "lesson") lessons++;
}
return { memories, lessons };
}
@@ -101,6 +108,7 @@ export class SearchIndex {
search(
query: string,
limit = 20,
+ targetLayer: SearchLayer = "all",
): Array<{ obsId: string; sessionId: string; score: number }> {
const rawTerms = this.tokenize(query.toLowerCase());
if (rawTerms.length === 0) return [];
@@ -135,6 +143,7 @@ export class SearchIndex {
for (const obsId of matchingDocs) {
const entry = this.entries.get(obsId)!;
+ if (!matchesSearchLayer(obsId, entry.sessionId, targetLayer, entry.layer)) continue;
const docTerms = this.docTermCounts.get(obsId);
const tf = docTerms?.get(term) || 0;
const docLen = entry.termCount;
@@ -162,6 +171,7 @@ export class SearchIndex {
for (const obsId of obsIds) {
if (matchingDocs?.has(obsId)) continue;
const entry = this.entries.get(obsId)!;
+ if (!matchesSearchLayer(obsId, entry.sessionId, targetLayer, entry.layer)) continue;
const docTerms = this.docTermCounts.get(obsId);
const tf = docTerms?.get(indexTerm) || 0;
const docLen = entry.termCount;
@@ -228,7 +238,7 @@ export class SearchIndex {
[id, Array.from(counts.entries())] as [string, [string, number][]],
);
return JSON.stringify({
- v: 2,
+ v: 3,
entries,
inverted,
docTerms,
@@ -242,7 +252,10 @@ export class SearchIndex {
const data = JSON.parse(json);
if (!data?.entries || !data?.inverted || !data?.docTerms) return idx;
for (const [key, val] of data.entries) {
- idx.entries.set(key, val);
+ idx.entries.set(key, {
+ ...val,
+ layer: isSearchResultLayer(val.layer) ? val.layer : getSearchResultLayer(key, val.sessionId),
+ });
}
for (const [term, ids] of data.inverted) {
idx.invertedIndex.set(term, new Set(ids));
diff --git a/src/state/search-layer.ts b/src/state/search-layer.ts
new file mode 100644
index 00000000..e84ee8a7
--- /dev/null
+++ b/src/state/search-layer.ts
@@ -0,0 +1,27 @@
+export type SearchLayer = "all" | "memory" | "observation";
+export type SearchResultLayer = "memory" | "observation" | "lesson" | "insight";
+export type SearchLayerResolver = (obsId: string, sessionId: string) => SearchResultLayer | undefined;
+
+export function isSearchLayer(value: unknown): value is SearchLayer {
+ return value === "all" || value === "memory" || value === "observation";
+}
+
+export function isSearchResultLayer(value: unknown): value is SearchResultLayer {
+ return value === "memory" || value === "observation" || value === "lesson" || value === "insight";
+}
+
+export function getSearchResultLayer(obsId: string, sessionId: string): SearchResultLayer {
+ if (obsId.startsWith("mem_")) return "memory";
+ if (sessionId === "lesson" || obsId.startsWith("lsn_")) return "lesson";
+ if (sessionId === "insight" || obsId.startsWith("ins_")) return "insight";
+ return "observation";
+}
+
+export function matchesSearchLayer(
+ obsId: string,
+ sessionId: string,
+ targetLayer: SearchLayer = "all",
+ layer?: SearchResultLayer,
+): boolean {
+ return targetLayer === "all" || (layer ?? getSearchResultLayer(obsId, sessionId)) === targetLayer;
+}
diff --git a/src/state/vector-index.ts b/src/state/vector-index.ts
index d66a14d0..b3145965 100644
--- a/src/state/vector-index.ts
+++ b/src/state/vector-index.ts
@@ -1,3 +1,5 @@
+import { matchesSearchLayer, type SearchLayer, type SearchLayerResolver } from "./search-layer.js";
+
export function float32ToBase64(arr: Float32Array): string {
return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength).toString(
"base64",
@@ -97,6 +99,8 @@ export class VectorIndex {
search(
query: Float32Array,
limit = 20,
+ targetLayer: SearchLayer = "all",
+ resolveLayer?: SearchLayerResolver,
): Array<{ obsId: string; sessionId: string; score: number }> {
const results: Array<{
obsId: string;
@@ -106,6 +110,7 @@ export class VectorIndex {
let minScore = -Infinity;
for (const [obsId, entry] of this.vectors) {
+ if (!matchesSearchLayer(obsId, entry.sessionId, targetLayer, resolveLayer?.(obsId, entry.sessionId))) continue;
const score = cosineSimilarity(query, entry.embedding);
if (results.length < limit) {
results.push({ obsId, sessionId: entry.sessionId, score });
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 3147c3cf..c3278714 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -6,6 +6,7 @@ import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSu
import { AUDIT_MIGRATION_STATE_KEY } from "../functions/audit.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import { KV } from "../state/schema.js";
+import { isSearchLayer, type SearchLayer } from "../state/search-layer.js";
import { checkPayloadFrameSize } from "../state/frame-guard.js";
import { StateKV } from "../state/kv.js";
import { addSessionToProjectIndex } from "../state/session-index.js";
@@ -847,10 +848,14 @@ export function registerApiTriggers(
cwd?: string;
format?: string;
token_budget?: number;
+ targetLayer?: SearchLayer;
agentId?: string;
}>,
): Promise<Response> => {
const body = (req.body ?? {}) as Record<string, unknown>;
+ if (body.targetLayer !== undefined && !isSearchLayer(body.targetLayer)) {
+ return { status_code: 400, body: { error: "targetLayer must be one of: all, memory, observation" } };
+ }
const queryAgentId =
typeof (req as { query_params?: Record<string, string> })
.query_params?.["agentId"] === "string"
@@ -866,11 +871,10 @@ export function registerApiTriggers(
) {
return { status_code: 400, body: { error: "limit must be a positive integer" } };
}
- if (body.project !== undefined && typeof body.project !== "string") {
- return { status_code: 400, body: { error: "project must be a string" } };
- }
- if (body.cwd !== undefined && typeof body.cwd !== "string") {
- return { status_code: 400, body: { error: "cwd must be a string" } };
+ for (const field of ["project", "cwd", "agentId"] as const) {
+ if (body[field] !== undefined && typeof body[field] !== "string") {
+ return { status_code: 400, body: { error: `${field} must be a string` } };
+ }
}
if (
body.format !== undefined &&
@@ -906,6 +910,7 @@ export function registerApiTriggers(
: undefined,
token_budget: body.token_budget as number | undefined,
agentId: bodyAgentId ?? queryAgentId,
+ targetLayer: body.targetLayer ?? "all",
};
const result = await sdk.trigger({ function_id: "mem::search", payload: payload });
return { status_code: 200, body: result };
@@ -1775,10 +1780,11 @@ export function registerApiTriggers(
async (
req: HttpRequest<{
query?: string;
- expandIds?: Array<string | { obsId: string; sessionId: string }>;
+ expandIds?: Array<string | { obsId: string; sessionId?: string }>;
limit?: number;
project?: string;
includeLessons?: boolean;
+ targetLayer?: SearchLayer;
agentId?: string;
sessionId?: string;
source?: string;
@@ -1786,10 +1792,34 @@ export function registerApiTriggers(
): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- if (
- !req.body?.query &&
- (!req.body?.expandIds || req.body.expandIds.length === 0)
- ) {
+ if (req.body?.targetLayer !== undefined && !isSearchLayer(req.body.targetLayer)) {
+ return { status_code: 400, body: { error: "targetLayer must be one of: all, memory, observation" } };
+ }
+ const body = req.body ?? {};
+ for (const field of ["query", "project", "agentId", "sessionId", "source"] as const) {
+ if (body[field] !== undefined && typeof body[field] !== "string") {
+ return { status_code: 400, body: { error: `${field} must be a string` } };
+ }
+ }
+ if (body.includeLessons !== undefined && typeof body.includeLessons !== "boolean") {
+ return { status_code: 400, body: { error: "includeLessons must be a boolean" } };
+ }
+ if (body.expandIds !== undefined && (
+ !Array.isArray(body.expandIds) || !body.expandIds.every((entry) => {
+ if (typeof entry === "string") return entry.trim().length > 0;
+ return entry && typeof entry === "object" &&
+ typeof entry.obsId === "string" && entry.obsId.trim().length > 0 &&
+ (entry.sessionId === undefined || (typeof entry.sessionId === "string" && entry.sessionId.trim().length > 0));
+ })
+ )) {
+ return { status_code: 400, body: { error: "expandIds must be an array of non-empty IDs or objects with obsId and optional sessionId strings" } };
+ }
+ const expandIds = body.expandIds?.map((entry) => {
+ if (typeof entry === "string") return entry.trim();
+ if (entry.sessionId !== undefined) return { obsId: entry.obsId.trim(), sessionId: entry.sessionId.trim() };
+ return entry.obsId.trim();
+ });
+ if (!body.query?.trim() && !expandIds?.length) {
return {
status_code: 400,
body: { error: "query or expandIds is required" },
@@ -1803,11 +1833,12 @@ export function registerApiTriggers(
// section). Drops unknown fields so a misbehaving client can't
// inject downstream-only options.
const payload = {
- query: req.body?.query,
- expandIds: req.body?.expandIds,
+ query: body.query?.trim() || undefined,
+ expandIds,
limit: req.body?.limit,
project: req.body?.project,
includeLessons: req.body?.includeLessons,
+ targetLayer: req.body?.targetLayer ?? "all",
agentId: req.body?.agentId,
sessionId: req.body?.sessionId,
source: req.body?.source ?? sourceFromHeader,
diff --git a/src/types.ts b/src/types.ts
index a14daf92..b847f1e8 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -220,6 +220,7 @@ export interface SearchResult {
observation: CompressedObservation;
score: number;
sessionId: string;
+ layer?: "memory" | "observation" | "lesson" | "insight";
}
export interface ContextBlock {
@@ -304,6 +305,7 @@ export interface MemoryRelation {
export interface HybridSearchResult {
observation: CompressedObservation;
+ layer?: "memory" | "observation" | "lesson" | "insight";
bm25Score: number;
vectorScore: number;
graphScore: number;
@@ -319,6 +321,7 @@ export interface CompactSearchResult {
type: ObservationType;
score: number;
timestamp: string;
+ layer?: "memory" | "observation" | "lesson" | "insight";
}
export interface CompactLessonResult {
diff --git a/test/api-list-pagination.test.ts b/test/api-list-pagination.test.ts
index 3928af80..23fb8635 100644
--- a/test/api-list-pagination.test.ts
+++ b/test/api-list-pagination.test.ts
@@ -95,7 +95,7 @@ describe("paginated and filtered list endpoints", () => {
const other = memory("mem_db", "2026-09-05T00:00:00Z", { title: "db", content: "postgres vacuum schedule", project: "web" });
const scoped = memory("mem_auth_api", "2026-09-06T00:00:00Z", { title: "jwt", content: "jwt verification in api gateway", project: "api" });
const index = getSearchIndex();
- for (const m of [auth, other, scoped]) index.add(memoryToObservation(m));
+ for (const m of [auth, other, scoped]) index.add(memoryToObservation(m), "memory");
const { handlers } = setup({ [KV.memories]: { [auth.id]: auth, [other.id]: other, [scoped.id]: scoped } });
const res = await call(handlers, "api::memories", { q: "jwt", project: "web" });
@@ -111,7 +111,7 @@ describe("paginated and filtered list endpoints", () => {
it("fuses keyword and vector ranks so a meaning-only match still surfaces", async () => {
const index = getSearchIndex();
const keywordHit = memory("mem_kw", "2026-09-01T00:00:00Z", { title: "deploy", content: "deploy pipeline uses canary stage" });
- index.add(memoryToObservation(keywordHit));
+ index.add(memoryToObservation(keywordHit), "memory");
const vectors = new VectorIndex();
vectors.add("mem_vec", "memory", new Float32Array([1, 0, 0]));
vectors.add("mem_kw", "memory", new Float32Array([0, 1, 0]));
diff --git a/test/index-reconcile.test.ts b/test/index-reconcile.test.ts
index e96a7d4e..225d38d1 100644
--- a/test/index-reconcile.test.ts
+++ b/test/index-reconcile.test.ts
@@ -102,7 +102,7 @@ describe("reconcileIndex", () => {
const kv = mockKV();
await kv.set("mem:sessions", "s1", makeSession("s1", 1));
await kv.set("mem:obs:s1", "obs_a", makeObs("obs_a", "s1"));
- getSearchIndex().add(makeObs("mem_x", "s1"));
+ getSearchIndex().add(makeObs("mem_x", "s1"), "memory");
const added = await reconcileIndex(kv as never);
diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts
index fa0dbcf5..bb9e34b9 100644
--- a/test/mcp-standalone-proxy.test.ts
+++ b/test/mcp-standalone-proxy.test.ts
@@ -111,6 +111,7 @@ describe("@agentmemory/mcp standalone — server proxy", () => {
limit: 5,
format: "full",
token_budget: 800,
+ targetLayer: "all",
});
expect(calls.find((c) => c.url.endsWith("/agentmemory/smart-search"))).toBeUndefined();
});
@@ -205,9 +206,9 @@ describe("@agentmemory/mcp standalone — server proxy", () => {
await handleToolCall("memory_save", { content: "local only" }, localKv);
const recall = await handleToolCall("memory_recall", { query: "local" }, localKv);
const out = JSON.parse(recall.content[0].text);
- expect(out.mode).toBe("compact");
+ expect(out.format).toBe("full");
expect(out.results).toHaveLength(1);
- expect(out.results[0].content).toBe("local only");
+ expect(out.results[0].observation.narrative).toBe("local only");
});
it("invalidates the handle on proxy failure, so the next call re-probes", async () => {
diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts
index 7c0c128e..e9096cdd 100644
--- a/test/mcp-standalone.test.ts
+++ b/test/mcp-standalone.test.ts
@@ -17,6 +17,8 @@ vi.mock("../src/mcp/transport.js", () => ({
vi.mock("../src/config.js", () => ({
getStandalonePersistPath: vi.fn(() => "/tmp/test-standalone.json"),
+ getAgentId: vi.fn(() => undefined),
+ isAgentScopeIsolated: vi.fn(() => false),
}));
import {
@@ -214,7 +216,8 @@ describe("handleToolCall", () => {
);
const parsed = JSON.parse(result.content[0].text);
expect(parsed.results).toHaveLength(1);
- expect(parsed.results[0].content).toBe("TypeScript is great");
+ expect(parsed.format).toBe("full");
+ expect(parsed.results[0].observation.narrative).toBe("TypeScript is great");
});
it("memory_save accepts concepts/files as arrays (plugin skill format)", async () => {
diff --git a/test/recall-access.test.ts b/test/recall-access.test.ts
new file mode 100644
index 00000000..7e2e0249
--- /dev/null
+++ b/test/recall-access.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { getSearchIndex, registerSearchFunction, setHybridRanker, setVectorIndex } from "../src/functions/search.js";
+import { recordAccessBatch } from "../src/functions/access-tracker.js";
+import { KV } from "../src/state/schema.js";
+import type { CompressedObservation } from "../src/types.js";
+
+vi.mock("../src/functions/access-tracker.js", () => ({ recordAccessBatch: vi.fn() }));
+vi.mock("../src/logger.js", () => ({ logger: { info: vi.fn(), warn: vi.fn() } }));
+
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); getSearchIndex().clear(); });
+
+it("records access only for emitted recall content, not budget-excluded matches", async () => {
+ vi.stubEnv("AGENTMEMORY_AGENT_SCOPE", "shared");
+ setHybridRanker(null);
+ setVectorIndex(null);
+ const observations: CompressedObservation[] = ["first", "second"].map((name) => ({
+ id: `obs_${name}`, sessionId: "ses_budget", title: "deployment policy", type: "decision",
+ timestamp: "2026-01-01T00:00:00Z", facts: [], narrative: name + " policy ".repeat(1200),
+ concepts: [], files: [], importance: 8,
+ }));
+ const index = getSearchIndex();
+ for (const observation of observations) index.add(observation);
+ vi.spyOn(index, "search").mockReturnValue(observations.map((observation, i) => ({
+ obsId: observation.id, sessionId: observation.sessionId, score: 10 - i,
+ })));
+ const kv = { get: async (scope: string, id: string) =>
+ scope === KV.observations("ses_budget") ? observations.find((observation) => observation.id === id) : null };
+ let search: (data: unknown) => Promise<any>;
+ registerSearchFunction({ registerFunction: (_name: string, fn: typeof search) => { search = fn; } } as never, kv as never);
+ const preview = await search!({ query: "policy", token_budget: 300 });
+ expect(preview.results).toHaveLength(1);
+ expect(preview.results[0].content_truncated).toBe(true);
+ expect(preview.excluded_by_budget).toBe(1);
+ expect(recordAccessBatch).toHaveBeenLastCalledWith(kv, ["obs_first"]);
+
+ const excluded = await search!({ query: "policy", token_budget: 1 });
+ expect(excluded.matched_count).toBe(2);
+ expect(excluded.results).toEqual([]);
+ expect(recordAccessBatch).toHaveBeenLastCalledWith(kv, []);
+});
diff --git a/test/recall-boundaries.test.ts b/test/recall-boundaries.test.ts
new file mode 100644
index 00000000..39bce6f5
--- /dev/null
+++ b/test/recall-boundaries.test.ts
@@ -0,0 +1,257 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../src/mcp/transport.js", () => ({
+ createStdioTransport: () => ({ start: vi.fn(), stop: vi.fn() }),
+}));
+vi.mock("../src/config.js", async (original) => ({
+ ...await original<typeof import("../src/config.js")>(),
+ getStandalonePersistPath: () => undefined,
+}));
+
+import * as config from "../src/config.js";
+import { registerApiTriggers } from "../src/triggers/api.js";
+import { registerMcpEndpoints } from "../src/mcp/server.js";
+import { handleToolCall } from "../src/mcp/standalone.js";
+import { InMemoryKV } from "../src/mcp/in-memory-kv.js";
+import { resetHandleForTests, setLivezProbe } from "../src/mcp/rest-proxy.js";
+import { getAllTools } from "../src/mcp/tools-registry.js";
+
+type Handler = (req: unknown) => Promise<{ status_code: number; body: any }>;
+
+function endpoints(result: unknown = { results: [] }) {
+ const handlers = new Map<string, Handler>();
+ const kv = new InMemoryKV();
+ const trigger = vi.fn(async () => result);
+ const sdk = {
+ registerFunction: (name: string, handler: Handler) => handlers.set(name, handler),
+ registerTrigger: vi.fn(), trigger, on: vi.fn(),
+ };
+ registerApiTriggers(sdk as never, kv as never);
+ registerMcpEndpoints(sdk as never, kv as never);
+ const call = (name: string, body: unknown) => handlers.get(name)!({
+ method: "POST", headers: { "content-type": "application/json" }, query_params: {}, body,
+ });
+ return { call, trigger };
+}
+
+beforeEach(() => {
+ vi.stubEnv("AGENTMEMORY_AGENT_SCOPE", "shared");
+ vi.stubEnv("AGENT_ID", "");
+ vi.stubEnv("AGENTMEMORY_URL", "http://127.0.0.1:3111");
+ vi.stubEnv("AGENTMEMORY_FORCE_PROXY", "");
+ resetHandleForTests();
+});
+afterEach(() => {
+ resetHandleForTests();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+});
+
+describe("recall request boundaries", () => {
+ it.each(["project", "agentId"])("rejects malformed %s filters instead of broadening REST recall", async (field) => {
+ const { call, trigger } = endpoints();
+ for (const name of ["api::search", "api::smart-search"]) {
+ for (const value of [null, 42, [], {}]) {
+ const result = await call(name, { query: "context", targetLayer: "memory", [field]: value });
+ expect(result.status_code).toBe(400);
+ expect(result.body.error).toContain(field);
+ }
+ }
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it.each(["query", "sessionId", "source", "includeLessons"])("rejects malformed smart-search %s before dispatch", async (field) => {
+ const { call, trigger } = endpoints();
+ const result = await call("api::smart-search", { expandIds: ["mem_recover"], [field]: {} });
+ expect(result.status_code).toBe(400);
+ expect(result.body.error).toContain(field);
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("rejects malformed expansion requests rather than crashing or silently dropping entries", async () => {
+ const { call, trigger } = endpoints();
+ const invalid = [null, "mem_a", {}, [null], [1], [""], [" "], [{}], [{ obsId: 3 }],
+ [{ obsId: "mem_a", sessionId: 3 }], [{ obsId: "mem_a", sessionId: " " }]];
+ for (const expandIds of invalid) {
+ const result = await call("api::smart-search", { query: "context", expandIds });
+ expect(result.status_code).toBe(400);
+ expect(result.body.error).toContain("expandIds");
+ }
+ expect((await call("api::smart-search", { query: " ", expandIds: [] })).status_code).toBe(400);
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("normalizes valid expansion IDs and optional session hints while preserving recovery without a query", async () => {
+ const { call, trigger } = endpoints();
+ const result = await call("api::smart-search", {
+ expandIds: [" mem_first ", { obsId: " mem_second " }, { obsId: " obs_third ", sessionId: " ses_one " }],
+ targetLayer: "memory", project: "/alpha", agentId: "agent-a", includeLessons: false,
+ });
+ expect(result.status_code).toBe(200);
+ expect(trigger).toHaveBeenCalledWith({ function_id: "mem::smart-search", payload: expect.objectContaining({
+ query: undefined, expandIds: ["mem_first", "mem_second", { obsId: "obs_third", sessionId: "ses_one" }],
+ targetLayer: "memory", project: "/alpha", agentId: "agent-a", includeLessons: false,
+ }) });
+ });
+
+ it.each(["memory_recall", "memory_smart_search"])("advertises the exact layer enum for %s", (name) => {
+ const tool = getAllTools().find((entry) => entry.name === name)!;
+ expect(tool.inputSchema.properties.targetLayer.enum).toEqual(["all", "memory", "observation"]);
+ expect(tool.inputSchema.properties).toHaveProperty("project");
+ expect(tool.inputSchema.properties).toHaveProperty("agentId");
+ if (name === "memory_smart_search") expect(tool.inputSchema.required ?? []).not.toContain("query");
+ });
+
+ it.each([null, "", "Memory", "lesson", "insight", [], {}, 1])("rejects invalid targetLayer %j before dispatch at REST and MCP", async (targetLayer) => {
+ const { call, trigger } = endpoints();
+ for (const name of ["api::search", "api::smart-search"]) {
+ const result = await call(name, { query: "context", targetLayer });
+ expect(result.status_code).toBe(400);
+ expect(result.body.error).toContain("targetLayer");
+ }
+ for (const name of ["memory_recall", "memory_smart_search"]) {
+ const result = await call("mcp::tools::call", { name, arguments: { query: "context", targetLayer } });
+ expect(result.status_code).toBe(400);
+ expect(result.body.error).toContain("targetLayer");
+ }
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it.each(["all", "memory", "observation"])("forwards %s with recall scope and preserves narrative metadata", async (targetLayer) => {
+ const response = {
+ format: "narrative", text: "1. preview", results: [{ obsId: "mem_one", content_truncated: true }],
+ tokens_used: 100, tokens_budget: 100, truncated: true, matched_count: 2,
+ excluded_by_budget: 1, excluded_results: [{ obsId: "mem_two", sessionId: "memory", title: "second" }],
+ };
+ const { call, trigger } = endpoints(response);
+ const args = { query: "context", limit: 2, format: "narrative", token_budget: 100,
+ targetLayer, project: "/alpha", cwd: "/alpha/worktree", agentId: "agent-a" };
+ const rest = await call("api::search", args);
+ expect(rest.body).toEqual(response);
+ expect(trigger).toHaveBeenLastCalledWith({ function_id: "mem::search", payload: args });
+ const mcp = await call("mcp::tools::call", { name: "memory_recall", arguments: args });
+ expect(JSON.parse(mcp.body.content[0].text)).toEqual(response);
+ expect(trigger).toHaveBeenLastCalledWith({ function_id: "mem::search", payload: args });
+ });
+
+ it("preserves smart expansion hints, scopes and diagnostics fields without capping before layer filtering", async () => {
+ const { call, trigger } = endpoints();
+ const expandIds = Array.from({ length: 25 }, (_, index) => ({ obsId: `obs_${index}`, sessionId: "ses_one" }));
+ expandIds.push({ obsId: "mem_recover", sessionId: "memory" });
+ const args = { expandIds, limit: 5, project: "/alpha", agentId: "agent-a", sessionId: "ses_current",
+ source: "agent", includeLessons: false, targetLayer: "memory" };
+ expect((await call("api::smart-search", args)).status_code).toBe(200);
+ expect(trigger).toHaveBeenLastCalledWith({ function_id: "mem::smart-search", payload: { ...args, query: undefined } });
+ expect((await call("mcp::tools::call", { name: "memory_smart_search", arguments: args })).status_code).toBe(200);
+ expect(trigger).toHaveBeenLastCalledWith({ function_id: "mem::smart-search", payload: { ...args, query: undefined } });
+ });
+
+ it("defaults omitted targetLayer to all at both REST routes", async () => {
+ const { call, trigger } = endpoints();
+ for (const name of ["api::search", "api::smart-search"]) {
+ await call(name, { query: "context" });
+ expect(trigger).toHaveBeenLastCalledWith(expect.objectContaining({ payload: expect.objectContaining({ targetLayer: "all" }) }));
+ }
+ });
+});
+
+describe("standalone recall boundaries", () => {
+ it("forwards recall and smart search scopes, layer and expansion to the daemon", async () => {
+ setLivezProbe(async () => ({ ok: true, status: 200, statusText: "OK" }));
+ const fetch = vi.fn(async (_url: unknown, init?: RequestInit) => new Response(init?.body, { status: 200 }));
+ vi.stubGlobal("fetch", fetch);
+ const recall = { query: "context", limit: 4, format: "narrative", token_budget: 200, targetLayer: "memory",
+ project: "/alpha", cwd: "/alpha/worktree", agentId: "agent-a" };
+ expect(JSON.parse((await handleToolCall("memory_recall", recall)).content[0].text)).toEqual(recall);
+ const smart = { limit: 4, targetLayer: "observation", project: "/alpha", agentId: "agent-a",
+ expandIds: [{ obsId: "obs_a", sessionId: "ses_a" }], sessionId: "ses_current", source: "agent", includeLessons: false };
+ expect(JSON.parse((await handleToolCall("memory_smart_search", smart)).content[0].text)).toEqual(smart);
+ expect(fetch.mock.calls.map(([url]) => String(url))).toEqual([
+ "http://127.0.0.1:3111/agentmemory/search", "http://127.0.0.1:3111/agentmemory/smart-search",
+ ]);
+ });
+
+ it.each(["memory_recall", "memory_smart_search"])("rejects invalid layers for %s without invoking a daemon route", async (tool) => {
+ setLivezProbe(async () => ({ ok: true, status: 200, statusText: "OK" }));
+ const fetch = vi.fn();
+ vi.stubGlobal("fetch", fetch);
+ for (const targetLayer of [null, "", "Memory", "lesson", [], 1]) {
+ await expect(handleToolCall(tool, { query: "context", targetLayer }, new InMemoryKV())).rejects.toThrow("targetLayer");
+ }
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("filters local durable memories before limits and returns no observations", async () => {
+ setLivezProbe(async () => ({ ok: false, status: 0, statusText: "offline" }));
+ const kv = new InMemoryKV();
+ await handleToolCall("memory_save", { content: "context wrong project", project: "/beta", agentId: "agent-a" }, kv);
+ await handleToolCall("memory_save", { content: "context wrong agent", project: "/alpha", agentId: "agent-b" }, kv);
+ const saved = JSON.parse((await handleToolCall("memory_save", {
+ content: "context selected memory", project: "/alpha", agentId: "agent-a",
+ }, kv)).content[0].text).saved;
+ for (const tool of ["memory_recall", "memory_smart_search"]) {
+ const args = { query: "context", project: "/alpha", agentId: "agent-a", limit: 1, targetLayer: "memory" };
+ const result = JSON.parse((await handleToolCall(tool, args, kv)).content[0].text);
+ expect(result.results).toHaveLength(1);
+ expect(result.results[0].layer).toBe("memory");
+ if (tool === "memory_smart_search") {
+ expect(result.results[0].obsId).toBe(saved);
+ expect(result.results[0].sessionId).toBe("memory");
+ }
+ expect(JSON.stringify(result.results[0])).toContain(saved);
+ const observations = JSON.parse((await handleToolCall(tool, { ...args, targetLayer: "observation" }, kv)).content[0].text);
+ expect(observations.results).toEqual([]);
+ }
+ });
+
+ it("discloses a tiny budget and recovers excluded local memory content by id", async () => {
+ setLivezProbe(async () => ({ ok: false, status: 0, statusText: "offline" }));
+ const kv = new InMemoryKV();
+ const content = `context ${"long memory body ".repeat(100)}`;
+ const saved = JSON.parse((await handleToolCall("memory_save", { content, project: "/alpha" }, kv)).content[0].text).saved;
+ for (const format of ["full", "compact", "narrative"]) {
+ const result = JSON.parse((await handleToolCall("memory_recall", {
+ query: "context", format, token_budget: 1, targetLayer: "memory", project: "/alpha",
+ }, kv)).content[0].text);
+ expect(result).toMatchObject({ format, results: [], truncated: true, matched_count: 1, excluded_by_budget: 1, tokens_budget: 1 });
+ expect(result.excluded_results[0].obsId).toBe(saved);
+ expect(result.minimum_budget).toBeGreaterThan(1);
+ const expanded = JSON.parse((await handleToolCall("memory_smart_search", {
+ expandIds: result.excluded_results.map((entry: { obsId: string }) => entry.obsId).join(","),
+ project: "/alpha", targetLayer: "memory",
+ }, kv)).content[0].text);
+ expect(expanded.mode).toBe("expanded");
+ expect(expanded.results[0].observation.narrative).toBe(content);
+ expect(expanded.results[0].layer).toBe("memory");
+ }
+ });
+
+ it("clips oversized local recall within budget and preserves complete stored content", async () => {
+ setLivezProbe(async () => ({ ok: false, status: 0, statusText: "offline" }));
+ const kv = new InMemoryKV();
+ const content = `context ${"recovery detail ".repeat(1000)}`;
+ await handleToolCall("memory_save", { content }, kv);
+ for (const format of ["full", "narrative"]) {
+ const result = JSON.parse((await handleToolCall("memory_recall", {
+ query: "context", format, token_budget: 200, targetLayer: "memory",
+ }, kv)).content[0].text);
+ expect(result.results).toHaveLength(1);
+ expect(result.results[0].content_truncated).toBe(true);
+ expect(result.truncated).toBe(true);
+ expect(result.tokens_used).toBeLessThanOrEqual(200);
+ expect(result.matched_count).toBe(1);
+ }
+ expect((await kv.list<{ content: string }>("mem:memories"))[0].content).toBe(content);
+ });
+
+ it("fails closed without an agent in isolated fallback and honors a wildcard", async () => {
+ setLivezProbe(async () => ({ ok: false, status: 0, statusText: "offline" }));
+ const kv = new InMemoryKV();
+ await handleToolCall("memory_save", { content: "context shared" }, kv);
+ vi.spyOn(config, "isAgentScopeIsolated").mockReturnValue(true);
+ await expect(handleToolCall("memory_recall", { query: "context" }, kv)).rejects.toThrow("requires an agentId");
+ const result = JSON.parse((await handleToolCall("memory_recall", { query: "context", agentId: "*" }, kv)).content[0].text);
+ expect(result.results).toHaveLength(1);
+ });
+});
diff --git a/test/recall-layer.test.ts b/test/recall-layer.test.ts
new file mode 100644
index 00000000..98cc50d5
--- /dev/null
+++ b/test/recall-layer.test.ts
@@ -0,0 +1,302 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { GraphRetrieval } from "../src/functions/graph-retrieval.js";
+import {
+ getSearchIndex,
+ rankMemoryIds,
+ rebuildKeywordIndex,
+ registerSearchFunction,
+ setEmbeddingProvider,
+ setHybridRanker,
+ setVectorIndex,
+} from "../src/functions/search.js";
+import { registerSmartSearchFunction } from "../src/functions/smart-search.js";
+import { HybridSearch } from "../src/state/hybrid-search.js";
+import { memoryToObservation } from "../src/state/memory-utils.js";
+import { KV } from "../src/state/schema.js";
+import { SearchIndex } from "../src/state/search-index.js";
+import { VectorIndex } from "../src/state/vector-index.js";
+import type { CompressedObservation, Memory } from "../src/types.js";
+
+vi.mock("../src/logger.js", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock("../src/functions/access-tracker.js", () => ({ recordAccessBatch: vi.fn() }));
+
+const timestamp = "2026-10-10T00:00:00.000Z";
+
+function observation(id: string): CompressedObservation {
+ return {
+ id, sessionId: "capture-session", timestamp, type: "command_run", title: "quasar policy",
+ narrative: "quasar policy", facts: [], concepts: [], files: [], importance: 5, confidence: 0.3,
+ };
+}
+
+function memory(overrides: Partial<Memory> = {}): Memory {
+ return {
+ id: "mem_decision", title: "quasar policy", content: "Use a single authority for deployment decisions. ".repeat(80),
+ type: "fact", concepts: [], files: [], sessionIds: [], strength: 7, createdAt: timestamp,
+ updatedAt: timestamp, version: 1, isLatest: true, ...overrides,
+ } as Memory;
+}
+
+function fixture() {
+ const records = new Map<string, unknown>();
+ const kv = {
+ get: async <T>(scope: string, id: string): Promise<T | null> => (records.get(`${scope}/${id}`) as T) ?? null,
+ set: async <T>(scope: string, id: string, value: T): Promise<T> => { records.set(`${scope}/${id}`, value); return value; },
+ list: async <T>(scope: string): Promise<T[]> => [...records].filter(([key]) => key.startsWith(`${scope}/`)).map(([, value]) => value as T),
+ };
+ const handlers = new Map<string, (data: any) => Promise<any>>();
+ const sdk = {
+ registerFunction: (id: string, handler: (data: any) => Promise<any>) => handlers.set(id, handler),
+ trigger: vi.fn(async ({ function_id, payload }: { function_id: string; payload: unknown }) => {
+ if (function_id === "mem::lesson-recall") return { success: true, lessons: [] };
+ const handler = handlers.get(function_id);
+ if (!handler) throw new Error(`Unknown function ${function_id}`);
+ return handler(payload);
+ }),
+ };
+ const index = getSearchIndex();
+ const vector = new VectorIndex();
+ const embedding = { name: "fixed", dimensions: 2, embed: async () => new Float32Array([1, 0]), embedBatch: async () => [] };
+ const hybrid = new HybridSearch(index, vector, embedding, kv as never, 0.4, 0.6, 0);
+ const search = vi.fn((query: string, limit: number, targetLayer?: "all" | "memory" | "observation") => hybrid.search(query, limit, targetLayer));
+ registerSearchFunction(sdk as never, kv as never);
+ registerSmartSearchFunction(sdk as never, kv as never, search);
+ return {
+ kv, sdk, index, vector, embedding, search,
+ call: (id: string, args: Record<string, unknown>) => sdk.trigger({ function_id: id, payload: args }),
+ addObservation: async (obs: CompressedObservation) => {
+ index.add(obs);
+ vector.add(obs.id, obs.sessionId, new Float32Array([1, 0]));
+ await kv.set(KV.observations(obs.sessionId), obs.id, obs);
+ },
+ addMemory: async (saved: Memory) => {
+ index.add(memoryToObservation(saved), "memory");
+ vector.add(saved.id, saved.sessionIds[0] ?? "memory", new Float32Array([0.8, 0.6]));
+ await kv.set(KV.memories, saved.id, saved);
+ },
+ };
+}
+
+beforeEach(() => {
+ getSearchIndex().clear();
+ setVectorIndex(null);
+ setEmbeddingProvider(null);
+ setHybridRanker(null);
+ vi.stubEnv("AGENTMEMORY_AGENT_SCOPE", "shared");
+ vi.stubEnv("AGENT_ID", "");
+});
+
+afterEach(() => {
+ setVectorIndex(null);
+ setEmbeddingProvider(null);
+ setHybridRanker(null);
+ vi.unstubAllEnvs();
+});
+
+describe("recall layer selection", () => {
+ it("filters keyword and vector candidates before their top-k windows under dense capture noise", async () => {
+ const f = fixture();
+ for (let i = 0; i < 360; i++) await f.addObservation(observation(`obs_${i}`));
+ await f.addMemory(memory());
+
+ expect(f.index.search("quasar policy", 1)[0].obsId).toMatch(/^obs_/);
+ expect(f.vector.search(new Float32Array([1, 0]), 1)[0].obsId).toMatch(/^obs_/);
+ expect(f.index.search("quasar policy", 1, "memory").map((hit) => hit.obsId)).toEqual(["mem_decision"]);
+ expect(f.index.search("quas", 1, "memory").map((hit) => hit.obsId)).toEqual(["mem_decision"]);
+ expect(f.vector.search(new Float32Array([1, 0]), 1, "memory").map((hit) => hit.obsId)).toEqual(["mem_decision"]);
+ expect(SearchIndex.deserialize(f.index.serialize()).search("quasar", 1, "memory")[0].obsId).toBe("mem_decision");
+ expect(VectorIndex.deserialize(f.vector.serialize()).search(new Float32Array([1, 0]), 1, "memory")[0].obsId).toBe("mem_decision");
+
+ setVectorIndex(f.vector);
+ setEmbeddingProvider(f.embedding);
+ expect(await rankMemoryIds("quasar policy", 1)).toEqual({ ids: ["mem_decision"], mode: "hybrid" });
+ setHybridRanker(f.search);
+ const recall = await f.call("mem::search", { query: "quasar policy", limit: 1, targetLayer: "memory" });
+ expect(recall.results[0]).toMatchObject({ layer: "memory", observation: { id: "mem_decision" } });
+ expect(f.search).toHaveBeenLastCalledWith("quasar policy", 1, "memory");
+ const smart = await f.call("mem::smart-search", { query: "quasar policy", limit: 1, targetLayer: "memory" });
+ expect(smart.results).toEqual([expect.objectContaining({ obsId: "mem_decision", layer: "memory" })]);
+ expect(smart).not.toHaveProperty("lessons");
+ });
+
+ it("keeps keyword-only saved-memory recall independent of capture volume", async () => {
+ const f = fixture();
+ for (let i = 0; i < 100; i++) await f.addObservation(observation(`obs_${i}`));
+ await f.addMemory(memory());
+ expect(await rankMemoryIds("quasar", 1)).toEqual({ ids: ["mem_decision"], mode: "keyword" });
+ const result = await f.call("mem::search", { query: "quasar", targetLayer: "memory", limit: 1 });
+ expect(result.results[0].observation.id).toBe("mem_decision");
+ expect((await f.call("mem::search", { query: "quasar", limit: 1 })).results[0].observation.id).toMatch(/^obs_/);
+ });
+
+ it("excludes saved memories and synthetic higher layers from observation-only recall", async () => {
+ const f = fixture();
+ await f.addMemory(memory());
+ await f.addObservation(observation("obs_1"));
+ for (const [id, sessionId] of [["lsn_1", "lesson"], ["ins_1", "insight"]]) {
+ f.index.add({ ...observation(id), sessionId }, sessionId as "lesson" | "insight");
+ f.vector.add(id, sessionId, new Float32Array([1, 0]));
+ }
+ expect(f.index.search("quasar", 10, "observation").map((hit) => hit.obsId)).toEqual(["obs_1"]);
+ expect(f.vector.search(new Float32Array([1, 0]), 10, "observation").map((hit) => hit.obsId)).toEqual(["obs_1"]);
+ const result = await f.call("mem::smart-search", { query: "quasar", targetLayer: "observation", includeLessons: true });
+ expect(result.results.map((hit: any) => hit.obsId)).toEqual(["obs_1"]);
+ expect(result).not.toHaveProperty("lessons");
+ expect(f.sdk.trigger.mock.calls.some(([call]) => call.function_id === "mem::lesson-recall")).toBe(false);
+ });
+
+ it("retains the default mixed search and lesson behavior", async () => {
+ const f = fixture();
+ await f.addMemory(memory());
+ await f.addObservation(observation("obs_1"));
+ const result = await f.call("mem::smart-search", { query: "quasar" });
+ expect(result.results.map((hit: any) => hit.layer).sort()).toEqual(["memory", "observation"]);
+ expect(result.lessons).toEqual([]);
+ });
+
+ it("filters graph evidence before its result cap and expansion cap", async () => {
+ const f = fixture();
+ await f.kv.set(KV.graphNodes, "node", {
+ id: "node", name: "Quasar", type: "service", properties: {},
+ sourceObservationIds: ["obs_1", "obs_2", "mem_decision", "mem_other"],
+ });
+ await f.kv.set(KV.graphNodes, "neighbor", {
+ id: "neighbor", name: "Rollout", type: "service", properties: {},
+ sourceObservationIds: ["obs_3", "mem_other"],
+ });
+ await f.kv.set(KV.graphEdges, "edge", { id: "edge", sourceNodeId: "node", targetNodeId: "neighbor", type: "uses", weight: 1 });
+ const graph = new GraphRetrieval(f.kv as never);
+ expect((await graph.searchByEntities(["Quasar"], 2, 1, "memory")).map((hit) => hit.obsId)).toEqual(["mem_decision"]);
+ expect((await graph.expandFromChunks(["mem_decision"], 1, 1, "memory")).map((hit) => hit.obsId)).toEqual(["mem_other"]);
+ });
+
+ it.each(["mem::search", "mem::smart-search"])("preserves project and agent scope in %s memory-only queries", async (handler) => {
+ const f = fixture();
+ await f.kv.set(KV.sessions, "linked-session", { id: "linked-session", project: "wrong-project", cwd: "/wrong" });
+ await f.addMemory(memory({ id: "mem_owned", project: "project-a", sessionIds: ["linked-session"], agentId: "agent-a" }));
+ await f.addMemory(memory({ id: "mem_other_project", project: "project-b", agentId: "agent-a" }));
+ await f.addMemory(memory({ id: "mem_other_agent", project: "project-a", agentId: "agent-b" }));
+ const result = await f.call(handler, { query: "quasar", targetLayer: "memory", project: "project-a", agentId: "agent-a" });
+ const ids = result.results.map((hit: any) => hit.obsId ?? hit.observation.id);
+ expect(ids).toEqual(["mem_owned"]);
+ });
+
+ it("filters expanded IDs before the expansion cap and respects scope", async () => {
+ const f = fixture();
+ await f.addMemory(memory({ agentId: "agent-a", project: "project-a" }));
+ await f.addObservation(observation("obs_1"));
+ const expandIds = [...Array.from({ length: 21 }, (_, i) => `obs_${i}`), "mem_decision"];
+ const result = await f.call("mem::smart-search", { expandIds, targetLayer: "memory", project: "project-a", agentId: "agent-a" });
+ expect(result.results).toEqual([expect.objectContaining({ obsId: "mem_decision", layer: "memory" })]);
+ expect(result.truncated).toBe(false);
+ expect((await f.call("mem::smart-search", { expandIds, targetLayer: "memory", agentId: "agent-b" })).results).toEqual([]);
+ const observations = await f.call("mem::smart-search", { expandIds: ["mem_decision", { obsId: "obs_1", sessionId: "capture-session" }], targetLayer: "observation" });
+ expect(observations.results.map((hit: any) => hit.obsId)).toEqual(["obs_1"]);
+ });
+
+ it.each(["mem::search", "mem::smart-search"])("rejects invalid layers in %s without retrieval", async (handler) => {
+ const f = fixture();
+ await expect(f.call(handler, { query: "quasar", targetLayer: "L2" })).rejects.toThrow("targetLayer must be one of");
+ expect(f.search).not.toHaveBeenCalled();
+ });
+
+ it("returns no matches when the requested layer has no matching records", async () => {
+ const f = fixture();
+ await f.addObservation(observation("obs_1"));
+ expect((await f.call("mem::search", { query: "quasar", targetLayer: "memory" })).results).toEqual([]);
+ expect((await f.call("mem::smart-search", { query: "quasar", targetLayer: "memory" })).results).toEqual([]);
+ });
+
+ it("preserves storage provenance for imported IDs through retrieval, expansion, and persisted indexes", async () => {
+ const f = fixture();
+ const imported = memory({ id: "external-decision", sessionIds: ["real-session"], project: "project-a" });
+ await f.addMemory(imported);
+ await f.kv.set(KV.sessions, "real-session", { id: "real-session", project: "project-a" });
+ const captures = [
+ { ...observation("mem_capture"), sessionId: "memory" },
+ { ...observation("lsn_capture"), sessionId: "lesson" },
+ { ...observation("ins_capture"), sessionId: "insight" },
+ ];
+ for (const capture of captures) {
+ await f.addObservation(capture);
+ await f.kv.set(KV.sessions, capture.sessionId, { id: capture.sessionId, project: "project-a" });
+ }
+
+ const restored = SearchIndex.deserialize(f.index.serialize());
+ expect(restored.layerOf(imported.id)).toBe("memory");
+ expect(restored.search("quasar", 10, "memory").map((hit) => hit.obsId)).toEqual([imported.id]);
+ expect(restored.search("quasar", 10, "observation").map((hit) => hit.obsId).sort()).toEqual(captures.map((capture) => capture.id).sort());
+ const restoredVectors = VectorIndex.deserialize(f.vector.serialize());
+ expect(restoredVectors.search(new Float32Array([1, 0]), 10, "memory", (id) => restored.layerOf(id)).map((hit) => hit.obsId)).toEqual([imported.id]);
+ const hybrid = new HybridSearch(restored, restoredVectors, f.embedding, f.kv as never, 0.4, 0.6, 0);
+ expect((await hybrid.search("quasar", 10, "memory")).map((hit) => [hit.observation.id, hit.layer])).toEqual([[imported.id, "memory"]]);
+ setVectorIndex(restoredVectors);
+ setEmbeddingProvider(f.embedding);
+ expect((await rankMemoryIds("quasar", 10)).ids).toEqual([imported.id]);
+
+ for (const handler of ["mem::search", "mem::smart-search"]) {
+ const result = await f.call(handler, { query: "quasar", targetLayer: "memory" });
+ expect(result.results.map((hit: any) => hit.obsId ?? hit.observation.id)).toEqual([imported.id]);
+ const observations = await f.call(handler, { query: "quasar", targetLayer: "observation" });
+ expect(observations.results.map((hit: any) => hit.obsId ?? hit.observation.id).sort()).toEqual(captures.map((capture) => capture.id).sort());
+ }
+
+ const expanded = await f.call("mem::smart-search", { expandIds: ["mem_capture", imported.id], targetLayer: "memory" });
+ expect(expanded.results.map((hit: any) => [hit.obsId, hit.layer])).toEqual([[imported.id, "memory"]]);
+ const expandedObservation = await f.call("mem::smart-search", {
+ expandIds: [{ obsId: "lsn_capture", sessionId: "lesson" }], targetLayer: "observation",
+ });
+ expect(expandedObservation.results[0]).toMatchObject({ obsId: "lsn_capture", layer: "observation" });
+
+ const oldSnapshot = JSON.parse(f.index.serialize());
+ oldSnapshot.v = 2;
+ for (const [, entry] of oldSnapshot.entries) delete entry.layer;
+ f.index.restoreFrom(SearchIndex.deserialize(JSON.stringify(oldSnapshot)));
+ expect(f.index.size).toBe(4);
+ await rebuildKeywordIndex(f.kv as never);
+ expect(f.index.layerOf(imported.id)).toBe("memory");
+ expect(f.index.search("quasar", 10, "memory").map((hit) => hit.obsId)).toEqual([imported.id]);
+ expect(f.index.observationCountsBySession()).toEqual(new Map(captures.map((capture) => [capture.sessionId, 1])));
+ });
+
+ it("uses indexed provenance for graph candidates with arbitrary imported IDs", async () => {
+ const f = fixture();
+ await f.addMemory(memory({ id: "imported-decision" }));
+ await f.addObservation(observation("mem_capture"));
+ await f.kv.set(KV.graphNodes, "node", {
+ id: "node", name: "Quasar", type: "service", properties: {},
+ sourceObservationIds: ["mem_capture", "imported-decision"],
+ });
+ const graph = new GraphRetrieval(f.kv as never, (id) => f.index.layerOf(id));
+ expect((await graph.searchByEntities(["Quasar"], 2, 1, "memory")).map((hit) => hit.obsId)).toEqual(["imported-decision"]);
+ expect((await graph.searchByEntities(["Quasar"], 2, 1, "observation")).map((hit) => hit.obsId)).toEqual(["mem_capture"]);
+ });
+
+ it("bounds expansion work and reports unprocessed IDs", async () => {
+ const f = fixture();
+ await f.addMemory(memory({ id: "imported-decision" }));
+ const get = vi.spyOn(f.kv, "get");
+ const result = await f.call("mem::smart-search", {
+ expandIds: [...Array.from({ length: 100 }, (_, index) => `absent-${index}`), "imported-decision"],
+ targetLayer: "memory",
+ });
+ expect(result.results).toEqual([]);
+ expect(result.truncated).toBe(true);
+ expect(get.mock.calls.filter(([scope]) => scope === KV.memories)).toHaveLength(100);
+ });
+
+ it("fails closed when a saved memory's owning project cannot be loaded", async () => {
+ const f = fixture();
+ const saved = memory({ project: "private", sessionIds: ["public-session"] });
+ await f.addMemory(saved);
+ await f.kv.set(KV.sessions, "public-session", { id: "public-session", project: "public" });
+ setVectorIndex(f.vector);
+ setHybridRanker(async () => [{ observation: memoryToObservation(saved), layer: "memory", sessionId: "public-session", combinedScore: 1 }]);
+ const originalGet = f.kv.get;
+ vi.spyOn(f.kv, "get").mockImplementation(async (scope, id) => {
+ if (scope === KV.memories) throw new Error("project lookup failed");
+ return originalGet(scope, id);
+ });
+ await expect(f.call("mem::search", { query: "quasar", targetLayer: "memory", project: "public" })).rejects.toThrow("project lookup failed");
+ });
+});
diff --git a/test/recall-response.test.ts b/test/recall-response.test.ts
new file mode 100644
index 00000000..4bada945
--- /dev/null
+++ b/test/recall-response.test.ts
@@ -0,0 +1,278 @@
+import { describe, expect, it } from "vitest";
+import { buildRecallResponse, type RecallFormat } from "../src/functions/recall-response.js";
+import type { SearchResult } from "../src/types.js";
+
+function savedMemory(id = "mem_decision", title = "Database migration decision"): SearchResult {
+ const narrative = "Use the existing migration runner and retain the rollback plan. ".repeat(100);
+ return {
+ observation: {
+ id,
+ sessionId: "memory",
+ timestamp: "2026-10-10T00:00:00.000Z",
+ type: "decision",
+ title,
+ facts: [narrative],
+ narrative,
+ concepts: ["database", "migration"],
+ files: ["src/database.ts"],
+ importance: 8,
+ },
+ score: 25.3,
+ sessionId: "memory",
+ layer: "memory",
+ };
+}
+
+function smallMemory(id = "mem_small"): SearchResult {
+ const result = savedMemory(id, "Small decision");
+ result.observation.narrative = "Use migrations.";
+ result.observation.facts = ["Use migrations."];
+ return result;
+}
+
+function estimatedResults(results: unknown[]): number {
+ return results.reduce<number>((sum, result) => sum + Math.max(1, Math.ceil(JSON.stringify(result).length / 3)), 0);
+}
+
+function firstId(response: ReturnType<typeof buildRecallResponse>): string | undefined {
+ const result = response.results[0];
+ if (!result) return undefined;
+ return "observation" in result ? result.observation.id : result.obsId;
+}
+
+const formats: RecallFormat[] = ["full", "compact", "narrative"];
+
+describe.each(formats)("recall response in %s format", (format) => {
+ it("keeps all results without a budget and reports the candidate page size", () => {
+ const response = buildRecallResponse([savedMemory(), smallMemory()], format);
+
+ expect(response.format).toBe(format);
+ expect(response.results).toHaveLength(2);
+ expect(response.tokens_used).toBe(estimatedResults(response.results));
+ expect(response.tokens_budget).toBeUndefined();
+ expect(response.matched_count).toBe(2);
+ expect(response.excluded_by_budget).toBe(0);
+ expect(response.excluded_results).toEqual([]);
+ expect(response.excluded_results_truncated).toBe(false);
+ expect(response.truncated).toBe(false);
+ expect(response.results[0].layer).toBe("memory");
+ });
+
+ it("preserves the unchanged result at an exact budget fit", () => {
+ const result = smallMemory();
+ const complete = buildRecallResponse([result], format);
+ const response = buildRecallResponse([result], format, complete.tokens_used);
+
+ expect(response.results).toEqual(complete.results);
+ expect(response.results[0]).not.toHaveProperty("content_truncated");
+ expect(response.tokens_used).toBe(complete.tokens_used);
+ expect(response.truncated).toBe(false);
+ });
+
+ it("clips the first ranked match instead of returning a lower ranked small result", () => {
+ const first = savedMemory("mem_first", "Database migration decision ".repeat(200));
+ const response = buildRecallResponse([first, smallMemory()], format, 250);
+
+ expect(response.results).toHaveLength(1);
+ expect(firstId(response)).toBe("mem_first");
+ expect(response.results[0].content_truncated).toBe(true);
+ expect(response.results[0].layer).toBe("memory");
+ expect(response.results[0].score).toBe(first.score);
+ expect(response.results[0].sessionId).toBe(first.sessionId);
+ expect(response.tokens_used).toBe(estimatedResults(response.results));
+ expect(response.tokens_used).toBeLessThanOrEqual(250);
+ expect(response.matched_count).toBe(2);
+ expect(response.excluded_by_budget).toBe(1);
+ expect(response.excluded_results).toEqual([
+ { obsId: "mem_small", sessionId: "memory", title: "Small decision" },
+ ]);
+ expect(response.truncated).toBe(true);
+ });
+
+ it("keeps a ranked prefix when a later result exceeds the remaining budget", () => {
+ const first = smallMemory("mem_first");
+ const budget = buildRecallResponse([first], format).tokens_used;
+ const response = buildRecallResponse([first, savedMemory(), smallMemory("mem_last")], format, budget);
+
+ expect(response.results).toHaveLength(1);
+ expect(firstId(response)).toBe("mem_first");
+ expect(response.results[0]).not.toHaveProperty("content_truncated");
+ expect(response.excluded_by_budget).toBe(2);
+ expect(response.excluded_results.map((result) => result.obsId)).toEqual(["mem_decision", "mem_last"]);
+ expect(response.tokens_used).toBe(budget);
+ expect(response.minimum_budget).toBeUndefined();
+ });
+
+ it("distinguishes a tiny budget from no matches and reports the recoverable minimum", () => {
+ const result = savedMemory();
+ const response = buildRecallResponse([result], format, 1);
+ const empty = buildRecallResponse([], format, 1);
+
+ expect(response.results).toEqual([]);
+ expect(response.tokens_used).toBe(0);
+ expect(response.matched_count).toBe(1);
+ expect(response.excluded_by_budget).toBe(1);
+ expect(response.excluded_results[0].obsId).toBe(result.observation.id);
+ expect(response.minimum_budget).toBeGreaterThan(1);
+ expect(response.truncated).toBe(true);
+ expect(empty.matched_count).toBe(0);
+ expect(empty.excluded_by_budget).toBe(0);
+ expect(empty.minimum_budget).toBeUndefined();
+ expect(empty.truncated).toBe(false);
+
+ const atMinimum = buildRecallResponse([result], format, response.minimum_budget);
+ expect(firstId(atMinimum)).toBe(result.observation.id);
+ expect(atMinimum.tokens_used).toBeLessThanOrEqual(response.minimum_budget!);
+ expect(atMinimum.minimum_budget).toBeUndefined();
+ const belowMinimum = buildRecallResponse([result], format, response.minimum_budget! - 1);
+ expect(belowMinimum.results).toEqual([]);
+ });
+
+ it("preserves valid Unicode and accounts for JSON escaping when clipping", () => {
+ const first = savedMemory("mem_unicode", '漢字😀"\\\n'.repeat(400));
+ first.observation.narrative = '決定😀"\\\n'.repeat(400);
+ for (const budget of [200, 201, 202, 203, 250]) {
+ const response = buildRecallResponse([first], format, budget);
+ expect(response.results).toHaveLength(1);
+ expect(response.tokens_used).toBe(estimatedResults(response.results));
+ expect(response.tokens_used).toBeLessThanOrEqual(budget);
+ const result = response.results[0];
+ const content = "observation" in result ? result.observation : result;
+ expect(Buffer.from(content.title, "utf8").toString("utf8")).toBe(content.title);
+ if ("narrative" in content) {
+ expect(Buffer.from(content.narrative, "utf8").toString("utf8")).toBe(content.narrative);
+ }
+ }
+ });
+
+ it("bounds excluded references without losing the excluded count", () => {
+ const results = Array.from({ length: 15 }, (_, index) => savedMemory(`mem_${index}`, "😀".repeat(100)));
+ const response = buildRecallResponse(results, format, 1);
+
+ expect(response.matched_count).toBe(15);
+ expect(response.excluded_by_budget).toBe(15);
+ expect(response.excluded_results).toHaveLength(10);
+ expect(response.excluded_results_truncated).toBe(true);
+ expect(response.excluded_results.every((result) => result.title.length <= 120)).toBe(true);
+ expect(response.excluded_results.every((result) => Buffer.from(result.title).toString() === result.title)).toBe(true);
+ });
+
+ it("reports a truthful minimum when the original is cheaper than a marked preview", () => {
+ const result = smallMemory();
+ result.observation.title = "";
+ result.observation.narrative = "";
+ result.observation.facts = [];
+ result.observation.files = [];
+ result.observation.concepts = [];
+ const complete = buildRecallResponse([result], format);
+ const response = buildRecallResponse([result], format, 1);
+
+ expect(response.minimum_budget).toBe(complete.tokens_used);
+ const atMinimum = buildRecallResponse([result], format, response.minimum_budget);
+ expect(atMinimum.results).toEqual(complete.results);
+ expect(atMinimum.truncated).toBe(false);
+ });
+});
+
+describe("full recall previews", () => {
+ it("retains ownership and trust metadata while omitting oversized origin detail", () => {
+ const result = savedMemory();
+ result.observation.agentId = "agent-a";
+ result.observation.confidence = 0.3;
+ result.observation.origin = {
+ channel: "import", capturedAt: "2026-10-09T12:00:00.000Z", detail: "x".repeat(10_000),
+ };
+ const original = structuredClone(result);
+ const response = buildRecallResponse([result], "full", 250);
+
+ if (response.format !== "full") throw new Error("Expected full response");
+ expect(response.results[0].observation).toMatchObject({
+ agentId: "agent-a", confidence: 0.3,
+ origin: { channel: "import", capturedAt: "2026-10-09T12:00:00.000Z" },
+ });
+ expect(response.results[0].observation.origin).not.toHaveProperty("detail");
+ expect(response.results[0].content_truncated).toBe(true);
+ expect(response.tokens_used).toBeLessThanOrEqual(250);
+ expect(response.tokens_used).toBe(estimatedResults(response.results));
+ expect(result).toEqual(original);
+
+ const tiny = buildRecallResponse([result], "full", 1);
+ const atMinimum = buildRecallResponse([result], "full", tiny.minimum_budget);
+ if (atMinimum.format !== "full") throw new Error("Expected full response");
+ expect(atMinimum.results[0].observation.agentId).toBe("agent-a");
+ expect(atMinimum.results[0].observation.origin?.channel).toBe("import");
+ expect(atMinimum.tokens_used).toBeLessThanOrEqual(tiny.minimum_budget!);
+ });
+
+ it("uses remaining budget for the next ranked result after dropping oversized optional fields", () => {
+ const first = smallMemory("mem_first");
+ first.observation.imageData = "x".repeat(3_000);
+ const second = smallMemory("mem_second");
+ const response = buildRecallResponse([first, second], "full", 300);
+
+ if (response.format !== "full") throw new Error("Expected full response");
+ expect(response.results.map((result) => result.observation.id)).toEqual(["mem_first", "mem_second"]);
+ expect(response.results[0].content_truncated).toBe(true);
+ expect(response.results[1]).toEqual(second);
+ expect(response.tokens_used).toBe(estimatedResults(response.results));
+ expect(response.tokens_used).toBeLessThanOrEqual(300);
+ expect(response.excluded_by_budget).toBe(0);
+ expect(response.excluded_results).toEqual([]);
+ expect(response.truncated).toBe(true);
+
+ const blocked = buildRecallResponse([first, savedMemory("mem_middle"), second], "full", 300);
+ if (blocked.format !== "full") throw new Error("Expected full response");
+ expect(blocked.results.map((result) => result.observation.id)).toEqual(["mem_first"]);
+ expect(blocked.excluded_results.map((result) => result.obsId)).toEqual(["mem_middle", "mem_second"]);
+ });
+
+ it("omits duplicate and oversized fields while retaining an actual content prefix", () => {
+ const result = savedMemory();
+ result.observation.subtitle = "x".repeat(10_000);
+ result.observation.imageData = "x".repeat(10_000);
+ result.observation.imageDescription = "x".repeat(10_000);
+ result.observation.files = ["x".repeat(10_000)];
+ result.observation.concepts = ["x".repeat(10_000)];
+ const original = structuredClone(result);
+ Object.freeze(result.observation);
+ Object.freeze(result);
+ const response = buildRecallResponse([result], "full", 250);
+
+ expect(response.format).toBe("full");
+ if (response.format !== "full") throw new Error("Expected full response");
+ const preview = response.results[0];
+ expect(preview.content_truncated).toBe(true);
+ expect(preview.observation.facts).toEqual([]);
+ expect(preview.observation.files).toEqual([]);
+ expect(preview.observation.concepts).toEqual([]);
+ expect(preview.observation).not.toHaveProperty("subtitle");
+ expect(preview.observation).not.toHaveProperty("imageData");
+ expect(preview.observation).not.toHaveProperty("imageDescription");
+ expect(preview.observation.narrative.length).toBeGreaterThan(0);
+ expect(result.observation.narrative.startsWith(preview.observation.narrative)).toBe(true);
+ expect(preview.observation.title).toBe(original.observation.title);
+ expect(preview.observation.timestamp).toBe(original.observation.timestamp);
+ expect(preview.observation.type).toBe(original.observation.type);
+ expect(result).toEqual(original);
+ });
+
+ it("uses facts for a preview when the observation has no narrative", () => {
+ const result = savedMemory();
+ result.observation.narrative = "";
+ const response = buildRecallResponse([result], "full", 250);
+
+ if (response.format !== "full") throw new Error("Expected full response");
+ expect(response.results[0].observation.narrative).not.toBe("");
+ expect(result.observation.facts[0].startsWith(response.results[0].observation.narrative)).toBe(true);
+ });
+});
+
+it("renders narrative text from the packed rows only", () => {
+ const response = buildRecallResponse([savedMemory(), smallMemory("mem_omitted")], "narrative", 250);
+
+ if (response.format !== "narrative") throw new Error("Expected narrative response");
+ expect(response.results).toHaveLength(1);
+ expect(response.text).toBe(`1. ${response.results[0].title}\n${response.results[0].narrative}`);
+ expect(response.text).not.toContain("Small decision");
+ expect(response.excluded_by_budget).toBe(1);
+});
diff --git a/test/search-index.test.ts b/test/search-index.test.ts
index ea1d8054..b17fe652 100644
--- a/test/search-index.test.ts
+++ b/test/search-index.test.ts
@@ -31,9 +31,9 @@ describe("SearchIndex", () => {
it("counts memory and lesson documents apart from observations", () => {
index.add(makeObs({ id: "obs_1" }));
- index.add(makeObs({ id: "mem_1", sessionId: "memory" }));
- index.add(makeObs({ id: "mem_2", sessionId: "ses_1" }));
- index.add(makeObs({ id: "lsn_1", sessionId: "lesson" }));
+ index.add(makeObs({ id: "mem_1", sessionId: "memory" }), "memory");
+ index.add(makeObs({ id: "mem_2", sessionId: "ses_1" }), "memory");
+ index.add(makeObs({ id: "lsn_1", sessionId: "lesson" }), "lesson");
expect(index.documentKindCounts()).toEqual({ memories: 2, lessons: 1 });
});