diff --git a/AGENTS.md b/AGENTS.md index 626ff4de24..d2ed292f93 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` (4,500+ 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` (4,600+ 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 - 322+ iii functions -- 4,500+ tests +- 4,600+ tests diff --git a/README.md b/README.md index 227c54e556..31ad6a5546 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1311,7 +1311,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 43d2c4d432..13a79a42b6 100644 --- a/READMEs/README.ar-SA.md +++ b/READMEs/README.ar-SA.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 8310128629..98bcbaa9ce 100644 --- a/READMEs/README.bn-BD.md +++ b/READMEs/README.bn-BD.md @@ -69,7 +69,7 @@ 54 MCP টুল 12 অটো হুক 0 এক্সটার্নাল ডিবি - 4,500+ টেস্ট পাস + 4,600+ টেস্ট পাস

@@ -1255,7 +1255,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 5a6c82efe5..5a64f8b08a 100644 --- a/READMEs/README.cs-CZ.md +++ b/READMEs/README.cs-CZ.md @@ -69,7 +69,7 @@ 54 MCP nástrojů 12 automatických hooks 0 externích databází - 4,500+ testů úspěšně proběhlo + 4,600+ testů úspěšně proběhlo

@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 4a2d0e1000..2b4f540c29 100644 --- a/READMEs/README.da-DK.md +++ b/READMEs/README.da-DK.md @@ -69,7 +69,7 @@ 54 MCP-værktøjer 12 automatiske hooks 0 eksterne databaser - 4,500+ beståede tests + 4,600+ beståede tests

@@ -1249,7 +1249,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 40064c7371..f4053424a3 100644 --- a/READMEs/README.de-DE.md +++ b/READMEs/README.de-DE.md @@ -69,7 +69,7 @@ 54 MCP-Tools 12 Auto-Hooks 0 externe DBs - 4,500+ bestandene Tests + 4,600+ bestandene Tests

@@ -1247,7 +1247,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 63d3a6fe5d..87964c0e5c 100644 --- a/READMEs/README.el-GR.md +++ b/READMEs/README.el-GR.md @@ -69,7 +69,7 @@ 54 εργαλεία MCP 12 αυτόματα hooks 0 εξωτερικές βάσεις δεδομένων - 4,500+ επιτυχημένες δοκιμές + 4,600+ επιτυχημένες δοκιμές

@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 798c26c413..ec06c15d98 100644 --- a/READMEs/README.es-ES.md +++ b/READMEs/README.es-ES.md @@ -69,7 +69,7 @@ 54 tools MCP 12 hooks automáticos 0 bases de datos externas - 4,500+ tests superados + 4,600+ tests superados

@@ -1243,7 +1243,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 1a7520e672..e31f85b642 100644 --- a/READMEs/README.fi-FI.md +++ b/READMEs/README.fi-FI.md @@ -69,7 +69,7 @@ 54 MCP-työkalua 12 automaattista hookia 0 ulkoista tietokantaa - 4,500+ testiä läpäisty + 4,600+ testiä läpäisty

@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 42bba1dc7d..9af69d3629 100644 --- a/READMEs/README.fr-FR.md +++ b/READMEs/README.fr-FR.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1250,7 +1250,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 0b116fa100..034ed34170 100644 --- a/READMEs/README.he-IL.md +++ b/READMEs/README.he-IL.md @@ -71,7 +71,7 @@ 54 כלי MCP 12 hooks אוטומטיים 0 מסדי נתונים חיצוניים - 4,500+ בדיקות עוברות + 4,600+ בדיקות עוברות

@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 c628d732be..117ad51d40 100644 --- a/READMEs/README.hi-IN.md +++ b/READMEs/README.hi-IN.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1256,7 +1256,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 6afe735b63..d3cdef2c89 100644 --- a/READMEs/README.hu-HU.md +++ b/READMEs/README.hu-HU.md @@ -69,7 +69,7 @@ 54 MCP eszköz 12 automatikus hook 0 külső adatbázis - 4,500+ sikeres teszt + 4,600+ sikeres teszt

@@ -1239,7 +1239,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 85d729f1ec..c4e5f5a9ef 100644 --- a/READMEs/README.id-ID.md +++ b/READMEs/README.id-ID.md @@ -69,7 +69,7 @@ 54 tool MCP 12 hook otomatis 0 DB eksternal - 4,500+ pengujian lolos + 4,600+ pengujian lolos

@@ -1256,7 +1256,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 d473421353..1db24899f8 100644 --- a/READMEs/README.it-IT.md +++ b/READMEs/README.it-IT.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1249,7 +1249,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 253ea84286..679309b6b8 100644 --- a/READMEs/README.ja-JP.md +++ b/READMEs/README.ja-JP.md @@ -69,7 +69,7 @@ 54 MCP ツール 12 自動 hooks 外部 DB 0 個 - 4,500+ 件のテストが成功 + 4,600+ 件のテストが成功

@@ -1255,7 +1255,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 25091180c3..68a70a99f8 100644 --- a/READMEs/README.ko-KR.md +++ b/READMEs/README.ko-KR.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1254,7 +1254,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 fe6b9e189f..906c9afed5 100644 --- a/READMEs/README.nb-NO.md +++ b/READMEs/README.nb-NO.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1247,7 +1247,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 d83f316edf..82f7752da7 100644 --- a/READMEs/README.nl-NL.md +++ b/READMEs/README.nl-NL.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1243,7 +1243,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 6c5a94a121..bc03deaebe 100644 --- a/READMEs/README.pl-PL.md +++ b/READMEs/README.pl-PL.md @@ -69,7 +69,7 @@ 54 narzędzia MCP 12 automatycznych hooków 0 zewnętrznych baz danych - 4,500+ zaliczonych testów + 4,600+ zaliczonych testów

@@ -1239,7 +1239,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 785e39df45..c057540f82 100644 --- a/READMEs/README.pt-BR.md +++ b/READMEs/README.pt-BR.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1247,7 +1247,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 c13dd11522..4df36d9384 100644 --- a/READMEs/README.pt-PT.md +++ b/READMEs/README.pt-PT.md @@ -69,7 +69,7 @@ 54 ferramentas MCP 12 hooks automáticos 0 bases de dados externas - 4,500+ testes aprovados + 4,600+ testes aprovados

@@ -1243,7 +1243,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 2333786508..04daaa1692 100644 --- a/READMEs/README.ro-RO.md +++ b/READMEs/README.ro-RO.md @@ -69,7 +69,7 @@ 54 de instrumente MCP 12 hook-uri automate 0 baze de date externe - 4,500+ teste trecute + 4,600+ teste trecute

@@ -1235,7 +1235,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 2155e0c98a..3dc2bd036b 100644 --- a/READMEs/README.ru-RU.md +++ b/READMEs/README.ru-RU.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 4381b16ac6..a3cc9e47c3 100644 --- a/READMEs/README.sv-SE.md +++ b/READMEs/README.sv-SE.md @@ -69,7 +69,7 @@ 54 MCP-verktyg 12 automatiska hooks 0 externa databaser - 4,500+ godkända tester + 4,600+ godkända tester

@@ -1249,7 +1249,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 47fe863712..2c33f0df62 100644 --- a/READMEs/README.th-TH.md +++ b/READMEs/README.th-TH.md @@ -69,7 +69,7 @@ 54 เครื่องมือ MCP 12 hook อัตโนมัติ ไม่ต้องพึ่ง external DB เลย - ผ่านการทดสอบ 4,500+ รายการ + ผ่านการทดสอบ 4,600+ รายการ

@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 4c3c0788be..60847a4785 100644 --- a/READMEs/README.tl-PH.md +++ b/READMEs/README.tl-PH.md @@ -69,7 +69,7 @@ 54 MCP tool 12 awtomatikong hook 0 panlabas na DB - 4,500+ pumapasang test + 4,600+ pumapasang test

@@ -1251,7 +1251,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 74a7497fe1..c414df3087 100644 --- a/READMEs/README.tr-TR.md +++ b/READMEs/README.tr-TR.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 a7dcc8236a..f6c7cbeffe 100644 --- a/READMEs/README.uk-UA.md +++ b/READMEs/README.uk-UA.md @@ -69,7 +69,7 @@ 54 інструменти MCP 12 автоматичних хуків 0 зовнішніх БД - 4,500+ тестів пройдено + 4,600+ тестів пройдено

@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 8527ed85cf..5f04968cc3 100644 --- a/READMEs/README.ur-PK.md +++ b/READMEs/README.ur-PK.md @@ -71,7 +71,7 @@ 54 MCP ٹولز 12 خودکار ہکس 0 خارجی ڈیٹابیسز - 4,500+ ٹیسٹس پاس ہو رہے ہیں + 4,600+ ٹیسٹس پاس ہو رہے ہیں

@@ -1246,7 +1246,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 f00703fa98..a58f67266f 100644 --- a/READMEs/README.vi-VN.md +++ b/READMEs/README.vi-VN.md @@ -69,7 +69,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,500+ tests passing + 4,600+ tests passing

@@ -1251,7 +1251,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 13233660b0..d065aa3500 100644 --- a/READMEs/README.zh-CN.md +++ b/READMEs/README.zh-CN.md @@ -69,7 +69,7 @@ 54 个 MCP 工具 12 个自动 hooks 0 个外部数据库 - 4,500+ 项测试通过 + 4,600+ 项测试通过

@@ -1252,7 +1252,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 0041886d6c..1c5117fbb5 100644 --- a/READMEs/README.zh-TW.md +++ b/READMEs/README.zh-TW.md @@ -69,7 +69,7 @@ 54 個 MCP 工具 12 個自動 hooks 0 個外部資料庫 - 4,500+ 測試通過 + 4,600+ 測試通過

@@ -1244,7 +1244,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: ```bash npm run dev # Hot reload npm run build # Production build -npm test # 4,500+ tests +npm test # 4,600+ 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 3439518513..bf36e50014 100644 --- a/assets/tags/light/stat-tests.svg +++ b/assets/tags/light/stat-tests.svg @@ -1,5 +1,5 @@ - + - 4500+ + 4600+ TESTS PASSING diff --git a/assets/tags/stat-tests.svg b/assets/tags/stat-tests.svg index 9352019436..f10da955ac 100644 --- a/assets/tags/stat-tests.svg +++ b/assets/tags/stat-tests.svg @@ -1,5 +1,5 @@ - + - 4500+ + 4600+ TESTS PASSING diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json index 72cc03775c..2318551be7 100644 --- a/scripts/docs-sync.state.json +++ b/scripts/docs-sync.state.json @@ -20,7 +20,7 @@ "12" ], "tests": [ - "4500+" + "4600+" ], "functions": [ "323" diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.ts index 9a580a2ede..5f778af1dd 100644 --- a/src/functions/consolidate.ts +++ b/src/functions/consolidate.ts @@ -5,10 +5,12 @@ import type { Session, MemoryProvider, } from "../types.js"; -import { KV, generateId } from "../state/schema.js"; +import { KV, fingerprintId, generateId } from "../state/schema.js"; import { StateKV, collectAll } from "../state/kv.js"; +import { safeAudit } from "./audit.js"; +import { withKeyedLocks } from "../state/keyed-mutex.js"; +import { stableStringify } from "../capture/event-id.js"; import { supersededAt } from "../state/memory-utils.js"; -import { recordAudit } from "./audit.js"; const CONSOLIDATION_SYSTEM = `You are a memory consolidation engine. Given a set of related observations from coding sessions, synthesize them into a single long-term memory. @@ -63,6 +65,22 @@ function parseMemoryXml( }; } +function evidence(o: CompressedObservation) { + return { id: o.id, type: o.type, title: o.title, narrative: o.narrative, files: o.files, importance: o.importance, concepts: o.concepts }; +} + +function consolidationKey(sources: Array): string { + const rows = sources + .map((o) => ({ sid: o.sid, ...evidence(o) })) + .sort((a, b) => (a.sid === b.sid ? (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) : a.sid < b.sid ? -1 : 1)); + return fingerprintId("cons", stableStringify(rows)); +} + +function sameIds(left: string[] | undefined, right: string[]): boolean { + const ids = new Set(left); + return ids.size === right.length && right.every((id) => ids.has(id)); +} + export function registerConsolidateFunction( sdk: IIIClient, kv: StateKV, @@ -112,10 +130,6 @@ export function registerConsolidateFunction( } let consolidated = 0; - const existingMemories = await collectAll(kv, KV.memories); - const existingTitles = new Set( - existingMemories.map((m) => m.title.toLowerCase()), - ); const MAX_LLM_CALLS = 10; let llmCallCount = 0; @@ -139,99 +153,138 @@ export function registerConsolidateFunction( ) .join("\n\n"); + let timer: ReturnType | undefined; try { + llmCallCount++; const response = await Promise.race([ provider.compress( CONSOLIDATION_SYSTEM, `Concept: "${concept}"\n\nObservations:\n${prompt}`, ), - new Promise((_, reject) => - setTimeout(() => reject(new Error("compress timeout")), 30_000), - ), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("compress timeout")), 30_000); + }), ]); - llmCallCount++; + clearTimeout(timer); const parsed = parseMemoryXml(response, sessionIds); if (!parsed) continue; const now = new Date().toISOString(); const obsIds = [...new Set(top.map((o) => o.id))]; + const sourceKey = consolidationKey(top); const scopedProject = typeof data.project === "string" && data.project.trim().length > 0 ? data.project.trim() : undefined; - // A scoped consolidation run must only evolve memories that belong - // to the same project. Without this guard, two projects that happen - // to consolidate observations into an identically-titled memory would - // cause one project's memory to silently evolve the other's — the - // exact class of cross-project corruption this fix is designed to - // prevent. An unscoped run (no data.project, background cron path) - // preserves the pre-existing behavior and may evolve any memory. - const existingMatch = existingMemories.find( - (m) => - m.title.toLowerCase() === parsed.title.toLowerCase() && - (!scopedProject || !m.project || m.project === scopedProject), - ); - - if (existingMatch) { - existingMatch.isLatest = false; - existingMatch.updatedAt = supersededAt(existingMatch.updatedAt, now); - await kv.set(KV.memories, existingMatch.id, existingMatch); - await recordAudit(kv, "evolve", "mem::consolidate", [existingMatch.id], { - action: "mark_non_latest", - concept, - }); + const publicationLocks = ["mem:remember", ...sessionIds.map((sid) => `obs:${sid}`)]; + let adoptedId: string | undefined; + const published = await withKeyedLocks(publicationLocks, async () => { + for (const sid of sessionIds) { + const current = await kv.get(KV.sessions, sid); + const original = filtered.find((session) => session.id === sid)!; + if (!current || current.project !== original.project || current.agentId !== original.agentId) return false; + } + for (const { sid, ...original } of top) { + const current = await kv.get(KV.observations(sid), original.id); + if (!current || stableStringify(evidence(current)) !== stableStringify(evidence(original))) return false; + } + const memories = await collectAll(kv, KV.memories); + const candidates = memories.filter((memory) => + memory.isLatest !== false && + memory.agentId === undefined && + (!scopedProject || memory.project === scopedProject), + ); + const children = new Map(); + for (const memory of candidates) { + if (!memory.parentId) continue; + const siblings = children.get(memory.parentId) ?? []; + siblings.push(memory); + children.set(memory.parentId, siblings); + } + for (const parent of candidates) { + const successors = children.get(parent.id); + if (successors?.length !== 1) continue; + const child = successors[0]; + if (child.title.toLowerCase() !== parent.title.toLowerCase() || + child.version !== (parent.version || 1) + 1 || + !child.supersedes?.includes(parent.id)) continue; + const updatedAt = supersededAt(parent.updatedAt, new Date().toISOString()); + await kv.set(KV.memories, parent.id, { ...parent, isLatest: false, updatedAt }); + parent.isLatest = false; + parent.updatedAt = updatedAt; + await safeAudit(kv, "evolve", "mem::consolidate", [parent.id], { + action: "complete_publication", newId: child.id, + }); + } + const heads = candidates.filter((memory) => memory.isLatest !== false); + if (heads.some((memory) => memory.consolidationKeys?.[concept] === sourceKey)) return false; + const legacy = heads.find((memory) => + !memory.consolidationKeys && + sameIds(memory.sourceObservationIds, obsIds) && + sameIds(memory.sessionIds, sessionIds), + ); + if (legacy) { + await kv.set(KV.memories, legacy.id, { ...legacy, consolidationKeys: { [concept]: sourceKey } }); + adoptedId = legacy.id; + return false; + } - const evolved: Memory = { - id: generateId("mem"), - createdAt: now, - updatedAt: now, - ...parsed, - version: (existingMatch.version || 1) + 1, - recurrence: (existingMatch.recurrence ?? 1) + - (obsIds.some((id) => !(existingMatch.sourceObservationIds ?? []).includes(id)) ? 1 : 0), - parentId: existingMatch.id, - supersedes: [ - existingMatch.id, - ...(existingMatch.supersedes || []), - ], - sourceObservationIds: obsIds, - isLatest: true, - ...(scopedProject !== undefined && { project: scopedProject }), - }; - await kv.set(KV.memories, evolved.id, evolved); - await recordAudit(kv, "evolve", "mem::consolidate", [evolved.id], { - action: "evolve_memory", - oldId: existingMatch.id, - newId: evolved.id, - concept, - }); - existingTitles.add(evolved.title.toLowerCase()); - consolidated++; - } else { + const sameTitle = heads.filter((memory) => + memory.title.toLowerCase() === parsed.title.toLowerCase(), + ); + if (sameTitle.length > 1) return false; + const previous = sameTitle[0]; const memory: Memory = { id: generateId("mem"), createdAt: now, updatedAt: now, ...parsed, sourceObservationIds: obsIds, - version: 1, + consolidationKeys: { ...previous?.consolidationKeys, [concept]: sourceKey }, + version: previous ? (previous.version || 1) + 1 : 1, isLatest: true, + ...(previous && { + recurrence: (previous.recurrence ?? 1) + + (obsIds.some((id) => !(previous.sourceObservationIds ?? []).includes(id)) ? 1 : 0), + parentId: previous.id, + supersedes: [previous.id, ...(previous.supersedes || [])], + }), ...(scopedProject !== undefined && { project: scopedProject }), }; - await kv.set(KV.memories, memory.id, memory); - await recordAudit(kv, "remember", "mem::consolidate", [memory.id], { - action: "create_memory", + + try { + await kv.set(KV.memories, memory.id, memory); + } catch (error) { + if (!(await kv.get(KV.memories, memory.id))) throw error; + } + if (previous) { + try { + await kv.set(KV.memories, previous.id, { ...previous, isLatest: false, updatedAt: supersededAt(previous.updatedAt, now) }); + } catch (error) { + await kv.set(KV.memories, previous.id, previous); + await kv.delete(KV.memories, memory.id); + throw error; + } + } + await safeAudit(kv, previous ? "evolve" : "remember", "mem::consolidate", [memory.id], { + action: previous ? "evolve_memory" : "create_memory", + ...(previous && { oldId: previous.id, newId: memory.id }), concept, }); - existingTitles.add(memory.title.toLowerCase()); - consolidated++; + return true; + }); + if (adoptedId) { + await safeAudit(kv, "evolve", "mem::consolidate", [adoptedId], { action: "adopt_legacy", concept }); } + if (published) consolidated++; } catch (err) { logger.warn("Consolidation failed for concept", { concept, error: err instanceof Error ? err.message : String(err), }); + } finally { + clearTimeout(timer); } } diff --git a/src/functions/remember.ts b/src/functions/remember.ts index 1498bafc6c..587c931d8e 100644 --- a/src/functions/remember.ts +++ b/src/functions/remember.ts @@ -339,12 +339,15 @@ export function registerRememberFunction(sdk: IIIClient, kv: StateKV): void { if (data.memoryId) { const memoryId = data.memoryId; await attempt(memoryId, async () => { - const mem = await kv.get(KV.memories, memoryId); + const mem = await withKeyedLock("mem:remember", async () => { + const current = await kv.get(KV.memories, memoryId); + if (current) await kv.delete(KV.memories, memoryId); + return current; + }); if (!mem) { await deleteFacetsForTargets(kv, [memoryId]); return false; } - await kv.delete(KV.memories, memoryId); deletedMemoryIds.push(memoryId); getSearchIndex().remove(memoryId); vectorIndexRemove(memoryId); diff --git a/src/types.ts b/src/types.ts index 29c134010f..269da0c576 100644 --- a/src/types.ts +++ b/src/types.ts @@ -151,6 +151,7 @@ export interface Memory { supersedes?: string[]; relatedIds?: string[]; sourceObservationIds?: string[]; + consolidationKeys?: Record; isLatest: boolean; forgetAfter?: string; imageRef?: string; diff --git a/test/consolidate-project-scope.test.ts b/test/consolidate-project-scope.test.ts index c3d338a2e2..c4f8e08c76 100644 --- a/test/consolidate-project-scope.test.ts +++ b/test/consolidate-project-scope.test.ts @@ -5,7 +5,7 @@ vi.mock("../src/logger.js", () => ({ })); vi.mock("../src/functions/audit.js", () => ({ - recordAudit: vi.fn(), + safeAudit: vi.fn(), })); import { registerConsolidateFunction } from "../src/functions/consolidate.js"; diff --git a/test/consolidate-publication.test.ts b/test/consolidate-publication.test.ts new file mode 100644 index 0000000000..c31edae4cc --- /dev/null +++ b/test/consolidate-publication.test.ts @@ -0,0 +1,433 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { registerConsolidateFunction } from "../src/functions/consolidate.js"; +import { KV } from "../src/state/schema.js"; +import { withKeyedLock } from "../src/state/keyed-mutex.js"; +import { safeAudit } from "../src/functions/audit.js"; +import type { CompressedObservation, Memory, MemoryProvider, Session } from "../src/types.js"; + +vi.mock("../src/logger.js", () => ({ logger: { info: vi.fn(), warn: vi.fn() } })); +vi.mock("../src/functions/audit.js", () => ({ safeAudit: vi.fn() })); + +function fixture() { + const rows = new Map>(); + const kv = { + get: async (scope: string, id: string): Promise => + structuredClone(rows.get(scope)?.get(id) as T ?? null), + list: async (scope: string): Promise => + structuredClone([...rows.get(scope)?.values() ?? []] as T[]), + set: vi.fn(async (scope: string, id: string, value: T): Promise => { + if (!rows.has(scope)) rows.set(scope, new Map()); + rows.get(scope)!.set(id, structuredClone(value)); + return value; + }), + delete: vi.fn(async (scope: string, id: string) => { rows.get(scope)?.delete(id); }), + }; + const functions = new Map Promise>(); + const sdk = { registerFunction: (id: string, handler: (data: unknown) => Promise) => functions.set(id, handler) }; + const compress = vi.fn(async (_system: string, _prompt: string) => xml("Shared title")); + registerConsolidateFunction(sdk as never, kv as never, { compress } as unknown as MemoryProvider); + const run = (project = "app") => functions.get("mem::consolidate")!({ project, minObservations: 1 }); + const memories = () => kv.list(KV.memories); + return { kv, compress, run, memories }; +} + +function xml(title: string) { + return `fact${title}Independent contentauth8`; +} + +async function seed(f: ReturnType, sessionId = "session-a", concept = "auth", project = "app") { + const session: Session = { id: sessionId, project, cwd: "/synthetic", startedAt: "2026-01-01T00:00:00Z", status: "completed", observationCount: 3 }; + await f.kv.set(KV.sessions, sessionId, session); + for (let i = 0; i < 3; i++) { + const id = `${sessionId}-${concept}-${i}`; + const observation: CompressedObservation = { + id, sessionId, timestamp: session.startedAt, type: "decision", title: `${concept} ${i}`, + narrative: `Evidence ${i}`, facts: [], concepts: [concept], files: [], importance: 8, + }; + await f.kv.set(KV.observations(sessionId), id, observation); + } +} + +function memory(id: string, extra: Partial = {}): Memory { + return { + id, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", type: "fact", + title: "Shared title", content: "Previous content", concepts: [], files: [], sessionIds: [], + strength: 7, version: 1, isLatest: true, project: "app", ...extra, + }; +} + +afterEach(() => vi.useRealTimers()); + +describe("consolidation publication", () => { + it("publishes overlapping concurrent runs once even when model titles differ", async () => { + const f = fixture(); + await seed(f); + let release!: () => void; + const barrier = new Promise((resolve) => { release = resolve; }); + let started = 0; + f.compress.mockImplementation(async () => { + const title = `Title ${++started}`; + if (started === 2) release(); + await barrier; + return xml(title); + }); + const results = await Promise.all([f.run(), f.run()]); + expect(results.map((r) => (r as { consolidated: number }).consolidated).sort()).toEqual([0, 1]); + expect(await f.memories()).toHaveLength(1); + expect(f.compress).toHaveBeenCalledTimes(2); + }); + + it("uses the current latest version for multiple groups within one run", async () => { + const f = fixture(); + await seed(f, "session-a", "auth"); + await seed(f, "session-a", "tokens"); + await f.kv.set(KV.memories, "old", memory("old", { isLatest: false })); + await f.kv.set(KV.memories, "current", memory("current", { version: 2, parentId: "old", supersedes: ["old"] })); + expect(await f.run()).toMatchObject({ consolidated: 2 }); + const rows = await f.memories(); + const latest = rows.filter((m) => m.isLatest !== false); + expect(latest).toHaveLength(1); + expect(latest[0].version).toBe(4); + expect(latest[0].supersedes).toHaveLength(3); + expect(latest[0].supersedes).toContain("current"); + }); + + it.each(["delete", "edit", "move-project", "move-agent"])("discards model output after source changes: %s", async (change) => { + const f = fixture(); + await seed(f); + f.compress.mockImplementation(async () => { + if (change === "delete") { + await f.kv.delete(KV.observations("session-a"), "session-a-auth-0"); + } else if (change === "edit") { + const row = await f.kv.get(KV.observations("session-a"), "session-a-auth-0"); + await f.kv.set(KV.observations("session-a"), row!.id, { ...row, narrative: "Changed evidence" }); + } else { + const session = await f.kv.get(KV.sessions, "session-a"); + await f.kv.set(KV.sessions, "session-a", { ...session, + ...(change === "move-project" ? { project: "other" } : { agentId: "other-agent" }), + }); + } + return xml("Stale model result"); + }); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect(await f.memories()).toHaveLength(0); + }); + + it.each(["session-a", "session-b"])("holds source locks through publication before a writer changes %s", async (sessionId) => { + const f = fixture(); + await seed(f, "session-b"); + await seed(f, "session-a"); + let entered!: () => void; + let release!: () => void; + const publicationEntered = new Promise((resolve) => { entered = resolve; }); + const publicationBarrier = new Promise((resolve) => { release = resolve; }); + const list = f.kv.list; + f.kv.list = async (scope: string): Promise => { + if (scope === KV.memories) { + entered(); + await publicationBarrier; + } + return list(scope); + }; + const publication = f.run(); + await publicationEntered; + let writerStarted = false; + const writer = withKeyedLock(`obs:${sessionId}`, async () => { + writerStarted = true; + await f.kv.delete(KV.observations(sessionId), `${sessionId}-auth-0`); + }); + try { + await Promise.resolve(); + expect(writerStarted).toBe(false); + } finally { + release(); + await Promise.all([publication, writer]); + } + expect(await publication).toMatchObject({ consolidated: 1 }); + expect(writerStarted).toBe(true); + expect(await f.memories()).toHaveLength(1); + expect(await f.kv.get(KV.observations(sessionId), `${sessionId}-auth-0`)).toBeNull(); + }); + + it("does not deduplicate equal observation IDs from different sessions", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "elsewhere", memory("elsewhere", { + sessionIds: ["another-session"], sourceObservationIds: ["session-a-auth-0", "session-a-auth-1", "session-a-auth-2"], + })); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + expect((await f.memories()).filter((m) => m.isLatest !== false)).toHaveLength(1); + }); + + it("does not deduplicate another project's matching provenance", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "elsewhere", memory("elsewhere", { + project: "other", sessionIds: ["session-a"], sourceObservationIds: ["session-a-auth-0", "session-a-auth-1", "session-a-auth-2"], + })); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + expect((await f.memories()).filter((m) => m.isLatest !== false)).toHaveLength(2); + }); + + it("preserves the previous latest memory when successor creation fails", async () => { + const f = fixture(); + await seed(f); + const previous = memory("previous"); + await f.kv.set(KV.memories, previous.id, previous); + const write = f.kv.set.getMockImplementation()!; + f.kv.set.mockImplementation(async (scope, id, value) => { + if (scope === KV.memories && id !== previous.id) throw new Error("storage unavailable"); + return write(scope, id, value); + }); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect(await f.memories()).toEqual([previous]); + }); + + it("confirms a committed successor after its write acknowledgement fails", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "previous", memory("previous")); + const write = f.kv.set.getMockImplementation()!; + f.kv.set.mockImplementation(async (scope, id, value) => { + await write(scope, id, value); + if (scope === KV.memories && id !== "previous") throw new Error("lost acknowledgement"); + return value; + }); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + const rows = await f.memories(); + expect(rows.filter((m) => m.isLatest !== false)).toHaveLength(1); + expect(rows.find((m) => m.id === "previous")?.isLatest).toBe(false); + }); + + it("repairs an interrupted publication before evolving changed evidence", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "previous", memory("previous")); + await f.kv.set(KV.memories, "committed", memory("committed", { + version: 2, parentId: "previous", supersedes: ["previous"], + sourceObservationIds: ["older-source"], sessionIds: ["session-a"], + })); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + const rows = await f.memories(); + const latest = rows.filter((m) => m.isLatest !== false); + expect(latest).toHaveLength(1); + expect(latest[0]).toMatchObject({ version: 3, parentId: "committed" }); + }); + + it("does not repair ambiguous siblings or unrelated parent references", async () => { + const f = fixture(); + await seed(f); + for (const row of [memory("parent"), + memory("child-one", { version: 2, parentId: "parent", supersedes: ["parent"] }), + memory("child-two", { version: 2, parentId: "parent", supersedes: ["parent"] }), + memory("other", { title: "Other title" }), + memory("unrelated", { title: "Another title", version: 2, parentId: "other", supersedes: ["other"] }), + ]) await f.kv.set(KV.memories, row.id, row); + f.compress.mockResolvedValue(xml("New independent title")); + await f.run(); + expect((await f.memories()).filter((m) => m.isLatest !== false)).toHaveLength(6); + }); + + it.each([false, true])("rolls back a failed predecessor demotion (write committed: %s)", async (committed) => { + const f = fixture(); + await seed(f); + const previous = memory("previous"); + await f.kv.set(KV.memories, previous.id, previous); + const write = f.kv.set.getMockImplementation()!; + f.kv.set.mockImplementation(async (scope, id, value) => { + if (scope === KV.memories && id === previous.id && (value as Memory).isLatest === false) { + if (committed) await write(scope, id, value); + throw new Error("acknowledgement failed"); + } + return write(scope, id, value); + }); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect(await f.memories()).toEqual([previous]); + }); + + it("keeps the successor if restoring the predecessor also fails", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "previous", memory("previous")); + const write = f.kv.set.getMockImplementation()!; + f.kv.set.mockImplementation(async (scope, id, value) => { + if (scope === KV.memories && id === "previous") { + if ((value as Memory).isLatest === false) await write(scope, id, value); + throw new Error("storage unavailable"); + } + return write(scope, id, value); + }); + await f.run(); + const latest = (await f.memories()).filter((m) => m.isLatest !== false); + expect(latest).toHaveLength(1); + expect(latest[0].parentId).toBe("previous"); + expect(f.kv.delete).not.toHaveBeenCalled(); + }); + + it("limits failed provider attempts and clears every timeout", async () => { + vi.useFakeTimers(); + const f = fixture(); + for (let i = 0; i < 15; i++) await seed(f, "session-a", `concept-${i}`); + f.compress.mockRejectedValue(new Error("provider unavailable")); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect(f.compress).toHaveBeenCalledTimes(10); + expect(vi.getTimerCount()).toBe(0); + }); + + it("clears the timeout after a valid or malformed response", async () => { + vi.useFakeTimers(); + const f = fixture(); + await seed(f); + await f.run(); + expect(vi.getTimerCount()).toBe(0); + f.compress.mockResolvedValue("not XML"); + await f.run(); + expect(vi.getTimerCount()).toBe(0); + }); + + it("publishes a distinct insight for each concept that shares the same observations", async () => { + const f = fixture(); + const session: Session = { id: "session-a", project: "app", cwd: "/synthetic", startedAt: "2026-01-01T00:00:00Z", status: "completed", observationCount: 3 }; + await f.kv.set(KV.sessions, session.id, session); + for (let i = 0; i < 3; i++) { + const id = `shared-${i}`; + await f.kv.set(KV.observations(session.id), id, { + id, sessionId: session.id, timestamp: session.startedAt, type: "decision", title: `shared ${i}`, + narrative: `Evidence ${i}`, facts: [], concepts: ["auth", "tokens"], files: [], importance: 8, + } satisfies CompressedObservation); + } + f.compress.mockImplementation(async (_system: string, prompt: string) => + xml(prompt.startsWith('Concept: "auth"') ? "Auth insight" : "Token insight")); + expect(await f.run()).toMatchObject({ consolidated: 2 }); + const titles = (await f.memories()).filter((m) => m.isLatest !== false).map((m) => m.title).sort(); + expect(titles).toEqual(["Auth insight", "Token insight"]); + }); + + it("publishes a new version when an observation is recompressed in place", async () => { + const f = fixture(); + await seed(f); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + const row = await f.kv.get(KV.observations("session-a"), "session-a-auth-0"); + await f.kv.set(KV.observations("session-a"), row!.id, { ...row!, narrative: "Recompressed evidence" }); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + const latest = (await f.memories()).filter((m) => m.isLatest !== false); + expect(latest).toHaveLength(1); + expect(latest[0].version).toBe(2); + }); + + it("skips a rerun when the concept and its source contents are unchanged", async () => { + const f = fixture(); + await seed(f); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect(await f.memories()).toHaveLength(1); + }); + + it("recognises a memory published before consolidation keys existed", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "legacy", memory("legacy", { + sourceObservationIds: ["session-a-auth-0", "session-a-auth-1", "session-a-auth-2"], + sessionIds: ["session-a"], + })); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect(await f.memories()).toHaveLength(1); + }); + + it("keeps both concepts settled when they produce the same title", async () => { + const f = fixture(); + const session: Session = { id: "session-a", project: "app", cwd: "/synthetic", startedAt: "2026-01-01T00:00:00Z", status: "completed", observationCount: 3 }; + await f.kv.set(KV.sessions, session.id, session); + for (let i = 0; i < 3; i++) { + await f.kv.set(KV.observations(session.id), `shared-${i}`, { + id: `shared-${i}`, sessionId: session.id, timestamp: session.startedAt, type: "decision", title: `shared ${i}`, + narrative: `Evidence ${i}`, facts: [], concepts: ["auth", "tokens"], files: [], importance: 8, + } satisfies CompressedObservation); + } + expect(await f.run()).toMatchObject({ consolidated: 2 }); + const count = (await f.memories()).length; + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect(await f.memories()).toHaveLength(count); + }); + + it("ignores compression bookkeeping when deciding whether evidence changed", async () => { + const f = fixture(); + await seed(f); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + const row = await f.kv.get(KV.observations("session-a"), "session-a-auth-0"); + await f.kv.set(KV.observations("session-a"), row!.id, { ...row!, compressedAt: "2026-02-01T00:00:00Z", compression: { revision: "r2", attempts: 2 } } as CompressedObservation); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + }); + + it("does not extend a lineage that already has two latest heads with the same title", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "a", memory("a")); + await f.kv.set(KV.memories, "b", memory("b")); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect((await f.memories()).filter((m) => m.isLatest !== false).map((m) => m.id).sort()).toEqual(["a", "b"]); + }); + + it("leaves an agent-owned memory with the same title as the latest version", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "owned", memory("owned", { agentId: "agent-1" })); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + const owned = await f.kv.get(KV.memories, "owned"); + expect(owned!.isLatest).toBe(true); + const created = (await f.memories()).find((m) => m.id !== "owned")!; + expect(created.parentId).toBeUndefined(); + }); + + it("does not demote a global memory during a project-scoped run", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "global", memory("global", { project: undefined })); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + expect((await f.kv.get(KV.memories, "global"))!.isLatest).toBe(true); + }); + + it("publishes when only compression bookkeeping changes while the model runs", async () => { + const f = fixture(); + await seed(f); + f.compress.mockImplementation(async () => { + const row = await f.kv.get(KV.observations("session-a"), "session-a-auth-0"); + await f.kv.set(KV.observations("session-a"), row!.id, { ...row!, compression: { revision: "retry", attempts: 2 } } as CompressedObservation); + return xml("Shared title"); + }); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + }); + + it("adopts a legacy memory once and publishes when its evidence later changes", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "legacy", memory("legacy", { + sourceObservationIds: ["session-a-auth-0", "session-a-auth-1", "session-a-auth-2"], + sessionIds: ["session-a"], + })); + expect(await f.run()).toMatchObject({ consolidated: 0 }); + expect((await f.kv.get(KV.memories, "legacy"))!.consolidationKeys?.auth).toBeTruthy(); + expect(safeAudit).toHaveBeenCalledWith(f.kv, "evolve", "mem::consolidate", ["legacy"], { action: "adopt_legacy", concept: "auth" }); + const row = await f.kv.get(KV.observations("session-a"), "session-a-auth-0"); + await f.kv.set(KV.observations("session-a"), row!.id, { ...row!, narrative: "Recompressed evidence" }); + expect(await f.run()).toMatchObject({ consolidated: 1 }); + }); + + it("records the legacy adoption after releasing the publication locks", async () => { + const f = fixture(); + await seed(f); + await f.kv.set(KV.memories, "legacy", memory("legacy", { + sourceObservationIds: ["session-a-auth-0", "session-a-auth-1", "session-a-auth-2"], + sessionIds: ["session-a"], + })); + let lockFree = false; + vi.mocked(safeAudit).mockImplementationOnce(async () => { + lockFree = await Promise.race([ + withKeyedLock("mem:remember", async () => true), + new Promise((resolve) => setTimeout(() => resolve(false), 200)), + ]); + }); + await f.run(); + expect(lockFree).toBe(true); + }); +}); diff --git a/test/remember-lock-scope.test.ts b/test/remember-lock-scope.test.ts index 0d2f5c4926..5ad6b3eaa3 100644 --- a/test/remember-lock-scope.test.ts +++ b/test/remember-lock-scope.test.ts @@ -16,6 +16,7 @@ import { import { logger } from "../src/logger.js"; import { VectorIndex } from "../src/state/vector-index.js"; import { KV } from "../src/state/schema.js"; +import { withKeyedLock } from "../src/state/keyed-mutex.js"; import type { EmbeddingProvider, Memory } from "../src/types.js"; function mockKV() { @@ -256,4 +257,20 @@ describe("mem::remember lock scope", () => { expect.anything(), ); }); + + it("waits for the mem:remember lock before deleting a memory", async () => { + const sdk = mockSdk(); + const kv = mockKV(); + registerRememberFunction(sdk as never, kv as never); + await kv.set(KV.memories, "held", { id: "held", title: "t", content: "c", isLatest: true } as unknown as Memory); + let release!: () => void; + const held = withKeyedLock("mem:remember", () => new Promise((resolve) => { release = resolve; })); + const forget = sdk.trigger({ function_id: "mem::forget", payload: { memoryId: "held" } }); + await delay(20); + expect(await kv.get(KV.memories, "held")).not.toBeNull(); + release(); + await held; + await forget; + expect(await kv.get(KV.memories, "held")).toBeNull(); + }); });