#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix: share and bound graph retrieval per search request (#1541)
Rohit Ghumareaadba01bc49b
diff --git a/README.md b/README.mdindex 748cb5a5..49b285db 100644--- a/README.md+++ b/README.md@@ -1435,7 +1435,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Custom plugin systems | `iii worker add <name>` |-**230 source files · ~54,000 LOC · 3,200+ tests · 312 functions · 62 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself.+**230 source files · ~55,000 LOC · 3,200+ tests · 312 functions · 62 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself.---diff --git a/READMEs/README.ar-SA.md b/READMEs/README.ar-SA.mdindex 4d6ceb35..2e44223c 100644--- a/READMEs/README.ar-SA.md+++ b/READMEs/README.ar-SA.md@@ -1439,7 +1439,7 @@ fi| Prometheus / Grafana | OTEL في iii + مراقب الحالة الصحية || أنظمة إضافات مخصصة | `iii worker add <name>` |-**230 ملف مصدري · ~54,000 سطر برمجي · 3,200+ اختبار · 312 دالة · 62 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه.+**230 ملف مصدري · ~55,000 سطر برمجي · 3,200+ اختبار · 312 دالة · 62 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه.---diff --git a/READMEs/README.bn-BD.md b/READMEs/README.bn-BD.mdindex 6cacd5ef..e7af5228 100644--- a/READMEs/README.bn-BD.md+++ b/READMEs/README.bn-BD.md@@ -1437,7 +1437,7 @@ fi| Prometheus / Grafana | iii OTEL + হেলথ মনিটর || কাস্টম প্লাগইন সিস্টেম | `iii worker add <name>` |-**230 সোর্স ফাইল · ~54,000 LOC · 3,200+ টেস্ট · 312 ফাংশন · 62 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে।+**230 সোর্স ফাইল · ~55,000 LOC · 3,200+ টেস্ট · 312 ফাংশন · 62 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে।---diff --git a/READMEs/README.cs-CZ.md b/READMEs/README.cs-CZ.mdindex 280889fe..7329b489 100644--- a/READMEs/README.cs-CZ.md+++ b/READMEs/README.cs-CZ.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Vlastní systémy pluginů | `iii worker add <name>` |-**230 zdrojových souborů · ~54,000 řádků kódu · 3,200+ testů · 312 funkcí · 62 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii.+**230 zdrojových souborů · ~55,000 řádků kódu · 3,200+ testů · 312 funkcí · 62 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii.---diff --git a/READMEs/README.da-DK.md b/READMEs/README.da-DK.mdindex d3dfdc6f..6c314940 100644--- a/READMEs/README.da-DK.md+++ b/READMEs/README.da-DK.md@@ -1436,7 +1436,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Custom plugin-systemer | `iii worker add <name>` |-**230 kildefiler · ~54,000 LOC · 3,200+ tests · 312 funktioner · 62 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv.+**230 kildefiler · ~55,000 LOC · 3,200+ tests · 312 funktioner · 62 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv.---diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.mdindex d83f5d52..757028ec 100644--- a/READMEs/README.de-DE.md+++ b/READMEs/README.de-DE.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + Health-Monitor || Eigene Plugin-Systeme | `iii worker add <name>` |-**230 Quelldateien · ~54,000 LOC · 3,200+ Tests · 312 Funktionen · 62 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst.+**230 Quelldateien · ~55,000 LOC · 3,200+ Tests · 312 Funktionen · 62 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst.---diff --git a/READMEs/README.el-GR.md b/READMEs/README.el-GR.mdindex 6ab0a055..3d5c9a0e 100644--- a/READMEs/README.el-GR.md+++ b/READMEs/README.el-GR.md@@ -1438,7 +1438,7 @@ fi| Prometheus / Grafana | iii OTEL + monitor υγείας || Προσαρμοσμένα συστήματα plugin | `iii worker add <name>` |-**230 αρχεία πηγαίου κώδικα · ~54,000 LOC · 3,200+ δοκιμές · 312 functions · 62 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii.+**230 αρχεία πηγαίου κώδικα · ~55,000 LOC · 3,200+ δοκιμές · 312 functions · 62 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii.---diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.mdindex cecca56c..c7aaf340 100644--- a/READMEs/README.es-ES.md+++ b/READMEs/README.es-ES.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + monitor de salud || Sistemas de plugins propios | `iii worker add <name>` |-**230 ficheros de código · ~54,000 LOC · 3,200+ tests · 312 funciones · 62 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo.+**230 ficheros de código · ~55,000 LOC · 3,200+ tests · 312 funciones · 62 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo.---diff --git a/READMEs/README.fi-FI.md b/READMEs/README.fi-FI.mdindex 6460dcca..3c79b516 100644--- a/READMEs/README.fi-FI.md+++ b/READMEs/README.fi-FI.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + terveysmonitori || Mukautetut plugin-järjestelmät | `iii worker add <name>` |-**230 lähdetiedostoa · ~54,000 LOC · 3,200+ testiä · 312 funktiota · 62 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse.+**230 lähdetiedostoa · ~55,000 LOC · 3,200+ testiä · 312 funktiota · 62 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse.---diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.mdindex 92f054b6..071f0fd4 100644--- a/READMEs/README.fr-FR.md+++ b/READMEs/README.fr-FR.md@@ -1448,7 +1448,7 @@ fi| Prometheus / Grafana | iii OTEL + moniteur de santé || Systèmes de plugins custom | `iii worker add <name>` |-**230 fichiers sources · ~54,000 LOC · 3,200+ tests · 312 fonctions · 62 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même.+**230 fichiers sources · ~55,000 LOC · 3,200+ tests · 312 fonctions · 62 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même.---diff --git a/READMEs/README.he-IL.md b/READMEs/README.he-IL.mdindex 671067f3..4743e4ff 100644--- a/READMEs/README.he-IL.md+++ b/READMEs/README.he-IL.md@@ -1439,7 +1439,7 @@ fi| Prometheus / Grafana | iii OTEL + מוניטור health || מערכות plugin מותאמות אישית | `iii worker add <name>` |-**230 קבצי מקור · ~54,000 LOC · 3,200+ בדיקות · 312 פונקציות · 62 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו.+**230 קבצי מקור · ~55,000 LOC · 3,200+ בדיקות · 312 פונקציות · 62 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו.---diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.mdindex 6bf67f82..bae20190 100644--- a/READMEs/README.hi-IN.md+++ b/READMEs/README.hi-IN.md@@ -1449,7 +1449,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Custom plugin systems | `iii worker add <name>` |-**230 source files · ~54,000 LOC · 3,200+ tests · 312 functions · 62 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है।+**230 source files · ~55,000 LOC · 3,200+ tests · 312 functions · 62 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है।---diff --git a/READMEs/README.hu-HU.md b/READMEs/README.hu-HU.mdindex 94f8ea90..12496fa7 100644--- a/READMEs/README.hu-HU.md+++ b/READMEs/README.hu-HU.md@@ -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>` |-**230 forrásfájl · ~54,000 LOC · 3,200+ teszt · 312 funkció · 62 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii.+**230 forrásfájl · ~55,000 LOC · 3,200+ teszt · 312 funkció · 62 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii.---diff --git a/READMEs/README.id-ID.md b/READMEs/README.id-ID.mdindex c1c4da3f..f085ede8 100644--- a/READMEs/README.id-ID.md+++ b/READMEs/README.id-ID.md@@ -1447,7 +1447,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Sistem plugin custom | `iii worker add <name>` |-**230 file sumber · ~54,000 LOC · 3,200+ pengujian · 312 fungsi · 62 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri.+**230 file sumber · ~55,000 LOC · 3,200+ pengujian · 312 fungsi · 62 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri.---diff --git a/READMEs/README.it-IT.md b/READMEs/README.it-IT.mdindex c2b55bfb..16848b83 100644--- a/READMEs/README.it-IT.md+++ b/READMEs/README.it-IT.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + monitor di salute || Sistemi di plugin personalizzati | `iii worker add <name>` |-**230 file sorgente · ~54,000 righe di codice · 3,200+ test · 312 funzioni · 62 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso.+**230 file sorgente · ~55,000 righe di codice · 3,200+ test · 312 funzioni · 62 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso.---diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.mdindex ba64a24f..06fbb5c6 100644--- a/READMEs/README.ja-JP.md+++ b/READMEs/README.ja-JP.md@@ -1445,7 +1445,7 @@ fi| Prometheus / Grafana | iii OTEL + ヘルスモニタ || カスタムプラグインシステム | `iii worker add <name>` |-**230 ソースファイル · ~54,000 LOC · 3,200+ テスト · 312 functions · 62 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。+**230 ソースファイル · ~55,000 LOC · 3,200+ テスト · 312 functions · 62 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。---diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.mdindex 53bb568f..001410a8 100644--- a/READMEs/README.ko-KR.md+++ b/READMEs/README.ko-KR.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + health 모니터 || 커스텀 플러그인 시스템 | `iii worker add <name>` |-**소스 파일 230개 · LOC ~54,000줄 · 테스트 3,200+개 · 함수 312개 · KV 스코프 62개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다.+**소스 파일 230개 · LOC ~55,000줄 · 테스트 3,200+개 · 함수 312개 · KV 스코프 62개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다.---diff --git a/READMEs/README.nb-NO.md b/READMEs/README.nb-NO.mdindex c6efd9fc..e27f84ab 100644--- a/READMEs/README.nb-NO.md+++ b/READMEs/README.nb-NO.md@@ -1447,7 +1447,7 @@ fi| Prometheus / Grafana | iii OTEL + helseovervåker || Egendefinerte plugin-systemer | `iii worker add <name>` |-**230 kildefiler · ~54,000 LOC · 3,200+ tester · 312 funksjoner · 62 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv.+**230 kildefiler · ~55,000 LOC · 3,200+ tester · 312 funksjoner · 62 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv.---diff --git a/READMEs/README.nl-NL.md b/READMEs/README.nl-NL.mdindex ac4a93f4..c1076205 100644--- a/READMEs/README.nl-NL.md+++ b/READMEs/README.nl-NL.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Custom plugin-systemen | `iii worker add <name>` |-**230 bronbestanden · ~54,000 LOC · 3,200+ tests · 312 functies · 62 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf.+**230 bronbestanden · ~55,000 LOC · 3,200+ tests · 312 functies · 62 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf.---diff --git a/READMEs/README.pl-PL.md b/READMEs/README.pl-PL.mdindex 48e06115..28ccd098 100644--- a/READMEs/README.pl-PL.md+++ b/READMEs/README.pl-PL.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + monitor stanu || Niestandardowe systemy pluginów | `iii worker add <name>` |-**230 plików źródłowych · ~54,000 LOC · 3,200+ testów · 312 funkcji · 62 zakresy KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii.+**230 plików źródłowych · ~55,000 LOC · 3,200+ testów · 312 funkcji · 62 zakresy KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii.---diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.mdindex 319de1bd..d85a2c1e 100644--- a/READMEs/README.pt-BR.md+++ b/READMEs/README.pt-BR.md@@ -1447,7 +1447,7 @@ fi| Prometheus / Grafana | iii OTEL + monitor de saúde || Sistemas de plugin customizados | `iii worker add <name>` |-**230 arquivos de código · ~54,000 LOC · 3,200+ testes · 312 funções · 62 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.+**230 arquivos de código · ~55,000 LOC · 3,200+ testes · 312 funções · 62 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.---diff --git a/READMEs/README.pt-PT.md b/READMEs/README.pt-PT.mdindex 28f7e0f8..6a607969 100644--- a/READMEs/README.pt-PT.md+++ b/READMEs/README.pt-PT.md@@ -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>` |-**230 ficheiros de código-fonte · ~54,000 LOC · 3,200+ testes · 312 funções · 62 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.+**230 ficheiros de código-fonte · ~55,000 LOC · 3,200+ testes · 312 funções · 62 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.---diff --git a/READMEs/README.ro-RO.md b/READMEs/README.ro-RO.mdindex 721775b8..c2e2f023 100644--- a/READMEs/README.ro-RO.md+++ b/READMEs/README.ro-RO.md@@ -1430,7 +1430,7 @@ fi| Prometheus / Grafana | iii OTEL + monitor de sănătate || Sisteme de plugin-uri personalizate | `iii worker add <name>` |-**230 fișiere sursă · ~54,000 LOC · 3,200+ teste · 312 funcții · 62 de domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii.+**230 fișiere sursă · ~55,000 LOC · 3,200+ teste · 312 funcții · 62 de domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii.---diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.mdindex a6c80e5f..7e0fb08f 100644--- a/READMEs/README.ru-RU.md+++ b/READMEs/README.ru-RU.md@@ -1446,7 +1446,7 @@ fi| Prometheus / Grafana | iii OTEL + монитор состояния || Самописные плагинные системы | `iii worker add <name>` |-**230 исходных файлов · ~54,000 LOC · 3,200+ тестов · 312 функций · 62 KV-scope**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii.+**230 исходных файлов · ~55,000 LOC · 3,200+ тестов · 312 функций · 62 KV-scope**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii.---diff --git a/READMEs/README.sv-SE.md b/READMEs/README.sv-SE.mdindex 14e076fd..82d0923c 100644--- a/READMEs/README.sv-SE.md+++ b/READMEs/README.sv-SE.md@@ -1437,7 +1437,7 @@ fi| Prometheus / Grafana | iii OTEL + hälsoövervakare || Anpassade pluginsystem | `iii worker add <name>` |-**230 källkodsfiler · ~54,000 LOC · 3,200+ tester · 312 funktioner · 62 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt.+**230 källkodsfiler · ~55,000 LOC · 3,200+ tester · 312 funktioner · 62 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt.---diff --git a/READMEs/README.th-TH.md b/READMEs/README.th-TH.mdindex fb90867f..7834e5c7 100644--- a/READMEs/README.th-TH.md+++ b/READMEs/README.th-TH.md@@ -1444,7 +1444,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Custom plugin systems | `iii worker add <name>` |-**230 source file · ~54,000 LOC · 3,200+ การทดสอบ · 312 function · 62 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ+**230 source file · ~55,000 LOC · 3,200+ การทดสอบ · 312 function · 62 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ---diff --git a/READMEs/README.tl-PH.md b/READMEs/README.tl-PH.mdindex fa65be43..e6cce952 100644--- a/READMEs/README.tl-PH.md+++ b/READMEs/README.tl-PH.md@@ -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>` |-**230 na source file · ~54,000 LOC · 3,200+ na test · 312 na function · 62 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii.+**230 na source file · ~55,000 LOC · 3,200+ na test · 312 na function · 62 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii.---diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.mdindex 584c504c..7605adc0 100644--- a/READMEs/README.tr-TR.md+++ b/READMEs/README.tr-TR.md@@ -1437,7 +1437,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Custom eklenti sistemleri | `iii worker add <name>` |-**230 kaynak dosya · ~54,000 LOC · 3,200+ test · 312 fonksiyon · 62 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir.+**230 kaynak dosya · ~55,000 LOC · 3,200+ test · 312 fonksiyon · 62 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir.---diff --git a/READMEs/README.uk-UA.md b/READMEs/README.uk-UA.mdindex efcb570a..848bee13 100644--- a/READMEs/README.uk-UA.md+++ b/READMEs/README.uk-UA.md@@ -1447,7 +1447,7 @@ fi| Prometheus / Grafana | iii OTEL + монітор стану здоров'я || Власні системи плагінів | `iii worker add <name>` |-**230 вихідних файлів · ~54,000 LOC · 3,200+ тестів · 312 функцій · 62 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii.+**230 вихідних файлів · ~55,000 LOC · 3,200+ тестів · 312 функцій · 62 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii.---diff --git a/READMEs/README.ur-PK.md b/READMEs/README.ur-PK.mdindex a8c4cea2..9b9959aa 100644--- a/READMEs/README.ur-PK.md+++ b/READMEs/README.ur-PK.md@@ -1432,7 +1432,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || کسٹم plugin سسٹمز | `iii worker add <name>` |-**230 سورس فائلز · ~54,000 لائنز کوڈ · 3,200+ ٹیسٹس · 312 فنکشنز · 62 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔+**230 سورس فائلز · ~55,000 لائنز کوڈ · 3,200+ ٹیسٹس · 312 فنکشنز · 62 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔---diff --git a/READMEs/README.vi-VN.md b/READMEs/README.vi-VN.mdindex abcb83d8..89609570 100644--- a/READMEs/README.vi-VN.md+++ b/READMEs/README.vi-VN.md@@ -1437,7 +1437,7 @@ fi| Prometheus / Grafana | iii OTEL + health monitor || Hệ thống plugin tùy chỉnh | `iii worker add <name>` |-**230 file source · ~54,000 LOC · 3,200+ test · 312 function · 62 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii.+**230 file source · ~55,000 LOC · 3,200+ test · 312 function · 62 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii.---diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.mdindex 23357d75..4f272fb7 100644--- a/READMEs/README.zh-CN.md+++ b/READMEs/README.zh-CN.md@@ -1444,7 +1444,7 @@ fi| Prometheus / Grafana | iii OTEL + 健康监控 || Custom plugin systems | `iii worker add <name>` |-**230 个源文件 · ~54,000 行代码 · 3,200+ 个测试 · 312 个函数 · 62 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。+**230 个源文件 · ~55,000 行代码 · 3,200+ 个测试 · 312 个函数 · 62 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。---diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.mdindex fc376f1e..8d61a3f5 100644--- a/READMEs/README.zh-TW.md+++ b/READMEs/README.zh-TW.md@@ -1430,7 +1430,7 @@ fi| Prometheus / Grafana | iii OTEL + 健康監控 || 自訂外掛系統 | `iii worker add <name>` |-**230 個原始檔 · ~54,000 行程式碼 · 3,200+ 測試 · 312 個函式 · 62 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。+**230 個原始檔 · ~55,000 行程式碼 · 3,200+ 測試 · 312 個函式 · 62 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。---diff --git a/docs/graph-search.md b/docs/graph-search.mdnew file mode 100644index 00000000..68dee5b9--- /dev/null+++ b/docs/graph-search.md@@ -0,0 +1,13 @@+# Graph search limits and freshness++Hybrid search loads graph nodes and edges once per search request, when a graph stream is needed. Entity search, vector-result expansion and query reformulations share that request's graph view and adjacency index. Setting `AGENTMEMORY_GRAPH_WEIGHT=0` skips graph reads entirely.++Normal recall and smart search can use graph evidence when embeddings are disabled or the vector index is empty. Graph-only observation hits resolve their owning session through the keyword index, preserving record loading and project, agent and layer filters.++A new request reads current state. There is no graph cache with a time-to-live, so completed imports, mesh updates, snapshot restores, deletions and resets are visible to the next search. Both graph lists are pinned to one generation: a reset during loading cannot combine old nodes with new edges. This pin does not provide a transactional snapshot of individual writes within the same generation.++Entity retrieval and chunk expansion each select at most 25 starting nodes. Entity selection prefers exact names, then uses a stable name and ID ordering. Chunk expansion uses stable node ID ordering. Each stream invocation shares a traversal budget across its starting nodes: at most 2,000 node discoveries and 10,000 examined adjacency entries. Stronger edges are examined first. These limits bound traversal work on hubs and dense graphs; broad queries can omit lower-priority paths. Temporal queries retain their existing complete history behavior.++The initial graph read still uses two complete `state::list` calls. Traversal limits do not bound the size of these responses, graph materialization, or the number of independent requests. Large stores can still exceed the engine's transport or memory budget. Bounding those reads requires engine-side pagination or a maintained query index; an in-process cache does not solve that limit.++The scale benchmark uses an in-memory state mock, deterministic embeddings and no graph stream. Its timings measure local retrieval work, not the latency of a REST request with an embedding service and engine transport.diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.jsonindex afd23a80..6985a97a 100644--- a/scripts/docs-sync.state.json+++ b/scripts/docs-sync.state.json@@ -29,7 +29,7 @@"230"],"loc": [- "54000"+ "55000"],"kvScopes": ["62"diff --git a/src/functions/graph-retrieval.ts b/src/functions/graph-retrieval.tsindex 67fbc76e..5f545880 100644--- a/src/functions/graph-retrieval.ts+++ b/src/functions/graph-retrieval.ts@@ -40,40 +40,100 @@ function buildGraphContext(return parts.join(" ");}+const MAX_START_NODES = 25;+const MAX_DISCOVERED_NODES = 2000;+const MAX_EXAMINED_EDGES = 10_000;++type GraphView = {+ nodes: GraphNode[];+ edges: GraphEdge[];+ byId: Map<string, GraphNode>;+ adjacency: Map<string, Array<{ neighborId: string; edge: GraphEdge }>>;+};+type TraversalBudget = { nodes: number; edges: number };++function compareText(a: string, b: string): number {+ if (a === b) return 0;+ return a < b ? -1 : 1;+}++async function readGraph(kv: StateKV): Promise<GraphView> {+ const pinned = await pinGraphState(kv);+ const nodes = (await pinned.list<GraphNode>(KV.graphNodes)).filter((node) => !node.stale);+ const edges = (await pinned.list<GraphEdge>(KV.graphEdges)).filter((edge) => !edge.stale);+ const byId = new Map(nodes.map((node) => [node.id, node]));+ const adjacency: GraphView["adjacency"] = new Map();+ for (const edge of edges) {+ if (!byId.has(edge.sourceNodeId) || !byId.has(edge.targetNodeId)) continue;+ for (const [from, to] of [[edge.sourceNodeId, edge.targetNodeId], [edge.targetNodeId, edge.sourceNodeId]]) {+ let neighbors = adjacency.get(from);+ if (!neighbors) adjacency.set(from, neighbors = []);+ neighbors.push({ neighborId: to, edge });+ }+ }+ for (const neighbors of adjacency.values()) {+ neighbors.sort((a, b) =>+ b.edge.weight - a.edge.weight ||+ compareText(a.neighborId, b.neighborId) ||+ compareText(a.edge.id, b.edge.id),+ );+ }+ return { nodes, edges, byId, adjacency };+}+export class GraphRetrieval {constructor(private kv: StateKV, private resolveLayer?: SearchLayerResolver) {}+ // The caller owns this query's lifetime; never retain its view across searches.+ createQuery(): GraphQuery {+ let view: Promise<GraphView> | undefined;+ return new GraphQuery(() => view ??= readGraph(this.kv), this.resolveLayer);+ }++ searchByEntities(...args: Parameters<GraphQuery["searchByEntities"]>): Promise<GraphRetrievalResult[]> {+ return this.createQuery().searchByEntities(...args);+ }++ expandFromChunks(...args: Parameters<GraphQuery["expandFromChunks"]>): Promise<GraphRetrievalResult[]> {+ return this.createQuery().expandFromChunks(...args);+ }++ temporalQuery(...args: Parameters<GraphQuery["temporalQuery"]>): ReturnType<GraphQuery["temporalQuery"]> {+ return this.createQuery().temporalQuery(...args);+ }+}++export class GraphQuery {+ constructor(private loadGraph: () => Promise<GraphView>, private resolveLayer?: SearchLayerResolver) {}+async searchByEntities(entityNames: string[],maxDepth = 2,maxResults = 20,targetLayer: SearchLayer = "all",): Promise<GraphRetrievalResult[]> {- const kv = await pinGraphState(this.kv);- const allNodes = (await kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);- const allEdges = (await kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);-- const matchingNodes = allNodes.filter((n) => {- const nameLower = n.name.toLowerCase();- return entityNames.some(- (e) =>- nameLower.includes(e.toLowerCase()) ||- e.toLowerCase().includes(nameLower),- );- });+ const exactNames = new Set(entityNames.map((name) => name.trim().toLowerCase()).filter(Boolean));+ const names = [...exactNames];+ if (names.length === 0 || maxResults <= 0) return [];+ const graph = await this.loadGraph();+ const matchingNodes = graph.nodes+ .map((node) => ({ node, name: node.name.toLowerCase() }))+ .filter(({ name }) => name.length > 0 && names.some((entity) => name.includes(entity) || entity.includes(name)))+ .sort((a, b) =>+ Number(exactNames.has(b.name)) - Number(exactNames.has(a.name)) ||+ compareText(a.name, b.name) || compareText(a.node.id, b.node.id),+ )+ .slice(0, MAX_START_NODES)+ .map(({ node }) => node);if (matchingNodes.length === 0) return [];const results: GraphRetrievalResult[] = [];const visitedObs = new Set<string>();+ const budget = { nodes: MAX_DISCOVERED_NODES, edges: MAX_EXAMINED_EDGES };for (const startNode of matchingNodes) {- const paths = this.dijkstraTraversal(- startNode,- allNodes,- allEdges,- maxDepth,- );+ const paths = this.dijkstraTraversal(startNode, graph, maxDepth, budget);for (const path of paths) {const lastNode = path[path.length - 1].node;@@ -124,19 +184,20 @@ export class GraphRetrieval {maxResults = 10,targetLayer: SearchLayer = "all",): Promise<GraphRetrievalResult[]> {- const kv = await pinGraphState(this.kv);- const allNodes = (await kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);- const allEdges = (await kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);-- const linkedNodes = allNodes.filter((n) =>- n.sourceObservationIds.some((id) => obsIds.includes(id)),- );+ if (obsIds.length === 0 || maxResults <= 0) return [];+ const graph = await this.loadGraph();+ const wanted = new Set(obsIds);+ const linkedNodes = graph.nodes+ .filter((node) => node.sourceObservationIds.some((id) => wanted.has(id)))+ .sort((a, b) => compareText(a.id, b.id))+ .slice(0, MAX_START_NODES);const results: GraphRetrievalResult[] = [];const visitedObs = new Set<string>(obsIds);+ const budget = { nodes: MAX_DISCOVERED_NODES, edges: MAX_EXAMINED_EDGES };for (const node of linkedNodes) {- const paths = this.dijkstraTraversal(node, allNodes, allEdges, maxDepth);+ const paths = this.dijkstraTraversal(node, graph, maxDepth, budget);for (const path of paths) {const lastNode = path[path.length - 1].node;for (const obsId of lastNode.sourceObservationIds) {@@ -169,9 +230,7 @@ export class GraphRetrieval {currentState: GraphEdge[];history: GraphEdge[];}> {- const kv = await pinGraphState(this.kv);- const allNodes = (await kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);- const allEdges = (await kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);+ const { nodes: allNodes, edges: allEdges } = await this.loadGraph();const entity = allNodes.find((n) => n.name.toLowerCase() === entityName.toLowerCase(),@@ -236,22 +295,13 @@ export class GraphRetrieval {private dijkstraTraversal(startNode: GraphNode,- allNodes: GraphNode[],- allEdges: GraphEdge[],+ graph: GraphView,maxDepth: number,+ budget: TraversalBudget,): Array<Array<{ node: GraphNode; edge?: GraphEdge }>> {- const nodeIndex = new Map<string, GraphNode>();- for (const n of allNodes) nodeIndex.set(n.id, n);-- const adjacency = new Map<string, Array<{ neighborId: string; edge: GraphEdge }>>();- for (const edge of allEdges) {- const a = edge.sourceNodeId;- const b = edge.targetNodeId;- if (!adjacency.has(a)) adjacency.set(a, []);- if (!adjacency.has(b)) adjacency.set(b, []);- adjacency.get(a)!.push({ neighborId: b, edge });- adjacency.get(b)!.push({ neighborId: a, edge });- }+ if (budget.nodes <= 0 || budget.edges <= 0 || maxDepth <= 0) return [];+ budget.nodes--;+ const { byId: nodeIndex, adjacency } = graph;const dist = new Map<string, number>();const pathTo = new Map<string, Array<{ node: GraphNode; edge?: GraphEdge }>>();@@ -263,7 +313,7 @@ export class GraphRetrieval {);heap.push({ nodeId: startNode.id, depth: 0, cost: 0 });- while (heap.size() > 0) {+ while (heap.size() > 0 && budget.edges > 0) {const { nodeId, depth, cost } = heap.pop()!;// Skip stale heap entries (cost beaten by a later push).if (cost > (dist.get(nodeId) ?? Infinity)) continue;@@ -271,6 +321,8 @@ export class GraphRetrieval {const neighbors = adjacency.get(nodeId) ?? [];for (const { neighborId, edge } of neighbors) {+ if (budget.edges <= 0) break;+ budget.edges--;const nextNode = nodeIndex.get(neighborId);if (!nextNode) continue;// Clamp weight to avoid division-by-zero on malformed edges;@@ -278,6 +330,10 @@ export class GraphRetrieval {const edgeCost = 1 / Math.max(edge.weight, 0.01);const newCost = cost + edgeCost;if (newCost < (dist.get(neighborId) ?? Infinity)) {+ if (!dist.has(neighborId)) {+ if (budget.nodes <= 0) continue;+ budget.nodes--;+ }dist.set(neighborId, newCost);pathTo.set(neighborId, [...pathTo.get(nodeId)!,diff --git a/src/functions/search.ts b/src/functions/search.tsindex bae04b6c..7e1c4885 100644--- a/src/functions/search.ts+++ b/src/functions/search.ts@@ -25,10 +25,8 @@ let currentEmbeddingProvider: EmbeddingProvider | null = null// Hybrid ranking hook for mem::search. Wired by index.ts once the// hybrid searcher exists (it is constructed after this module's-// registration runs). When set and the vector index has entries,-// mem::search ranks candidates through the full BM25+vector+graph-// fusion instead of BM25 alone — previously only mem::smart-search got-// hybrid ranking while the primary recall surface stayed keyword-only.+// registration runs). The graph stream can retrieve evidence even when+// embeddings are disabled or the vector index is still empty.type HybridRanker = (query: string,limit: number,@@ -818,7 +816,7 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {observation?: CompressedObservationlayer?: SearchResultLayer}>- if (hybridRanker && vectorIndex && vectorIndex.size > 0) {+ if (hybridRanker) {try {const hybrid = await hybridRanker(query, fetchLimit, targetLayer)results = hybrid.map((r) => ({diff --git a/src/state/hybrid-search.ts b/src/state/hybrid-search.tsindex 47b11ce2..7df7743d 100644--- a/src/state/hybrid-search.ts+++ b/src/state/hybrid-search.ts@@ -14,6 +14,7 @@ import { KV } from "./schema.js";import {GraphRetrieval,type GraphRetrievalResult,+ type GraphQuery,} from "../functions/graph-retrieval.js";import { extractEntitiesFromQuery } from "../functions/query-expansion.js";import { rerank } from "./reranker.js";@@ -37,7 +38,7 @@ export class HybridSearch {}async search(query: string, limit = 20, targetLayer: SearchLayer = "all"): Promise<HybridSearchResult[]> {- return this.tripleStreamSearch(query, limit, targetLayer);+ return this.tripleStreamSearch(query, limit, targetLayer, this.graphRetrieval.createQuery());}async searchWithExpansion(@@ -57,8 +58,9 @@ export class HybridSearch {...extractEntitiesFromQuery(query),];+ const graphQuery = this.graphRetrieval.createQuery();const resultSets = await Promise.all(- allQueries.map((q) => this.tripleStreamSearch(q, limit, targetLayer, allEntities)),+ allQueries.map((q) => this.tripleStreamSearch(q, limit, targetLayer, graphQuery, allEntities)),);const merged = new Map<string, HybridSearchResult>();@@ -84,6 +86,7 @@ export class HybridSearch {query: string,limit: number,targetLayer: SearchLayer,+ graphQuery: GraphQuery,entityHints?: string[],): Promise<HybridSearchResult[]> {const bm25Results = this.bm25.search(query, limit * 2, targetLayer);@@ -114,7 +117,7 @@ export class HybridSearch {const graphEnabled = this.graphWeight > 0;if (graphEnabled && entities.length > 0) {try {- graphResults = await this.graphRetrieval.searchByEntities(+ graphResults = await graphQuery.searchByEntities(entities,2,limit,@@ -129,7 +132,7 @@ export class HybridSearch {if (graphEnabled && topVectorObs.length > 0) {try {const expansionResults =- await this.graphRetrieval.expandFromChunks(topVectorObs, 1, 5, targetLayer);+ await graphQuery.expandFromChunks(topVectorObs, 1, 5, targetLayer);graphResults = [...graphResults, ...expansionResults];} catch {// expansion is best-effort@@ -193,7 +196,7 @@ export class HybridSearch {bm25Rank: Infinity,vectorRank: Infinity,graphRank: i + 1,- sessionId: r.sessionId,+ sessionId: r.sessionId || this.bm25.sessionOf(r.obsId) || "",bm25Score: 0,vectorScore: 0,graphScore: r.score,diff --git a/test/graph-query.test.ts b/test/graph-query.test.tsnew file mode 100644index 00000000..c47d3532--- /dev/null+++ b/test/graph-query.test.ts@@ -0,0 +1,352 @@+import { mkdtempSync, rmSync } from "node:fs";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { GraphRetrieval } from "../src/functions/graph-retrieval.js";+import { registerExportImportFunction } from "../src/functions/export-import.js";+import { registerMeshFunction } from "../src/functions/mesh.js";+import { registerGraphFunction } from "../src/functions/graph.js";+import { registerSnapshotFunction } from "../src/functions/snapshot.js";+import { getSearchIndex, registerSearchFunction, setHybridRanker, setVectorIndex } from "../src/functions/search.js";+import { registerSmartSearchFunction } from "../src/functions/smart-search.js";+import { StateKV, applyUpdateOps } from "../src/state/kv.js";+import { KV } from "../src/state/schema.js";+import { persistGraphRecords } from "../src/state/graph-ingestion.js";+import { setGraphGenerationListener } from "../src/state/graph-generation.js";+import { HybridSearch } from "../src/state/hybrid-search.js";+import { SearchIndex } from "../src/state/search-index.js";+import { VectorIndex } from "../src/state/vector-index.js";+import type { CompressedObservation, GraphNode, GraphEdge } from "../src/types.js";++vi.mock("../src/logger.js", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const timestamp = "2026-10-13T00:00:00.000Z";+const node = (id: string, name = id, sources = [`obs_${id}`]): GraphNode => ({+ id, name, type: "concept", properties: {}, sourceObservationIds: sources, createdAt: timestamp,+});+const edge = (id: string, from: string, to: string, weight = 0.8): GraphEdge => ({+ id, sourceNodeId: from, targetNodeId: to, type: "related_to", weight,+ sourceObservationIds: [], createdAt: timestamp,+});+const observation = (id: string): CompressedObservation => ({+ id, sessionId: "session", timestamp, type: "discovery", title: "React auth", narrative: "React authentication",+ facts: [], concepts: [], files: [], importance: 5,+});++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => { resolve = done; });+ return { promise, resolve };+}++function rig() {+ const store = new Map<string, Map<string, unknown>>();+ const handlers = new Map<string, (data: any) => Promise<any>>();+ const lists: string[] = [];+ let afterList: ((scope: string) => Promise<void>) | undefined;+ const sdk = {+ registerFunction: (id: string, fn: (data: any) => Promise<any>) => handlers.set(id, fn),+ registerTrigger: vi.fn(),+ trigger: async ({ function_id: id, payload }: { function_id: string; payload: any }): Promise<any> => {+ if (id.startsWith("stream::")) return {};+ if (!id.startsWith("state::")) return handlers.get(id)!(payload);+ const rows = store.get(payload.scope) ?? new Map<string, unknown>();+ if (id === "state::get") return structuredClone(rows.get(payload.key) ?? null);+ if (id === "state::list") {+ lists.push(payload.scope);+ const result = structuredClone([...rows.values()]);+ await afterList?.(payload.scope);+ return result;+ }+ const previous = rows.get(payload.key) ?? null;+ if (id === "state::set") rows.set(payload.key, structuredClone(payload.value));+ else if (id === "state::delete") rows.delete(payload.key);+ else if (id === "state::update") rows.set(payload.key, applyUpdateOps(previous, payload.ops));+ else throw new Error(`unexpected state call ${id}`);+ store.set(payload.scope, rows);+ return structuredClone(rows.get(payload.key) ?? null);+ },+ };+ const kv = new StateKV(sdk as never);+ registerGraphFunction(sdk as never, kv, { name: "noop" } as never);+ registerExportImportFunction(sdk as never, kv);+ registerMeshFunction(sdk as never, kv);+ return {+ kv, sdk, lists,+ call: (id: string, payload: any = {}) => sdk.trigger({ function_id: id, payload }),+ intercept: (fn?: typeof afterList) => { afterList = fn; },+ seed: async (nodes: GraphNode[], edges: GraphEdge[] = []) => {+ for (const row of nodes) await kv.set(KV.graphNodes, row.id, row);+ for (const row of edges) await kv.set(KV.graphEdges, row.id, row);+ },+ };+}++function graphReads(lists: string[]) {+ return lists.filter((scope) => scope.startsWith(KV.graphNodes) || scope.startsWith(KV.graphEdges));+}++const dirs: string[] = [];+afterEach(() => {+ vi.restoreAllMocks();+ setGraphGenerationListener(null);+ setHybridRanker(null);+ setVectorIndex(null);+ getSearchIndex().clear();+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("request graph views", () => {+ it("shares a lazy pinned view across concurrent streams, but never across requests", async () => {+ const r = rig();+ await r.seed([node("a", "React"), node("b", "Hooks")], [edge("ab", "a", "b")]);+ const retrieval = new GraphRetrieval(r.kv);+ const query = retrieval.createQuery();+ expect(graphReads(r.lists)).toEqual([]);+ const [entities, expanded, temporal] = await Promise.all([+ query.searchByEntities(["React"]), query.expandFromChunks(["obs_a"]), query.temporalQuery("React"),+ ]);+ expect(entities.map((hit) => hit.obsId)).toContain("obs_b");+ expect(expanded.map((hit) => hit.obsId)).toEqual(["obs_b"]);+ expect(temporal.entity?.id).toBe("a");+ expect(graphReads(r.lists)).toEqual([KV.graphNodes, KV.graphEdges]);+ await retrieval.searchByEntities(["React"]);+ expect(graphReads(r.lists)).toHaveLength(4);+ });++ it("refreshes after writes, updates, deletion and stale markers without a TTL", async () => {+ const r = rig();+ const retrieval = new GraphRetrieval(r.kv);+ await r.seed([node("a", "React"), node("b", "Hooks")], [edge("ab", "a", "b")]);+ expect(await retrieval.expandFromChunks(["obs_a"])).toHaveLength(1);+ await r.kv.update(KV.graphNodes, "b", [{ type: "set", path: "name", value: "Renamed" }]);+ expect((await retrieval.temporalQuery("Renamed")).entity?.id).toBe("b");+ await r.kv.set(KV.graphEdges, "ab", { ...edge("ab", "a", "b"), stale: true });+ expect(await retrieval.expandFromChunks(["obs_a"])).toEqual([]);+ await r.kv.delete(KV.graphNodes, "a");+ expect(await retrieval.searchByEntities(["React"])).toEqual([]);+ await r.seed([node("fresh", "React")]);+ expect((await retrieval.searchByEntities(["React"])).map((hit) => hit.obsId)).toEqual(["obs_fresh"]);+ });++ it("does not mix generations when reset occurs between node and edge reads", async () => {+ const r = rig();+ await r.seed([node("a", "React"), node("b", "Hooks")], [edge("ab", "a", "b")]);+ const entered = deferred(); const release = deferred();+ r.intercept(async (scope) => {+ if (scope === KV.graphNodes) { r.intercept(); entered.resolve(); await release.promise; }+ });+ const retrieval = new GraphRetrieval(r.kv);+ const pending = retrieval.searchByEntities(["React"]);+ await entered.promise;+ await r.call("mem::graph-reset");+ await r.seed([node("fresh", "React")]);+ release.resolve();+ expect((await pending).map((hit) => hit.obsId).sort()).toEqual(["obs_a", "obs_b"]);+ expect((await retrieval.searchByEntities(["React"])).map((hit) => hit.obsId)).toEqual(["obs_fresh"]);+ });++ it("retries a failed load on the next request while sharing failure within one request", async () => {+ const r = rig();+ await r.seed([node("a", "React")]);+ r.intercept(async () => { throw new Error("unavailable"); });+ const retrieval = new GraphRetrieval(r.kv);+ const query = retrieval.createQuery();+ await expect(query.searchByEntities(["React"])).rejects.toThrow("unavailable");+ await expect(query.expandFromChunks(["obs_a"])).rejects.toThrow("unavailable");+ expect(graphReads(r.lists)).toHaveLength(1);+ r.intercept();+ expect(await retrieval.searchByEntities(["React"])).toHaveLength(1);+ });++ it("keeps stores and layer resolvers separate and skips empty work", async () => {+ const a = rig(); const b = rig();+ await a.seed([node("a", "React", ["custom_memory", "mem_observation"])]);+ await b.seed([node("b", "React")]);+ const retrieval = new GraphRetrieval(a.kv, (id) => id === "custom_memory" ? "memory" : "observation");+ const query = retrieval.createQuery();+ expect((await query.searchByEntities(["React"], 2, 20, "memory")).map((hit) => hit.obsId)).toEqual(["custom_memory"]);+ expect((await query.searchByEntities(["React"], 2, 20, "observation")).map((hit) => hit.obsId)).toEqual(["mem_observation"]);+ expect((await new GraphRetrieval(b.kv).searchByEntities(["React"])).map((hit) => hit.obsId)).toEqual(["obs_b"]);+ a.lists.length = 0;+ expect(await retrieval.searchByEntities(["", " "])).toEqual([]);+ expect(await retrieval.expandFromChunks([])).toEqual([]);+ expect(await retrieval.searchByEntities(["React"], 2, 0)).toEqual([]);+ expect(graphReads(a.lists)).toEqual([]);+ });+});++describe("graph traversal bounds", () => {+ it("caps matching starts and retains an exact match after many partial matches", async () => {+ const r = rig();+ await r.seed([...Array.from({ length: 100 }, (_,i) => node(`partial_${i}`, `auth-${i}`)), node("exact", "auth")]);+ const hits = await new GraphRetrieval(r.kv).searchByEntities(["auth"], 2, 1000);+ expect(hits).toHaveLength(25);+ expect(hits[0].obsId).toBe("obs_exact");+ });++ it("orders exact names, partial names, and duplicate-name IDs by code units before the start cap", async () => {+ const r = rig();+ await r.seed([+ ...["ä", "a", "Z", "😀"].map((id) => node(id, id === "Z" ? "AUTH" : "auth")),+ ...["Ä", "Z", "á", "a", "😀"].map((name) => node(`partial-${name}`, `auth-${name}`)),+ ...Array.from({ length: 30 }, (_, i) => node(`tail-${i}`, `auth-界${String(i).padStart(2, "0")}`)),+ ].reverse());+ const hits = await new GraphRetrieval(r.kv).searchByEntities([" AUTH ", "auth"], 0, 1000);+ expect(hits.map((hit) => hit.obsId)).toEqual([+ "obs_Z", "obs_a", "obs_ä", "obs_😀",+ "obs_partial-a", "obs_partial-Z", "obs_partial-á", "obs_partial-Ä",+ ...Array.from({ length: 17 }, (_, i) => `obs_tail-${i}`),+ ]);+ });++ it("orders chunk-expansion starts by code units rather than host collation", async () => {+ const r = rig();+ const ids = ["ä", "a", "Z", "😀"];+ await r.seed([+ ...ids.map((id) => node(id, id, ["seed"])),+ ...ids.map((id) => node(`end-${id}`)),+ ], ids.map((id) => edge(`edge-${id}`, id, `end-${id}`)));+ const hits = await new GraphRetrieval(r.kv).expandFromChunks(["seed"], 1, 10);+ expect(hits.map((hit) => hit.obsId)).toEqual(["obs_end-Z", "obs_end-a", "obs_end-ä", "obs_end-😀"]);+ });++ it("breaks equal-weight adjacency ties by neighbor and edge IDs using code units", async () => {+ const r = rig();+ const ids = ["ä", "a", "Z", "😀"];+ await r.seed([node("hub", "Anchor", ["seed"]), ...ids.map((id) => node(id))], [+ ...ids.map((id) => edge(`edge-${id}`, "hub", id)),+ { ...edge("A", "hub", "Z"), type: "uses" },+ { ...edge("a", "hub", "Z"), type: "imports" },+ ]);+ const hits = await new GraphRetrieval(r.kv).expandFromChunks(["seed"], 1, 10);+ expect(hits.map((hit) => hit.obsId)).toEqual(["obs_Z", "obs_a", "obs_ä", "obs_😀"]);+ expect(hits[0].graphContext).toContain("--uses-->");+ });++ it("caps chunk expansion starts as well as entity starts", async () => {+ const r = rig();+ const starts = Array.from({ length: 100 }, (_, i) => node(`start_${i}`, `source-${i}`, ["seed"]));+ const ends = starts.map((_, i) => node(`end_${i}`));+ await r.seed([...starts, ...ends], starts.map((start, i) => edge(`edge_${i}`, start.id, ends[i].id)));+ const hits = await new GraphRetrieval(r.kv).expandFromChunks(["seed"], 1, 1000);+ expect(hits).toHaveLength(25);+ expect(hits.some((hit) => hit.obsId === "seed")).toBe(false);+ });++ it.each(["entities", "chunks"])("bounds discovered nodes on a wide hub for %s", async (mode) => {+ const r = rig();+ const spokes = Array.from({ length: 2500 }, (_, i) => node(`spoke_${i}`));+ await r.seed([node("hub", "Anchor"), ...spokes], spokes.map((spoke, i) => edge(`edge_${i}`, "hub", spoke.id)));+ const retrieval = new GraphRetrieval(r.kv);+ const hits = mode === "entities" ? await retrieval.searchByEntities(["Anchor"], 2, 5000) : await retrieval.expandFromChunks(["obs_hub"], 2, 5000);+ expect(hits.length).toBeGreaterThan(0);+ expect(hits.length).toBeLessThanOrEqual(2000);+ });++ it("bounds examined edges even when parallel edges discover very few nodes", async () => {+ const r = rig();+ await r.seed([node("hub", "Anchor"), node("a"), node("tail")], [+ ...Array.from({ length: 10_001 }, (_, i) => edge(`parallel_${i}`, "hub", "a", 1)),+ edge("tail", "hub", "tail", 0.1),+ ]);+ const hits = await new GraphRetrieval(r.kv).searchByEntities(["Anchor"], 2, 100);+ expect(hits.map((hit) => hit.obsId)).toContain("obs_a");+ expect(hits.map((hit) => hit.obsId)).not.toContain("obs_tail");+ });+});++describe("hybrid graph query lifetime", () => {+ it.each(["mem::search", "mem::smart-search"])("retrieves graph-only observations through %s without embeddings and preserves scope", async (handler) => {+ const r = rig();+ const index = getSearchIndex();+ const captures = [+ { ...observation("owned"), sessionId: "owned_session", agentId: "agent-a" },+ { ...observation("other_project"), sessionId: "other_session", agentId: "agent-a" },+ { ...observation("other_agent"), sessionId: "owned_session", agentId: "agent-b" },+ ].map((obs) => ({ ...obs, title: "Opaque evidence", narrative: "Opaque evidence" }));+ for (const obs of captures) {+ index.add(obs);+ await r.kv.set(KV.observations(obs.sessionId), obs.id, obs);+ }+ await r.kv.set(KV.sessions, "owned_session", { id: "owned_session", project: "project-a", cwd: "/owned" });+ await r.kv.set(KV.sessions, "other_session", { id: "other_session", project: "project-b", cwd: "/other" });+ await r.seed([node("anchor", "GraphAnchor", captures.map((obs) => obs.id))]);+ const hybrid = new HybridSearch(index, null, null, r.kv, 0.4, 0.6, 0.3, false);+ const rank = (query: string, limit: number, layer?: "all" | "memory" | "observation") => hybrid.search(query, limit, layer);+ setHybridRanker(rank);+ registerSearchFunction(r.sdk as never, r.kv);+ registerSmartSearchFunction(r.sdk as never, r.kv, rank);+ expect(index.search("GraphAnchor", 20)).toEqual([]);+ for (const vectors of [null, new VectorIndex()]) {+ setVectorIndex(vectors);+ const result = await r.call(handler, { query: "GraphAnchor", project: "project-a", agentId: "agent-a", targetLayer: "observation", includeLessons: false });+ expect(result.results.map((hit: any) => hit.observation?.id ?? hit.obsId)).toEqual(["owned"]);+ expect((await r.call(handler, { query: "GraphAnchor", targetLayer: "memory", includeLessons: false })).results).toEqual([]);+ }+ const expanded = await hybrid.searchWithExpansion("missing", 20, { original: "missing", reformulations: ["GraphAnchor"], temporalConcretizations: [], entityExtractions: ["GraphAnchor"] });+ expect(expanded.map((hit) => hit.observation.id).sort()).toEqual(captures.map((obs) => obs.id).sort());+ expect(expanded.every((hit) => hit.graphScore > 0 && hit.bm25Score === 0)).toBe(true);+ });++ async function hybridRig(weight = 0.3) {+ const r = rig(); const index = new SearchIndex(); const vectors = new VectorIndex();+ const obs = observation("obs_a"); index.add(obs); vectors.add(obs.id, obs.sessionId, new Float32Array([1, 0]));+ await r.kv.set(KV.observations(obs.sessionId), obs.id, obs);+ await r.seed([node("a", "React"), node("b", "Hooks")], [edge("ab", "a", "b")]);+ const embed = vi.fn(async () => new Float32Array([1, 0]));+ const hybrid = new HybridSearch(index, vectors, { name: "fixture", dimensions: 2, embed, embedBatch: async () => [] }, r.kv, 0.4, 0.6, weight, false);+ return { ...r, hybrid };+ }++ it.each([false, true])("loads once for entity, vector and reformulated streams (expanded: %s)", async (expanded) => {+ const r = await hybridRig();+ const run = () => expanded+ ? r.hybrid.searchWithExpansion("React auth", 10, { reformulations: ["React", "authentication"], temporalConcretizations: ["recent React"], entityExtractions: ["React"] })+ : r.hybrid.search("React auth", 10);+ expect(await run()).not.toEqual([]);+ expect(graphReads(r.lists)).toHaveLength(2);+ await run();+ expect(graphReads(r.lists)).toHaveLength(4);+ });++ it("does not read or pin graph state when graph weight is zero, including expansion", async () => {+ const r = await hybridRig(0);+ const get = vi.spyOn(r.kv, "get");+ await r.hybrid.search("React");+ await r.hybrid.searchWithExpansion("React", 10, { reformulations: ["auth"], temporalConcretizations: [], entityExtractions: ["React"] });+ expect(graphReads(r.lists)).toEqual([]);+ expect(get.mock.calls.some(([scope]) => scope === KV.graphControl)).toBe(false);+ });+});++describe("graph mutations between search requests", () => {+ it.each(["import", "mesh"])("sees %s changes without a stale warmed view", async (mode) => {+ const r = rig();+ const retrieval = new GraphRetrieval(r.kv);+ await r.call("mem::graph-reset");+ expect(await retrieval.searchByEntities(["React"])).toEqual([]);+ const graphNodes = [node("a", "React"), node("b", "Hooks")];+ const graphEdges = [edge("ab", "a", "b")];+ const result = mode === "import"+ ? await r.call("mem::import", { exportData: { version: "0.9.30", exportedAt: timestamp, sessions: [], observations: {}, memories: [], summaries: [], graphNodes, graphEdges } })+ : await r.call("mem::mesh-receive", { graphNodes, graphEdges });+ expect(result.success).toBe(true);+ expect((await retrieval.searchByEntities(["React"])).map((hit) => hit.obsId).sort()).toEqual(["obs_a", "obs_b"]);+ expect((await retrieval.expandFromChunks(["obs_a"])).map((hit) => hit.obsId)).toEqual(["obs_b"]);+ expect((await retrieval.temporalQuery("React")).currentState.map((item) => item.id)).toEqual(["ab"]);+ });++ it("refreshes the same retrieval instance after snapshot restoration and reset", async () => {+ const r = rig(); const dir = mkdtempSync(join(process.cwd(), ".graph-query-snapshot-")); dirs.push(dir);+ registerSnapshotFunction(r.sdk as never, r.kv, dir);+ await persistGraphRecords(r.kv, [node("a", "React"), node("b", "Hooks")], [edge("ab", "a", "b")]);+ const saved = await r.call("mem::snapshot-create"); expect(saved.success).toBe(true);+ const retrieval = new GraphRetrieval(r.kv);+ expect(await retrieval.searchByEntities(["React"])).toHaveLength(2);+ await r.call("mem::graph-reset");+ expect(await retrieval.searchByEntities(["React"])).toEqual([]);+ expect((await r.call("mem::snapshot-restore", { commitHash: saved.snapshot.commitHash })).success).toBe(true);+ expect(await retrieval.searchByEntities(["React"])).toHaveLength(2);+ expect((await retrieval.expandFromChunks(["obs_a"])).map((hit) => hit.obsId)).toEqual(["obs_b"]);+ });+});