diff --git a/.env.example b/.env.example
index a9495aee55..d24b3f654d 100644
--- a/.env.example
+++ b/.env.example
@@ -1,7 +1,5 @@
-# =============================================================================
-# agentmemory configuration
-# =============================================================================
-#
+# ======================================================================# agentmemory configuration
+# ======================================================================#
# Copy this file to `~/.agentmemory/.env` (or to your project root if you
# prefer scoped config) and uncomment the lines you want to override.
#
@@ -220,10 +218,17 @@
# 8. iii engine pin
# -----------------------------------------------------------------------------
#
-# agentmemory pins iii-engine and its iii-sdk dependencies to v0.25.1.
+# agentmemory pins iii-engine and its iii-sdk dependencies to v0.26.0.
# The CLI downloads the engine into ~/.agentmemory/bin, including the Windows ZIP.
-# AGENTMEMORY_III_VERSION=0.25.1 # Override only when deliberately matching a different engine
+# AGENTMEMORY_III_VERSION=0.26.0 # Override only when deliberately matching a different engine
# AGENTMEMORY_LOCAL_DISPATCH=true # iii 0.25 runs calls to the worker's own functions in-process; set false for full engine traces
+# AGENTMEMORY_BINDINGS= # set to inline to run the post-capture pipeline inline instead of through observers
+# AGENTMEMORY_STATE_READY_TIMEOUT_MS=60000 # max wait for the state probe reported as runtime.stateWorker in /status (1000-600000)
+# AGENTMEMORY_ROUTE_MAX_IN_FLIGHT=1024 # max concurrent requests per observer-bound route (1-65536)
+# AGENTMEMORY_COMPRESS_MAX_CONCURRENT=2 # max concurrent LLM compressions via the capture observer (1-32)
+# AGENTMEMORY_COMPRESSION_SWEEP_MS=600000 # pending-compression recovery sweep interval; 0 disables (0 or 60000-86400000)
+# AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS=0 # min ms between per-session graph extractions (0-86400000; 0 = no cooldown)
+# AGENTMEMORY_GRAPH_STRUCTURAL=true # heuristic/structural graph pass; false leaves only the LLM pass
# Engine usage telemetry (iii). Off unless you set it; true opts in.
# III_TELEMETRY_ENABLED=false
diff --git a/AGENTS.md b/AGENTS.md
index c2e9d97cc5..ca6f8322f6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -4,7 +4,7 @@
agentmemory is a persistent memory system for AI coding agents, built on iii-engine's three primitives (Worker/Function/Trigger). Everything goes through `registerFunction`/`registerTrigger`/`sdk.trigger()` — never bypass iii-engine with standalone SQLite or in-process alternatives.
-- **Engine**: iii-sdk 0.25.1 with @iii-dev/helpers 0.25.1 (Worker Compose-managed iii-engine 0.25.1 on port 49134; the client type is `IIIClient`, HTTP requests are `HttpRequest` from `@iii-dev/helpers/http`)
+- **Engine**: iii-sdk 0.26.0 with @iii-dev/helpers 0.26.0 (Worker Compose-managed iii-engine 0.26.0 on port 49134; the client type is `IIIClient`, HTTP requests are `HttpRequest` from `@iii-dev/helpers/http`)
- **State**: iii state worker with a file-backed KV store by default (`./data/state_store.db`); Docker pins `save_interval_ms` to 2000 ms
- **Build**: TypeScript → ESM via tsdown, output to `dist/`
- **Test**: vitest (`npm test` excludes integration tests)
@@ -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,900+ 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` (5,000+ 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
@@ -113,5 +113,5 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
- 147 REST endpoints
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 17 skills
-- 322+ iii functions
-- 4,900+ tests
+- 320 iii functions
+- 5,000+ tests
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 4464c49ad3..359c5e9055 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -4,7 +4,7 @@ You are a coding agent. Follow this runbook top to bottom to install agentmemory
## What you are installing
-agentmemory is a local memory server for coding agents. Its CLI starts an iii Worker Compose runtime using the pinned iii 0.25.1 engine and registry workers `state@0.22.22` and `http@0.22.8`. The default listeners are REST/MCP HTTP on port 3111, the viewer on 3113, and the internal engine WebSocket on 49134. The viewer receives live updates as SSE through `GET /agentmemory/viewer/events` on the REST port.
+agentmemory is a local memory server for coding agents. Its CLI starts an iii Worker Compose runtime using the pinned iii 0.26.0 engine and registry workers `state@0.22.22` and `http@0.22.8`. The default listeners are REST/MCP HTTP on port 3111, the viewer on 3113, and the internal engine WebSocket on 49134. The viewer receives live updates as SSE through `GET /agentmemory/viewer/events` on the REST port.
The CLI downloads the pinned engine into `~/.agentmemory/bin`. On native Windows it downloads and extracts the pinned ZIP; WSL2 follows the Linux path. Persistent state defaults to `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. Override the directory with `--data-dir ` or `AGENTMEMORY_DATA_DIR`, and reuse the same override on every restart. `AGENTMEMORY_ENV_FILE` selects a non-default env file. Instance 0 reuses an existing `./data/state_store.db` when present. `--instance N` creates an isolated directory and port set for another runtime.
@@ -14,7 +14,7 @@ Default keyless mode needs no API key or cloud account and disables vector embed
- Node.js >= 20 with npm and npx. Check with `node -v`, `npm -v`, and `npx -v`.
- macOS/Linux automatic iii installation also requires `curl`, a POSIX `sh`, and `tar`. Check with `command -v curl sh tar`. Minimal images such as `node:20-slim` may not include them.
-- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.25.1 ZIP automatically. Native `connect` works for every adapter. WSL `connect` applies only to agents installed in that same WSL environment.
+- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.26.0 ZIP automatically. Native `connect` works for every adapter. WSL `connect` applies only to agents installed in that same WSL environment.
- Default ports 3111 (REST), 3113 (viewer), and 49134 (engine) must be free. Viewer events are carried over REST.
## Running non-interactively
@@ -38,12 +38,12 @@ If the automatic install fails on native Windows, install the engine manually:
```powershell
# Download the matching archive from the pinned release:
-# https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1
+# https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0
# Extract iii.exe to a directory on PATH, such as $HOME\.local\bin, then verify:
iii.exe --version
```
-Expect: exactly `0.25.1`. Verify the archive against its matching SHA-256 asset before extracting it. Do not install an unpinned iii release.
+Expect: exactly `0.26.0`. Verify the archive against its matching SHA-256 asset before extracting it. Do not install an unpinned iii release.
## 2. Start the server
@@ -61,7 +61,7 @@ npx -y @agentmemory/agentmemory@latest --data-dir /absolute/path/to/agentmemory-
For a second isolated runtime, add `--instance 1`; it stores data under `instance-1` and defaults to ports 3211 (REST), 3213 (viewer), and 49234 (engine). `--instance N` supports N from 0 to 50. Do not use `--port` alone for concurrent daemons: it changes ports but preserves instance 0's canonical lifecycle ownership. Use `--instance` for isolation.
-Expect: iii 0.25.1 starts, the agentmemory worker registers with iii, and the ready panel lists REST, viewer, and engine addresses. First boot can take longer while the engine binary and registry workers are installed.
+Expect: iii 0.26.0 starts, the agentmemory worker registers with iii, and the ready panel lists REST, viewer, and engine addresses. First boot can take longer while the engine binary and registry workers are installed.
## 3. Validate the server and runtime ports
@@ -216,7 +216,7 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` (
- `The engine process started but the REST API never responded.`: inspect the REST, viewer, and engine ports, confirm the pinned iii process stayed alive, and use `--verbose` for captured engine stderr.
- Engine version conflict / another iii engine already running: if an unmanaged engine is already listening on the engine port, agentmemory will not adopt it. Stop that engine or choose another `--instance` or `--port`. The CLI keeps its private pinned binary separate from a user-managed `iii` on `PATH`.
- Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx -y @agentmemory/agentmemory@latest`, ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP.
-- Native Windows: if the automatic engine install fails, install the pinned v0.25.1 `iii.exe` manually or use WSL2.
+- Native Windows: if the automatic engine install fails, install the pinned v0.26.0 `iii.exe` manually or use WSL2.
- Semantic demo query returns zero hits: this is expected with vectors disabled in default keyless mode. Set `EMBEDDING_PROVIDER=local`, restart, allow the first model download to complete, and rerun the demo.
## Report success
@@ -224,7 +224,7 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` (
Report back to the user:
- agentmemory installed, version, and the server running on port 3111
-- iii-engine v0.25.1 running, the selected platform data directory, REST/viewer/engine ports, and the status `enginePinnedVersion`
+- iii-engine v0.26.0 running, the selected platform data directory, REST/viewer/engine ports, and the status `enginePinnedVersion`
- which agent was wired via `agentmemory connect`, and the tool count the agent now sees
- the save and recall round-trip returned the probe memory after a full stop/start
- the viewer is available at `http://localhost:3113`
diff --git a/README.md b/README.md
index e12cba755a..d66126b653 100644
--- a/README.md
+++ b/README.md
@@ -69,7 +69,7 @@
-
+
@@ -334,7 +334,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).
### What's new in 0.9.33
-- **Large stores keep working:** state reads page, so scopes above 64 MiB no longer fail, on iii 0.25.1.
+- **Large stores keep working:** state reads page, so scopes above 64 MiB no longer fail, on iii 0.26.0.
- **Better recall:** saved memories are no longer capped at three per search, and evicted memories leave the indexes.
- **Hooks reach the model:** PreToolUse context arrives in the hook envelope, scoped to the current project.
- **Steadier providers:** placeholder keys count as unset, and the circuit breaker resets on success.
@@ -688,7 +688,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory runs on Windows 10/11. WSL2 follows the Linux path and can install the pinned engine automatically. Native Windows also installs the pinned iii-engine v0.25.1 automatically: the CLI downloads the Windows ZIP, verifies its SHA-256 and extracts `iii.exe` into `%USERPROFILE%\.agentmemory\bin`. If that fails, download the matching archive from the [iii v0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verify its checksum, and extract `iii.exe` into the same directory.
+agentmemory runs on Windows 10/11. WSL2 follows the Linux path and can install the pinned engine automatically. Native Windows also installs the pinned iii-engine v0.26.0 automatically: the CLI downloads the Windows ZIP, verifies its SHA-256 and extracts `iii.exe` into `%USERPROFILE%\.agentmemory\bin`. If that fails, download the matching archive from the [iii v0.26.0 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verify its checksum, and extract `iii.exe` into the same directory.
`agentmemory connect ` works on native Windows. It writes the MCP server as `cmd /c npx -y @agentmemory/mcp`, because Windows cannot start `npx` without a shell, and it writes hook script paths as absolute paths with forward slashes, either quoted or passed as a separate argument, so a home folder with spaces is safe. Antigravity hooks cannot use quoted paths. When the install path has spaces, `connect antigravity --with-hooks` uses the Windows short (8.3) path. If the short path is not available, it prints the hook JSON to paste by hand, and the MCP wiring still applies. Run `connect` inside WSL only when the target agent is installed in that same WSL environment.
@@ -1313,7 +1313,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,900+ tests
+npm test # 5,000+ 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 de713f7766..8f6af59070 100644
--- a/READMEs/README.ar-SA.md
+++ b/READMEs/README.ar-SA.md
@@ -71,7 +71,7 @@
-
+
@@ -667,7 +667,7 @@ npm install && npm run build && npm start
### Windows
-يعمل agentmemory على Windows 10/11. يتبع WSL2 مسار Linux ويمكنه تثبيت المحرك المثبّت تلقائيًا. يتطلب Windows الأصلي تثبيت ملف iii-engine 0.25.1 المثبّت يدويًا؛ نزّل الأرشيف المطابق من [صفحة إصدار iii 0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1)، وتحقق من بصمته، وضع `iii.exe` على `PATH` (مثل `%USERPROFILE%\.local\bin\iii.exe`). لا يستخرج CLI ملف ZIP الخاص بـ Windows تلقائيًا.
+يعمل agentmemory على Windows 10/11. يتبع WSL2 مسار Linux ويمكنه تثبيت المحرك المثبّت تلقائيًا. يثبّت Windows الأصلي أيضًا iii-engine 0.26.0 المثبّت تلقائيًا: ينزّل CLI ملف ZIP الخاص بـ Windows، ويتحقق من SHA-256 الخاص به، ويستخرج `iii.exe` إلى `%USERPROFILE%\.agentmemory\bin`. إذا فشل ذلك، نزّل الأرشيف المطابق من [صفحة إصدار iii 0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0)، وتحقق من بصمته، واستخرج `iii.exe` إلى المجلد نفسه.
لا يدعم الربط الآلي لـ MCP على Windows الأصلي إلا `agentmemory connect copilot-cli`. أما وكلاء Windows الأصليون الآخرون، فاستخدم كتلة MCP اليدوية من [وكلاء آخرون](#other-agents). شغّل `connect` داخل WSL فقط عندما يكون الوكيل المستهدف مثبتًا في بيئة WSL نفسها.
@@ -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,900+ tests
+npm test # 5,000+ 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 c878a5d8c8..dfdc8dec2b 100644
--- a/READMEs/README.bn-BD.md
+++ b/READMEs/README.bn-BD.md
@@ -69,7 +69,7 @@
-
+
@@ -658,7 +658,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory Windows 10/11-এ চলে। WSL2 Linux-এর পথ অনুসরণ করে এবং পিন করা engine স্বয়ংক্রিয়ভাবে ইনস্টল করতে পারে। নেটিভ Windows-এর জন্য পিন করা iii-engine 0.25.1 বাইনারি ম্যানুয়ালি ইনস্টল করতে হবে; [iii 0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1) থেকে মিলে যাওয়া archive ডাউনলোড করে checksum যাচাই করুন, তারপর `iii.exe` `PATH`-এ রাখুন (যেমন `%USERPROFILE%\.local\bin\iii.exe`)। CLI Windows ZIP স্বয়ংক্রিয়ভাবে extract করে না।
+agentmemory Windows 10/11-এ চলে। WSL2 Linux-এর পথ অনুসরণ করে এবং পিন করা engine স্বয়ংক্রিয়ভাবে ইনস্টল করতে পারে। নেটিভ Windows-ও পিন করা iii-engine 0.26.0 স্বয়ংক্রিয়ভাবে ইনস্টল করে: CLI Windows ZIP ডাউনলোড করে, এর SHA-256 যাচাই করে এবং `iii.exe` `%USERPROFILE%\.agentmemory\bin`-এ extract করে। এটি ব্যর্থ হলে [iii 0.26.0 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0) থেকে মিলে যাওয়া archive ডাউনলোড করুন, checksum যাচাই করুন, তারপর `iii.exe` একই ফোল্ডারে extract করুন।
নেটিভ Windows-এ স্বয়ংক্রিয় MCP wiring কেবল `agentmemory connect copilot-cli` সাপোর্ট করে। অন্য নেটিভ Windows এজেন্টের জন্য [Other agents](#other-agents) থেকে ম্যানুয়াল MCP block ব্যবহার করুন। লক্ষ্য এজেন্টটি একই WSL পরিবেশে ইনস্টল থাকলেই কেবল WSL-এর ভিতরে `connect` চালান।
@@ -1257,7 +1257,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,900+ tests
+npm test # 5,000+ 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 05d3df1055..f3b5b8eb6f 100644
--- a/READMEs/README.cs-CZ.md
+++ b/READMEs/README.cs-CZ.md
@@ -69,7 +69,7 @@
-
+
@@ -665,7 +665,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory běží na Windows 10/11. WSL2 používá cestu pro Linux a může pinned engine nainstalovat automaticky. Nativní Windows vyžaduje ručně nainstalovanou binárku iii-engine v0.25.1; stáhněte odpovídající archiv ze [stránky vydání iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), ověřte kontrolní součet a umístěte `iii.exe` do `PATH` (například `%USERPROFILE%\.local\bin\iii.exe`). CLI ZIP pro Windows automaticky nerozbaluje.
+agentmemory běží na Windows 10/11. WSL2 používá cestu pro Linux a může pinned engine nainstalovat automaticky. Nativní Windows také instaluje pinned iii-engine v0.26.0 automaticky: CLI stáhne ZIP pro Windows, ověří jeho SHA-256 a rozbalí `iii.exe` do `%USERPROFILE%\.agentmemory\bin`. Pokud to selže, stáhněte odpovídající archiv ze [stránky vydání iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), ověřte kontrolní součet a rozbalte `iii.exe` do stejného adresáře.
Automatizované zapojení MCP na nativním Windows podporuje pouze `agentmemory connect copilot-cli`. U ostatních nativních agentů použijte manuální blok MCP ze sekce [Další agenti](#other-agents). `connect` ve WSL spouštějte pouze tehdy, pokud je cílový agent nainstalován ve stejném prostředí WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 62c1373564..e108765536 100644
--- a/READMEs/README.da-DK.md
+++ b/READMEs/README.da-DK.md
@@ -69,7 +69,7 @@
-
+
@@ -657,7 +657,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory kører på Windows 10/11. WSL2 følger Linux-vejen og kan installere den fastlåste engine automatisk. Native Windows kræver, at den fastlåste iii-engine v0.25.1-binary installeres manuelt; download det tilsvarende arkiv fra [iii v0.25.1-udgivelsessiden](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verificér checksum, og placér `iii.exe` på `PATH` (for eksempel `%USERPROFILE%\.local\bin\iii.exe`). CLI’en pakker ikke Windows-ZIP’en ud automatisk.
+agentmemory kører på Windows 10/11. WSL2 følger Linux-vejen og kan installere den fastlåste engine automatisk. Native Windows installerer også den fastlåste iii-engine v0.26.0 automatisk: CLI’en downloader Windows-ZIP’en, verificerer dens SHA-256 og pakker `iii.exe` ud i `%USERPROFILE%\.agentmemory\bin`. Hvis det mislykkes, så download det tilsvarende arkiv fra [iii v0.26.0-udgivelsessiden](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verificér checksum, og pak `iii.exe` ud i samme mappe.
Automatisk MCP-opsætning på native Windows understøtter kun `agentmemory connect copilot-cli`. Brug den manuelle MCP-blok fra [Andre agenter](#other-agents) til andre native Windows-agenter. Kør kun `connect` i WSL, hvis målagenten er installeret i samme WSL-miljø.
@@ -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,900+ tests
+npm test # 5,000+ 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 60cbd1df16..08ab242dad 100644
--- a/READMEs/README.de-DE.md
+++ b/READMEs/README.de-DE.md
@@ -69,7 +69,7 @@
-
+
@@ -655,7 +655,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory läuft unter Windows 10/11. WSL2 folgt dem Linux-Pfad und kann die gepinnte Engine automatisch installieren. Unter nativem Windows muss das gepinnte iii-engine-Binary v0.25.1 manuell installiert werden: Laden Sie das passende Archiv von der [iii-v0.25.1-Release-Seite](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1) herunter, prüfen Sie die Prüfsumme und legen Sie `iii.exe` auf den `PATH` (zum Beispiel `%USERPROFILE%\.local\bin\iii.exe`). Die CLI entpackt das Windows-ZIP nicht automatisch.
+agentmemory läuft unter Windows 10/11. WSL2 folgt dem Linux-Pfad und kann die gepinnte Engine automatisch installieren. Auch unter nativem Windows wird die gepinnte iii-engine v0.26.0 automatisch installiert: Die CLI lädt das Windows-ZIP herunter, prüft seine SHA-256-Prüfsumme und entpackt `iii.exe` nach `%USERPROFILE%\.agentmemory\bin`. Schlägt das fehl, laden Sie das passende Archiv von der [iii-v0.26.0-Release-Seite](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0) herunter, prüfen Sie die Prüfsumme und entpacken Sie `iii.exe` in dasselbe Verzeichnis.
Die automatisierte MCP-Verdrahtung unter nativem Windows unterstützt nur `agentmemory connect copilot-cli`. Für andere native Windows-Agenten verwenden Sie den manuellen MCP-Block unter [Andere Agenten](#other-agents). Führen Sie `connect` in WSL nur aus, wenn der Ziel-Agent in derselben WSL-Umgebung installiert ist.
@@ -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,900+ tests
+npm test # 5,000+ 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 4962170a4c..8c7d17cdee 100644
--- a/READMEs/README.el-GR.md
+++ b/READMEs/README.el-GR.md
@@ -69,7 +69,7 @@
-
+
@@ -665,7 +665,7 @@ npm install && npm run build && npm start
### Windows
-Το agentmemory εκτελείται σε Windows 10/11. Το WSL2 ακολουθεί τη διαδρομή Linux και μπορεί να εγκαταστήσει αυτόματα τον καρφιτσωμένο engine. Σε native Windows απαιτείται χειροκίνητη εγκατάσταση του καρφιτσωμένου binary iii-engine v0.25.1: κατεβάστε το αντίστοιχο archive από τη [σελίδα έκδοσης iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), επαληθεύστε το checksum και τοποθετήστε το `iii.exe` στο `PATH` (για παράδειγμα `%USERPROFILE%\.local\bin\iii.exe`). Το CLI δεν εξάγει αυτόματα το Windows ZIP.
+Το agentmemory εκτελείται σε Windows 10/11. Το WSL2 ακολουθεί τη διαδρομή Linux και μπορεί να εγκαταστήσει αυτόματα τον καρφιτσωμένο engine. Και στα native Windows το CLI εγκαθιστά αυτόματα τον καρφιτσωμένο iii-engine v0.26.0: κατεβάζει το Windows ZIP, επαληθεύει το SHA-256 του και εξάγει το `iii.exe` στο `%USERPROFILE%\.agentmemory\bin`. Αν αυτό αποτύχει, κατεβάστε το αντίστοιχο archive από τη [σελίδα έκδοσης iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), επαληθεύστε το checksum και εξαγάγετε το `iii.exe` στον ίδιο φάκελο.
Η αυτοματοποιημένη ρύθμιση MCP σε native Windows υποστηρίζει μόνο το `agentmemory connect copilot-cli`. Για άλλους native Windows agents, χρησιμοποιήστε το χειροκίνητο block MCP από τους [Άλλους agents](#other-agents). Εκτελέστε `connect` μέσα στο WSL μόνο αν ο agent-στόχος είναι εγκατεστημένος στο ίδιο περιβάλλον WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 71d33dbb10..59661801ca 100644
--- a/READMEs/README.es-ES.md
+++ b/READMEs/README.es-ES.md
@@ -69,7 +69,7 @@
-
+
@@ -657,7 +657,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory funciona en Windows 10/11. WSL2 sigue la ruta de Linux y puede instalar el motor fijado automáticamente. Windows nativo requiere instalar manualmente el binario fijado de iii-engine v0.25.1; descarga el archivo correspondiente desde la [página de la release iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verifica su checksum y coloca `iii.exe` en `PATH` (por ejemplo, `%USERPROFILE%\.local\bin\iii.exe`). La CLI no extrae automáticamente el ZIP de Windows.
+agentmemory funciona en Windows 10/11. WSL2 sigue la ruta de Linux y puede instalar el motor fijado automáticamente. Windows nativo también instala automáticamente el iii-engine v0.26.0 fijado: la CLI descarga el ZIP de Windows, verifica su SHA-256 y extrae `iii.exe` en `%USERPROFILE%\.agentmemory\bin`. Si eso falla, descarga el archivo correspondiente desde la [página de la release iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verifica su checksum y extrae `iii.exe` en el mismo directorio.
La conexión MCP automatizada en Windows nativo solo admite `agentmemory connect copilot-cli`. Para otros agentes nativos de Windows, usa el bloque MCP manual de [Otros agentes](#other-agents). Ejecuta `connect` dentro de WSL solo si el agente de destino está instalado en ese mismo entorno WSL.
@@ -1245,7 +1245,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,900+ tests
+npm test # 5,000+ 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 175efd508c..4e4a4989e0 100644
--- a/READMEs/README.fi-FI.md
+++ b/READMEs/README.fi-FI.md
@@ -69,7 +69,7 @@
-
+
@@ -665,7 +665,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory toimii Windows 10/11:ssä. WSL2 noudattaa Linuxin polkua ja voi asentaa kiinnitetyn moottorin automaattisesti. Natiivi Windows vaatii iii-engine v0.25.1:n kiinnitetyn binäärin asentamisen käsin; lataa sopiva paketti [iii v0.25.1 -julkaisusivulta](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), tarkista sen tarkistussumma ja sijoita `iii.exe` `PATH`-polkuun (esimerkiksi `%USERPROFILE%\.local\bin\iii.exe`). CLI ei pura Windows-ZIP-pakettia automaattisesti.
+agentmemory toimii Windows 10/11:ssä. WSL2 noudattaa Linuxin polkua ja voi asentaa kiinnitetyn moottorin automaattisesti. Myös natiivi Windows asentaa kiinnitetyn iii-engine v0.26.0:n automaattisesti: CLI lataa Windows-ZIP-paketin, tarkistaa sen SHA-256-summan ja purkaa `iii.exe`:n hakemistoon `%USERPROFILE%\.agentmemory\bin`. Jos tämä epäonnistuu, lataa sopiva paketti [iii v0.26.0 -julkaisusivulta](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), tarkista sen tarkistussumma ja pura `iii.exe` samaan hakemistoon.
Natiivin Windowsin automaattinen MCP-kytkentä tukee vain komentoa `agentmemory connect copilot-cli`. Muiden natiivien Windows-agenttien kanssa käytä manuaalista MCP-lohkoa kohdasta [Muut agentit](#other-agents). Suorita `connect` WSL:ssä vain, kun kohdeagentti on asennettu samaan WSL-ympäristöön.
@@ -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,900+ tests
+npm test # 5,000+ 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 c898e17a93..e1e95b575e 100644
--- a/READMEs/README.fr-FR.md
+++ b/READMEs/README.fr-FR.md
@@ -69,7 +69,7 @@
-
+
@@ -657,7 +657,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory fonctionne sous Windows 10/11. WSL2 suit le parcours Linux et peut installer automatiquement le moteur épinglé. Sous Windows natif, installez manuellement le binaire iii-engine v0.25.1 épinglé : téléchargez l'archive correspondante depuis la [page de version iii 0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), vérifiez son checksum et placez `iii.exe` dans `PATH` (par exemple `%USERPROFILE%\.local\bin\iii.exe`). La CLI n'extrait pas automatiquement le ZIP Windows.
+agentmemory fonctionne sous Windows 10/11. WSL2 suit le parcours Linux et peut installer automatiquement le moteur épinglé. Windows natif installe aussi automatiquement le moteur iii-engine v0.26.0 épinglé : la CLI télécharge le ZIP Windows, vérifie son SHA-256 et extrait `iii.exe` dans `%USERPROFILE%\.agentmemory\bin`. En cas d'échec, téléchargez l'archive correspondante depuis la [page de version iii 0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), vérifiez son checksum et extrayez `iii.exe` dans le même répertoire.
Sous Windows natif, le câblage MCP automatisé ne prend en charge que `agentmemory connect copilot-cli`. Pour les autres agents natifs Windows, utilisez le bloc MCP manuel de [Autres agents](#other-agents). Lancez `connect` dans WSL uniquement si l'agent cible est installé dans ce même environnement WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 0586f40d7b..f59ba4b7c9 100644
--- a/READMEs/README.he-IL.md
+++ b/READMEs/README.he-IL.md
@@ -71,7 +71,7 @@
-
+
@@ -667,7 +667,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory פועל ב-Windows 10/11. WSL2 פועל במסלול Linux ויכול להתקין את המנוע הנעוץ אוטומטית. ב-Windows מקורי יש להתקין ידנית את הבינארי הנעוץ iii-engine v0.25.1: הורידו את הארכיון המתאים מ-[דף ההפצה של iii 0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), אמתו את ה-checksum והוסיפו את `iii.exe` ל-`PATH` (למשל `%USERPROFILE%\.local\bin\iii.exe`). ה-CLI אינו מחלץ אוטומטית את ZIP של Windows.
+agentmemory פועל ב-Windows 10/11. WSL2 פועל במסלול Linux ויכול להתקין את המנוע הנעוץ אוטומטית. גם ב-Windows מקורי ה-CLI מתקין אוטומטית את iii-engine v0.26.0 הנעוץ: הוא מוריד את ה-ZIP של Windows, מאמת את ה-SHA-256 שלו ומחלץ את `iii.exe` אל `%USERPROFILE%\.agentmemory\bin`. אם זה נכשל, הורידו את הארכיון המתאים מ-[דף ההפצה של iii 0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), אמתו את ה-checksum וחלצו את `iii.exe` לאותה תיקייה.
חיבור MCP אוטומטי ב-Windows מקורי נתמך רק עבור `agentmemory connect copilot-cli`. עבור סוכנים מקומיים אחרים ב-Windows, השתמשו בבלוק MCP הידני מתוך [סוכנים אחרים](#other-agents). הפעילו `connect` בתוך WSL רק אם סוכן היעד מותקן באותה סביבת WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 9185983cda..4f2a62b704 100644
--- a/READMEs/README.hi-IN.md
+++ b/READMEs/README.hi-IN.md
@@ -69,7 +69,7 @@
-
+
@@ -658,7 +658,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory Windows 10/11 पर चलता है। WSL2 Linux path अपनाता है और pinned engine को automatically install कर सकता है। Native Windows पर pinned iii-engine v0.25.1 binary manually install करें: [iii v0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1) से सही archive download करें, checksum verify करें और `iii.exe` को `PATH` में रखें (उदाहरण: `%USERPROFILE%\.local\bin\iii.exe`)। CLI Windows ZIP को automatically extract नहीं करता।
+agentmemory Windows 10/11 पर चलता है। WSL2 Linux path अपनाता है और pinned engine को automatically install कर सकता है। Native Windows पर भी pinned iii-engine v0.26.0 automatically install होता है: CLI Windows ZIP download करता है, उसका SHA-256 verify करता है और `iii.exe` को `%USERPROFILE%\.agentmemory\bin` में extract करता है। यह fail हो तो [iii v0.26.0 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0) से सही archive download करें, checksum verify करें और `iii.exe` को उसी directory में extract करें।
Native Windows में automated MCP wiring केवल `agentmemory connect copilot-cli` को support करती है। अन्य native Windows agents के लिए [Other agents](#other-agents) वाला manual MCP block इस्तेमाल करें। `connect` को WSL में तभी चलाएँ जब target agent भी उसी WSL environment में installed हो।
@@ -1258,7 +1258,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,900+ tests
+npm test # 5,000+ 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 b1fcd2e91e..fa44df3d01 100644
--- a/READMEs/README.hu-HU.md
+++ b/READMEs/README.hu-HU.md
@@ -69,7 +69,7 @@
-
+
@@ -663,7 +663,7 @@ Az `npm start` ugyanazt a helyi szervert indítja, mint a telepített CLI. A kö
### Windows
-Az agentmemory Windows 10/11 rendszeren fut. A WSL2 a Linux útvonalat követi, és automatikusan telepítheti a rögzített motort. Natív Windowson kézzel telepítse a rögzített iii-engine v0.25.1 binárist: töltse le a megfelelő archívumot az [iii v0.25.1 kiadási oldaláról](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), ellenőrizze az ellenőrzőösszeget, majd helyezze az `iii.exe` fájlt a `PATH`-ra (például `%USERPROFILE%\.local\bin\iii.exe`). A CLI nem bontja ki automatikusan a Windows ZIP-et.
+Az agentmemory Windows 10/11 rendszeren fut. A WSL2 a Linux útvonalat követi, és automatikusan telepítheti a rögzített motort. Natív Windowson is automatikusan települ a rögzített iii-engine v0.26.0: a CLI letölti a Windows ZIP-et, ellenőrzi az SHA-256 értékét, és kibontja az `iii.exe` fájlt ide: `%USERPROFILE%\.agentmemory\bin`. Ha ez nem sikerül, töltse le a megfelelő archívumot az [iii v0.26.0 kiadási oldaláról](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), ellenőrizze az ellenőrzőösszeget, majd bontsa ki az `iii.exe` fájlt ugyanebbe a könyvtárba.
A natív Windows automatizált MCP-kapcsolat csak az `agentmemory connect copilot-cli` parancsot támogatja. Más natív Windows-ügynökökhöz használja az [Egyéb ügynökök](#other-agents) kézi MCP-blokkját. A `connect` parancsot csak akkor futtassa WSL-ben, ha a célügynök is ugyanabban a WSL-környezetben van telepítve.
@@ -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,900+ tests
+npm test # 5,000+ 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 6be8f90a25..95ced5d36d 100644
--- a/READMEs/README.id-ID.md
+++ b/READMEs/README.id-ID.md
@@ -69,7 +69,7 @@
-
+
@@ -658,7 +658,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory berjalan di Windows 10/11. WSL2 mengikuti jalur Linux dan dapat memasang engine yang dipatok secara otomatis. Pada Windows native, pasang biner iii-engine v0.25.1 yang dipatok secara manual: unduh arsip yang sesuai dari [halaman rilis iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verifikasi checksum, lalu letakkan `iii.exe` di `PATH` (misalnya `%USERPROFILE%\.local\bin\iii.exe`). CLI tidak mengekstrak ZIP Windows secara otomatis.
+agentmemory berjalan di Windows 10/11. WSL2 mengikuti jalur Linux dan dapat memasang engine yang dipatok secara otomatis. Windows native juga memasang iii-engine v0.26.0 yang dipatok secara otomatis: CLI mengunduh ZIP Windows, memverifikasi SHA-256-nya, dan mengekstrak `iii.exe` ke `%USERPROFILE%\.agentmemory\bin`. Jika gagal, unduh arsip yang sesuai dari [halaman rilis iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verifikasi checksum, lalu ekstrak `iii.exe` ke direktori yang sama.
Wiring MCP otomatis di Windows native hanya mendukung `agentmemory connect copilot-cli`. Untuk agen Windows native lainnya, gunakan blok MCP manual dari [Agen lainnya](#other-agents). Jalankan `connect` di WSL hanya jika agen target juga dipasang di lingkungan WSL yang sama.
@@ -1258,7 +1258,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,900+ tests
+npm test # 5,000+ 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 341799588d..526acdff02 100644
--- a/READMEs/README.it-IT.md
+++ b/READMEs/README.it-IT.md
@@ -69,7 +69,7 @@
-
+
@@ -657,7 +657,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory funziona su Windows 10/11. WSL2 segue il percorso Linux e può installare automaticamente l'engine fissato. Su Windows nativo, installare manualmente il binario iii-engine v0.25.1 fissato: scaricare l'archivio corrispondente dalla [pagina della release iii 0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verificarne il checksum e mettere `iii.exe` nel `PATH` (ad esempio `%USERPROFILE%\.local\bin\iii.exe`). La CLI non estrae automaticamente lo ZIP Windows.
+agentmemory funziona su Windows 10/11. WSL2 segue il percorso Linux e può installare automaticamente l'engine fissato. Anche Windows nativo installa automaticamente l'engine iii-engine v0.26.0 fissato: la CLI scarica lo ZIP Windows, ne verifica lo SHA-256 ed estrae `iii.exe` in `%USERPROFILE%\.agentmemory\bin`. Se non riesce, scaricare l'archivio corrispondente dalla [pagina della release iii 0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verificarne il checksum ed estrarre `iii.exe` nella stessa directory.
La configurazione MCP automatica su Windows nativo supporta solo `agentmemory connect copilot-cli`. Per gli altri agenti Windows nativi, usare il blocco MCP manuale da [Altri agenti](#other-agents). Eseguire `connect` in WSL solo se l'agente di destinazione è installato nello stesso ambiente WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 43913c0fd7..681dbe5a9b 100644
--- a/READMEs/README.ja-JP.md
+++ b/READMEs/README.ja-JP.md
@@ -69,7 +69,7 @@
-
+
@@ -658,7 +658,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory は Windows 10/11 で動作します。WSL2 は Linux の経路に従い、ピン留めされたエンジンを自動インストールできます。ネイティブ Windows では、ピン留めされた iii-engine v0.25.1 バイナリを手動でインストールしてください。[iii v0.25.1 リリースページ](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1)から該当アーカイブをダウンロードして checksum を確認し、`iii.exe` を `PATH` に配置します(例: `%USERPROFILE%\.local\bin\iii.exe`)。CLI は Windows ZIP を自動展開しません。
+agentmemory は Windows 10/11 で動作します。WSL2 は Linux の経路に従い、ピン留めされたエンジンを自動インストールできます。ネイティブ Windows でも、ピン留めされた iii-engine v0.26.0 が自動インストールされます。CLI が Windows ZIP をダウンロードして SHA-256 を検証し、`iii.exe` を `%USERPROFILE%\.agentmemory\bin` に展開します。失敗した場合は、[iii v0.26.0 リリースページ](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0)から該当アーカイブをダウンロードして checksum を確認し、`iii.exe` を同じディレクトリに展開してください。
ネイティブ Windows の自動 MCP 接続は `agentmemory connect copilot-cli` のみをサポートします。それ以外のネイティブ Windows エージェントには[その他のエージェント](#other-agents)の手動 MCP ブロックを使用してください。`connect` を WSL 内で実行するのは、対象エージェントも同じ WSL 環境にインストールされている場合に限ります。
@@ -1257,7 +1257,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,900+ tests
+npm test # 5,000+ 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 a70c02477a..3f13f8ad3f 100644
--- a/READMEs/README.ko-KR.md
+++ b/READMEs/README.ko-KR.md
@@ -69,7 +69,7 @@
-
+
@@ -656,7 +656,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory는 Windows 10/11에서 실행됩니다. WSL2는 Linux 경로를 따르며 고정 엔진을 자동 설치할 수 있습니다. 네이티브 Windows에서는 고정된 iii-engine v0.25.1 바이너리를 수동 설치하십시오: [iii v0.25.1 릴리스 페이지](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1)에서 맞는 아카이브를 다운로드하고 checksum을 확인한 뒤 `iii.exe`를 `PATH`에 두십시오(예: `%USERPROFILE%\.local\bin\iii.exe`). CLI는 Windows ZIP을 자동으로 압축 해제하지 않습니다.
+agentmemory는 Windows 10/11에서 실행됩니다. WSL2는 Linux 경로를 따르며 고정 엔진을 자동 설치할 수 있습니다. 네이티브 Windows에서도 고정된 iii-engine v0.26.0이 자동 설치됩니다: CLI가 Windows ZIP을 다운로드하고 SHA-256을 확인한 뒤 `iii.exe`를 `%USERPROFILE%\.agentmemory\bin`에 압축 해제합니다. 실패하면 [iii v0.26.0 릴리스 페이지](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0)에서 맞는 아카이브를 다운로드하고 checksum을 확인한 뒤 `iii.exe`를 같은 디렉터리에 압축 해제하십시오.
네이티브 Windows 자동 MCP 연결은 `agentmemory connect copilot-cli`만 지원합니다. 다른 네이티브 Windows 에이전트는 [다른 에이전트](#other-agents)의 수동 MCP 블록을 사용하십시오. 대상 에이전트도 같은 WSL 환경에 설치된 경우에만 WSL에서 `connect`를 실행하십시오.
@@ -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,900+ tests
+npm test # 5,000+ 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 9cce02dcf8..d561735203 100644
--- a/READMEs/README.nb-NO.md
+++ b/READMEs/README.nb-NO.md
@@ -69,7 +69,7 @@
-
+
@@ -655,7 +655,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory kjører på Windows 10/11. WSL2 følger Linux-stien og kan installere den fastlåste engine-en automatisk. Native Windows krever at den fastlåste iii-engine v0.25.1-binærfilen installeres manuelt; last ned det tilsvarende arkivet fra [iii v0.25.1-utgivelsessiden](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), kontroller kontrollsummen og legg `iii.exe` på `PATH` (for eksempel `%USERPROFILE%\.local\bin\iii.exe`). CLI-en pakker ikke ut Windows-ZIP-filen automatisk.
+agentmemory kjører på Windows 10/11. WSL2 følger Linux-stien og kan installere den fastlåste engine-en automatisk. Native Windows installerer også den fastlåste iii-engine v0.26.0 automatisk: CLI-en laster ned Windows-ZIP-filen, kontrollerer SHA-256-summen og pakker ut `iii.exe` til `%USERPROFILE%\.agentmemory\bin`. Hvis det mislykkes, last ned det tilsvarende arkivet fra [iii v0.26.0-utgivelsessiden](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), kontroller kontrollsummen og pakk ut `iii.exe` i samme mappe.
Automatisert native Windows-MCP-tilkobling støtter bare `agentmemory connect copilot-cli`. For andre native Windows-agenter bruker du den manuelle MCP-blokken fra [Andre agenter](#other-agents). Kjør `connect` i WSL bare når målagenten er installert i det samme WSL-miljøet.
@@ -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,900+ tests
+npm test # 5,000+ 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 6af924de0f..bf07145968 100644
--- a/READMEs/README.nl-NL.md
+++ b/READMEs/README.nl-NL.md
@@ -69,7 +69,7 @@
-
+
@@ -653,7 +653,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory draait op Windows 10/11. WSL2 volgt het Linux-pad en kan de vastgezette engine automatisch installeren. Native Windows vereist handmatige installatie van de vastgezette iii-engine v0.25.1-binary; download het passende archief van de [iii v0.25.1-releasepagina](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), controleer de checksum en plaats `iii.exe` op `PATH` (bijvoorbeeld `%USERPROFILE%\.local\bin\iii.exe`). De CLI pakt de Windows ZIP niet automatisch uit.
+agentmemory draait op Windows 10/11. WSL2 volgt het Linux-pad en kan de vastgezette engine automatisch installeren. Native Windows installeert de vastgezette iii-engine v0.26.0 ook automatisch: de CLI downloadt de Windows ZIP, controleert de SHA-256 en pakt `iii.exe` uit naar `%USERPROFILE%\.agentmemory\bin`. Als dat mislukt, download dan het passende archief van de [iii v0.26.0-releasepagina](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), controleer de checksum en pak `iii.exe` uit in dezelfde map.
Geautomatiseerde MCP-koppeling op native Windows ondersteunt alleen `agentmemory connect copilot-cli`. Gebruik voor andere native Windows-agents het handmatige MCP-blok uit [Other agents](#other-agents). Voer `connect` binnen WSL alleen uit wanneer de doelagent in dezelfde WSL-omgeving is geïnstalleerd.
@@ -1245,7 +1245,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,900+ tests
+npm test # 5,000+ 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 098d6dbdd2..1a5a27adbc 100644
--- a/READMEs/README.pl-PL.md
+++ b/READMEs/README.pl-PL.md
@@ -69,7 +69,7 @@
-
+
@@ -663,7 +663,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory działa w Windows 10/11. WSL2 korzysta ze ścieżki linuksowej i może automatycznie zainstalować przypięty silnik. Natywny Windows wymaga ręcznie zainstalowanego przypiętego pliku binarnego iii-engine v0.25.1; pobierz pasujące archiwum ze [strony wydania iii 0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), zweryfikuj sumę kontrolną i umieść `iii.exe` w `PATH` (na przykład `%USERPROFILE%\.local\bin\iii.exe`). CLI nie wypakowuje automatycznie archiwum ZIP dla Windows.
+agentmemory działa w Windows 10/11. WSL2 korzysta ze ścieżki linuksowej i może automatycznie zainstalować przypięty silnik. Natywny Windows także automatycznie instaluje przypięty iii-engine v0.26.0: CLI pobiera archiwum ZIP dla Windows, weryfikuje jego SHA-256 i wypakowuje `iii.exe` do `%USERPROFILE%\.agentmemory\bin`. Jeśli to się nie uda, pobierz pasujące archiwum ze [strony wydania iii 0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), zweryfikuj sumę kontrolną i wypakuj `iii.exe` do tego samego katalogu.
Zautomatyzowane podłączanie MCP w natywnym Windows obsługuje tylko `agentmemory connect copilot-cli`. Dla pozostałych natywnych agentów Windows użyj ręcznego bloku MCP z sekcji [Inni agenci](#other-agents). Uruchamiaj `connect` w WSL tylko wtedy, gdy docelowy agent jest zainstalowany w tym samym środowisku WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 fee630c5cd..ddf9e3ef14 100644
--- a/READMEs/README.pt-BR.md
+++ b/READMEs/README.pt-BR.md
@@ -69,7 +69,7 @@
-
+
@@ -655,7 +655,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory roda no Windows 10/11. O WSL2 segue o caminho Linux e pode instalar o engine fixado automaticamente. O Windows nativo exige a instalação manual do binário iii-engine v0.25.1 fixado; baixe o arquivo correspondente na [página de releases do iii 0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), confira o checksum e coloque `iii.exe` no `PATH` (por exemplo, `%USERPROFILE%\.local\bin\iii.exe`). O CLI não extrai o ZIP do Windows automaticamente.
+agentmemory roda no Windows 10/11. O WSL2 segue o caminho Linux e pode instalar o engine fixado automaticamente. O Windows nativo também instala o iii-engine v0.26.0 fixado automaticamente: o CLI baixa o ZIP do Windows, verifica o SHA-256 e extrai `iii.exe` em `%USERPROFILE%\.agentmemory\bin`. Se isso falhar, baixe o arquivo correspondente na [página de releases do iii 0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), confira o checksum e extraia `iii.exe` no mesmo diretório.
A configuração MCP automatizada no Windows nativo dá suporte apenas a `agentmemory connect copilot-cli`. Para os outros agentes nativos do Windows, use o bloco MCP manual em [Outros agentes](#other-agents). Rode `connect` no WSL somente quando o agente de destino estiver instalado no mesmo ambiente WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 91747393a5..9ea0ee5914 100644
--- a/READMEs/README.pt-PT.md
+++ b/READMEs/README.pt-PT.md
@@ -69,7 +69,7 @@
-
+
@@ -657,7 +657,7 @@ npm install && npm run build && npm start
### Windows
-O agentmemory funciona no Windows 10/11. O WSL2 segue o caminho Linux e pode instalar automaticamente o engine fixado. O Windows nativo exige que o binário iii-engine v0.25.1 fixado seja instalado manualmente; descarregue o ficheiro correspondente na [página de lançamento iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verifique o checksum e coloque `iii.exe` no `PATH` (por exemplo, `%USERPROFILE%\.local\bin\iii.exe`). O CLI não extrai automaticamente o ZIP do Windows.
+O agentmemory funciona no Windows 10/11. O WSL2 segue o caminho Linux e pode instalar automaticamente o engine fixado. O Windows nativo também instala automaticamente o iii-engine v0.26.0 fixado: o CLI descarrega o ZIP do Windows, verifica o SHA-256 e extrai `iii.exe` para `%USERPROFILE%\.agentmemory\bin`. Se isso falhar, descarregue o ficheiro correspondente na [página de lançamento iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verifique o checksum e extraia `iii.exe` para o mesmo diretório.
A ligação MCP automatizada no Windows nativo só suporta `agentmemory connect copilot-cli`. Para os restantes agentes nativos do Windows, use o bloco MCP manual de [Outros agentes](#other-agents). Execute `connect` no WSL apenas quando o agente de destino também estiver instalado nesse mesmo ambiente WSL.
@@ -1245,7 +1245,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,900+ tests
+npm test # 5,000+ 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 d6173acd64..ae06efce15 100644
--- a/READMEs/README.ro-RO.md
+++ b/READMEs/README.ro-RO.md
@@ -69,7 +69,7 @@
-
+
@@ -665,7 +665,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory rulează pe Windows 10/11. WSL2 urmează calea Linux și poate instala automat engine-ul fixat. Windows nativ necesită instalarea manuală a binarului iii-engine v0.25.1 fixat; descarcă arhiva potrivită de pe [pagina de release iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verifică checksum-ul și pune `iii.exe` în `PATH` (de exemplu `%USERPROFILE%\.local\bin\iii.exe`). CLI-ul nu extrage automat arhiva ZIP pentru Windows.
+agentmemory rulează pe Windows 10/11. WSL2 urmează calea Linux și poate instala automat engine-ul fixat. Și Windows nativ instalează automat engine-ul iii-engine v0.26.0 fixat: CLI-ul descarcă arhiva ZIP pentru Windows, îi verifică SHA-256 și extrage `iii.exe` în `%USERPROFILE%\.agentmemory\bin`. Dacă acest pas eșuează, descarcă arhiva potrivită de pe [pagina de release iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verifică checksum-ul și extrage `iii.exe` în același director.
Conectarea MCP automatizată pe Windows nativ acceptă doar `agentmemory connect copilot-cli`. Pentru ceilalți agenți nativi Windows, folosește blocul MCP manual din [Alți agenți](#other-agents). Rulează `connect` în WSL doar când agentul țintă este instalat în același mediu WSL.
@@ -1237,7 +1237,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,900+ tests
+npm test # 5,000+ 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 be1e91e4e4..e5e1455b8f 100644
--- a/READMEs/README.ru-RU.md
+++ b/READMEs/README.ru-RU.md
@@ -69,7 +69,7 @@
-
+
@@ -666,7 +666,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory работает на Windows 10/11. В WSL2 используется путь Linux, и закреплённый движок устанавливается автоматически. Для нативной работы в Windows требуется вручную установить закреплённый бинарь iii-engine v0.25.1: скачайте подходящий архив со [страницы релиза iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), проверьте контрольную сумму и поместите `iii.exe` в `PATH` (например, `%USERPROFILE%\.local\bin\iii.exe`). CLI не распаковывает Windows ZIP автоматически.
+agentmemory работает на Windows 10/11. В WSL2 используется путь Linux, и закреплённый движок устанавливается автоматически. В нативной Windows закреплённый iii-engine v0.26.0 тоже устанавливается автоматически: CLI скачивает Windows ZIP, проверяет его SHA-256 и распаковывает `iii.exe` в `%USERPROFILE%\.agentmemory\bin`. Если это не удалось, скачайте подходящий архив со [страницы релиза iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), проверьте контрольную сумму и распакуйте `iii.exe` в тот же каталог.
Автоматизированное подключение MCP в нативной Windows поддерживает только `agentmemory connect copilot-cli`. Для других нативных Windows-агентов используйте ручной блок MCP из раздела [Другие агенты](#other-agents). Запускайте `connect` внутри WSL только если целевой агент установлен в той же среде WSL.
@@ -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,900+ tests
+npm test # 5,000+ 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 82f04762eb..2be275b7ec 100644
--- a/READMEs/README.sv-SE.md
+++ b/READMEs/README.sv-SE.md
@@ -69,7 +69,7 @@
-
+
@@ -658,7 +658,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory körs på Windows 10/11. WSL2 följer Linux-vägen och kan installera den fastlåsta enginen automatiskt. Native Windows kräver att den fastlåsta iii-engine v0.25.1-binären installeras manuellt: ladda ner rätt arkiv från [iii v0.25.1-utgåvan](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verifiera kontrollsumman och placera `iii.exe` på `PATH` (till exempel `%USERPROFILE%\.local\bin\iii.exe`). CLI:n packar inte upp Windows-ZIP-filen automatiskt.
+agentmemory körs på Windows 10/11. WSL2 följer Linux-vägen och kan installera den fastlåsta enginen automatiskt. Native Windows installerar också den fastlåsta iii-engine v0.26.0 automatiskt: CLI:n laddar ner Windows-ZIP-filen, verifierar dess SHA-256 och packar upp `iii.exe` i `%USERPROFILE%\.agentmemory\bin`. Om det misslyckas, ladda ner rätt arkiv från [iii v0.26.0-utgåvan](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), verifiera kontrollsumman och packa upp `iii.exe` i samma katalog.
Automatiserad MCP-inkoppling på native Windows stöder bara `agentmemory connect copilot-cli`. För andra native Windows-agenter använder du det manuella MCP-blocket från [Andra agenter](#other-agents). Kör `connect` i WSL endast om målagenten är installerad i samma WSL-miljö.
@@ -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,900+ tests
+npm test # 5,000+ 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 c93db2f895..87b7667abc 100644
--- a/READMEs/README.th-TH.md
+++ b/READMEs/README.th-TH.md
@@ -69,7 +69,7 @@
-
+
@@ -650,7 +650,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory รองรับ Windows 10/11; WSL2 ใช้ขั้นตอน Linux และติดตั้ง engine อัตโนมัติได้ Windows แบบ native ต้องติดตั้งไบนารี iii-engine v0.25.1 ด้วยตนเอง ดาวน์โหลด archive จาก [หน้า release iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), ตรวจ checksum และวาง `iii.exe` บน `PATH` (เช่น `%USERPROFILE%\.local\bin\iii.exe`) CLI ไม่แตก Windows ZIP ให้อัตโนมัติ
+agentmemory รองรับ Windows 10/11; WSL2 ใช้ขั้นตอน Linux และติดตั้ง engine อัตโนมัติได้ Windows แบบ native ก็ติดตั้ง iii-engine v0.26.0 อัตโนมัติเช่นกัน: CLI ดาวน์โหลด Windows ZIP ตรวจ SHA-256 และแตก `iii.exe` ไปที่ `%USERPROFILE%\.agentmemory\bin` หากไม่สำเร็จ ให้ดาวน์โหลด archive จาก [หน้า release iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), ตรวจ checksum และแตก `iii.exe` ไปที่ไดเรกทอรีเดียวกัน
การตั้งค่า MCP อัตโนมัติบน Windows รองรับเฉพาะ `agentmemory connect copilot-cli`; สำหรับ agent อื่นให้ใช้ MCP block ใน [Other agents](#other-agents) เรียก `connect` ใน WSL เมื่อ agent เป้าหมายติดตั้งใน WSL เดียวกันเท่านั้น
@@ -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,900+ tests
+npm test # 5,000+ 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 6d50865f29..43688ba5d0 100644
--- a/READMEs/README.tl-PH.md
+++ b/READMEs/README.tl-PH.md
@@ -69,7 +69,7 @@
-
+
@@ -658,7 +658,7 @@ Pinapatakbo ng `npm start` ang kaparehong local server ng naka-install na CLI. N
### Windows
-Tumatakbo ang agentmemory sa Windows 10/11. Awtomatikong nag-i-install ng engine ang WSL2 gamit ang Linux path. Sa native Windows, manu-manong i-install ang pinned na iii-engine v0.25.1: i-download ang archive mula sa [iii v0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), tiyakin ang checksum, at ilagay ang `iii.exe` sa `PATH`. Hindi awtomatikong nag-e-extract ng ZIP ang CLI
+Tumatakbo ang agentmemory sa Windows 10/11. Awtomatikong nag-i-install ng engine ang WSL2 gamit ang Linux path. Awtomatiko ring ini-install ng native Windows ang pinned na iii-engine v0.26.0: dina-download ng CLI ang Windows ZIP, tinitiyak ang SHA-256 nito, at ine-extract ang `iii.exe` sa `%USERPROFILE%\.agentmemory\bin`. Kung pumalya ito, i-download ang archive mula sa [iii v0.26.0 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), tiyakin ang checksum, at i-extract ang `iii.exe` sa parehong directory.
Native Windows MCP automation ay para lamang sa `agentmemory connect copilot-cli`; gamitin ang manual MCP block sa [Other agents](#other-agents) para sa iba. Sa WSL, patakbuhin ang `connect` lamang kung naroon din ang target agent
@@ -1253,7 +1253,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,900+ tests
+npm test # 5,000+ 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 d4ef91d08b..b3ae722354 100644
--- a/READMEs/README.tr-TR.md
+++ b/READMEs/README.tr-TR.md
@@ -69,7 +69,7 @@
-
+
@@ -665,7 +665,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory Windows 10/11’de çalışır. WSL2 Linux yolunu izleyerek engine’i otomatik kurabilir. Yerel Windows’ta iii-engine v0.25.1 elle kurulmalıdır: arşivi [iii v0.25.1 sürüm sayfasından](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1) indirin, checksum’u doğrulayın ve `iii.exe` dosyasını `PATH` üzerine koyun. CLI Windows ZIP’ini otomatik açmaz
+agentmemory Windows 10/11’de çalışır. WSL2 Linux yolunu izleyerek engine’i otomatik kurabilir. Yerel Windows da sabitlenmiş iii-engine v0.26.0’ı otomatik kurar: CLI Windows ZIP’ini indirir, SHA-256 değerini doğrular ve `iii.exe` dosyasını `%USERPROFILE%\.agentmemory\bin` dizinine açar. Bu başarısız olursa arşivi [iii v0.26.0 sürüm sayfasından](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0) indirin, checksum’u doğrulayın ve `iii.exe` dosyasını aynı dizine açın.
Yerel Windows’ta otomatik MCP yapılandırması yalnızca `agentmemory connect copilot-cli` için vardır; diğerleri için [Other agents](#other-agents) bölümünü kullanın. WSL’de `connect` yalnızca hedef agent aynı WSL ortamındaysa çalıştırılmalıdır
@@ -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,900+ tests
+npm test # 5,000+ 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 b26305144d..d1f552ed9d 100644
--- a/READMEs/README.uk-UA.md
+++ b/READMEs/README.uk-UA.md
@@ -69,7 +69,7 @@
-
+
@@ -665,7 +665,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory працює у Windows 10/11; WSL2 може автоматично встановити engine. Нативна Windows потребує ручного встановлення iii-engine v0.25.1: завантажте архів зі [сторінки iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), перевірте checksum і розмістіть `iii.exe` у `PATH`. CLI не розпаковує ZIP автоматично
+agentmemory працює у Windows 10/11; WSL2 може автоматично встановити engine. Нативна Windows теж встановлює iii-engine v0.26.0 автоматично: CLI завантажує Windows ZIP, перевіряє його SHA-256 і розпаковує `iii.exe` у `%USERPROFILE%\.agentmemory\bin`. Якщо це не вдалося, завантажте архів зі [сторінки iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), перевірте checksum і розпакуйте `iii.exe` у той самий каталог.
Автоматичне налаштування MCP у нативній Windows підтримує лише `agentmemory connect copilot-cli`; для інших скористайтеся [Other agents](#other-agents). У WSL виконуйте `connect`, лише якщо агент встановлений у тому самому середовищі
@@ -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,900+ tests
+npm test # 5,000+ 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 31250f113a..683b77385f 100644
--- a/READMEs/README.ur-PK.md
+++ b/READMEs/README.ur-PK.md
@@ -71,7 +71,7 @@
-
+
@@ -660,7 +660,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory Windows 10/11 پر چلتا ہے؛ WSL2 Linux طریقے سے engine خود انسٹال کر سکتا ہے۔ Native Windows پر iii-engine v0.25.1 binary دستی طور پر انسٹال کریں: [iii v0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1) سے archive ڈاؤن لوڈ، checksum کی تصدیق، اور `iii.exe` کو `PATH` پر رکھیں۔ CLI ZIP خود نہیں کھولتا
+agentmemory Windows 10/11 پر چلتا ہے؛ WSL2 Linux طریقے سے engine خود انسٹال کر سکتا ہے۔ Native Windows بھی iii-engine v0.26.0 خود انسٹال کرتا ہے: CLI Windows ZIP ڈاؤن لوڈ کرتا ہے، اس کے SHA-256 کی تصدیق کرتا ہے اور `iii.exe` کو `%USERPROFILE%\.agentmemory\bin` میں extract کرتا ہے۔ اگر یہ ناکام ہو تو [iii v0.26.0 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0) سے archive ڈاؤن لوڈ کریں، checksum کی تصدیق کریں، اور `iii.exe` کو اسی ڈائریکٹری میں extract کریں۔
Native Windows پر MCP خودکار wiring صرف `agentmemory connect copilot-cli` کے لیے ہے؛ دوسرے agents کے لیے [Other agents](#other-agents) کا دستی MCP block استعمال کریں۔ WSL میں `connect` تب چلائیں جب target agent وہیں نصب ہو
@@ -1248,7 +1248,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,900+ tests
+npm test # 5,000+ 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 fd842721a3..b2680eb1e0 100644
--- a/READMEs/README.vi-VN.md
+++ b/READMEs/README.vi-VN.md
@@ -69,7 +69,7 @@
-
+
@@ -101,7 +101,7 @@ Yêu cầu:
- Node.js 20 hoặc mới hơn kèm npm và npx (`node -v`, `npm -v`, và `npx -v`).
- Thiết lập tự động trên macOS/Linux cần `curl`, POSIX `sh` và `tar`.
-Windows native cần cài thủ công `iii.exe` của iii v0.25.1 đã pin; WSL2 dùng trình cài tự động cho macOS/Linux
+Windows native và WSL2 đều tự cài iii v0.26.0 đã pin; xem [Windows](#windows)
Lệnh cài mới chuẩn (canonical):
@@ -658,7 +658,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory chạy trên Windows 10/11; WSL2 có thể tự cài engine theo quy trình Linux. Windows native cần cài thủ công iii-engine v0.25.1: tải archive từ [trang phát hành iii v0.25.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), xác minh checksum và đặt `iii.exe` trong `PATH`. CLI không tự giải nén ZIP Windows
+agentmemory chạy trên Windows 10/11; WSL2 có thể tự cài engine theo quy trình Linux. Windows native cũng tự cài iii-engine v0.26.0 đã pin: CLI tải ZIP Windows, xác minh SHA-256 và giải nén `iii.exe` vào `%USERPROFILE%\.agentmemory\bin`. Nếu bước này thất bại, tải archive từ [trang phát hành iii v0.26.0](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0), xác minh checksum và giải nén `iii.exe` vào cùng thư mục.
Cấu hình MCP tự động trên Windows native chỉ hỗ trợ `agentmemory connect copilot-cli`; agent khác dùng khối MCP thủ công trong [Other agents](#other-agents). Chỉ chạy `connect` trong WSL nếu agent đích cũng cài trong cùng môi trường WSL
@@ -1253,7 +1253,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,900+ tests
+npm test # 5,000+ 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 4c56b9e1e0..e8be9c3ff9 100644
--- a/READMEs/README.zh-CN.md
+++ b/READMEs/README.zh-CN.md
@@ -69,7 +69,7 @@
-
+
@@ -658,7 +658,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory 支持 Windows 10/11;WSL2 可按 Linux 流程自动安装 engine。原生 Windows 需手动安装 iii-engine v0.25.1:从 [iii v0.25.1 发布页](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1) 下载对应归档、验证校验和,并将 `iii.exe` 放到 `PATH`。CLI 不会自动解压 ZIP
+agentmemory 支持 Windows 10/11;WSL2 可按 Linux 流程自动安装 engine。原生 Windows 同样会自动安装固定版本的 iii-engine v0.26.0:CLI 下载 Windows ZIP、验证其 SHA-256,并将 `iii.exe` 解压到 `%USERPROFILE%\.agentmemory\bin`。如果失败,请从 [iii v0.26.0 发布页](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0) 下载对应归档、验证校验和,并将 `iii.exe` 解压到同一目录。
原生 Windows 仅为 `agentmemory connect copilot-cli` 提供自动 MCP 配置;其他 agent 请使用 [Other agents](#other-agents) 中的手动配置。仅当目标 agent 也安装在同一 WSL 环境时,才在 WSL 中运行 `connect`
@@ -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,900+ tests
+npm test # 5,000+ 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 16d550226f..5d5334d4a9 100644
--- a/READMEs/README.zh-TW.md
+++ b/READMEs/README.zh-TW.md
@@ -69,7 +69,7 @@
-
+
@@ -656,7 +656,7 @@ npm install && npm run build && npm start
### Windows
-agentmemory 可在 Windows 10/11 執行;WSL2 可依 Linux 流程自動安裝 engine。原生 Windows 需手動安裝 iii-engine v0.25.1:從 [iii v0.25.1 發行頁面](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1) 下載相符封存檔、驗證 checksum,並將 `iii.exe` 放入 `PATH`。CLI 不會自動解壓 ZIP
+agentmemory 可在 Windows 10/11 執行;WSL2 可依 Linux 流程自動安裝 engine。原生 Windows 也會自動安裝固定版本的 iii-engine v0.26.0:CLI 下載 Windows ZIP、驗證其 SHA-256,並將 `iii.exe` 解壓縮到 `%USERPROFILE%\.agentmemory\bin`。若失敗,請從 [iii v0.26.0 發行頁面](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.26.0) 下載相符封存檔、驗證 checksum,並將 `iii.exe` 解壓縮到同一目錄。
原生 Windows 僅支援 `agentmemory connect copilot-cli` 自動設定 MCP;其他 agent 請使用 [Other agents](#other-agents) 的手動設定。只有目標 agent 也安裝在相同 WSL 環境時,才在 WSL 執行 `connect`
@@ -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,900+ tests
+npm test # 5,000+ 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 e6fccac91e..ab7d6c3b5c 100644
--- a/assets/tags/light/stat-tests.svg
+++ b/assets/tags/light/stat-tests.svg
@@ -1,5 +1,5 @@
-
+
- 4900+
+ 5000+
TESTS PASSING
diff --git a/assets/tags/stat-tests.svg b/assets/tags/stat-tests.svg
index 3b31eea1ea..f28674a600 100644
--- a/assets/tags/stat-tests.svg
+++ b/assets/tags/stat-tests.svg
@@ -1,5 +1,5 @@
-
+
- 4900+
+ 5000+
TESTS PASSING
diff --git a/deploy/Dockerfile b/deploy/Dockerfile
index 681abc5a79..929596311f 100644
--- a/deploy/Dockerfile
+++ b/deploy/Dockerfile
@@ -1,8 +1,8 @@
# Shared build for local Compose and every deployment platform.
# Update these four pins together when promoting the runtime.
-ARG III_VERSION=0.25.1
-ARG STATE_VERSION=0.22.22
-ARG HTTP_VERSION=0.22.8
+ARG III_VERSION=0.26.0
+ARG STATE_VERSION=0.23.1
+ARG HTTP_VERSION=0.23.2
FROM node:24-slim AS agent-build
ARG III_VERSION
diff --git a/deploy/README.md b/deploy/README.md
index 8022a0456c..f80dc206ea 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -1,6 +1,6 @@
# Docker deployments
-agentmemory runs on iii 0.25.1 with the `state` 0.22.22 and `http` 0.22.8 registry workers. All image builds use one [`Dockerfile`](Dockerfile), with engine and registry worker pins declared once. Update those build arguments together when promoting a release. Workers are fetched from the iii registry at startup; the `worker-compose.yaml` uses the same Worker Compose format as the CLI.
+agentmemory runs on iii 0.26.0 with the `state` 0.23.1 and `http` 0.23.2 registry workers. All image builds use one [`Dockerfile`](Dockerfile), with engine and registry worker pins declared once. Update those build arguments together when promoting a release. Workers are fetched from the iii registry at startup; the `worker-compose.yaml` uses the same Worker Compose format as the CLI.
The container runs `iii compose --up`: Compose owns the engine and supervises `state`, `http`, and the local `agentmemory` worker. There is no legacy embedded engine config, standalone stream, pubsub, or queue worker. The registry worker artifacts are pinned in the compose manifest. Engine and worker state, agentmemory state, generated secret, Compose cache, and logs live on the persistent `/data` volume. For Docker Compose, the volume key is `iii-data`, normally stored as `_iii-data`; set `AGENTMEMORY_DATA_DIR` to a host path to use a bind mount instead. The state worker continues to use `/data/state_store.db`, so the existing 0.22.1 file-based store is read in place without conversion or deletion.
diff --git a/deploy/coolify/docker-compose.yml b/deploy/coolify/docker-compose.yml
index e35233996f..6e5399f626 100644
--- a/deploy/coolify/docker-compose.yml
+++ b/deploy/coolify/docker-compose.yml
@@ -61,6 +61,13 @@ services:
AGENTMEMORY_REDIS_URL: "${AGENTMEMORY_REDIS_URL:-}"
AGENTMEMORY_STATE_SAVE_INTERVAL_MS: "${AGENTMEMORY_STATE_SAVE_INTERVAL_MS:-}"
AGENTMEMORY_LOCAL_DISPATCH: "${AGENTMEMORY_LOCAL_DISPATCH:-}"
+ AGENTMEMORY_BINDINGS: "${AGENTMEMORY_BINDINGS:-}"
+ AGENTMEMORY_STATE_READY_TIMEOUT_MS: "${AGENTMEMORY_STATE_READY_TIMEOUT_MS:-}"
+ AGENTMEMORY_ROUTE_MAX_IN_FLIGHT: "${AGENTMEMORY_ROUTE_MAX_IN_FLIGHT:-}"
+ AGENTMEMORY_COMPRESS_MAX_CONCURRENT: "${AGENTMEMORY_COMPRESS_MAX_CONCURRENT:-}"
+ AGENTMEMORY_COMPRESSION_SWEEP_MS: "${AGENTMEMORY_COMPRESSION_SWEEP_MS:-}"
+ AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS: "${AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS:-}"
+ AGENTMEMORY_GRAPH_STRUCTURAL: "${AGENTMEMORY_GRAPH_STRUCTURAL:-}"
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}"
AGENT_ID: "${AGENT_ID:-}"
TEAM_ID: "${TEAM_ID:-}"
diff --git a/deploy/fly/README.md b/deploy/fly/README.md
index 8c2b3e525d..a1683ae5e9 100644
--- a/deploy/fly/README.md
+++ b/deploy/fly/README.md
@@ -8,7 +8,7 @@ fly volumes create agentmemory_data --region iad --size 1 --app
```
-The shared `deploy/Dockerfile` build runs iii 0.25.1 Worker Compose. `/data` persists engine configuration, state, secret, registry cache, and logs. REST is served over HTTPS on internal port `3111`; the authenticated viewer uses internal port `3113`, exposed only through the TLS listener on public port `8443`.
+The shared `deploy/Dockerfile` build runs iii 0.26.0 Worker Compose. `/data` persists engine configuration, state, secret, registry cache, and logs. REST is served over HTTPS on internal port `3111`; the authenticated viewer uses internal port `3113`, exposed only through the TLS listener on public port `8443`.
Set `VIEWER_ALLOWED_HOSTS` to `.fly.dev:8443,localhost:3113` and `VIEWER_ALLOWED_ORIGINS` to `https://.fly.dev:8443` before enabling the viewer. Keep `localhost:3113` for Fly's internal viewer healthcheck. Browse to `https://.fly.dev:8443`; enter the bearer secret when prompted. The API/SSE proxy requires bearer auth. Never expose port `49134`.
diff --git a/deploy/railway/README.md b/deploy/railway/README.md
index 160d1598a4..af103898f0 100644
--- a/deploy/railway/README.md
+++ b/deploy/railway/README.md
@@ -1,6 +1,6 @@
# Railway
-Connect the GitHub repository with its root directory left at the repository root; the shared Dockerfile needs root-level `package.json` and source files in its build context. In service settings, set the Config-as-Code path to `/deploy/railway/railway.json` (Railway resolves this path independently of the selected root directory). This config selects `deploy/Dockerfile` while the build context remains the repository root. Add a persistent volume mounted at `/data` before starting the service. The service runs iii 0.25.1 Worker Compose and serves the health endpoint at `/agentmemory/livez`.
+Connect the GitHub repository with its root directory left at the repository root; the shared Dockerfile needs root-level `package.json` and source files in its build context. In service settings, set the Config-as-Code path to `/deploy/railway/railway.json` (Railway resolves this path independently of the selected root directory). This config selects `deploy/Dockerfile` while the build context remains the repository root. Add a persistent volume mounted at `/data` before starting the service. The service runs iii 0.26.0 Worker Compose and serves the health endpoint at `/agentmemory/livez`.
The REST API listens on `3111`; Railway's generated HTTP domain exposes that service. Read the secret with `railway ssh --service agentmemory -- 'cat /data/secret'` and send it as `Authorization: Bearer `.
diff --git a/deploy/render/README.md b/deploy/render/README.md
index eb1bfc8adc..4e29e03c78 100644
--- a/deploy/render/README.md
+++ b/deploy/render/README.md
@@ -1,6 +1,6 @@
# Render
-Create a Blueprint from `deploy/render/render.yaml`. Render builds the shared `deploy/Dockerfile` and provisions a persistent `/data` disk. The web service exposes REST on `3111` and uses `/agentmemory/livez` for health checks. The runtime is iii 0.25.1 Worker Compose with registry workers pinned in `deploy/Dockerfile` and `deploy/runtime/worker-compose.yaml`.
+Create a Blueprint from `deploy/render/render.yaml`. Render builds the shared `deploy/Dockerfile` and provisions a persistent `/data` disk. The web service exposes REST on `3111` and uses `/agentmemory/livez` for health checks. The runtime is iii 0.26.0 Worker Compose with registry workers pinned in `deploy/Dockerfile` and `deploy/runtime/worker-compose.yaml`.
The viewer listens on container port `3113`. Render's web service exposes only the primary HTTP port; reach the viewer through an SSH tunnel or a separately configured TLS proxy. For a public proxy, set `VIEWER_ALLOWED_HOSTS` and `VIEWER_ALLOWED_ORIGINS` to exact values. Viewer API/SSE routes require the bearer secret. Read it over SSH with `cat /data/secret`. Do not expose the engine WebSocket on `49134`.
diff --git a/deploy/runtime/entrypoint.sh b/deploy/runtime/entrypoint.sh
index 49a0ccde1d..d94069312d 100755
--- a/deploy/runtime/entrypoint.sh
+++ b/deploy/runtime/entrypoint.sh
@@ -114,6 +114,6 @@ fs.writeFileSync(target, input, { mode: 0o600 });
NODE
chown node:node "$DATA_DIR/config/iii-observability.yaml" "$WORKER_COMPOSE_FILE"
-# Compose owns the 0.25.1 engine and supervises state, http, and agentmemory.
+# Compose owns the 0.26.0 engine and supervises state, http, and agentmemory.
exec gosu node:node /usr/local/bin/iii compose \
--namespace agentmemory --up --file "$WORKER_COMPOSE_FILE"
diff --git a/deploy/runtime/worker-compose.yaml b/deploy/runtime/worker-compose.yaml
index d3f8b91308..8b1bc7e37e 100644
--- a/deploy/runtime/worker-compose.yaml
+++ b/deploy/runtime/worker-compose.yaml
@@ -120,6 +120,13 @@ containers:
AGENTMEMORY_REDIS_URL: "${AGENTMEMORY_REDIS_URL:-}"
AGENTMEMORY_STATE_SAVE_INTERVAL_MS: "${AGENTMEMORY_STATE_SAVE_INTERVAL_MS:-}"
AGENTMEMORY_LOCAL_DISPATCH: "${AGENTMEMORY_LOCAL_DISPATCH:-}"
+ AGENTMEMORY_BINDINGS: "${AGENTMEMORY_BINDINGS:-}"
+ AGENTMEMORY_STATE_READY_TIMEOUT_MS: "${AGENTMEMORY_STATE_READY_TIMEOUT_MS:-}"
+ AGENTMEMORY_ROUTE_MAX_IN_FLIGHT: "${AGENTMEMORY_ROUTE_MAX_IN_FLIGHT:-}"
+ AGENTMEMORY_COMPRESS_MAX_CONCURRENT: "${AGENTMEMORY_COMPRESS_MAX_CONCURRENT:-}"
+ AGENTMEMORY_COMPRESSION_SWEEP_MS: "${AGENTMEMORY_COMPRESSION_SWEEP_MS:-}"
+ AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS: "${AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS:-}"
+ AGENTMEMORY_GRAPH_STRUCTURAL: "${AGENTMEMORY_GRAPH_STRUCTURAL:-}"
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}"
AGENT_ID: "${AGENT_ID:-}"
TEAM_ID: "${TEAM_ID:-}"
diff --git a/docker-compose.yml b/docker-compose.yml
index 0fd899e20e..6398183f33 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -4,9 +4,9 @@ services:
context: .
dockerfile: deploy/Dockerfile
args:
- III_VERSION: "${III_VERSION:-0.25.1}"
- STATE_VERSION: "${STATE_VERSION:-0.22.22}"
- HTTP_VERSION: "${HTTP_VERSION:-0.22.8}"
+ III_VERSION: "${III_VERSION:-0.26.0}"
+ STATE_VERSION: "${STATE_VERSION:-0.23.1}"
+ HTTP_VERSION: "${HTTP_VERSION:-0.23.2}"
restart: unless-stopped
environment:
AGENTMEMORY_DATA_DIR: /data
@@ -65,6 +65,13 @@ services:
AGENTMEMORY_AUDIT_MIGRATE_MAX_BYTES: "${AGENTMEMORY_AUDIT_MIGRATE_MAX_BYTES:-}"
AGENTMEMORY_STATE_SAVE_INTERVAL_MS: "${AGENTMEMORY_STATE_SAVE_INTERVAL_MS:-}"
AGENTMEMORY_LOCAL_DISPATCH: "${AGENTMEMORY_LOCAL_DISPATCH:-}"
+ AGENTMEMORY_BINDINGS: "${AGENTMEMORY_BINDINGS:-}"
+ AGENTMEMORY_STATE_READY_TIMEOUT_MS: "${AGENTMEMORY_STATE_READY_TIMEOUT_MS:-}"
+ AGENTMEMORY_ROUTE_MAX_IN_FLIGHT: "${AGENTMEMORY_ROUTE_MAX_IN_FLIGHT:-}"
+ AGENTMEMORY_COMPRESS_MAX_CONCURRENT: "${AGENTMEMORY_COMPRESS_MAX_CONCURRENT:-}"
+ AGENTMEMORY_COMPRESSION_SWEEP_MS: "${AGENTMEMORY_COMPRESSION_SWEEP_MS:-}"
+ AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS: "${AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS:-}"
+ AGENTMEMORY_GRAPH_STRUCTURAL: "${AGENTMEMORY_GRAPH_STRUCTURAL:-}"
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}"
AGENT_ID: "${AGENT_ID:-}"
TEAM_ID: "${TEAM_ID:-}"
diff --git a/docs/upgrades/iii-0.25.md b/docs/upgrades/iii-0.25.md
index 5ef252863a..730236d6b8 100644
--- a/docs/upgrades/iii-0.25.md
+++ b/docs/upgrades/iii-0.25.md
@@ -22,7 +22,11 @@ Existing file state remains at `state_store.db`; this upgrade does not convert o
- MCP tools, HTTP routes, capture, recall, search, export/import and the AgentMemory viewer keep their existing interfaces.
- The viewer remains on port 3113 by default. Live updates use authenticated SSE at `/agentmemory/viewer/events` on the REST port. Port 3112 is no longer used.
- `/agentmemory/status` reports the configured engine pin as `service.enginePinnedVersion`, replacing the old `engineVersion` field. This is the supported version, not a probe of an arbitrary remote engine.
-- `registerTrigger` and `registerTriggerType` remain supported by iii 0.25, with deprecation warnings. HTTP and state providers still use these APIs; their warnings do not mean route registration failed.
+- HTTP routes and state subscriptions are bound through `src/runtime/bindings.ts` (`getBindings(sdk).http/.state`). They are observers of `http::on-request` and `state::on-changed`. iii 0.26 removed triggers, so there is no `registerTrigger` fallback: `AGENTMEMORY_BINDINGS=trigger` is treated as `AGENTMEMORY_BINDINGS=inline`, which keeps routes and state subscriptions on observers and runs only the post-capture pipeline inline. See the [iii 0.26 upgrade guide](iii-0.26.md). `AGENTMEMORY_STATE_READY_TIMEOUT_MS` (1000-600000, default 60000) bounds the state-worker readiness probe before boot reads; late arrival is covered by event-driven re-arm. `AGENTMEMORY_ROUTE_MAX_IN_FLIGHT` (1-65536, default 1024) bounds concurrent deliveries per observer-bound route.
+
+### Background work runs through observers
+
+With `AGENTMEMORY_BINDINGS` unset or `auto` (and an SDK that supports `observe`), background work is dispatched by engine observers instead of inline fire-and-forget triggers: per-observation LLM compression follows `mem::observe` output (`agentmemory:pipeline:compress-on-capture`, bounded by `AGENTMEMORY_COMPRESS_MAX_CONCURRENT`, default 2), post-session graph extraction/reflection/consolidation follow `event::session::stopped`, and graph extraction on `mem::remember` is observe-only. `AGENTMEMORY_COMPRESSION_SWEEP_MS` (default 600000, 0 disables) runs a recovery sweep for observations still pending compression. `AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS` (default 0) rate-limits per-session delta extraction, `AGENTMEMORY_GRAPH_STRUCTURAL=false` disables the heuristic graph pass (LLM pass only), and per-session markers in `mem:graph:extract-marks` dedupe extraction to new observations only. Function failures feed `mem::record-failure` through error and soft-failure observers (`agentmemory:pipeline:failure::*`) that write `*-failed` audit rows and move the status `failures` counters (#766). State observers cascade deletes (`agentmemory:cascade:deleted` → `mem::on-record-deleted` clears BM25/vector/facet entries and reconciles session counts, #1624) and react to `mem:relations` rows (`agentmemory:cascade:relation-reaction` → `event::graph::edge-reaction` applies supersedes/contradicts/extends effects, #768). With `AGENTMEMORY_BINDINGS=inline`, these pipeline steps run as direct calls instead of observers.
- iii 0.25 can dispatch calls to a worker's own functions locally. Engine-side spans differ for those calls; SDK tracing and state-worker persistence still apply.
- Local dispatch is on by default, so AgentMemory's internal calls to its own functions run in-process and produce only the SDK's execute span, not an engine call span. Set `AGENTMEMORY_LOCAL_DISPATCH=false` for full engine traces at the cost of a round trip per call.
diff --git a/docs/upgrades/iii-0.26.md b/docs/upgrades/iii-0.26.md
new file mode 100644
index 0000000000..3d35e42113
--- /dev/null
+++ b/docs/upgrades/iii-0.26.md
@@ -0,0 +1,30 @@
+# Upgrading the AgentMemory runtime to iii 0.26
+
+This release pins the engine, `iii-sdk` and `@iii-dev/helpers` to 0.26.0. Worker Compose starts the `state@0.23.1` and `http@0.23.2` registry workers, the releases built for the 0.26 observer model. Coming from a release older than 0.25, read the [iii 0.25 upgrade guide](iii-0.25.md) first.
+
+## Before upgrading
+
+Stop the running instance with its currently installed CLI, then install and start the new one:
+
+```sh
+agentmemory stop
+npm install -g @agentmemory/agentmemory@latest
+agentmemory
+agentmemory status
+```
+
+Use the same `--instance`, `--port` and `--data-dir` flags you used to start it. Data at `state_store.db` and in `~/.agentmemory` is kept as is; this upgrade does not convert or delete it. The engine and the state and http workers must move together: a 0.25 worker that binds with triggers gets no events from a 0.26 engine, so the CLI never mixes versions.
+
+## What changed
+
+- iii 0.26 removes triggers. Every HTTP route is an observer of `http::on-request` with the route as `args` (`method`, `path`, `middleware_function_ids`), and every state subscription is an observer of `state::on-changed` with filters on `input.scope` and `input.key`. Routes, paths and responses are unchanged.
+- The trigger fallback is gone. `AGENTMEMORY_BINDINGS=trigger` is treated as `AGENTMEMORY_BINDINGS=inline` with a warning: routes and state subscriptions still use observers, and only the post-capture pipeline (compression, post-session graph, reflection and consolidation) runs inline.
+- Observers use `capture` only. Background observers receive the `Observed` payload and read the event from its `input` or `output`; HTTP route handlers still receive the `HttpRequest`.
+- Failure audit observers capture `["input", "error"]` with an `error` filter for thrown errors, and `["input", "output"]` with an `output.success == false` filter for soft failures.
+- When the state or http worker has not registered within 30 seconds of boot, `runtime.bindings` in `/agentmemory/status` reports that provider as `pending` instead of falling back. Its observers attach as soon as the worker connects.
+- A pipeline step runs as a direct call while its own observer is not active (pending, rejected or suspended), so compression and post-session work keep running. `runtime.bindings.reasons` lists the steps that use direct calls.
+- The compression sweep retries a failed compression at most 5 times and sends pending observations before failed ones.
+
+## Custom deployments
+
+Custom Compose manifests must pin `state` 0.23.x and `http` 0.23.x with a 0.26 engine. An `iii-sandbox` entry under `engine.workers` or in `config.yaml` is refused by 0.26; see the [iii 0.26 migration guide](https://iii.dev/docs/upgrading/from-0-25-x).
diff --git a/eval/README.md b/eval/README.md
index eaa9b3ef58..f03708af9c 100644
--- a/eval/README.md
+++ b/eval/README.md
@@ -15,7 +15,7 @@ npm run eval:lifecycle
npm run eval:recall
```
-The defaults are local and require no model API keys. The HTTP adapter and lifecycle suite require an installed **iii 0.25.1** binary, matching the version pinned by the CLI. Set `AGENTMEMORY_EVAL_III` to its absolute path, or use the binary installed by AgentMemory at `~/.agentmemory/bin/iii`.
+The defaults are local and require no model API keys. The HTTP adapter and lifecycle suite require an installed **iii 0.26.0** binary, matching the version pinned by the CLI. Set `AGENTMEMORY_EVAL_III` to its absolute path, or use the binary installed by AgentMemory at `~/.agentmemory/bin/iii`.
Each HTTP case launches the actual built CLI in a new temporary home, state directory, and port block, with an environment that excludes provider credentials. It uses the noop compression provider, with automatic compression, consolidation, and graph extraction disabled. The parent home and existing daemon are not used. Cleanup runs even after a failed query. `AGENTMEMORY_EVAL_KEEP=1` preserves scratch files for diagnosis; the daemon still stops. This sandbox supports macOS/Linux and needs permission to bind local ports.
diff --git a/examples/python/README.md b/examples/python/README.md
index 6265cdc3ed..60f0db98f5 100644
--- a/examples/python/README.md
+++ b/examples/python/README.md
@@ -10,7 +10,7 @@ This example uses the official Python SDK.
## Install
```bash
-pip install iii-sdk==0.25.1
+pip install iii-sdk==0.26.0
```
## Quickstart
diff --git a/examples/python/observe_and_recall.py b/examples/python/observe_and_recall.py
index 4b6626169f..32fed16e73 100644
--- a/examples/python/observe_and_recall.py
+++ b/examples/python/observe_and_recall.py
@@ -4,7 +4,7 @@
agentmemory to render the most relevant context back at a fixed token budget.
Prerequisites:
- pip install iii-sdk==0.25.1
+ pip install iii-sdk==0.26.0
npx -y @agentmemory/agentmemory
Run:
diff --git a/examples/python/quickstart.py b/examples/python/quickstart.py
index 7a2ef3a8bb..576f2d3063 100644
--- a/examples/python/quickstart.py
+++ b/examples/python/quickstart.py
@@ -1,7 +1,7 @@
"""Minimal agentmemory usage via iii-sdk.
Prerequisites:
- pip install iii-sdk==0.25.1
+ pip install iii-sdk==0.26.0
npx -y @agentmemory/agentmemory # daemon at ws://127.0.0.1:49134
Run:
diff --git a/package.json b/package.json
index 5540b52f8f..892b38d907 100644
--- a/package.json
+++ b/package.json
@@ -91,8 +91,8 @@
"@anthropic-ai/sdk": "^0.100.1",
"@clack/prompts": "^1.2.0",
"dotenv": "^18.0.3",
- "@iii-dev/helpers": "0.25.1",
- "iii-sdk": "0.25.1",
+ "@iii-dev/helpers": "0.26.0",
+ "iii-sdk": "0.26.0",
"picocolors": "^1.1.1",
"zod": "^4.0.0",
"yaml": "^2.8.1",
diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md
index e3439400a4..5211bbddba 100644
--- a/plugin/skills/agentmemory-config/REFERENCE.md
+++ b/plugin/skills/agentmemory-config/REFERENCE.md
@@ -3,7 +3,7 @@
Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded.
-Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 83 recognized variables:
+Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 90 recognized variables:
- `AGENTMEMORY_AGENT_SCOPE`
- `AGENTMEMORY_ALLOW_AGENT_SDK`
@@ -11,6 +11,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_AUDIT_MIGRATE_MAX_BYTES`
- `AGENTMEMORY_AUDIT_RETENTION_MONTHS`
- `AGENTMEMORY_AUTO_COMPRESS`
+- `AGENTMEMORY_BINDINGS`
- `AGENTMEMORY_CALL_TIMEOUT_MS`
- `AGENTMEMORY_CAPTURE_ALLOW`
- `AGENTMEMORY_CAPTURE_DEAD_MAX`
@@ -27,6 +28,8 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_CAPTURE_SPOOL_MAX_AGE_HOURS`
- `AGENTMEMORY_CAPTURE_SPOOL_MAX_BYTES`
- `AGENTMEMORY_COMMIT_SHA`
+- `AGENTMEMORY_COMPRESSION_SWEEP_MS`
+- `AGENTMEMORY_COMPRESS_MAX_CONCURRENT`
- `AGENTMEMORY_CONSOLIDATION_COOLDOWN_MS`
- `AGENTMEMORY_COPILOT_MCP_BLOCK`
- `AGENTMEMORY_CREDENTIAL_MODE`
@@ -44,8 +47,10 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS`
- `AGENTMEMORY_FORCE_PROXY`
- `AGENTMEMORY_GRAPH_COMPACT_ON_BOOT`
+- `AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS`
- `AGENTMEMORY_GRAPH_IMPORT_MAX_EDGES`
- `AGENTMEMORY_GRAPH_IMPORT_MAX_NODES`
+- `AGENTMEMORY_GRAPH_STRUCTURAL`
- `AGENTMEMORY_GRAPH_WEIGHT`
- `AGENTMEMORY_III_VERSION`
- `AGENTMEMORY_IMAGE_EMBEDDINGS`
@@ -66,6 +71,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_READY_TIMEOUT_MS`
- `AGENTMEMORY_REDIS_URL`
- `AGENTMEMORY_REFLECT`
+- `AGENTMEMORY_ROUTE_MAX_IN_FLIGHT`
- `AGENTMEMORY_RUNTIME_DIR`
- `AGENTMEMORY_SDK_CHILD`
- `AGENTMEMORY_SECRET`
@@ -75,6 +81,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_SESSION_SWEEP_STALE_HOURS`
- `AGENTMEMORY_SLOTS`
- `AGENTMEMORY_STATE_BACKEND`
+- `AGENTMEMORY_STATE_READY_TIMEOUT_MS`
- `AGENTMEMORY_STATE_SAVE_INTERVAL_MS`
- `AGENTMEMORY_SUMMARY_TIMEOUT_MS`
- `AGENTMEMORY_SUPPRESS_COST_WARNING`
diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json
index 7f6afbb042..6e4748561c 100644
--- a/scripts/docs-sync.state.json
+++ b/scripts/docs-sync.state.json
@@ -20,20 +20,20 @@
"12"
],
"tests": [
- "4900+"
+ "5000+"
],
"functions": [
- "323"
+ "320"
],
"sourceFiles": [
- "262"
+ "271"
],
"loc": [
- "62000"
+ "63000"
],
"kvScopes": [
- "65"
+ "67"
]
},
- "engineVersion": "0.25.1"
+ "engineVersion": "0.26.0"
}
diff --git a/scripts/release-gate/graph-index.mjs b/scripts/release-gate/graph-index.mjs
index 47793288b5..a620f871df 100644
--- a/scripts/release-gate/graph-index.mjs
+++ b/scripts/release-gate/graph-index.mjs
@@ -124,7 +124,7 @@ async function profile(name, instance = 0, sharedHome) {
"containers:",
" state:",
" worker: 'package://api.workers.iii.dev/state'",
- " version: '0.22.22'",
+ " version: '0.23.1'",
" config_name: state",
" config_override:",
" adapter:",
@@ -135,7 +135,7 @@ async function profile(name, instance = 0, sharedHome) {
" save_interval_ms: 2000",
" http:",
" worker: 'package://api.workers.iii.dev/http'",
- " version: '0.22.8'",
+ " version: '0.23.2'",
" config_name: http",
" config_override:",
" host: 127.0.0.1",
diff --git a/scripts/release-gate/large-store.mjs b/scripts/release-gate/large-store.mjs
index eaab957052..658fbdd948 100644
--- a/scripts/release-gate/large-store.mjs
+++ b/scripts/release-gate/large-store.mjs
@@ -317,7 +317,9 @@ async function probe(name, path, body, { allowRefusal = false } = {}) {
const detail = json && typeof json === "object" ? json.error ?? json.message : undefined;
if (detail) result.error = String(typeof detail === "string" ? detail : JSON.stringify(detail)).slice(0, 500);
else if (json && typeof json === "object" && json.success === false) result.error = "success:false";
- } catch {}
+ } catch {
+ if (/^\s*\{\s*"success"\s*:\s*false\b/.test(text)) result.error = "success:false";
+ }
if (!result.error && res.status >= 400) result.error = `HTTP ${res.status}`;
} catch (cause) {
result.error = String(cause?.message ?? cause).slice(0, 500);
diff --git a/scripts/release-gate/startup.mjs b/scripts/release-gate/startup.mjs
index e9bfe0f0c4..3958d77223 100644
--- a/scripts/release-gate/startup.mjs
+++ b/scripts/release-gate/startup.mjs
@@ -229,7 +229,7 @@ class Instance {
"containers:",
" state:",
` worker: ${quote(localWorkers ? `path://${join(this.data, "local-workers/state")}` : "package://api.workers.iii.dev/state")}`,
- ...(!localWorkers ? [" version: '0.22.22'"] : []),
+ ...(!localWorkers ? [" version: '0.23.1'"] : []),
" config_name: state",
...(localWorkers ? [" scripts:", ` run: ${quote(join(localWorkers, "state"))}`] : []),
" config_override:",
@@ -241,7 +241,7 @@ class Instance {
` file_path: ${quote(join(this.data, "state_store.db"))}`,
" http:",
` worker: ${quote(localWorkers ? `path://${join(this.data, "local-workers/http")}` : "package://api.workers.iii.dev/http")}`,
- ...(!localWorkers ? [" version: '0.22.8'"] : []),
+ ...(!localWorkers ? [" version: '0.23.2'"] : []),
" config_name: http",
...(localWorkers ? [" scripts:", ` run: ${quote(join(localWorkers, "http"))}`] : []),
" config_override:",
diff --git a/scripts/release-gate/vector-recovery.mjs b/scripts/release-gate/vector-recovery.mjs
index 49dd5af199..3a09b39d1b 100644
--- a/scripts/release-gate/vector-recovery.mjs
+++ b/scripts/release-gate/vector-recovery.mjs
@@ -103,7 +103,7 @@ const config = [
"containers:",
" state:",
" worker: 'package://api.workers.iii.dev/state'",
- " version: '0.22.22'",
+ " version: '0.23.1'",
" config_name: state",
" config_override:",
" adapter:",
@@ -114,7 +114,7 @@ const config = [
" save_interval_ms: 2000",
" http:",
" worker: 'package://api.workers.iii.dev/http'",
- " version: '0.22.8'",
+ " version: '0.23.2'",
" config_name: http",
" config_override:",
" host: 127.0.0.1",
diff --git a/scripts/skills/rest-endpoints.ts b/scripts/skills/rest-endpoints.ts
index d3f32b549e..a5a90b6337 100644
--- a/scripts/skills/rest-endpoints.ts
+++ b/scripts/skills/rest-endpoints.ts
@@ -16,9 +16,9 @@ export function collectRestEndpoints(...texts: string[]): { path: string; method
const rows = new Map();
const sources = texts.map((text, index) => ts.createSourceFile(`source-${index}.ts`, text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS));
function visit(node: ts.Node): void {
- if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "registerTrigger") {
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "http") {
const registration = node.arguments[0];
- if (registration && ts.isObjectLiteralExpression(registration) && literal(property(registration, "type")) === "http") {
+ if (registration && ts.isObjectLiteralExpression(registration)) {
const config = property(registration, "config");
if (config && ts.isObjectLiteralExpression(config)) {
const path = literal(property(config, "api_path"));
diff --git a/src/cli-data-dir.ts b/src/cli-data-dir.ts
index e27fc60a90..4a494e6553 100644
--- a/src/cli-data-dir.ts
+++ b/src/cli-data-dir.ts
@@ -137,3 +137,22 @@ export function resolveDataDir(options: ResolveDataDirOptions = {}): ResolvedDat
source: "default",
};
}
+
+export function managedRuntimeDirs(options: ResolveDataDirOptions = {}): string[] {
+ const args = options.args ?? process.argv.slice(2);
+ const home = options.home ?? homedir();
+ const baseArgs: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === "--instance") {
+ i++;
+ continue;
+ }
+ if (args[i]!.startsWith("--instance=")) continue;
+ baseArgs.push(args[i]!);
+ }
+ const dirs = [join(home, ".agentmemory")];
+ for (let instance = 1; instance <= 50; instance++) {
+ dirs.push(resolveDataDir({ ...options, args: [...baseArgs, "--instance", String(instance)] }).dataDir);
+ }
+ return dirs;
+}
diff --git a/src/cli.ts b/src/cli.ts
index a1f6c0e611..3fc7d1e051 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -98,12 +98,12 @@ import { knownAgents } from "./cli/connect/index.js";
const ALL_TOOLS_COUNT = getAllTools().length;
const CORE_TOOLS_COUNT = getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name)).length;
-import { resolveDataDir } from "./cli-data-dir.js";
+import { managedRuntimeDirs, resolveDataDir } from "./cli-data-dir.js";
import { runCaptureCommand } from "./cli/capture.js";
import { runCompressionCommand } from "./cli/compression.js";
import { runGraphIndexCommand } from "./cli/graph-index.js";
import { bearerHeaders, resolveClientSecret } from "./secret-store.js";
-import { assertComposePortsFree, composeCall, composeRegistryFailureMessage, composeStateRegistryFailure, composeWorkerFailureSummary, ownedComposeProject, readComposeLogFromOffset, startComposeDaemon, writeComposeState, type ComposeStatus } from "./cli/compose-control.js";
+import { assertComposePortsFree, composeCall, composeRegistryFailureMessage, composeRuntimeVersionMismatch, composeStateRegistryFailure, composeWorkerFailureSummary, ownedComposeProject, readComposeLogFromOffset, startComposeDaemon, writeComposeState, type ComposeStatus } from "./cli/compose-control.js";
import { COMPOSE_WORKER_VERSIONS, composeDownTimeoutMs, composeNamespace } from "./cli/compose-project.js";
import { legacyDockerStateMessage, type LegacyDockerEngineState } from "./cli/legacy-docker-state.js";
import { DEFAULT_START_COMMAND, engineOnlyLines, probeWorkerConnection, shellArg, tcpPortOpen, unrecognizedServiceLines, type WorkerConnection } from "./cli/worker-connection.js";
@@ -364,6 +364,7 @@ if (Number.isFinite(restPort) && restPort > 0) {
}
const dataDirResolution = resolveDataDir({ args });
+const unsuffixedDataDirEnv = process.env["AGENTMEMORY_DATA_DIR"];
process.env["AGENTMEMORY_DATA_DIR"] = dataDirResolution.dataDir;
process.env["AGENTMEMORY_RUNTIME_DIR"] = selectedInstance > 0
? dataDirResolution.dataDir
@@ -643,6 +644,7 @@ type ComposeEngineState = {
logFile: string;
logStartOffset?: number;
binPath: string;
+ engineVersion?: string;
composePid?: number;
enginePid?: number;
workerBinDir?: string;
@@ -698,9 +700,9 @@ function clearWorkerPidfile(): void {
} catch {}
}
-function readEngineState(): EngineState | null {
+function readEngineState(path: string = engineStatePath()): EngineState | null {
try {
- const raw = readFileSync(engineStatePath(), "utf-8");
+ const raw = readFileSync(path, "utf-8");
const parsed = JSON.parse(raw) as Partial;
if (parsed && (parsed.kind === "native" || parsed.kind === "docker" || parsed.kind === "compose")) {
return parsed as EngineState;
@@ -1274,6 +1276,7 @@ async function startIiiBin(iiiBin: string): Promise {
spawnedComposeDaemon = compose.child;
composeStartupCompleted = false;
if (typeof compose.child.pid !== "number") throw new Error("Failed to spawn the iii Compose daemon.");
+ const engineVersion = iiiBinVersion(iiiBin);
const state = {
kind: "compose" as const,
restPort: getRestPort(),
@@ -1286,6 +1289,7 @@ async function startIiiBin(iiiBin: string): Promise {
logFile: compose.logFile,
logStartOffset: compose.logStartOffset,
binPath: iiiBin,
+ ...(engineVersion ? { engineVersion } : {}),
composePid: compose.child.pid,
...(workerBinDir ? { workerBinDir: resolve(process.cwd(), workerBinDir) } : {}),
};
@@ -1583,6 +1587,11 @@ async function reconcilePersistedComposeEngine(): Promise {
p.log.error(`Compose metadata points to PID ${state.composePid}, but its process identity does not match the saved engine/file/namespace.`);
process.exit(1);
}
+ const staleRuntime = composeRuntimeVersionMismatch(state, IIPINNED_VERSION);
+ if (staleRuntime) {
+ p.log.error(`The running managed Compose engine/workers are an older version: ${staleRuntime}. Run agentmemory stop before changing the runtime.`);
+ process.exit(1);
+ }
if (version !== IIPINNED_VERSION) {
p.log.error(`Managed Compose engine is ${version ?? "unverified"}; expected ${IIPINNED_VERSION}. Run agentmemory stop before changing the runtime.`);
process.exit(1);
@@ -1597,6 +1606,27 @@ async function reconcilePersistedComposeEngine(): Promise {
return true;
}
+async function managedComposeEngineRunning(): Promise {
+ const own = engineStatePath();
+ if (await composeStateRunning(readEngineState(own), true)) return true;
+ const baseEnv = { ...process.env, AGENTMEMORY_DATA_DIR: unsuffixedDataDirEnv };
+ if (unsuffixedDataDirEnv === undefined) delete baseEnv["AGENTMEMORY_DATA_DIR"];
+ for (const dir of managedRuntimeDirs({ args, env: baseEnv })) {
+ const path = runtimeMetadataPath("engine-state.json", { env: { AGENTMEMORY_RUNTIME_DIR: dir } });
+ if (path === own) continue;
+ if (await composeStateRunning(readEngineState(path), false)) return true;
+ }
+ return false;
+}
+
+async function composeStateRunning(state: EngineState | null, own: boolean): Promise {
+ if (state?.kind !== "compose") return false;
+ if (state.composePid && pidAlive(state.composePid) && composePidIdentity(state.composePid, state) !== "foreign") return true;
+ if (own) return isEngineRunning();
+ const result = await withinStartupDeadline(startupDeadline(2000), (signal) => probeEngine(`http://127.0.0.1:${state.restPort}`, signal)).catch(() => null);
+ return result?.completed === true && result.value;
+}
+
async function main() {
startupTimeouts();
await assertRuntimePortOwnership();
@@ -2173,6 +2203,7 @@ function buildDoctorEffects(): DoctorEffects {
},
iiiBinaryVersion: (binPath: string) => iiiBinVersion(binPath),
externalEngineRunning: async () => !doctorTargetsManagedCompose() && await isEngineRunning(),
+ managedEngineRunning: managedComposeEngineRunning,
workerConnection: async () => {
const connection = await probeTargetWorker(getBaseUrl());
if (connection === "connected" || connection === "unreachable") return connection;
@@ -2189,6 +2220,18 @@ function buildDoctorEffects(): DoctorEffects {
return false;
}
},
+ daemonStatus: async () => {
+ try {
+ const base = getBaseUrl();
+ const res = await fetch(`${base}/agentmemory/status`, {
+ headers: bearerHeaders(base),
+ signal: AbortSignal.timeout(8000),
+ });
+ return res.ok ? (await res.json()) as never : null;
+ } catch {
+ return null;
+ }
+ },
runInit: async () => {
try {
await runInit();
@@ -2965,6 +3008,11 @@ function runCommand(
async function runUpgrade() {
p.intro("agentmemory upgrade");
+ if (await managedComposeEngineRunning()) {
+ p.log.error("A managed agentmemory engine is running. Upgrade replaces its iii binary and pinned workers, so run agentmemory stop first, then run agentmemory upgrade again.");
+ process.exit(1);
+ }
+
const cwd = process.cwd();
const hasPackageJson = existsSync(join(cwd, "package.json"));
const hasPnpmLock = existsSync(join(cwd, "pnpm-lock.yaml"));
@@ -3753,7 +3801,7 @@ async function runConsole(): Promise {
p.note([
`AgentMemory viewer: ${getViewerUrl()} (start agentmemory first if it is offline).`,
"Use agentmemory status for runtime health and worker status.",
- "Engine console migration: https://github.com/iii-hq/iii/blob/iii/v0.25.1/docs/using-iii/console.mdx",
+ "Engine console migration: https://github.com/iii-hq/iii/blob/iii/v0.26.0/docs/using-iii/console.mdx",
].join("\n"), "Console migration");
}
diff --git a/src/cli/compose-control.ts b/src/cli/compose-control.ts
index 6aea5df41c..59fc1cbd09 100644
--- a/src/cli/compose-control.ts
+++ b/src/cli/compose-control.ts
@@ -295,6 +295,7 @@ export function writeComposeState(path: string, state: {
logFile: string;
logStartOffset?: number;
binPath: string;
+ engineVersion?: string;
enginePid?: number;
workerBinDir?: string;
workerFailure?: string;
@@ -305,3 +306,21 @@ export function writeComposeState(path: string, state: {
chmodSync(path, 0o600);
}
+export function composeRuntimeVersionMismatch(state: {
+ engineVersion?: string;
+ workerVersions?: Partial> | { local: true };
+}, pinnedEngineVersion: string): string | null {
+ const stale: string[] = [];
+ if (state.engineVersion && state.engineVersion !== pinnedEngineVersion) {
+ stale.push(`engine ${state.engineVersion} (expected ${pinnedEngineVersion})`);
+ }
+ const workers = state.workerVersions;
+ if (workers && !("local" in workers && workers.local === true)) {
+ const running = workers as Partial>;
+ for (const [name, pinned] of Object.entries(COMPOSE_WORKER_VERSIONS)) {
+ if (running[name] !== pinned) stale.push(`${name} worker ${running[name] ?? "unknown"} (expected ${pinned})`);
+ }
+ }
+ return stale.length ? stale.join(", ") : null;
+}
+
diff --git a/src/cli/compose-project.ts b/src/cli/compose-project.ts
index 21957a44c1..9b3a6a8f8f 100644
--- a/src/cli/compose-project.ts
+++ b/src/cli/compose-project.ts
@@ -17,8 +17,8 @@ export interface StateBackendOptions {
/** Registry versions are pinned here so every generated project uses one reviewed set. */
export const COMPOSE_WORKER_VERSIONS = {
- state: "0.22.22",
- http: "0.22.8",
+ state: "0.23.1",
+ http: "0.23.2",
} as const;
export const COMPOSE_STOP_TIMEOUT_SECONDS = 20;
@@ -89,6 +89,13 @@ const AGENTMEMORY_WORKER_ENV_ALLOWLIST = new Set([
"OBSIDIAN_AUTO_EXPORT", "AUTO_FORGET_ENABLED", "AUTO_FORGET_INTERVAL_MS", "LESSON_DECAY_ENABLED",
"INSIGHT_DECAY_ENABLED", "REBUILD_EMBED_BATCH_SIZE", "RERANK_ENABLED",
"AGENTMEMORY_LOCAL_DISPATCH",
+ "AGENTMEMORY_BINDINGS",
+ "AGENTMEMORY_STATE_READY_TIMEOUT_MS",
+ "AGENTMEMORY_ROUTE_MAX_IN_FLIGHT",
+ "AGENTMEMORY_COMPRESS_MAX_CONCURRENT",
+ "AGENTMEMORY_COMPRESSION_SWEEP_MS",
+ "AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS",
+ "AGENTMEMORY_GRAPH_STRUCTURAL",
]);
const COMPOSE_RESERVED_ENV = new Set([
diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts
index 3063f49fe9..31501e3d24 100644
--- a/src/cli/doctor-diagnostics.ts
+++ b/src/cli/doctor-diagnostics.ts
@@ -57,6 +57,10 @@ export type DoctorContext = {
export type DoctorWorkerConnection = WorkerConnection | "managed-worker-down";
+function managedEngineRunningMessage(targetArgs = ""): string {
+ return `A managed agentmemory engine is running from the iii binary the installer would replace. Run agentmemory stop${targetArgs} first, then run the fix again.`;
+}
+
export type Diagnostic = {
/** Stable id. Used in --json and tests. */
id: string;
@@ -104,6 +108,7 @@ export const DIAGNOSTIC_IDS = [
"stale-pidfile",
"env-placeholder-keys",
"iii-on-path-not-local-bin",
+ "duplicate-workers",
] as const;
export type DiagnosticId = (typeof DIAGNOSTIC_IDS)[number];
@@ -156,9 +161,12 @@ export type DoctorEffects = {
/** Run `iii --version`; null if it fails. */
iiiBinaryVersion: (binPath: string) => string | null;
externalEngineRunning: () => Promise;
+ managedEngineRunning: () => Promise;
workerConnection: () => Promise;
/** Probe the viewer URL; true if it returns OK within timeoutMs. */
viewerReachable: (timeoutMs?: number) => Promise;
+ /** Fetch the running daemon's status report; null when unreachable. */
+ daemonStatus: () => Promise<{ runtime?: { duplicateWorkers?: { count: number; workerIds: string[] } | null } } | null>;
/** Run init logic (copies .env.example). */
runInit: () => Promise;
/** Open a file in $EDITOR (or fallback). Resolves when editor exits. */
@@ -292,10 +300,13 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] {
detail: `${pathVersion} (pinned ${ctx.pinnedVersion})`,
};
},
- fix: async () => {
+ fix: async (ctx) => {
if (await effects.externalEngineRunning()) {
return { ok: false, message: "Verify or stop the external engine manually." };
}
+ if (await effects.managedEngineRunning()) {
+ return { ok: false, message: managedEngineRunningMessage(ctx.targetArgs) };
+ }
const r = await effects.runIiiInstaller();
if (!r.ok) return r;
// Best-effort restart: stop then start.
@@ -447,14 +458,41 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] {
}
return { ok: false, detail };
},
- fix: async () =>
- effects.runIiiInstaller().then((r) => ({
+ fix: async (ctx) => {
+ if (await effects.managedEngineRunning()) {
+ return { ok: false, message: managedEngineRunningMessage(ctx.targetArgs) };
+ }
+ return effects.runIiiInstaller().then((r) => ({
ok: r.ok,
message:
r.message ??
"Installer wrote to ~/.agentmemory/bin/iii. Your PATH wasn't modified.",
- })),
+ }));
+ },
},
+ {
+ id: "duplicate-workers",
+ message: "More than one agentmemory worker is registered to the engine.",
+ fixPreview: "Stop the extra daemon with `agentmemory stop`, or run `agentmemory status` to see the registered workers.",
+ moreInfo:
+ "The engine owns each function id to one worker per namespace, so a second agentmemory worker " +
+ "is rejected and fails. This happens when two daemons (or a stale process from an older install) " +
+ "share one engine and namespace.",
+ manualOnly: true,
+ check: async () => {
+ const status = await effects.daemonStatus();
+ const dup = status?.runtime?.duplicateWorkers;
+ if (dup && dup.count > 1) {
+ return { ok: false, detail: `${dup.count} workers: ${dup.workerIds.join(", ")}` };
+ }
+ return { ok: true, detail: status === null ? "status endpoint unreachable; check skipped" : undefined };
+ },
+ fix: async () => ({
+ ok: false,
+ message: "Stop the extra daemon with `agentmemory stop`, then restart with `agentmemory start`.",
+ }),
+ },
+
];
}
diff --git a/src/cli/engine-install.ts b/src/cli/engine-install.ts
index 790258cf53..d92a5c3fd5 100644
--- a/src/cli/engine-install.ts
+++ b/src/cli/engine-install.ts
@@ -15,6 +15,15 @@ const RETRYABLE_HTTP_STATUS = new Set([408, 429, 500, 502, 503, 504]);
type ChecksumTable = Readonly>>>;
export const III_RELEASE_SHA256: ChecksumTable = {
+ "0.26.0": {
+ "iii-aarch64-apple-darwin.tar.gz": "2730296a08ae5843757b2e7913ad65b6282901c98b951dbc23018e0eb425e285",
+ "iii-x86_64-apple-darwin.tar.gz": "5f98e6679e8489947c1383377fda8a620c2e014f68005018886d673efaf85967",
+ "iii-x86_64-unknown-linux-gnu.tar.gz": "f241cd8bce013851b2825dd49d7b6c317476fa068c039688f300effa50d04c0b",
+ "iii-aarch64-unknown-linux-gnu.tar.gz": "e2ee44d1eb38f0e337d3e77b3b8601da26ff1bd934cc8a4c849b9bcf414ab40b",
+ "iii-armv7-unknown-linux-gnueabihf.tar.gz": "9f8772235fb4c542b2f692520d16ec7095240071606b969ff1bbfbe471bc0a54",
+ "iii-x86_64-pc-windows-msvc.zip": "3df9e089826f26ddc157d2e504a8e3aa11b9bc5fe21b3faeece85599b21c7081",
+ "iii-aarch64-pc-windows-msvc.zip": "ac3a94945741b7194f678347a7275524a63c5e4261cb2bcf34a9ae51d68ccaf0",
+ },
"0.25.1": {
"iii-aarch64-apple-darwin.tar.gz": "f7eff803540436a4964958048abc0083e638f53b500d737819f62913c270f141",
"iii-x86_64-apple-darwin.tar.gz": "d93511a72336c19a6028a18f43819e6b3c49522589fc6303f0a0880b3f02d8ae",
diff --git a/src/config.ts b/src/config.ts
index b1472436c3..1a9031645f 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -614,6 +614,35 @@ export function isAutoCompressEnabled(): boolean {
return getMergedEnv()["AGENTMEMORY_AUTO_COMPRESS"] === "true";
}
+export function compressMaxConcurrent(): number {
+ const raw = getMergedEnv()["AGENTMEMORY_COMPRESS_MAX_CONCURRENT"];
+ if (raw === undefined) return 2;
+ const parsed = Number(raw);
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 32) return 2;
+ return parsed;
+}
+
+export function compressionSweepMs(): number {
+ const raw = getMergedEnv()["AGENTMEMORY_COMPRESSION_SWEEP_MS"];
+ if (raw === undefined || raw.trim() === "") return 600_000;
+ const parsed = Number(raw);
+ if (parsed === 0) return 0;
+ if (!Number.isInteger(parsed) || parsed < 60_000 || parsed > 86_400_000) return 600_000;
+ return parsed;
+}
+
+export function graphExtractCooldownMs(): number {
+ const raw = getMergedEnv()["AGENTMEMORY_GRAPH_EXTRACT_COOLDOWN_MS"];
+ if (raw === undefined) return 0;
+ const parsed = Number(raw);
+ if (!Number.isInteger(parsed) || parsed < 0 || parsed > 86_400_000) return 0;
+ return parsed;
+}
+
+export function isGraphStructuralEnabled(): boolean {
+ return getMergedEnv()["AGENTMEMORY_GRAPH_STRUCTURAL"] !== "false";
+}
+
// Hook-level context injection into Claude Code's conversation is OFF by
// default as of 0.8.10. When disabled, pre-tool-use and
// session-start hooks still POST observations for background capture, but
diff --git a/src/functions/cascade-audit.ts b/src/functions/cascade-audit.ts
new file mode 100644
index 0000000000..3dc5ada85d
--- /dev/null
+++ b/src/functions/cascade-audit.ts
@@ -0,0 +1,420 @@
+import type { IIIClient } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import { withKeyedLock, withReentrantKeyedLock } from "../state/keyed-mutex.js";
+import type { AuditEntry, Memory, MemoryRelation, RelationReactionMark, Session } from "../types.js";
+import { recordAudit } from "./audit.js";
+import { deleteFacetsCascade } from "./facets.js";
+import { getSearchIndex, scheduleIndexSave, vectorIndexAddGuarded, vectorIndexRemove } from "./search.js";
+import { memoryToObservation, observationEmbedText } from "../state/memory-utils.js";
+import { singleFlight } from "../runtime/recovery.js";
+import { logger } from "../logger.js";
+import { registerObserverTarget } from "../runtime/observed.js";
+
+const FAILURE_OPS: Record = {
+ "mem::compress": "compress-failed",
+ "mem::summarize": "summarize-failed",
+ "mem::graph-extract": "graph-extract-failed",
+ "mem::consolidate-pipeline": "consolidate-failed",
+ "mem::reflect": "reflect-failed",
+ "mem::skill-extract": "skill-extract-failed",
+};
+
+const RETRYABLE_CODES = new Set([
+ "compression_timeout", "timeout", "ECONNRESET", "ECONNREFUSED", "ETIMEDOUT",
+ "circuit_breaker_open", "parse_failed", "empty_response", "overloaded", "compression_failed",
+]);
+const PERMANENT_CODES = new Set([
+ "source_unavailable", "invalid_raw_observation", "invalid_observation_identity",
+ "observation_changed", "observation_not_found", "prompt_too_long", "content_policy",
+]);
+
+function failureCode(envelope: Record): string {
+ const err = envelope.error as { code?: string; status?: number } | undefined;
+ if (err?.code) return err.code;
+ const output = envelope.output as { error?: string; code?: string } | undefined;
+ if (typeof output?.error === "string") return output.error;
+ if (typeof output?.code === "string") return output.code;
+ if (typeof err?.status === "number") return `http_${err.status}`;
+ return "unknown";
+}
+
+function isRetryable(code: string, envelope: Record): boolean {
+ if (RETRYABLE_CODES.has(code)) return true;
+ if (PERMANENT_CODES.has(code)) return false;
+ const err = envelope.error as { status?: number; statusCode?: number } | undefined;
+ const status = err?.status ?? err?.statusCode;
+ if (typeof status === "number") return status === 429 || status >= 500;
+ if (code.startsWith("invalid_")) return false;
+ if (code.includes("timeout") || code.includes("unavailable")) return true;
+ return false;
+}
+
+const DEDUPE_WINDOW_MS = 60_000;
+const DEDUPE_MAX = 512;
+const dedupe = new Map();
+const counters = { transient: 0, permanent: 0, lastAt: null as string | null };
+
+export function failureCounters(): { transient: number; permanent: number; lastAt: string | null } {
+ return { ...counters };
+}
+
+function extractTargetIds(envelope: Record): string[] {
+ const input = (envelope.input ?? {}) as Record;
+ const ids = [input.observationId, input.sessionId, input.memoryId, input.id]
+ .filter((v): v is string => typeof v === "string" && v.length > 0);
+ const obs = input.observations;
+ if (Array.isArray(obs)) {
+ for (const o of obs.slice(0, 10)) {
+ if (o && typeof o.id === "string" && !ids.includes(o.id)) ids.push(o.id);
+ }
+ }
+ return [...new Set(ids)].slice(0, 20);
+}
+
+function pruneDedupe(now: number): void {
+ if (dedupe.size <= DEDUPE_MAX) return;
+ for (const [k, v] of dedupe) {
+ if (now - v.seenAt > DEDUPE_WINDOW_MS) dedupe.delete(k);
+ }
+ while (dedupe.size > DEDUPE_MAX) {
+ const first = dedupe.keys().next().value;
+ if (first === undefined) break;
+ dedupe.delete(first);
+ }
+}
+
+const DELETE_BATCH_MS = 500;
+const DELETE_BATCH_MAX = 200;
+const DELETE_BACKOFF_MAX_MS = 30_000;
+type PendingDelete = { id: string; kind: "memory" | "observation" | "lesson"; sessionId?: string; removeIndex?: boolean };
+const pendingDeletes = new Map();
+const pendingSessions = new Set();
+let deleteTimer: ReturnType | null = null;
+let deleteFlusher: (() => Promise) | null = null;
+let deleteDelayMs = DELETE_BATCH_MS;
+
+function scheduleDeleteFlush(): void {
+ if (deleteTimer) return;
+ deleteTimer = setTimeout(() => { deleteTimer = null; void flushDeleteCascade().catch(() => reportFlushFailure()); }, deleteDelayMs);
+ deleteTimer.unref();
+}
+
+function reportFlushFailure(): void {
+ scheduleDeleteFlush();
+}
+
+function queueDeleteCascade(item: PendingDelete): void {
+ const key = `${item.kind}:${item.id}`;
+ const queued = pendingDeletes.get(key);
+ pendingDeletes.set(key, queued?.removeIndex ? { ...item, removeIndex: true } : item);
+ if (item.sessionId) pendingSessions.add(item.sessionId);
+ if (pendingDeletes.size >= DELETE_BATCH_MAX) void flushDeleteCascade().catch(() => reportFlushFailure());
+ else scheduleDeleteFlush();
+}
+
+async function deleteTargetGone(kv: StateKV, item: PendingDelete): Promise {
+ if (item.kind === "memory") return (await kv.get(KV.memories, item.id)) === null;
+ if (item.kind === "observation" && item.sessionId) {
+ return (await kv.get(KV.observations(item.sessionId), item.id)) === null;
+ }
+ if (item.kind === "lesson") {
+ const lesson = await kv.get<{ deleted?: boolean }>(KV.lessons, item.id);
+ return lesson === null || lesson.deleted === true;
+ }
+ return true;
+}
+
+const UNSET_MEMORY_CONFIDENCE = 0.5;
+
+function contradictFloor(base: number, penalties: Record): number {
+ return Math.max(0.05, base - Object.values(penalties).reduce((sum, p) => sum + p, 0));
+}
+
+const KIND_TARGET_TYPE: Record = { memory: "memory", observation: "observation", lesson: "memory" };
+
+const SUPERSEDES_WALK_MAX = 1000;
+
+async function supersedesReaches(kv: StateKV, fromId: string, toId: string): Promise {
+ const seen = new Set([fromId]);
+ const frontier = [fromId];
+ while (frontier.length > 0 && seen.size <= SUPERSEDES_WALK_MAX) {
+ const id = frontier.shift()!;
+ const mark = await kv.get(KV.relationReactions, `${id}:supersedes`);
+ for (const sourceId of Object.values(mark?.sources ?? {})) {
+ if (sourceId === toId) return true;
+ if (seen.has(sourceId)) continue;
+ seen.add(sourceId);
+ frontier.push(sourceId);
+ }
+ }
+ return false;
+}
+
+async function commitReaction(
+ kv: StateKV,
+ targetId: string,
+ target: Memory,
+ markKey: string,
+ mark: RelationReactionMark,
+ removeMark: boolean,
+): Promise {
+ const { isLatest, strength, confidence, relatedIds } = target;
+ await kv.set(KV.relationReactions, markKey, { ...mark, pending: { target: { isLatest, strength, confidence, relatedIds }, removeMark } });
+ await kv.set(KV.memories, targetId, target);
+ if (removeMark) await kv.delete(KV.relationReactions, markKey);
+ else await kv.set(KV.relationReactions, markKey, mark);
+}
+
+async function settlePendingReaction(
+ kv: StateKV,
+ targetId: string,
+ target: Memory,
+ markKey: string,
+ mark: RelationReactionMark,
+): Promise {
+ const { pending, ...settled } = mark;
+ if (!pending) return mark;
+ Object.assign(target, pending.target);
+ await kv.set(KV.memories, targetId, target);
+ if (pending.removeMark) {
+ await kv.delete(KV.relationReactions, markKey);
+ return null;
+ }
+ await kv.set(KV.relationReactions, markKey, settled);
+ return settled;
+}
+
+export async function flushDeleteCascade(): Promise {
+ if (!deleteFlusher) return;
+ await deleteFlusher();
+}
+
+export function registerCascadeFunctions(sdk: IIIClient, kv: StateKV): void {
+ deleteFlusher = singleFlight(async () => {
+ if (deleteTimer) { clearTimeout(deleteTimer); deleteTimer = null; }
+ const items = [...pendingDeletes.values()];
+ const sessions = [...pendingSessions];
+ pendingDeletes.clear();
+ pendingSessions.clear();
+ if (items.length === 0 && sessions.length === 0) return;
+ let failed = false;
+ try {
+ const checks = await Promise.all(items.map((item) => deleteTargetGone(kv, item).then(
+ (isGone) => (isGone ? "gone" : "live"),
+ () => "retry",
+ )));
+ const byType = new Map();
+ items.forEach((item, i) => {
+ if (checks[i] === "retry") {
+ failed = true;
+ pendingDeletes.set(`${item.kind}:${item.id}`, item);
+ return;
+ }
+ if (checks[i] === "gone" && item.removeIndex) {
+ try { getSearchIndex().remove(item.id); } catch {}
+ try { vectorIndexRemove(item.id); } catch {}
+ }
+ const targetType = KIND_TARGET_TYPE[item.kind];
+ if (checks[i] !== "gone" || !targetType) return;
+ byType.set(targetType, [...(byType.get(targetType) ?? []), item.id]);
+ });
+ for (const [targetType, ids] of byType) await deleteFacetsCascade(kv, ids, targetType);
+ const reconciled: string[] = [];
+ for (const sessionId of sessions) {
+ await withKeyedLock(`obs:${sessionId}`, async () => {
+ const keys = await kv.listKeys(KV.observations(sessionId));
+ const session = await kv.get(KV.sessions, sessionId);
+ if (session && keys.length !== session.observationCount) {
+ await kv.update(KV.sessions, sessionId, [
+ { type: "set", path: "observationCount", value: keys.length },
+ ]);
+ reconciled.push(sessionId);
+ }
+ });
+ }
+ await recordAudit(kv, "cascade", "mem::on-record-deleted", items.map((item) => item.id).slice(0, 20), {
+ batched: items.length,
+ sessionsReconciled: reconciled,
+ });
+ } catch (err) {
+ failed = true;
+ logger.warn("Delete cascade flush failed", {
+ ids: items.length,
+ sessions: sessions.length,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ for (const item of items) pendingDeletes.set(`${item.kind}:${item.id}`, item);
+ for (const sessionId of sessions) pendingSessions.add(sessionId);
+ throw err;
+ } finally {
+ deleteDelayMs = failed ? Math.min(deleteDelayMs * 2, DELETE_BACKOFF_MAX_MS) : DELETE_BATCH_MS;
+ if (pendingDeletes.size > 0 || pendingSessions.size > 0) scheduleDeleteFlush();
+ }
+ });
+ sdk.registerFunction("mem::record-failure", async (envelope: Record, metadata?: unknown) => {
+ const sourceFn = (metadata as { source_fn?: unknown } | undefined)?.source_fn;
+ const observerId = envelope.observer_id;
+ const fromObserverId = typeof observerId === "string" ? /agentmemory:pipeline:failure:(mem::[a-z-]+):(?:error|soft|partial)/.exec(observerId)?.[1] : undefined;
+ const functionId = (typeof sourceFn === "string" ? sourceFn : undefined) ?? fromObserverId ?? "unknown";
+ const code = failureCode(envelope);
+ const retryable = isRetryable(code, envelope);
+ const now = Date.now();
+ const key = `${functionId}|${code}`;
+ pruneDedupe(now);
+ const prior = dedupe.get(key);
+ const dedupedCount = prior?.skipped ?? 0;
+ if (retryable) counters.transient++; else counters.permanent++;
+ counters.lastAt = new Date(now).toISOString();
+ if (prior && now - prior.seenAt < DEDUPE_WINDOW_MS) {
+ prior.skipped++;
+ return { deduped: true, code };
+ }
+ dedupe.set(key, { seenAt: now, skipped: 0 });
+ const errMsg = (envelope.error as { message?: string } | undefined)?.message ??
+ (envelope.output as { error?: string } | undefined)?.error ?? "";
+ const op = FAILURE_OPS[functionId] ?? "cascade";
+ await recordAudit(kv, op, functionId, extractTargetIds(envelope), {
+ code,
+ message: String(errMsg).slice(0, 300),
+ retryable,
+ durationMs: typeof envelope.duration_ms === "number" ? envelope.duration_ms : undefined,
+ dedupedCount,
+ });
+ return { recorded: true, code, retryable };
+ });
+
+ registerObserverTarget(sdk, "mem::on-record-deleted", "input", async (event: Record): Promise> => {
+ const scope = String(event.scope ?? "");
+ const id = String(event.key ?? "");
+ if (!id) return { skipped: "no_key" };
+ const sessionId = scope.startsWith("mem:obs:") ? scope.slice("mem:obs:".length) : undefined;
+ const kind = sessionId ? "observation" : scope === KV.lessons ? "lesson" : "memory";
+ let current: { deleted?: boolean } | null;
+ try {
+ current = await kv.get<{ deleted?: boolean }>(scope, id);
+ } catch {
+ queueDeleteCascade({ id, kind, sessionId, removeIndex: true });
+ return { deferred: id, queued: true };
+ }
+ const restored = current !== null && current.deleted !== true;
+ if (!restored) {
+ try { getSearchIndex().remove(id); } catch {}
+ try { vectorIndexRemove(id); } catch {}
+ }
+ queueDeleteCascade({ id, kind, sessionId });
+ return restored ? { restored: id, queued: true } : { removed: id, queued: true };
+ });
+
+ registerObserverTarget(sdk, "event::graph::edge-reaction", "input", async (event: Record) => {
+ const rel = (event.event_type === "state:deleted" ? event.old_value : event.new_value) as MemoryRelation | undefined;
+ if (!rel || typeof rel.targetId !== "string") return { skipped: "no_relation" };
+ const relationId = String(event.key ?? `${rel.sourceId}->${rel.targetId}:${rel.type}`);
+ const markKey = `${rel.targetId}:${rel.type}`;
+ const deleted = event.event_type === "state:deleted";
+ const result = await withKeyedLock(`mem:${rel.targetId}`, () => withReentrantKeyedLock("mem:remember", async () => {
+ const target = await kv.get(KV.memories, rel.targetId);
+ if (!target) {
+ await recordAudit(kv, "relation_reaction", "event::graph::edge-reaction", [rel.targetId], {
+ skipped: "missing_target", type: rel.type, relationId,
+ });
+ return { skipped: "missing_target" as const };
+ }
+ const stored = await kv.get(KV.relationReactions, markKey);
+ const mark = stored ? await settlePendingReaction(kv, rel.targetId, target, markKey, stored) : null;
+ if (!deleted) {
+ if (mark?.sources && Object.hasOwn(mark.sources, relationId)) {
+ return { skipped: "already_applied" as const, relationId };
+ }
+ if (rel.type === "supersedes") {
+ if (await supersedesReaches(kv, rel.sourceId, rel.targetId)) {
+ await recordAudit(kv, "relation_reaction", "event::graph::edge-reaction", [rel.targetId, rel.sourceId], {
+ skipped: "cycle", type: rel.type, relationId,
+ });
+ return { skipped: "cycle" as const };
+ }
+ }
+ const next: RelationReactionMark = mark ?? {
+ targetId: rel.targetId,
+ type: rel.type,
+ sources: {},
+ firstAppliedAt: rel.createdAt,
+ lastAppliedAt: rel.createdAt,
+ };
+ next.sources[relationId] = rel.sourceId;
+ next.lastAppliedAt = rel.createdAt;
+ if (rel.type === "supersedes") {
+ if (!mark) {
+ next.isLatestBefore = target.isLatest;
+ next.strengthBefore = target.strength;
+ const wasLatest = target.isLatest === true;
+ target.isLatest = false;
+ target.strength = target.strength * 0.5;
+ if (wasLatest) {
+ try { getSearchIndex().remove(rel.targetId); } catch {}
+ try { vectorIndexRemove(rel.targetId); } catch {}
+ }
+ }
+ } else if (rel.type === "contradicts") {
+ const base = next.contradictBase ?? target.confidence ?? UNSET_MEMORY_CONFIDENCE;
+ const penalties = next.contradictPenalties ?? {};
+ const before = contradictFloor(base, penalties);
+ const updated = { ...penalties, [relationId]: (rel.confidence ?? 0.5) * 0.3 };
+ target.confidence = Math.max(0.05, (target.confidence ?? base) + contradictFloor(base, updated) - before);
+ next.contradictBase = base;
+ next.contradictPenalties = updated;
+ } else if (rel.type === "extends") {
+ const related = target.relatedIds ?? [];
+ if (!related.includes(rel.sourceId)) {
+ target.relatedIds = [...related, rel.sourceId];
+ next.relatedIdsAdded = [...(next.relatedIdsAdded ?? []), rel.sourceId];
+ }
+ } else {
+ return { skipped: "unsupported_type" as const };
+ }
+ await commitReaction(kv, rel.targetId, target, markKey, next, false);
+ return { reacted: true as const, contributors: Object.keys(next.sources).length };
+ }
+ if (!mark || !Object.hasOwn(mark.sources, relationId)) {
+ return { skipped: "no_mark" as const };
+ }
+ delete mark.sources[relationId];
+ if (rel.type === "contradicts" && mark.contradictPenalties && mark.contradictBase !== undefined) {
+ const before = contradictFloor(mark.contradictBase, mark.contradictPenalties);
+ delete mark.contradictPenalties[relationId];
+ const after = contradictFloor(mark.contradictBase, mark.contradictPenalties);
+ target.confidence = Math.min(1, (target.confidence ?? mark.contradictBase) + after - before);
+ }
+ if (Object.keys(mark.sources).length > 0) {
+ await commitReaction(kv, rel.targetId, target, markKey, mark, false);
+ return { unreacted: false as const, remaining: Object.keys(mark.sources).length };
+ }
+ const restoredLatest = mark.isLatestBefore !== undefined && target.isLatest !== true && mark.isLatestBefore === true;
+ if (mark.isLatestBefore !== undefined) target.isLatest = mark.isLatestBefore;
+ if (mark.strengthBefore !== undefined) target.strength = mark.strengthBefore;
+ if (mark.confidenceBefore !== undefined) target.confidence = mark.confidenceBefore;
+ if (restoredLatest) {
+ try { getSearchIndex().add(memoryToObservation(target), "memory"); scheduleIndexSave(); } catch {}
+ void vectorIndexAddGuarded(
+ rel.targetId,
+ target.sessionIds?.[0] ?? "memory",
+ observationEmbedText({ title: target.title, narrative: target.content, concepts: target.concepts }),
+ { kind: "memory", logId: rel.targetId },
+ ).catch(() => {});
+ }
+ if (mark.relatedIdsAdded?.length) {
+ const added = new Set(mark.relatedIdsAdded);
+ target.relatedIds = (target.relatedIds ?? []).filter((id) => !added.has(id));
+ }
+ await commitReaction(kv, rel.targetId, target, markKey, mark, true);
+ return { unreacted: true as const };
+ }));
+ const skip = (result as { skipped?: string }).skipped;
+ if (skip !== "cycle" && skip !== "missing_target") {
+ await recordAudit(kv, "relation_reaction", "event::graph::edge-reaction", [rel.targetId], {
+ type: rel.type, relationId, deleted, ...result,
+ });
+ }
+ return { relationId, markKey, ...result };
+ });
+}
diff --git a/src/functions/compress.ts b/src/functions/compress.ts
index e632200a13..469a35975a 100644
--- a/src/functions/compress.ts
+++ b/src/functions/compress.ts
@@ -23,6 +23,7 @@ import { withKeyedLock } from "../state/keyed-mutex.js";
import { scrubRecord, stripPrivateData } from "./privacy.js";
import { compressionRaw, needsCompression, observationRevision, pendingCompression, type StoredObservation } from "./compression-state.js";
import { registerCompressionRecovery } from "./compression-recovery.js";
+import { registerObserverTarget } from "../runtime/observed.js";
export const COMPRESSION_TIMEOUT_MS = 60_000;
@@ -258,7 +259,7 @@ export function registerCompressFunction(
return task.promise;
}
- sdk.registerFunction("mem::compress", (data: CompressRequest): Promise => {
+ registerObserverTarget(sdk, "mem::compress", "output", (data: CompressRequest): Promise => {
if (!data || typeof data.sessionId !== "string" || !data.sessionId.trim() ||
typeof data.observationId !== "string" || !data.observationId.trim()) {
return Promise.resolve({ success: false, error: "invalid_observation_identity", retryable: false });
diff --git a/src/functions/compression-sweep.ts b/src/functions/compression-sweep.ts
new file mode 100644
index 0000000000..c043e2d314
--- /dev/null
+++ b/src/functions/compression-sweep.ts
@@ -0,0 +1,64 @@
+import type { IIIClient } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { collectAll } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type { CompressedObservation, Session } from "../types.js";
+import { compressMaxConcurrent, isAutoCompressEnabled } from "../config.js";
+import { needsCompression } from "./compression-state.js";
+import { logger } from "../logger.js";
+import { singleFlight } from "../runtime/recovery.js";
+
+const MAX_AGE_MS = 5 * 60_000;
+const MAX_PER_RUN = 50;
+export const MAX_SWEEP_ATTEMPTS = 5;
+
+export function createCompressionSweep(sdk: IIIClient, kv: StateKV) {
+ return singleFlight(async () => {
+ const pending: Array<{ sessionId: string; observationId: string }> = [];
+ const failed: Array<{ sessionId: string; observationId: string }> = [];
+ const cutoff = Date.now() - MAX_AGE_MS;
+ const sessions = await kv.list(KV.sessions);
+ for (const session of sessions) {
+ const observations = await collectAll(kv, KV.observations(session.id));
+ for (const obs of observations) {
+ if (pending.length >= MAX_PER_RUN) break;
+ if (!needsCompression(obs)) continue;
+ if (Date.parse(obs.timestamp) > cutoff) continue;
+ const candidate = { sessionId: session.id, observationId: obs.id };
+ if (obs.compression?.status !== "failed") pending.push(candidate);
+ else if (obs.compression.error !== "source_unavailable" && (obs.compression.attempts ?? 0) < MAX_SWEEP_ATTEMPTS && failed.length < MAX_PER_RUN) failed.push(candidate);
+ }
+ if (pending.length >= MAX_PER_RUN) break;
+ }
+ const candidates = [...pending, ...failed].slice(0, MAX_PER_RUN);
+ const concurrency = Math.min(compressMaxConcurrent(), Math.max(1, candidates.length));
+ let inFlight = 0;
+ let dispatched = 0;
+ await new Promise((resolve) => {
+ const next = () => {
+ while (inFlight < concurrency && dispatched < candidates.length) {
+ const c = candidates[dispatched++];
+ inFlight++;
+ sdk.trigger({ function_id: "mem::compress", payload: c })
+ .catch(() => {})
+ .finally(() => { inFlight--; if (dispatched >= candidates.length && inFlight === 0) resolve(); else next(); });
+ }
+ if (dispatched >= candidates.length && inFlight === 0) resolve();
+ };
+ next();
+ if (candidates.length === 0) resolve();
+ });
+ if (candidates.length > 0) logger.info("Compression sweep dispatched stale observations", { count: candidates.length });
+ return { dispatched: candidates.length };
+ });
+}
+
+export function registerCompressionSweepFunction(sdk: IIIClient, kv: StateKV): () => Promise<{ dispatched: number }> {
+ const run = createCompressionSweep(sdk, kv);
+ sdk.registerFunction("mem::compression-sweep", () => run());
+ return run;
+}
+
+export function compressionSweepEnabled(): boolean {
+ return isAutoCompressEnabled();
+}
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index 088d46f438..3cf2f754d9 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -40,12 +40,8 @@ import {
import { withKeyedLocks } from "../state/keyed-mutex.js";
import { VERSION } from "../version.js";
import { recordAudit } from "./audit.js";
-import {
- indexRecords,
- getSearchIndex,
- vectorIndexRemove,
- flushIndexSave,
-} from "./search.js";
+import { indexRecords, rebuildKeywordIndex, getSearchIndex, vectorIndexRemove, flushIndexSave } from "./search.js";
+import { singleFlight } from "../runtime/recovery.js";
import { resetLessonIndex } from "./lessons.js";
import { logger } from "../logger.js";
import { budgetImportedObservationSources } from "./observation-source-budget.js";
@@ -294,6 +290,9 @@ export function registerExportImportFunction(sdk: IIIClient, state: StateKV): vo
},
);
+ const rebuildAfterReplace = singleFlight(async () => {
+ await rebuildKeywordIndex(state);
+ });
sdk.registerFunction("mem::import",
async (data: {
exportData: ExportData;
@@ -826,6 +825,7 @@ export function registerExportImportFunction(sdk: IIIClient, state: StateKV): vo
strategy,
stats,
});
+ if (strategy === "replace") void rebuildAfterReplace().catch((err) => logger.warn("Post-replace index rebuild failed", { error: err instanceof Error ? err.message : String(err) }));
return { success: true, strategy, ...stats };
},
);
diff --git a/src/functions/facets.ts b/src/functions/facets.ts
index 181b0d622a..a4c76038dd 100644
--- a/src/functions/facets.ts
+++ b/src/functions/facets.ts
@@ -81,6 +81,19 @@ export async function deleteFacetsForTargets(
}
}
+export async function deleteFacetsCascade(
+ kv: StateKV,
+ targetIds: Iterable,
+ targetType?: string,
+): Promise {
+ const ids = new Set(targetIds);
+ ids.delete("");
+ if (ids.size === 0) return;
+ const all = await kv.list(KV.facets);
+ const matches = all.filter((f) => ids.has(f.targetId) && (targetType === undefined || f.targetType === targetType));
+ await Promise.all(matches.map((f) => kv.delete(KV.facets, f.id)));
+}
+
export async function findOrphanFacets(kv: StateKV): Promise {
const facets = await kv.list(KV.facets);
const actionIds = facets.some((f) => f.targetType === "action")
diff --git a/src/functions/graph.ts b/src/functions/graph.ts
index 096a4872ca..c92f43dbc5 100644
--- a/src/functions/graph.ts
+++ b/src/functions/graph.ts
@@ -18,7 +18,7 @@ import {
GRAPH_EXTRACTION_SYSTEM,
buildGraphExtractionPrompt,
} from "../prompts/graph-extraction.js";
-import { isGraphExtractionEnabled } from "../config.js";
+import { isGraphExtractionEnabled, isGraphStructuralEnabled } from "../config.js";
import { recordAudit, safeAudit } from "./audit.js";
import { logger } from "../logger.js";
import { scrubRecord } from "./privacy.js";
@@ -730,14 +730,16 @@ export function registerGraphFunction(
let nodes: GraphNode[] = [];
let edges: GraphEdge[] = [];
- try {
- const heuristic = extractGraphHeuristics(data.observations);
- nodes = heuristic.nodes;
- edges = heuristic.edges;
- } catch (err) {
- logger.warn("heuristic graph extraction failed", {
- error: err instanceof Error ? err.message : String(err),
- });
+ if (isGraphStructuralEnabled()) {
+ try {
+ const heuristic = extractGraphHeuristics(data.observations);
+ nodes = heuristic.nodes;
+ edges = heuristic.edges;
+ } catch (err) {
+ logger.warn("heuristic graph extraction failed", {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
}
const llmEnabled =
@@ -796,6 +798,7 @@ export function registerGraphFunction(
success: true,
nodesAdded: nodes.length,
edgesAdded: edges.length,
+ ...(llmError ? { partial: true, error: llmError } : {}),
};
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index 45dd08cd2d..b9da4a8710 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -10,6 +10,7 @@ import { indexObservationSession } from "../state/obs-index.js";
import { scrubRecord } from "./privacy.js";
import { DedupMap, recordDedupSkip } from "./dedup.js";
import { afterKeyedLock, withKeyedLock } from "../state/keyed-mutex.js";
+import { getBindings } from "../runtime/bindings.js";
import { getFinalizeIdleMs, isAutoCompressEnabled } from "../config.js";
import { buildSyntheticCompression } from "./compress-synthetic.js";
import { isCaptureKey, markCaptureEventDeleted } from "../capture/event-record.js";
@@ -503,7 +504,7 @@ export function registerObserveFunction(
},
});
- if (autoCompress) {
+ if (autoCompress && !getBindings(sdk).observing("mem::compress")) {
afterKeyedLock(`obs:${payload.sessionId}`, async () => {
try {
await sdk.trigger({
@@ -523,7 +524,7 @@ export function registerObserveFunction(
hook: payload.hookType,
compress: autoCompress ? "llm" : "synthetic",
});
- return { observationId: obsId };
+ return { observationId: obsId, sessionId: payload.sessionId };
});
},
);
diff --git a/src/functions/post-session.ts b/src/functions/post-session.ts
new file mode 100644
index 0000000000..adee606eef
--- /dev/null
+++ b/src/functions/post-session.ts
@@ -0,0 +1,88 @@
+import type { IIIClient } from "iii-sdk";
+import { TriggerAction } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { collectAll } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type { CompressedObservation, GraphExtractMark, Memory } from "../types.js";
+import { graphExtractCooldownMs, isConsolidationEnabled, detectLlmProviderKind } from "../config.js";
+import { isReflectEnabled } from "./slots.js";
+import { logger } from "../logger.js";
+import { consolidationDue } from "../triggers/events.js";
+import { getGraphGeneration } from "../state/graph-generation.js";
+import { registerObserverTarget } from "../runtime/observed.js";
+
+const graphStamp = (o: CompressedObservation): string => o.compressedAt ?? o.timestamp;
+
+const fireVoid = (sdk: IIIClient, function_id: string, payload: unknown, sessionId: string) =>
+ sdk
+ .trigger({ function_id, payload, action: TriggerAction.Void() })
+ .catch((err) =>
+ logger.warn(function_id + " trigger failed", {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
+
+export function registerPostSessionFunctions(sdk: IIIClient, kv: StateKV): void {
+ registerObserverTarget(sdk, "mem::post-session-graph", "input", async (data: { sessionId: string }) => {
+ const stored = await kv.get(KV.graphExtractMarks, data.sessionId);
+ const graphGeneration = await getGraphGeneration(kv);
+ const marker = stored && (stored.graphGeneration ?? null) === graphGeneration ? stored : null;
+ const cooldownMs = graphExtractCooldownMs();
+ if (marker && cooldownMs > 0 && Date.now() - Date.parse(marker.updatedAt) < cooldownMs) {
+ return { skipped: "cooldown", updatedAt: marker.updatedAt };
+ }
+ const since = marker ? Date.parse(marker.lastObservationTimestamp) : 0;
+ const observations = await collectAll(kv, KV.observations(data.sessionId));
+ const fresh = observations.filter((o) => o.title && Date.parse(graphStamp(o)) > since);
+ if (fresh.length === 0) return { extracted: 0 };
+ const result = await sdk.trigger<{ observations: CompressedObservation[] }, { success?: boolean; partial?: boolean; error?: string } | null>({
+ function_id: "mem::graph-extract",
+ payload: { observations: fresh },
+ });
+ if (result?.success === false || result?.partial === true) return { extracted: 0, error: result.error ?? "graph extraction failed" };
+ const maxTs = fresh.reduce((max, o) => (graphStamp(o) > max ? graphStamp(o) : max), marker?.lastObservationTimestamp ?? "");
+ await kv.set(KV.graphExtractMarks, data.sessionId, {
+ sessionId: data.sessionId,
+ lastObservationTimestamp: maxTs,
+ extractedCount: (marker?.extractedCount ?? 0) + fresh.length,
+ updatedAt: new Date().toISOString(),
+ graphGeneration,
+ } satisfies GraphExtractMark);
+ return { extracted: fresh.length };
+ });
+
+ registerObserverTarget(sdk, "mem::post-session-reflect", "input", async (data: { sessionId: string }) => {
+ if (!isReflectEnabled()) return { skipped: "reflect_disabled" };
+ return sdk.trigger({ function_id: "mem::slot-reflect", payload: { sessionId: data.sessionId } });
+ });
+
+ registerObserverTarget(sdk, "mem::post-session-consolidate", "input", async (data: { sessionId: string; skipConsolidation?: boolean }) => {
+ if (!isConsolidationEnabled()) return { skipped: "consolidation_disabled" };
+ if (!(await consolidationDue(kv))) return { skipped: "debounced" };
+ fireVoid(sdk, "mem::consolidate-pipeline", { tier: "all", force: true }, data.sessionId);
+ fireVoid(sdk, "mem::auto-crystallize", { olderThanDays: 0 }, data.sessionId);
+ if (detectLlmProviderKind() === "llm") {
+ fireVoid(sdk, "mem::skill-extract", { sessionId: data.sessionId }, data.sessionId);
+ }
+ return { fired: true };
+ });
+
+ sdk.registerFunction("mem::post-remember-graph", async (data: { input?: { content?: string; type?: string; concepts?: string[] }; output?: { success?: boolean; memory?: Memory } }) => {
+ const memory = data.output?.memory;
+ if (!data.output?.success || !memory) return { skipped: "no_memory" };
+ const content = typeof data.input?.content === "string" ? data.input.content : "";
+ const observation = {
+ id: memory.id,
+ title: memory.title || content.slice(0, 120) || memory.type,
+ narrative: content,
+ type: "compressed_observation",
+ timestamp: memory.createdAt,
+ sessionId: `memory:${memory.id}`,
+ hookType: "remember",
+ concepts: data.input?.concepts ?? memory.concepts ?? [],
+ files: memory.files ?? [],
+ } as unknown as CompressedObservation;
+ return sdk.trigger({ function_id: "mem::graph-extract", payload: { observations: [observation] } });
+ });
+}
diff --git a/src/functions/relations.ts b/src/functions/relations.ts
index 170e77c79c..e8f8fbaaae 100644
--- a/src/functions/relations.ts
+++ b/src/functions/relations.ts
@@ -10,7 +10,7 @@ import {
} from "./search.js";
import { KV, generateId } from "../state/schema.js";
import { StateKV, collectAll } from "../state/kv.js";
-import { withKeyedLock } from "../state/keyed-mutex.js";
+import { isKeyedLockHeld, withKeyedLock, withReentrantKeyedLock } from "../state/keyed-mutex.js";
import { safeAudit } from "./audit.js";
import { recordAccessBatch } from "./access-tracker.js";
import { logger } from "../logger.js";
@@ -65,6 +65,10 @@ export function registerRelationsFunction(sdk: IIIClient, kv: StateKV): void {
const lockKey =
firstId === secondId ? `mem:${firstId}` : `mem:${firstId}:${secondId}`;
+ const memoryLock = (id: string, fn: () => Promise): Promise => {
+ const write = () => withReentrantKeyedLock("mem:remember", fn);
+ return isKeyedLockHeld(`mem:${id}`) ? write() : withKeyedLock(`mem:${id}`, write);
+ };
return withKeyedLock(lockKey, async () => {
const source = await kv.get(KV.memories, data.sourceId);
const target = await kv.get(KV.memories, data.targetId);
@@ -91,21 +95,25 @@ export function registerRelationsFunction(sdk: IIIClient, kv: StateKV): void {
const relationId = generateId("rel");
await kv.set(KV.relations, relationId, relation);
- if (!source.relatedIds) source.relatedIds = [];
let sourceUpdated = false;
- if (!source.relatedIds.includes(data.targetId)) {
- source.relatedIds.push(data.targetId);
- await kv.set(KV.memories, data.sourceId, source);
- sourceUpdated = true;
- }
+ await memoryLock(data.sourceId, async () => {
+ const fresh = await kv.get(KV.memories, data.sourceId);
+ if (fresh && !(fresh.relatedIds ?? []).includes(data.targetId)) {
+ fresh.relatedIds = [...(fresh.relatedIds ?? []), data.targetId];
+ await kv.set(KV.memories, data.sourceId, fresh);
+ sourceUpdated = true;
+ }
+ });
- if (!target.relatedIds) target.relatedIds = [];
let targetUpdated = false;
- if (!target.relatedIds.includes(data.sourceId)) {
- target.relatedIds.push(data.sourceId);
- await kv.set(KV.memories, data.targetId, target);
- targetUpdated = true;
- }
+ await memoryLock(data.targetId, async () => {
+ const fresh = await kv.get(KV.memories, data.targetId);
+ if (fresh && !(fresh.relatedIds ?? []).includes(data.sourceId)) {
+ fresh.relatedIds = [...(fresh.relatedIds ?? []), data.sourceId];
+ await kv.set(KV.memories, data.targetId, fresh);
+ targetUpdated = true;
+ }
+ });
await safeAudit(kv, "relation_create", "mem::relate", [relationId], {
type: data.type,
diff --git a/src/functions/status.ts b/src/functions/status.ts
index c072a95cfc..8bfe8da91a 100644
--- a/src/functions/status.ts
+++ b/src/functions/status.ts
@@ -3,6 +3,7 @@ import type { VectorBackfillState } from "./search.js";
import { describeGraphCompactBoot, type GraphCompactBootStatus } from "./graph-compact-boot.js";
import type { CaptureStatus } from "./capture.js";
import type { GraphIndexMigrationStatus } from "../state/graph-index-migration.js";
+import { failureCounters } from "./cascade-audit.js";
export type StatusLevel = "ok" | "info" | "warn" | "error";
@@ -89,6 +90,13 @@ export interface StatusInputs {
stateStore?: { ok: boolean; latencyMs?: number } | null;
capture?: CaptureStatus | null;
observeDedup?: ObserveDedupStatus | null;
+ runtime?: StatusRuntimeInfo | null;
+}
+
+export interface StatusRuntimeInfo {
+ bindings: { state: string; http: string; pipeline?: string; observers: number; failedObservers?: number; reasons: string[] };
+ duplicateWorkers: { count: number; workerIds: string[] } | null;
+ stateWorker: { ready: boolean; waitedMs: number; lastReturnAt?: string };
}
export interface ObserveDedupStatus {
@@ -131,6 +139,8 @@ export interface StatusReport {
graphIndex: GraphIndexMigrationStatus | null;
capture: CaptureStatus | null;
observeDedup: ObserveDedupStatus | null;
+ runtime: StatusRuntimeInfo | null;
+ failures: { transient: number; permanent: number; lastAt: string | null };
functions: Array;
flags: Array;
problems: StatusProblem[];
@@ -284,6 +294,16 @@ export function evaluateStatus(input: StatusInputs): StatusReport {
problems.push({ level: d.level, code: "health-alert", message: d.message, fix: d.fix });
}
+ const failedObservers = input.runtime?.bindings.failedObservers ?? 0;
+ if (failedObservers > 0) {
+ problems.push({
+ level: "error",
+ code: "observer-rejected",
+ message: `${failedObservers} observer${failedObservers === 1 ? " was" : "s were"} rejected by the engine. Rejected route or state observers leave those endpoints or reactions inactive; rejected pipeline observers fall back to direct calls.`,
+ fix: "Check runtime.bindings.reasons in /agentmemory/status for the conflicting route, remove the conflict, then restart agentmemory.",
+ });
+ }
+
if (input.circuitBreaker?.state === "open") {
problems.push({
level: "error",
@@ -553,6 +573,8 @@ export function evaluateStatus(input: StatusInputs): StatusReport {
graphIndex,
capture: input.capture ?? null,
observeDedup: input.observeDedup ?? null,
+ runtime: input.runtime ?? null,
+ failures: failureCounters(),
functions,
flags: input.flags.map((flag) =>
flag.enabled && flag.needsLlm && noLlm
diff --git a/src/index.ts b/src/index.ts
index cda1df0641..9280f3c70c 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -10,6 +10,7 @@ import {
loadTeamConfig,
loadSnapshotConfig,
isGraphExtractionEnabled,
+ isGraphStructuralEnabled,
isAutoCompressEnabled,
isConsolidationEnabled,
getConsolidationIntervalMs,
@@ -106,7 +107,6 @@ import { registerCrystallizeFunction } from "./functions/crystallize.js";
import { registerDiagnosticsFunction } from "./functions/diagnostics.js";
import { registerFacetsFunction } from "./functions/facets.js";
import { registerVerifyFunction } from "./functions/verify.js";
-import { registerCascadeFunction } from "./functions/cascade.js";
import { registerLessonsFunctions } from "./functions/lessons.js";
import { registerObsidianExportFunction } from "./functions/obsidian-export.js";
import { registerReflectFunctions } from "./functions/reflect.js";
@@ -133,6 +133,16 @@ import { initMetrics, OTEL_CONFIG } from "./telemetry/setup.js";
import { VERSION } from "./version.js";
import { bootLog, bootWarn } from "./logger.js";
import { runtimeMetadataPath } from "./runtime-paths.js";
+import { getBindings } from "./runtime/bindings.js";
+import { waitForStateWorker, onStateWorkerReturn } from "./runtime/state-worker.js";
+import { singleFlight, shouldRearmIndex, rearmIndexRecovery, backfillFailedOutright } from "./runtime/recovery.js";
+import { checkDuplicateWorkers } from "./runtime/duplicates.js";
+import { registerPipelineObservers } from "./runtime/pipeline-observers.js";
+import { registerPostSessionFunctions } from "./functions/post-session.js";
+import { registerCompressionSweepFunction } from "./functions/compression-sweep.js";
+import { registerCascadeFunction } from "./functions/cascade.js";
+import { flushDeleteCascade, registerCascadeFunctions } from "./functions/cascade-audit.js";
+import { compressionSweepMs } from "./config.js";
import { ensureServerSecret, explicitSecret, secretFilePath } from "./secret-store.js";
import { mkdirSync, writeFileSync, unlinkSync } from "node:fs";
import { dirname } from "node:path";
@@ -347,7 +357,7 @@ async function main() {
const graphIndexMigration = registerGraphIndexMigrationFunctions(sdk, kv);
registerGraphImportFunction(sdk, kv);
bootLog(
- `Knowledge graph: structural extraction on (LLM relations ${isGraphExtractionEnabled() ? "enabled" : "off"})`,
+ `Knowledge graph: structural extraction ${isGraphStructuralEnabled() ? "on" : "off"} (LLM relations ${isGraphExtractionEnabled() ? "enabled" : "off"})`,
);
registerConsolidationPipelineFunction(sdk, kv, provider);
@@ -404,6 +414,7 @@ async function main() {
registerWorkingMemoryFunctions(sdk, kv, config.tokenBudget);
registerSkillExtractFunctions(sdk, kv, provider);
registerCascadeFunction(sdk, kv);
+ registerCascadeFunctions(sdk, kv);
registerSlidingWindowFunction(sdk, kv, provider);
registerQueryExpansionFunction(sdk, provider);
@@ -467,20 +478,38 @@ async function main() {
markKeywordRebuildPending();
registerApiTriggers(sdk, kv, secret, metricsStore, provider);
registerEventTriggers(sdk, kv);
+ registerPostSessionFunctions(sdk, kv);
+ const runCompressionSweep = registerCompressionSweepFunction(sdk, kv);
registerViewerStreamTriggers(sdk, kv, { secret, metricsStore, provider });
registerViewerSse(sdk);
registerMcpEndpoints(sdk, kv, secret);
const healthMonitor = registerHealthMonitor(sdk, kv);
+ registerPipelineObservers(sdk);
+
+ const bindings = getBindings(sdk);
+ if (isAutoCompressEnabled()) {
+ const sweepMs = compressionSweepMs();
+ if (sweepMs > 0) {
+ const sweepTimer = setInterval(() => { void runCompressionSweep(); }, sweepMs);
+ sweepTimer.unref();
+ }
+ }
+ void bindings.activate().then((modes) => bootLog(`Bindings: state=${modes.state} http=${modes.http} (${bindings.handles.length} observers)`));
+ await waitForStateWorker(sdk);
+
const indexPersistence = new IndexPersistence(kv, vectorIndex, { requireRecoveryPlan: true });
setIndexPersistence(indexPersistence);
- const loaded = await indexPersistence.load().catch((err) => {
- console.warn(`[agentmemory] Failed to load persisted vector index:`, err);
- return null;
- });
- let vectorBackfillSince = await indexPersistence.prepareBackfill(loaded, isVectorBackfillAllEnabled());
+ const restoreVectorCheckpoint = async (boot: boolean) => {
+ if (boot) vectorIndex?.trackLiveChanges();
+ const loaded = await indexPersistence.load().catch((err) => {
+ console.warn(`[agentmemory] Failed to load persisted vector index:`, err);
+ return null;
+ });
+ let checkpointBackfillSince = await indexPersistence.prepareBackfill(loaded, isVectorBackfillAllEnabled());
+ let mismatchBlocked = false;
if (loaded?.vector && vectorIndex && loaded.vector.size > 0) {
// Persisted vectors carry whatever dimension the provider had when
// they were written. If the active provider declares a different
@@ -505,7 +534,7 @@ async function main() {
const distinct = Array.from(seenDimensions).sort((a, b) => a - b).join(", ");
const dropStale = isDropStaleIndexEnabled();
if (dropStale) {
- vectorBackfillSince = await indexPersistence.prepareBackfill(loaded, true);
+ checkpointBackfillSince = await indexPersistence.prepareBackfill(loaded, true);
for (const [obsId] of loaded.vector.entries()) vectorIndex.markRemoved(obsId);
console.warn(
`[agentmemory] Persisted vector index has ${mismatches.length} of ` +
@@ -515,7 +544,7 @@ async function main() {
`AGENTMEMORY_DROP_STALE_INDEX=true is set — discarding the persisted ` +
`vectors. Live observations will rebuild the index over time.`,
);
- } else {
+ } else if (boot) {
throw new Error(
`[agentmemory] Refusing to start: persisted vector index has ` +
`${mismatches.length} of ${loaded.vector.size} vectors with the ` +
@@ -528,19 +557,37 @@ async function main() {
`vectors and rebuild from live observations.\n` +
` - Switch the embedding provider back to the one that wrote the index.`,
);
+ } else {
+ console.error(
+ `[agentmemory] Refusing to start: persisted vector index has ` +
+ `${mismatches.length} of ${loaded.vector.size} vectors with the ` +
+ `wrong dimension. Active provider (${embeddingProvider?.name}) ` +
+ `declares ${activeDim}; dimensions seen on disk: ${distinct}. ` +
+ `First mismatched obsIds: ${sample}. Loading would silently corrupt ` +
+ `search (cross-dimension cosine returns 0). Choose one:\n` +
+ ` - Re-embed the existing index against the new provider, then start.\n` +
+ ` - Set AGENTMEMORY_DROP_STALE_INDEX=true to discard the persisted ` +
+ `vectors and rebuild from live observations.\n` +
+ ` - Switch the embedding provider back to the one that wrote the index.`,
+ );
+ await indexPersistence.prepareBackfill(null);
+ mismatchBlocked = true;
}
- } else {
+ } else if (boot) {
vectorIndex.restoreFrom(loaded.vector);
bootLog(
`Loaded persisted vector index (${vectorIndex.size} vectors)`,
);
+ } else {
+ const merged = vectorIndex.mergeMissingFrom(loaded.vector);
+ bootLog(`Merged ${merged} persisted vectors into the live vector index`);
}
}
if (vectorIndex && loaded && loaded.state !== "unavailable") {
const replay = await indexPersistence.replayPendingLog(embeddingProvider?.dimensions ?? 0);
- if (replay.skipped > 0) vectorBackfillSince = null;
- if (indexPersistence.isRecoveryPaused()) vectorBackfillSince = undefined;
+ if (replay.skipped > 0) checkpointBackfillSince = null;
+ if (indexPersistence.isRecoveryPaused()) checkpointBackfillSince = undefined;
if (replay.entries > 0) {
bootLog(
`Recovered ${replay.added} vectors and ${replay.removed} removals written after the last index save, without calling the embedding provider` +
@@ -548,91 +595,105 @@ async function main() {
);
}
}
+ return { loaded, vectorBackfillSince: checkpointBackfillSince, mismatchBlocked };
+ };
+
+ const bootCheckpoint = await restoreVectorCheckpoint(true);
+ let vectorBackfillSince = bootCheckpoint.vectorBackfillSince;
+ const bootCheckpointUnavailable = !bootCheckpoint.loaded || bootCheckpoint.loaded.state === "unavailable";
+ if (!bootCheckpointUnavailable) vectorIndex?.finishLiveTracking();
const auditMigration = startAuditMigration(kv).catch(() => {});
const keywordStart = Date.now();
- try {
- let keyword = await rebuildKeywordIndex(kv, vectorBackfillSince);
- let supersededReleaseFailed = false;
- if (typeof vectorBackfillSince === "string" && !indexPersistence.isRecoveryPaused() && keyword.historicalVectorGaps > 0) {
- for (const job of keyword.vectorJobs) {
- const revision = job.revision;
- if (!revision) continue;
- try {
- revision.release();
- } catch (err) {
- supersededReleaseFailed = true;
- unreleasedSupersededRevisions.push({ id: job.id, revision });
- bootWarn(`Failed to release superseded vector revision ${job.id}: ${err instanceof Error ? err.message : String(err)}`);
+ let checkpointLoaded = bootCheckpoint.loaded;
+ let indexRecoveryFailed = false;
+ const runIndexRecovery = singleFlight(async () => {
+ indexRecoveryFailed = false;
+ try {
+ let keyword = await rebuildKeywordIndex(kv, vectorBackfillSince);
+ let supersededReleaseFailed = false;
+ if (typeof vectorBackfillSince === "string" && !indexPersistence.isRecoveryPaused() && keyword.historicalVectorGaps > 0) {
+ for (const job of keyword.vectorJobs) {
+ const revision = job.revision;
+ if (!revision) continue;
+ try {
+ revision.release();
+ } catch (err) {
+ supersededReleaseFailed = true;
+ unreleasedSupersededRevisions.push({ id: job.id, revision });
+ bootWarn(`Failed to release superseded vector revision ${job.id}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ keyword.vectorJobs = [];
+ if (!supersededReleaseFailed) {
+ vectorBackfillSince = await indexPersistence.prepareBackfill(checkpointLoaded, true);
+ if (vectorBackfillSince === null) keyword = await rebuildKeywordIndex(kv, vectorBackfillSince);
}
}
- // Jobs are superseded only after every watch is released. A failed release
- // stays in unreleasedSupersededRevisions; do not rebuild or embed over it.
- keyword.vectorJobs = [];
- if (!supersededReleaseFailed) {
- vectorBackfillSince = await indexPersistence.prepareBackfill(loaded, true);
- if (vectorBackfillSince === null) keyword = await rebuildKeywordIndex(kv, vectorBackfillSince);
- }
- }
- bootLog(
- `Rebuilt BM25 index from stored content (${keyword.documents} docs in ${Date.now() - keywordStart} ms)`,
- );
- const pending = keyword.vectorJobs.length + keyword.fullBackfillPending;
- const backlogScanComplete = !isBm25RebuildIncomplete() && isMemoryIndexReady();
- const optedIn = isVectorBackfillAllEnabled();
- const activeIds = new Set(keyword.vectorJobs.map((job) => job.id));
- const hasVector = (id: string) => Boolean(vectorIndex?.has(id));
- const countRemaining = () => bm25Index.countMissingDocuments(hasVector, vectorBackfillSince, activeIds);
- setPendingVectorBackfillCount(indexPersistence.isRecoveryPaused() || supersededReleaseFailed ? countRemaining() : pending);
- if (supersededReleaseFailed || indexPersistence.isRecoveryPaused()) {
- setVectorBackfillState("paused");
- } else if (vectorBackfillSince !== undefined) {
- setVectorBackfillState(!backlogScanComplete ? "paused" : keyword.fullBackfillPending > 0 && !optedIn ? "waiting-for-opt-in" : "idle");
- }
- if (keyword.fullBackfillPending > 0) {
- bootLog(optedIn
- ? `Vector backfill has ${keyword.fullBackfillPending} additional documents beyond this start's limit; restart to resume.`
- : `Vector backfill needs ${keyword.fullBackfillPending} embeddings (set AGENTMEMORY_VECTOR_BACKFILL=all to opt in). See /agentmemory/status.`);
- }
- if (!supersededReleaseFailed && vectorBackfillSince !== undefined && backlogScanComplete && pending === 0) {
- if (!(await indexPersistence.completeBackfill(() => countRemaining() === 0))) {
- setPendingVectorBackfillCount(countRemaining());
+ bootLog(
+ `Rebuilt BM25 index from stored content (${keyword.documents} docs in ${Date.now() - keywordStart} ms)`,
+ );
+ const pending = keyword.vectorJobs.length + keyword.fullBackfillPending;
+ const backlogScanComplete = !isBm25RebuildIncomplete() && isMemoryIndexReady();
+ const optedIn = isVectorBackfillAllEnabled();
+ const activeIds = new Set(keyword.vectorJobs.map((job) => job.id));
+ const hasVector = (id: string) => Boolean(vectorIndex?.has(id));
+ const countRemaining = () => bm25Index.countMissingDocuments(hasVector, vectorBackfillSince, activeIds);
+ setPendingVectorBackfillCount(indexPersistence.isRecoveryPaused() || supersededReleaseFailed ? countRemaining() : pending);
+ if (supersededReleaseFailed || indexPersistence.isRecoveryPaused()) {
setVectorBackfillState("paused");
+ } else if (vectorBackfillSince !== undefined) {
+ setVectorBackfillState(!backlogScanComplete ? "paused" : keyword.fullBackfillPending > 0 && !optedIn ? "waiting-for-opt-in" : "idle");
}
- }
- if (keyword.vectorJobs.length > 0 && (!backlogScanComplete || !(await indexPersistence.beginBackfill()))) {
- setVectorBackfillState("paused");
- activeIds.clear();
- for (const job of keyword.vectorJobs) job.revision?.release();
- } else if (keyword.vectorJobs.length > 0) {
- setVectorBackfillState("running");
- bootLog(`Backfilling ${keyword.vectorJobs.length} missing vectors, ${getVectorBackfillMax()} per batch in the background`);
- void backfillVectorBacklog(keyword.vectorJobs, {
- remainingAfter: keyword.fullBackfillPending,
- remainingCount: countRemaining,
- })
- .then(async (result) => {
- const complete = result.complete && backlogScanComplete && await indexPersistence.completeBackfill(() => countRemaining() === 0);
- const remaining = countRemaining();
- setPendingVectorBackfillCount(remaining);
- setVectorBackfillState(complete ? "idle" : "paused");
- if (result.added > 0) bootLog(`Vector index backfilled: ${result.added} entries`);
- if (!complete) bootWarn(`Vector recovery remains incomplete (${remaining} documents pending); it resumes on the next start.`);
- })
- .catch((err) => {
+ if (keyword.fullBackfillPending > 0) {
+ bootLog(optedIn
+ ? `Vector backfill has ${keyword.fullBackfillPending} additional documents beyond this start's limit; restart to resume.`
+ : `Vector backfill needs ${keyword.fullBackfillPending} embeddings (set AGENTMEMORY_VECTOR_BACKFILL=all to opt in). See /agentmemory/status.`);
+ }
+ if (!supersededReleaseFailed && vectorBackfillSince !== undefined && backlogScanComplete && pending === 0) {
+ if (!(await indexPersistence.completeBackfill(() => countRemaining() === 0))) {
+ setPendingVectorBackfillCount(countRemaining());
setVectorBackfillState("paused");
- console.warn(`[agentmemory] Failed to backfill vectors:`, err);
+ }
+ }
+ if (keyword.vectorJobs.length > 0 && (!backlogScanComplete || !(await indexPersistence.beginBackfill()))) {
+ setVectorBackfillState("paused");
+ activeIds.clear();
+ for (const job of keyword.vectorJobs) job.revision?.release();
+ } else if (keyword.vectorJobs.length > 0) {
+ setVectorBackfillState("running");
+ bootLog(`Backfilling ${keyword.vectorJobs.length} missing vectors, ${getVectorBackfillMax()} per batch in the background`);
+ void backfillVectorBacklog(keyword.vectorJobs, {
+ remainingAfter: keyword.fullBackfillPending,
+ remainingCount: countRemaining,
})
- .finally(() => {
- activeIds.clear();
- for (const job of keyword.vectorJobs) job.revision?.release();
- });
+ .then(async (result) => {
+ const complete = result.complete && backlogScanComplete && await indexPersistence.completeBackfill(() => countRemaining() === 0);
+ const remaining = countRemaining();
+ setPendingVectorBackfillCount(remaining);
+ setVectorBackfillState(complete ? "idle" : "paused");
+ if (backfillFailedOutright(result)) indexRecoveryFailed = true;
+ if (result.added > 0) bootLog(`Vector index backfilled: ${result.added} entries`);
+ if (!complete) bootWarn(`Vector recovery remains incomplete (${remaining} documents pending); it resumes on the next start.`);
+ })
+ .catch((err) => {
+ indexRecoveryFailed = true;
+ setVectorBackfillState("paused");
+ console.warn(`[agentmemory] Failed to backfill vectors:`, err);
+ })
+ .finally(() => {
+ activeIds.clear();
+ for (const job of keyword.vectorJobs) job.revision?.release();
+ });
+ }
+ } catch (err) {
+ indexRecoveryFailed = true;
+ setVectorBackfillState("paused");
+ console.warn(`[agentmemory] Failed to rebuild the BM25 index:`, err);
}
- } catch (err) {
- setVectorBackfillState("paused");
- console.warn(`[agentmemory] Failed to rebuild the BM25 index:`, err);
- }
+ });
+ await runIndexRecovery();
// Ready / Endpoints lines are emitted via `bootLog` so they're
// buffered in quiet mode and printed verbatim under --verbose. The
@@ -648,6 +709,12 @@ async function main() {
`MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`,
);
+ const runCaptureRecovery = singleFlight(async () => {
+ const swept = await capture.sweep();
+ if (swept.processed > 0) {
+ bootLog(`Capture inbox: ${swept.recovered} of ${swept.processed} unfinished observations stored after restart`);
+ }
+ });
void (async () => {
try {
const drained = await capture.drainLocalSpool();
@@ -657,10 +724,7 @@ async function main() {
if (delivered + duplicates + remaining > 0) {
bootLog(`Capture spool: ${delivered} recovered, ${duplicates} already stored, ${remaining} still waiting`);
}
- const swept = await capture.sweep();
- if (swept.processed > 0) {
- bootLog(`Capture inbox: ${swept.recovered} of ${swept.processed} unfinished observations stored after restart`);
- }
+ await runCaptureRecovery();
await capture.prune();
} catch (err) {
bootWarn(`Capture recovery at boot failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -668,6 +732,42 @@ async function main() {
capture.start();
})();
+ const rearm = onStateWorkerReturn(sdk, bindings, async () => {
+ try {
+ await rearmIndexRecovery({
+ retryCheckpoint: async () => {
+ if (!bootCheckpointUnavailable || !indexPersistence.resumeAfterUnavailable()) return false;
+ const retry = await restoreVectorCheckpoint(false);
+ checkpointLoaded = retry.loaded;
+ vectorBackfillSince = retry.vectorBackfillSince;
+ if (!retry.loaded || retry.loaded.state === "unavailable") return false;
+ vectorIndex?.finishLiveTracking();
+ return true;
+ },
+ indexNeedsRearm: () => shouldRearmIndex({
+ bm25Incomplete: isBm25RebuildIncomplete(),
+ persistencePaused: indexPersistence.isRecoveryPaused(),
+ lastRecoveryFailed: indexRecoveryFailed,
+ checkpointSaveFailed: Boolean(indexPersistence.status().vector?.lastError),
+ }),
+ runIndexRecovery,
+ });
+ await rebuildSessionIndexIfStale(kv).catch((err) => {
+ bootWarn(`Session index rebuild after state return failed: ${err instanceof Error ? err.message : String(err)}`);
+ });
+ await runCaptureRecovery();
+ await checkDuplicateWorkers(sdk);
+ } catch (err) {
+ bootWarn(`State-worker re-arm failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }, { pending: () => bootCheckpointUnavailable && indexPersistence.isPausedForUnavailable() });
+ const rearmTick = setInterval(() => {
+ void rearm.probeTick();
+ void checkDuplicateWorkers(sdk);
+ }, 30_000);
+ rearmTick.unref();
+ void checkDuplicateWorkers(sdk);
+
const viewerServer = startViewerServer(
config.viewerPort,
kv,
@@ -813,6 +913,7 @@ async function main() {
capture.stop();
stopKeywordRebuildRetry();
clearInterval(sessionFinalizeTimer);
+ await settleWithin(flushDeleteCascade().catch(() => {}), SHUTDOWN_FLUSH_TIMEOUT_MS);
await settleWithin(graphIndexMigration.stop(), SHUTDOWN_FLUSH_TIMEOUT_MS);
indexPersistence.stop();
const viewerClosed = new Promise((resolve) =>
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 80359bf24a..789f8a6bab 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -13,6 +13,7 @@ import { checkAuth, slotsDisabledResponse } from "../triggers/api.js";
import { isSlotsEnabled } from "../functions/slots.js";
import { LESSON_SOURCE_IDS_MAX, normalizeLessonSourceIds } from "../functions/lessons.js";
import { getAgentId, isAgentScopeIsolated } from "../config.js";
+import { getBindings } from "../runtime/bindings.js";
type McpResponse = {
status_code: number;
headers?: Record;
@@ -63,8 +64,7 @@ export function registerMcpEndpoints(
return { status_code: 200, body: { tools } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "mcp::tools::list",
config: { api_path: "/agentmemory/mcp/tools", http_method: "GET" },
});
@@ -1343,8 +1343,7 @@ export function registerMcpEndpoints(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "mcp::tools::call",
config: { api_path: "/agentmemory/mcp/call", http_method: "POST" },
});
@@ -1396,8 +1395,7 @@ export function registerMcpEndpoints(
return { status_code: 200, body: { resources: MCP_RESOURCES } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "mcp::resources::list",
config: { api_path: "/agentmemory/mcp/resources", http_method: "GET" },
});
@@ -1626,8 +1624,7 @@ export function registerMcpEndpoints(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "mcp::resources::read",
config: {
api_path: "/agentmemory/mcp/resources/read",
@@ -1680,8 +1677,7 @@ export function registerMcpEndpoints(
return { status_code: 200, body: { prompts: MCP_PROMPTS } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "mcp::prompts::list",
config: { api_path: "/agentmemory/mcp/prompts", http_method: "GET" },
});
@@ -1818,8 +1814,7 @@ export function registerMcpEndpoints(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "mcp::prompts::get",
config: { api_path: "/agentmemory/mcp/prompts/get", http_method: "POST" },
});
diff --git a/src/runtime/bindings.ts b/src/runtime/bindings.ts
new file mode 100644
index 0000000000..25b9104aa1
--- /dev/null
+++ b/src/runtime/bindings.ts
@@ -0,0 +1,257 @@
+import type { IIIClient, ObserveSource, ObserverHandle, ObserverOptions } from "iii-sdk";
+import { logger } from "../logger.js";
+import { GRAPH_SCOPES } from "../state/graph-generation.js";
+
+export type ProviderMode = "observe" | "pending";
+export type BindingModes = { state: ProviderMode; http: ProviderMode };
+
+export interface HttpRouteSpec {
+ function_id: string;
+ config: {
+ api_path: string;
+ http_method?: string;
+ middleware_function_ids?: string[];
+ public_webhook?: boolean;
+ };
+}
+
+export interface StateSpec {
+ function_id: string;
+ scope: string;
+ key?: string;
+ maxInFlight?: number;
+}
+
+export interface BindingReport {
+ state: ProviderMode;
+ http: ProviderMode;
+ pipeline: "observe" | "inline";
+ observers: number;
+ failedObservers: number;
+ reasons: string[];
+}
+
+interface SdkLike {
+ observe?: (source: ObserveSource, target: string, options?: ObserverOptions) => ObserverHandle;
+}
+
+type BindingKind = "http" | "state" | "pipeline";
+
+const instances = new WeakMap();
+
+const HTTP_ARG_KEYS = new Set(["api_path", "http_method", "middleware_function_ids", "public_webhook"]);
+
+const ACTIVATE_TIMEOUT_MS = 30_000;
+
+const ID_CONFLICT_RETRY_DELAYS_MS = [10_000, 20_000, 40_000, 80_000];
+
+export class Bindings {
+ private readonly sdk: SdkLike;
+ private readonly bound: Array<{ handle: ObserverHandle; kind: BindingKind; target: string }> = [];
+ private readonly reasons = new Set();
+ private readonly inline: boolean;
+ private failedObserverCount = 0;
+ private readonly boundWatchers = new Set<(entry: { handle: ObserverHandle; kind: BindingKind }) => void>();
+
+ constructor(sdk: SdkLike) {
+ this.sdk = sdk;
+ const forced = process.env.AGENTMEMORY_BINDINGS;
+ if (forced === "trigger") {
+ logger.warn("AGENTMEMORY_BINDINGS=trigger is no longer supported on iii 0.26 (triggers were removed); treating it as AGENTMEMORY_BINDINGS=inline");
+ }
+ this.inline = forced === "inline" || forced === "trigger" || typeof sdk.observe !== "function";
+ }
+
+ get handles(): readonly ObserverHandle[] {
+ return this.bound.map((entry) => entry.handle);
+ }
+
+ get stateHandles(): readonly ObserverHandle[] {
+ return this.handlesOf("state");
+ }
+
+ onStateHandle(listener: (handle: ObserverHandle) => void): () => void {
+ const watch = (entry: { handle: ObserverHandle; kind: BindingKind }) => {
+ if (entry.kind === "state") listener(entry.handle);
+ };
+ this.boundWatchers.add(watch);
+ return () => this.boundWatchers.delete(watch);
+ }
+
+ get pipeline(): "observe" | "inline" {
+ return this.inline ? "inline" : "observe";
+ }
+
+ observing(target: string): boolean {
+ if (this.inline) return false;
+ return this.bound.some((entry) => entry.kind === "pipeline" && entry.target === target && entry.handle.state === "active");
+ }
+
+ get modes(): BindingModes {
+ return { state: this.modeOf("state"), http: this.modeOf("http") };
+ }
+
+ private handlesOf(kind: BindingKind): ObserverHandle[] {
+ return this.bound.filter((entry) => entry.kind === kind).map((entry) => entry.handle);
+ }
+
+ private modeOf(kind: "state" | "http"): ProviderMode {
+ return this.handlesOf(kind).some((handle) => handle.state === "active") ? "observe" : "pending";
+ }
+
+ private routeMaxInFlight(): number {
+ const raw = process.env.AGENTMEMORY_ROUTE_MAX_IN_FLIGHT;
+ if (raw === undefined) return 1024;
+ const parsed = Number(raw);
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65536) return 1024;
+ return parsed;
+ }
+
+ private observe(kind: BindingKind, label: string, source: ObserveSource, target: string, options?: ObserverOptions, attempt = 0): ObserverHandle | null {
+ if (typeof this.sdk.observe !== "function") {
+ this.reasons.add("client has no observe(); bindings skipped");
+ return null;
+ }
+ const handle = this.sdk.observe(source, target, options);
+ const entry = { handle, kind, target };
+ this.bound.push(entry);
+ for (const watch of this.boundWatchers) watch(entry);
+ void handle.ready().catch((err: unknown) => {
+ const code = (err as { code?: string })?.code ?? String(err);
+ if (code === "OBSERVER_ID_CONFLICT" && attempt < ID_CONFLICT_RETRY_DELAYS_MS.length) {
+ const delay = ID_CONFLICT_RETRY_DELAYS_MS[attempt];
+ logger.warn(`Observer id for ${label} is still held by an earlier connection; retrying`, { attempt: attempt + 1, delayMs: delay });
+ const timer = setTimeout(() => {
+ void handle.dispose().catch(() => {}).finally(() => {
+ const index = this.bound.indexOf(entry);
+ if (index >= 0) this.bound.splice(index, 1);
+ this.observe(kind, label, source, target, options, attempt + 1);
+ });
+ }, delay);
+ timer.unref?.();
+ return;
+ }
+ this.failedObserverCount++;
+ this.reasons.add(`${label} observer rejected: ${code}`);
+ logger.error(`Observer failed for ${label}`, { error: code });
+ });
+ return handle;
+ }
+
+ http(spec: HttpRouteSpec): void {
+ const config = spec.config;
+ const method = (config.http_method ?? "GET").toUpperCase();
+ const unknown = Object.keys(config).filter((key) => !HTTP_ARG_KEYS.has(key));
+ if (unknown.length > 0) {
+ throw new Error(`route ${method} ${config.api_path} uses config the http worker does not accept: ${unknown.join(",")}`);
+ }
+ this.observe(
+ "http",
+ `route ${method} ${config.api_path}`,
+ {
+ function_id: "http::on-request",
+ args: {
+ method,
+ path: config.api_path,
+ ...(config.middleware_function_ids?.length ? { middleware_function_ids: config.middleware_function_ids } : {}),
+ ...(config.public_webhook ? { public_webhook: true } : {}),
+ },
+ },
+ spec.function_id,
+ { id: `agentmemory:route:${method} ${config.api_path}`, max_in_flight: this.routeMaxInFlight() },
+ );
+ }
+
+ state(spec: StateSpec): void {
+ const scopeClause = GRAPH_SCOPES.has(spec.scope)
+ ? { $or: [{ "input.scope": { $eq: spec.scope } }, { "input.scope": { $prefix: `${spec.scope}:generation:` } }] }
+ : { "input.scope": { $eq: spec.scope } };
+ const filters = {
+ ...scopeClause,
+ ...(spec.key !== undefined ? { "input.key": { $eq: spec.key } } : {}),
+ };
+ this.observe(
+ "state",
+ `state ${spec.function_id}`,
+ { function_id: "state::on-changed", filters, capture: ["input"] },
+ spec.function_id,
+ { id: `agentmemory:state:${spec.function_id}`, ...(spec.maxInFlight ? { max_in_flight: spec.maxInFlight } : {}) },
+ );
+ }
+
+ observePipeline(source: ObserveSource, target: string, options?: ObserverOptions): ObserverHandle | null {
+ if (this.inline) return null;
+ return this.observe("pipeline", `pipeline ${target}`, source, target, options);
+ }
+
+ observeStateChanges(filters: Record, target: string, options?: ObserverOptions): ObserverHandle | null {
+ return this.observe("pipeline", `pipeline ${target}`, { function_id: "state::on-changed", filters, capture: ["input"] }, target, options);
+ }
+
+ activate(timeoutMs = ACTIVATE_TIMEOUT_MS): Promise {
+ const settled = () => {
+ const modes = this.modes;
+ return (modes.state === "observe" || this.handlesOf("state").length === 0) &&
+ (modes.http === "observe" || this.handlesOf("http").length === 0);
+ };
+ if (settled()) return Promise.resolve(this.modes);
+ return new Promise((resolve) => {
+ const unsubscribes: Array<() => void> = [];
+ let done = false;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ for (const unsubscribe of unsubscribes) unsubscribe();
+ resolve(this.modes);
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ timer.unref?.();
+ const watch = ({ handle, kind }: { handle: ObserverHandle; kind: BindingKind }) => {
+ if (done || kind === "pipeline") return;
+ unsubscribes.push(handle.onStateChange(() => { if (settled()) finish(); }));
+ if (settled()) finish();
+ };
+ this.boundWatchers.add(watch);
+ unsubscribes.push(() => this.boundWatchers.delete(watch));
+ for (const entry of this.bound) watch(entry);
+ });
+ }
+
+ describe(): BindingReport {
+ const modes = this.modes;
+ const reasons = new Set(this.reasons);
+ if (modes.state === "pending" && this.handlesOf("state").length > 0) reasons.add("state::on-changed observers pending until the state worker connects");
+ if (modes.http === "pending" && this.handlesOf("http").length > 0) reasons.add("http::on-request observers pending until the http worker connects");
+ if (!this.inline) {
+ const inactive = this.bound.filter((entry) => entry.kind === "pipeline" && entry.handle.state !== "active");
+ if (inactive.length > 0) {
+ reasons.add(`${inactive.length} pipeline observers are not active, so their work runs as direct calls: ${inactive.map((entry) => entry.target).join(", ")}`);
+ }
+ }
+ for (const kind of ["state", "http"] as const) {
+ if (modes[kind] !== "observe") continue;
+ const handles = this.handlesOf(kind);
+ const inactive = handles.filter((handle) => handle.state !== "active");
+ if (inactive.length === 0) continue;
+ const states = [...new Set(inactive.map((handle) => handle.state))].join(", ");
+ reasons.add(`${inactive.length} of ${handles.length} ${kind} observers are not active (${states})`);
+ }
+ return {
+ ...modes,
+ pipeline: this.pipeline,
+ observers: this.bound.length - this.failedObserverCount,
+ failedObservers: this.failedObserverCount,
+ reasons: [...reasons],
+ };
+ }
+}
+
+export function getBindings(sdk: IIIClient): Bindings {
+ let binding = instances.get(sdk);
+ if (!binding) {
+ binding = new Bindings(sdk as unknown as SdkLike);
+ instances.set(sdk, binding);
+ }
+ return binding;
+}
diff --git a/src/runtime/duplicates.ts b/src/runtime/duplicates.ts
new file mode 100644
index 0000000000..1af727d32e
--- /dev/null
+++ b/src/runtime/duplicates.ts
@@ -0,0 +1,49 @@
+import type { IIIClient } from "iii-sdk";
+import { logger } from "../logger.js";
+
+export interface DuplicateWorkerInfo {
+ count: number;
+ workerIds: string[];
+}
+
+let last: DuplicateWorkerInfo | null = null;
+let lastKey = "";
+
+export function getDuplicateWorkers(): DuplicateWorkerInfo | null {
+ return last;
+}
+
+export function resetDuplicateWorkersForTest(): void {
+ last = null;
+ lastKey = "";
+}
+
+export async function checkDuplicateWorkers(sdk: IIIClient): Promise {
+ try {
+ const listed = await sdk.trigger({ function_id: "engine::workers::list", payload: {} });
+ const entries = Array.isArray(listed)
+ ? listed
+ : (((listed as { workers?: unknown[] })?.workers ?? []) as unknown[]);
+ const matches: string[] = [];
+ for (const entry of entries) {
+ if (typeof entry === "string") continue;
+ const w = entry as { worker_id?: string; id?: string; worker_name?: string; name?: string; workerName?: string };
+ const name = w.worker_name ?? w.workerName ?? w.name;
+ if (name === "agentmemory") matches.push(w.worker_id ?? w.id ?? "unknown");
+ }
+ if (matches.length > 1) {
+ last = { count: matches.length, workerIds: matches };
+ const key = matches.slice().sort().join(",");
+ if (key !== lastKey) {
+ lastKey = key;
+ logger.warn("Multiple agentmemory workers registered to the engine; this instance may be duplicated", { count: matches.length, workerIds: matches });
+ }
+ } else {
+ last = null;
+ lastKey = "";
+ }
+ return last;
+ } catch {
+ return last;
+ }
+}
diff --git a/src/runtime/observed.ts b/src/runtime/observed.ts
new file mode 100644
index 0000000000..3916d7a7ca
--- /dev/null
+++ b/src/runtime/observed.ts
@@ -0,0 +1,22 @@
+import type { IIIClient } from "iii-sdk";
+
+type ObservedField = "input" | "output";
+
+function isObserved(payload: unknown): payload is { input?: unknown; output?: unknown } {
+ return typeof payload === "object" && payload !== null &&
+ typeof (payload as { observer_id?: unknown }).observer_id === "string" &&
+ typeof (payload as { activation_id?: unknown }).activation_id === "string";
+}
+
+export function unwrapObserved(payload: unknown, field: ObservedField): T {
+ return (isObserved(payload) ? payload[field] : payload) as T;
+}
+
+export function registerObserverTarget(
+ sdk: IIIClient,
+ functionId: string,
+ field: ObservedField,
+ handler: (payload: T) => R | Promise,
+): void {
+ sdk.registerFunction(functionId, (payload: unknown) => handler(unwrapObserved(payload, field)));
+}
diff --git a/src/runtime/pipeline-observers.ts b/src/runtime/pipeline-observers.ts
new file mode 100644
index 0000000000..891e80ecea
--- /dev/null
+++ b/src/runtime/pipeline-observers.ts
@@ -0,0 +1,90 @@
+import type { Capture, IIIClient } from "iii-sdk";
+import { getBindings } from "./bindings.js";
+import { KV } from "../state/schema.js";
+import { compressMaxConcurrent, isAutoCompressEnabled, isGraphExtractionEnabled } from "../config.js";
+import { isReflectEnabled } from "../functions/slots.js";
+
+const FAILURE_OBSERVERS: Array<{ suffix: string; filters: Record; capture: Capture[] }> = [
+ { suffix: "error", filters: { error: { $exists: true } }, capture: ["input", "error"] },
+ { suffix: "soft", filters: { "output.success": { $eq: false } }, capture: ["input", "output"] },
+];
+
+export function registerPipelineObservers(sdk: IIIClient): void {
+ const bindings = getBindings(sdk);
+ if (isAutoCompressEnabled()) {
+ bindings.observePipeline(
+ {
+ function_id: "mem::observe",
+ filters: { "output.observationId": { $exists: true }, "output.deduplicated": { $ne: true } },
+ capture: ["output"],
+ },
+ "mem::compress",
+ { id: "agentmemory:pipeline:compress-on-capture", max_in_flight: compressMaxConcurrent() },
+ );
+ }
+ const sessionStopped = (filters: Record = {}) => ({
+ function_id: "event::session::stopped",
+ filters: { "output.unchanged": { $ne: true }, ...filters },
+ capture: ["input", "output"] as Capture[],
+ });
+ bindings.observePipeline(
+ sessionStopped(),
+ "mem::post-session-graph",
+ { id: "agentmemory:pipeline:post-session-graph", max_in_flight: 1 },
+ );
+ if (isReflectEnabled()) {
+ bindings.observePipeline(
+ sessionStopped(),
+ "mem::post-session-reflect",
+ { id: "agentmemory:pipeline:post-session-reflect", max_in_flight: 1 },
+ );
+ }
+ bindings.observePipeline(
+ sessionStopped({ "input.skipConsolidation": { $ne: true } }),
+ "mem::post-session-consolidate",
+ { id: "agentmemory:pipeline:post-session-consolidate", max_in_flight: 1 },
+ );
+ if (isGraphExtractionEnabled()) {
+ bindings.observePipeline(
+ { function_id: "mem::remember", capture: ["input", "output"] },
+ "mem::post-remember-graph",
+ { id: "agentmemory:pipeline:post-remember-graph", max_in_flight: 1 },
+ );
+ }
+ for (const fn of ["mem::compress", "mem::summarize", "mem::graph-extract", "mem::consolidate-pipeline", "mem::reflect", "mem::skill-extract"]) {
+ for (const failure of FAILURE_OBSERVERS) {
+ bindings.observePipeline(
+ { function_id: fn, filters: failure.filters, capture: failure.capture },
+ "mem::record-failure",
+ { id: `agentmemory:pipeline:failure:${fn}:${failure.suffix}`, max_in_flight: 4, metadata: { source_fn: fn } },
+ );
+ }
+ }
+ bindings.observePipeline(
+ { function_id: "mem::graph-extract", filters: { "output.partial": { $eq: true } }, capture: ["input", "output"] },
+ "mem::record-failure",
+ { id: "agentmemory:pipeline:failure:mem::graph-extract:partial", max_in_flight: 4, metadata: { source_fn: "mem::graph-extract" } },
+ );
+ bindings.observeStateChanges(
+ {
+ $or: [
+ { "input.event_type": { $eq: "state:deleted" }, "input.scope": { $prefix: "mem:obs:" } },
+ { "input.event_type": { $eq: "state:deleted" }, "input.scope": { $eq: KV.memories } },
+ { "input.event_type": { $eq: "state:deleted" }, "input.scope": { $eq: KV.lessons } },
+ { "input.scope": { $eq: KV.lessons }, "input.new_value.deleted": { $eq: true }, "input.old_value.deleted": { $ne: true } },
+ ],
+ },
+ "mem::on-record-deleted",
+ { id: "agentmemory:cascade:deleted", max_in_flight: 4 },
+ );
+ bindings.observeStateChanges(
+ {
+ $or: [
+ { "input.event_type": { $eq: "state:created" }, "input.scope": { $eq: KV.relations }, "input.new_value.type": { $in: ["supersedes", "contradicts", "extends"] } },
+ { "input.event_type": { $eq: "state:deleted" }, "input.scope": { $eq: KV.relations }, "input.old_value.type": { $in: ["supersedes", "contradicts", "extends"] } },
+ ],
+ },
+ "event::graph::edge-reaction",
+ { id: "agentmemory:cascade:relation-reaction", max_in_flight: 1 },
+ );
+}
diff --git a/src/runtime/recovery.ts b/src/runtime/recovery.ts
new file mode 100644
index 0000000000..28314c9394
--- /dev/null
+++ b/src/runtime/recovery.ts
@@ -0,0 +1,35 @@
+export function singleFlight(fn: (...args: A) => Promise): (...args: A) => Promise {
+ let inFlight: Promise | null = null;
+ return (...args: A) => {
+ if (!inFlight) {
+ inFlight = fn(...args).finally(() => { inFlight = null; });
+ }
+ return inFlight;
+ };
+}
+
+export interface RearmConditions {
+ bm25Incomplete: boolean;
+ persistencePaused: boolean;
+ lastRecoveryFailed: boolean;
+ checkpointSaveFailed: boolean;
+}
+
+export interface RearmSteps {
+ retryCheckpoint: () => Promise;
+ indexNeedsRearm: () => boolean;
+ runIndexRecovery: () => Promise;
+}
+
+export async function rearmIndexRecovery(steps: RearmSteps): Promise {
+ const restored = await steps.retryCheckpoint();
+ if (restored || steps.indexNeedsRearm()) await steps.runIndexRecovery();
+}
+
+export function backfillFailedOutright(result: { added: number; failed: number }): boolean {
+ return result.failed > 0 && result.added === 0;
+}
+
+export function shouldRearmIndex(input: RearmConditions): boolean {
+ return input.bm25Incomplete || input.persistencePaused || input.lastRecoveryFailed || input.checkpointSaveFailed;
+}
diff --git a/src/runtime/state-worker.ts b/src/runtime/state-worker.ts
new file mode 100644
index 0000000000..3532f451a0
--- /dev/null
+++ b/src/runtime/state-worker.ts
@@ -0,0 +1,175 @@
+import type { IIIClient, ObserverHandle } from "iii-sdk";
+import { logger } from "../logger.js";
+import type { Bindings } from "./bindings.js";
+import { unwrapObserved } from "./observed.js";
+
+export interface StateWorkerReadiness {
+ ready: boolean;
+ waitedMs: number;
+ attempts: number;
+ error?: string;
+}
+
+export const stateWorkerStatus: { ready: boolean; waitedMs: number; lastReturnAt?: string } = {
+ ready: false,
+ waitedMs: 0,
+};
+
+interface SdkLike {
+ trigger: (input: { function_id: string; payload: unknown; timeoutMs?: number }) => Promise;
+ observe?: (source: unknown, target: string, options?: Record) => ObserverHandle;
+ registerFunction?: (id: string, handler: (payload: unknown) => unknown) => unknown;
+}
+
+const RETRYABLE = /function_not_found|timeout|not.ready|unavailable|connection/i;
+
+function probeTimeoutMs(): number {
+ const raw = process.env.AGENTMEMORY_STATE_READY_TIMEOUT_MS;
+ if (raw === undefined) return 60_000;
+ const parsed = Number(raw);
+ if (!Number.isInteger(parsed) || parsed < 1000 || parsed > 600_000) return 60_000;
+ return parsed;
+}
+
+async function probeOnce(sdk: SdkLike, timeoutMs: number): Promise {
+ await sdk.trigger({
+ function_id: "state::get",
+ payload: { scope: "mem:config", key: "__agentmemory_state_probe__" },
+ timeoutMs,
+ });
+}
+
+export async function waitForStateWorker(
+ sdk: IIIClient,
+ opts: { timeoutMs?: number } = {},
+): Promise {
+ const started = Date.now();
+ const budget = Math.min(opts.timeoutMs ?? probeTimeoutMs(), 600_000);
+ const perProbe = Math.min(2000, budget);
+ let attempts = 0;
+ let lastError = "unknown";
+ while (Date.now() - started < budget) {
+ attempts++;
+ try {
+ await probeOnce(sdk as unknown as SdkLike, perProbe);
+ const waitedMs = Date.now() - started;
+ logger.info("State worker ready", { waitedMs, attempts });
+ stateWorkerStatus.ready = true;
+ stateWorkerStatus.waitedMs = waitedMs;
+ return { ready: true, waitedMs, attempts };
+ } catch (err) {
+ lastError = err instanceof Error ? err.message : String(err);
+ const code = (err as { code?: string })?.code;
+ if (code && !RETRYABLE.test(code) && !RETRYABLE.test(lastError)) break;
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+ }
+ const waitedMs = Date.now() - started;
+ logger.warn("State worker not ready before first boot read; continuing and re-arming", { waitedMs, attempts, error: lastError });
+ stateWorkerStatus.ready = false;
+ stateWorkerStatus.waitedMs = waitedMs;
+ return { ready: false, waitedMs, attempts, error: lastError };
+}
+
+export interface StateWorkerReturnState {
+ lastReturnAt?: string;
+ probeReady: boolean;
+}
+
+export function onStateWorkerReturn(
+ sdk: IIIClient,
+ bindings: Bindings,
+ cb: () => void | Promise,
+ opts: { pending?: () => boolean } = {},
+): { state: StateWorkerReturnState; probeTick: () => Promise; stop: () => void } {
+ const client = sdk as unknown as SdkLike;
+ const state: StateWorkerReturnState = { probeReady: stateWorkerStatus.ready };
+ let inFlight: Promise | null = null;
+ let queued = false;
+ let lastFireAt = 0;
+ let stopped = false;
+ let retryTimer: ReturnType | null = null;
+ const scheduleRetry = (delayMs: number) => {
+ if (retryTimer || stopped) return;
+ retryTimer = setTimeout(() => { retryTimer = null; fire(); }, delayMs);
+ retryTimer.unref();
+ };
+ const fire = () => {
+ if (stopped || inFlight) { if (!stopped) queued = true; return; }
+ const now = Date.now();
+ if (now - lastFireAt < 1000) { queued = true; scheduleRetry(1000 - (now - lastFireAt)); return; }
+ lastFireAt = now;
+ inFlight = Promise.resolve(cb()).then(() => {
+ inFlight = null;
+ if (queued) { queued = false; fire(); }
+ }, () => { inFlight = null; });
+ };
+ const markReturned = (observerId: string) => {
+ stateWorkerStatus.ready = true;
+ state.lastReturnAt = new Date().toISOString();
+ stateWorkerStatus.lastReturnAt = state.lastReturnAt;
+ logger.info("State worker observer active again; running re-arm", { observerId });
+ fire();
+ };
+ const watchStateHandle = (handle: ObserverHandle, added: boolean) => {
+ let wasPending = handle.state === "pending" || handle.state === "suspended";
+ handle.onStateChange((next) => {
+ if (next === "pending" || next === "suspended") stateWorkerStatus.ready = false;
+ if (next === "active" && wasPending) markReturned(handle.id);
+ wasPending = next === "pending" || next === "suspended";
+ });
+ if (added && handle.state === "active" && !stateWorkerStatus.ready) markReturned(handle.id);
+ };
+ for (const handle of bindings.stateHandles) watchStateHandle(handle, false);
+ bindings.onStateHandle?.((handle) => watchStateHandle(handle, true));
+ if (typeof client.observe === "function" && bindings.pipeline === "observe") {
+ client.registerFunction?.("runtime::on-workers-changed", async (payload: unknown) => {
+ if (unwrapObserved<{ event?: string } | undefined>(payload, "input")?.event !== "worker_connected") return { handled: false };
+ try {
+ await probeOnce(client, 2000);
+ stateWorkerStatus.ready = true;
+ state.lastReturnAt = new Date().toISOString();
+ stateWorkerStatus.lastReturnAt = state.lastReturnAt;
+ logger.info("State worker reconnected; running re-arm");
+ fire();
+ } catch {}
+ return { handled: true };
+ });
+ client.observe(
+ { function_id: "engine::on-workers-changed", capture: ["input"] },
+ "runtime::on-workers-changed",
+ { id: "agentmemory:runtime:workers-changed" },
+ );
+ }
+ const probeTick = async () => {
+ if (stopped) return;
+ if (bindings.modes.state === "observe") {
+ if (stateWorkerStatus.ready && opts.pending?.()) fire();
+ return;
+ }
+ try {
+ await probeOnce(client, 2000);
+ stateWorkerStatus.ready = true;
+ if (!state.probeReady) {
+ state.probeReady = true;
+ state.lastReturnAt = new Date().toISOString();
+ stateWorkerStatus.lastReturnAt = state.lastReturnAt;
+ logger.info("State worker reachable again; running re-arm");
+ fire();
+ } else if (opts.pending?.()) {
+ fire();
+ }
+ } catch {
+ state.probeReady = false;
+ stateWorkerStatus.ready = false;
+ }
+ };
+ return {
+ state,
+ probeTick,
+ stop: () => {
+ stopped = true;
+ if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
+ },
+ };
+}
diff --git a/src/state/graph-generation.ts b/src/state/graph-generation.ts
index db2c27377c..d943754c4f 100644
--- a/src/state/graph-generation.ts
+++ b/src/state/graph-generation.ts
@@ -7,7 +7,7 @@ import { initializeGraphIndex } from "./graph-retrieval-index.js";
const CONTROL_SCOPE = KV.graphControl;
const CONTROL_KEY = "generation";
-const GRAPH_SCOPES = new Set([
+export const GRAPH_SCOPES = new Set([
KV.graphNodes, KV.graphEdges, KV.graphEdgeHistory, KV.graphSnapshot,
KV.graphNameIndex, KV.graphEdgeKey, KV.graphNodeDegree, KV.graphMembership,
KV.graphRetrievalControl, KV.graphRetrievalData, KV.graphIndexMigration, KV.graphIndexManifest,
diff --git a/src/state/index-persistence.ts b/src/state/index-persistence.ts
index 65240646c2..e6ee1a655c 100644
--- a/src/state/index-persistence.ts
+++ b/src/state/index-persistence.ts
@@ -230,6 +230,7 @@ export class IndexPersistence {
private earlySaveQueued = false;
private backfillQueue: Promise = Promise.resolve();
private recoveryError: string | null = null;
+ private recoveryPausedForUnavailable = false;
private backfillRevision = 0;
private recoveryReady: boolean;
private backfillSince: string | null | undefined;
@@ -311,6 +312,7 @@ export class IndexPersistence {
}
const valid = (Array.isArray(rows) ? rows : []).filter(isPendingVectorRow).sort((a, b) => a.q - b.q);
this.logSuppressed = true;
+ vector.beginReplay();
try {
for (const row of valid) {
result.entries++;
@@ -346,6 +348,7 @@ export class IndexPersistence {
result.added++;
}
} finally {
+ vector.endReplay();
this.logSuppressed = false;
}
if (result.skipped > 0) {
@@ -398,6 +401,7 @@ export class IndexPersistence {
if (!this.vector || this.recoveryError) return undefined;
if (!loaded || loaded.state === "unavailable") {
this.pauseRecovery(new Error("Persisted vector checkpoint is unavailable"));
+ this.recoveryPausedForUnavailable = true;
return undefined;
}
const shortfall = loaded.expectedCount !== undefined && (loaded.vector?.size ?? 0) < loaded.expectedCount;
@@ -429,6 +433,21 @@ export class IndexPersistence {
}
}
+ resumeAfterUnavailable(): boolean {
+ if (!this.recoveryPausedForUnavailable) return false;
+ this.recoveryPausedForUnavailable = false;
+ if (this.leg.lastError === this.recoveryError) {
+ this.leg.lastError = null;
+ this.leg.lastErrorAt = null;
+ }
+ this.recoveryError = null;
+ return true;
+ }
+
+ isPausedForUnavailable(): boolean {
+ return this.recoveryPausedForUnavailable;
+ }
+
private checkpointRecoveryCutoff(): string | null | undefined {
return this.completingBackfill ? null : this.backfillSince;
}
diff --git a/src/state/schema.ts b/src/state/schema.ts
index 03bae2f02b..e44526ad2d 100644
--- a/src/state/schema.ts
+++ b/src/state/schema.ts
@@ -28,6 +28,8 @@ export const KV = {
graphRetrievalData: "mem:graph:retrieval-data",
graphIndexMigration: "mem:graph:index-migration",
graphIndexManifest: "mem:graph:index-manifest",
+ graphExtractMarks: "mem:graph:extract-marks",
+ relationReactions: "mem:relation-reactions",
semantic: "mem:semantic",
procedural: "mem:procedural",
teamShared: (teamId: string) => `mem:team:${teamId}:shared`,
diff --git a/src/state/vector-index.ts b/src/state/vector-index.ts
index b31459655e..d2977d0977 100644
--- a/src/state/vector-index.ts
+++ b/src/state/vector-index.ts
@@ -37,12 +37,15 @@ export class VectorIndex {
private vectors: Map = new Map();
private changes: Map = new Map();
private listener: VectorChangeListener | null = null;
+ private touched: Set | null = null;
+ private replaying = false;
setChangeListener(listener: VectorChangeListener | null): void {
this.listener = listener;
}
add(obsId: string, sessionId: string, embedding: Float32Array): void {
+ if (this.skipForLiveChange(obsId)) return;
const entry = { embedding, sessionId };
this.vectors.set(obsId, entry);
this.changes.set(obsId, true);
@@ -50,6 +53,7 @@ export class VectorIndex {
}
remove(obsId: string): void {
+ if (this.skipForLiveChange(obsId)) return;
if (this.vectors.delete(obsId)) {
this.changes.set(obsId, false);
this.listener?.(obsId, null);
@@ -157,6 +161,15 @@ export class VectorIndex {
}
clear(): void {
+ if (this.replaying && this.touched) {
+ for (const obsId of [...this.vectors.keys()]) {
+ if (this.touched.has(obsId)) continue;
+ this.vectors.delete(obsId);
+ this.changes.set(obsId, false);
+ }
+ this.listener?.(null, null);
+ return;
+ }
const hadVectors = this.vectors.size > 0;
for (const obsId of this.vectors.keys()) this.changes.set(obsId, false);
this.vectors.clear();
@@ -168,6 +181,7 @@ export class VectorIndex {
string,
{ embedding: Float32Array; sessionId: string }
>;
+ const live = this.vectors;
this.vectors = new Map();
for (const [obsId, entry] of src) {
this.vectors.set(obsId, {
@@ -175,7 +189,51 @@ export class VectorIndex {
sessionId: entry.sessionId,
});
}
+ const liveChanges = this.changes;
this.changes = new Map(other.changes);
+ for (const obsId of this.touched ?? []) {
+ const entry = live.get(obsId);
+ if (entry) this.vectors.set(obsId, entry);
+ else this.vectors.delete(obsId);
+ this.changes.set(obsId, liveChanges.get(obsId) ?? Boolean(entry));
+ }
+ }
+
+ trackLiveChanges(): void {
+ this.touched ??= new Set();
+ }
+
+ finishLiveTracking(): void {
+ if (!this.touched) return;
+ for (const obsId of this.touched) {
+ if (!this.vectors.has(obsId)) this.changes.set(obsId, false);
+ }
+ this.touched = null;
+ }
+
+ beginReplay(): void {
+ this.replaying = true;
+ }
+
+ endReplay(): void {
+ this.replaying = false;
+ }
+
+ private skipForLiveChange(obsId: string): boolean {
+ if (!this.touched) return false;
+ if (this.replaying) return this.touched.has(obsId);
+ this.touched.add(obsId);
+ return false;
+ }
+
+ mergeMissingFrom(other: VectorIndex): number {
+ let merged = 0;
+ for (const [obsId, entry] of other.entries()) {
+ if (this.vectors.has(obsId) || this.changes.get(obsId) === false || this.touched?.has(obsId)) continue;
+ this.vectors.set(obsId, { embedding: new Float32Array(entry.embedding), sessionId: entry.sessionId });
+ merged++;
+ }
+ return merged;
}
serialize(): string {
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 46e318b89d..22ff9f0be4 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -10,6 +10,8 @@ import { isSearchLayer, type SearchLayer } from "../state/search-layer.js";
import { checkPayloadFrameSize, oversizedPayloadError, payloadByteLength, SAFE_PAYLOAD_BYTES } from "../state/frame-guard.js";
import { insightHttpResponse } from "../state/insight-response.js";
import { StateKV, collectAll } from "../state/kv.js";
+import { getDuplicateWorkers } from "../runtime/duplicates.js";
+import { stateWorkerStatus } from "../runtime/state-worker.js";
import { pinGraphState } from "../state/graph-generation.js";
import { addSessionToProjectIndex } from "../state/session-index.js";
import { getLatestHealth } from "../health/monitor.js";
@@ -34,7 +36,6 @@ import {
} from "../functions/search.js";
import {
LIST_PAGE_MAX,
- decodeCursor,
encodeCursor,
matchesText,
pageAfterCursor,
@@ -65,6 +66,7 @@ import { withoutObservationSource } from "../functions/observation-source.js";
import { clearSessionFinalize, scheduleSessionFinalize } from "../functions/session-finalize.js";
import { getSummaryTriggerTimeoutMs, requestSummaryRefresh } from "../functions/summary-state.js";
import { registerCompressionApi } from "./compression.js";
+import { getBindings } from "../runtime/bindings.js";
import {
getFinalizeIdleMs,
isGraphExtractionEnabled,
@@ -476,6 +478,11 @@ export function createStatusReporter(sdk: IIIClient, kv: StateKV, deps: StatusRe
stateStore,
capture: capture ?? null,
observeDedup: { skippedSinceStart: getDedupSkippedCount(), windowSeconds: Math.round(DEDUP_WINDOW_MS / 1000) },
+ runtime: {
+ bindings: getBindings(sdk).describe(),
+ duplicateWorkers: getDuplicateWorkers(),
+ stateWorker: { ready: stateWorkerStatus.ready, waitedMs: stateWorkerStatus.waitedMs, lastReturnAt: stateWorkerStatus.lastReturnAt },
+ },
});
};
}
@@ -580,9 +587,9 @@ export function registerApiTriggers(
provider?: ResilientProvider | { circuitState?: unknown },
): void {
registerGraphIndexApi(sdk, secret, checkAuth);
- sdk.registerTrigger({ type: "http", function_id: "api::graph-index-status", config: { api_path: "/agentmemory/graph/index", http_method: "GET" } });
- sdk.registerTrigger({ type: "http", function_id: "api::graph-index-migrate", config: { api_path: "/agentmemory/graph/index/migrate", http_method: "POST" } });
- sdk.registerTrigger({ type: "http", function_id: "api::graph-index-resume", config: { api_path: "/agentmemory/graph/index/resume", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::graph-index-status", config: { api_path: "/agentmemory/graph/index", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::graph-index-migrate", config: { api_path: "/agentmemory/graph/index/migrate", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::graph-index-resume", config: { api_path: "/agentmemory/graph/index/resume", http_method: "POST" } });
sdk.registerFunction(
"middleware::api-auth",
async (input: {
@@ -621,8 +628,7 @@ export function registerApiTriggers(
body: { status: "ok", ...instanceInfo() },
}),
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::liveness",
config: { api_path: "/agentmemory/livez", http_method: "GET" },
});
@@ -647,8 +653,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::config-flags",
config: {
api_path: "/agentmemory/config/flags",
@@ -681,8 +686,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::health",
config: {
api_path: "/agentmemory/health",
@@ -715,8 +719,7 @@ export function registerApiTriggers(
return { status_code: 200, headers: { "Cache-Control": "no-store" }, body: { ...report, liveEvents: getLiveEventsStats() } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::status",
config: { api_path: "/agentmemory/status", http_method: "GET" },
});
@@ -786,8 +789,7 @@ export function registerApiTriggers(
return { status_code: 200, headers: { "Cache-Control": "no-store" }, body: { capture: summary, ...(list as object) } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::capture",
config: { api_path: "/agentmemory/capture", http_method: "GET" },
});
@@ -808,8 +810,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::capture-retry",
config: { api_path: "/agentmemory/capture/retry", http_method: "POST" },
});
@@ -822,13 +823,11 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::capture-drain",
config: { api_path: "/agentmemory/capture/drain", http_method: "POST" },
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::observe",
config: {
api_path: "/agentmemory/observe",
@@ -891,8 +890,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::context",
config: {
api_path: "/agentmemory/context",
@@ -978,8 +976,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::search",
config: {
api_path: "/agentmemory/search",
@@ -989,16 +986,14 @@ export function registerApiTriggers(
});
registerCompressionApi(sdk, secret);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::compression-status",
config: {
http_method: "GET",
api_path: "/agentmemory/compression",
},
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::compression-retry",
config: {
http_method: "POST",
@@ -1025,8 +1020,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::compress-file",
config: { api_path: "/agentmemory/compress-file", http_method: "POST" },
});
@@ -1046,8 +1040,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::replay::load",
config: { api_path: "/agentmemory/replay/load", http_method: "GET" },
});
@@ -1063,8 +1056,7 @@ export function registerApiTriggers(
return { status_code: 200, body: { success: true, sessions } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::replay::sessions",
config: { api_path: "/agentmemory/replay/sessions", http_method: "GET" },
});
@@ -1109,8 +1101,7 @@ export function registerApiTriggers(
return { status_code: 202, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::replay::import",
config: { api_path: "/agentmemory/replay/import-jsonl", http_method: "POST" },
});
@@ -1186,8 +1177,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::session::start",
config: {
api_path: "/agentmemory/session/start",
@@ -1273,8 +1263,7 @@ export function registerApiTriggers(
return { status_code: 200, body: { success: true, ended: true } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::session::end",
config: {
api_path: "/agentmemory/session/end",
@@ -1297,8 +1286,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::summarize",
config: {
api_path: "/agentmemory/summarize",
@@ -1364,8 +1352,7 @@ export function registerApiTriggers(
return { status_code: 200, body: { commit: link } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::session::commit",
config: {
api_path: "/agentmemory/session/commit",
@@ -1399,8 +1386,7 @@ export function registerApiTriggers(
return { status_code: 200, body: { commit: link, sessions } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::session::by-commit",
config: {
api_path: "/agentmemory/session/by-commit",
@@ -1426,8 +1412,7 @@ export function registerApiTriggers(
return { status_code: 200, body: { commits: filtered } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::commits",
config: {
api_path: "/agentmemory/commits",
@@ -1522,8 +1507,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::sessions",
config: { api_path: "/agentmemory/sessions", http_method: "GET" },
});
@@ -1580,8 +1564,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::observations",
config: { api_path: "/agentmemory/observations", http_method: "GET" },
});
@@ -1606,8 +1589,7 @@ export function registerApiTriggers(
return { status_code: 200, body: { sessions } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::observations-locate",
config: { api_path: "/agentmemory/observations/locate", http_method: "GET" },
});
@@ -1622,8 +1604,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::file-context",
config: { api_path: "/agentmemory/file-context", http_method: "POST" },
});
@@ -1686,8 +1667,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::enrich",
config: { api_path: "/agentmemory/enrich", http_method: "POST" },
});
@@ -1738,8 +1718,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::remember",
config: { api_path: "/agentmemory/remember", http_method: "POST" },
});
@@ -1764,8 +1743,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::forget",
config: { api_path: "/agentmemory/forget", http_method: "POST" },
});
@@ -1780,8 +1758,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::consolidate",
config: { api_path: "/agentmemory/consolidate", http_method: "POST" },
});
@@ -1797,8 +1774,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::patterns",
config: { api_path: "/agentmemory/patterns", http_method: "POST" },
});
@@ -1811,8 +1787,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::generate-rules",
config: { api_path: "/agentmemory/generate-rules", http_method: "POST" },
});
@@ -1844,8 +1819,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::migrate",
config: { api_path: "/agentmemory/migrate", http_method: "POST" },
});
@@ -1860,8 +1834,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::evict",
config: { api_path: "/agentmemory/evict", http_method: "POST" },
});
@@ -1937,8 +1910,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::smart-search",
config: { api_path: "/agentmemory/smart-search", http_method: "POST" },
});
@@ -1962,8 +1934,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::diagnostic-followup",
config: {
api_path: "/agentmemory/diagnostics/followup",
@@ -1990,8 +1961,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::timeline",
config: { api_path: "/agentmemory/timeline", http_method: "POST" },
});
@@ -2012,8 +1982,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::profile",
config: { api_path: "/agentmemory/profile", http_method: "GET" },
});
@@ -2069,8 +2038,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::export",
config: { api_path: "/agentmemory/export", http_method: "GET" },
});
@@ -2091,8 +2059,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::import",
config: { api_path: "/agentmemory/import", http_method: "POST" },
});
@@ -2113,8 +2080,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::relations",
config: { api_path: "/agentmemory/relations", http_method: "POST" },
});
@@ -2148,8 +2114,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::evolve",
config: { api_path: "/agentmemory/evolve", http_method: "POST" },
});
@@ -2164,8 +2129,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::auto-forget",
config: { api_path: "/agentmemory/auto-forget", http_method: "POST" },
});
@@ -2185,8 +2149,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::claude-bridge-read",
config: { api_path: "/agentmemory/claude-bridge/read", http_method: "GET" },
});
@@ -2206,8 +2169,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::claude-bridge-sync",
config: {
api_path: "/agentmemory/claude-bridge/sync",
@@ -2246,8 +2208,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-query",
config: { api_path: "/agentmemory/graph/query", http_method: "POST" },
});
@@ -2264,8 +2225,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-stats",
config: { api_path: "/agentmemory/graph/stats", http_method: "GET" },
});
@@ -2293,8 +2253,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-node",
config: { api_path: "/agentmemory/graph/node", http_method: "GET" },
});
@@ -2314,8 +2273,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-snapshot-rebuild",
config: { api_path: "/agentmemory/graph/snapshot-rebuild", http_method: "POST" },
});
@@ -2335,8 +2293,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-reset",
config: { api_path: "/agentmemory/graph/reset", http_method: "POST" },
});
@@ -2376,8 +2333,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-compact",
config: { api_path: "/agentmemory/graph/compact", http_method: "POST" },
});
@@ -2403,8 +2359,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-extract",
config: { api_path: "/agentmemory/graph/extract", http_method: "POST" },
});
@@ -2464,8 +2419,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-build",
config: { api_path: "/agentmemory/graph/build", http_method: "POST" },
});
@@ -2501,8 +2455,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::graph-import-graphify",
config: { api_path: "/agentmemory/graph/import-graphify", http_method: "POST" },
});
@@ -2520,8 +2473,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::consolidate-pipeline",
config: {
api_path: "/agentmemory/consolidate-pipeline",
@@ -2549,8 +2501,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::team-share",
config: { api_path: "/agentmemory/team/share", http_method: "POST" },
});
@@ -2569,8 +2520,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::team-feed",
config: { api_path: "/agentmemory/team/feed", http_method: "GET" },
});
@@ -2587,8 +2537,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::team-profile",
config: { api_path: "/agentmemory/team/profile", http_method: "GET" },
});
@@ -2624,8 +2573,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::audit",
config: { api_path: "/agentmemory/audit", http_method: "GET" },
});
@@ -2646,8 +2594,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::governance-delete",
config: {
api_path: "/agentmemory/governance/memories",
@@ -2672,8 +2619,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::governance-bulk",
config: {
api_path: "/agentmemory/governance/bulk-delete",
@@ -2693,8 +2639,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::snapshots",
config: { api_path: "/agentmemory/snapshots", http_method: "GET" },
});
@@ -2712,8 +2657,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::snapshot-create",
config: { api_path: "/agentmemory/snapshot/create", http_method: "POST" },
});
@@ -2733,8 +2677,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::snapshot-restore",
config: { api_path: "/agentmemory/snapshot/restore", http_method: "POST" },
});
@@ -2882,8 +2825,7 @@ export function registerApiTriggers(
return { status_code: 200, body };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::memories",
config: { api_path: "/agentmemory/memories", http_method: "GET" },
});
@@ -2903,8 +2845,7 @@ export function registerApiTriggers(
return { status_code: 200, body: { memory } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::memory-by-id",
config: { api_path: "/agentmemory/memories/:id", http_method: "GET" },
});
@@ -2920,8 +2861,7 @@ export function registerApiTriggers(
return { status_code: 200, body };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::semantic-list",
config: { api_path: "/agentmemory/semantic", http_method: "GET" },
});
@@ -2937,8 +2877,7 @@ export function registerApiTriggers(
return { status_code: 200, body };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::procedural-list",
config: { api_path: "/agentmemory/procedural", http_method: "GET" },
});
@@ -2952,8 +2891,7 @@ export function registerApiTriggers(
return { status_code: 200, body: await consolidationStatus() };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::consolidation-status",
config: { api_path: "/agentmemory/consolidation/status", http_method: "GET" },
});
@@ -2969,8 +2907,7 @@ export function registerApiTriggers(
return { status_code: 200, body };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::relations-list",
config: { api_path: "/agentmemory/relations", http_method: "GET" },
});
@@ -3008,8 +2945,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::vision-search",
config: { api_path: "/agentmemory/vision-search", http_method: "POST" },
});
@@ -3036,8 +2972,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::vision-embed",
config: { api_path: "/agentmemory/vision-embed", http_method: "POST" },
});
@@ -3049,8 +2984,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::slot-list",
config: { api_path: "/agentmemory/slots", http_method: "GET" },
});
@@ -3068,8 +3002,7 @@ export function registerApiTriggers(
}
return { status_code: 200, body: result };
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::slot-get",
config: { api_path: "/agentmemory/slot", http_method: "GET" },
});
@@ -3118,8 +3051,7 @@ export function registerApiTriggers(
}
return { status_code: 201, body: result };
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::slot-create",
config: { api_path: "/agentmemory/slot", http_method: "POST" },
});
@@ -3141,8 +3073,7 @@ export function registerApiTriggers(
}
return { status_code: 200, body: result };
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::slot-append",
config: { api_path: "/agentmemory/slot/append", http_method: "POST" },
});
@@ -3166,8 +3097,7 @@ export function registerApiTriggers(
}
return { status_code: 200, body: result };
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::slot-replace",
config: { api_path: "/agentmemory/slot/replace", http_method: "POST" },
});
@@ -3185,8 +3115,7 @@ export function registerApiTriggers(
}
return { status_code: 200, body: result };
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::slot-delete",
config: { api_path: "/agentmemory/slot", http_method: "DELETE" },
});
@@ -3206,8 +3135,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::slot-reflect", payload });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::slot-reflect",
config: { api_path: "/agentmemory/slot/reflect", http_method: "POST" },
});
@@ -3234,8 +3162,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::action-create",
config: { api_path: "/agentmemory/actions", http_method: "POST" },
});
@@ -3260,8 +3187,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::action-update",
config: { api_path: "/agentmemory/actions/update", http_method: "POST" },
});
@@ -3281,8 +3207,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::action-list",
config: { api_path: "/agentmemory/actions", http_method: "GET" },
});
@@ -3299,8 +3224,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::action-get",
config: { api_path: "/agentmemory/actions/get", http_method: "GET" },
});
@@ -3322,8 +3246,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::action-edge",
config: { api_path: "/agentmemory/actions/edges", http_method: "POST" },
});
@@ -3341,8 +3264,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::frontier",
config: { api_path: "/agentmemory/frontier", http_method: "GET" },
});
@@ -3358,8 +3280,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::next",
config: { api_path: "/agentmemory/next", http_method: "GET" },
});
@@ -3377,8 +3298,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::lease-acquire",
config: { api_path: "/agentmemory/leases/acquire", http_method: "POST" },
});
@@ -3396,8 +3316,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::lease-release",
config: { api_path: "/agentmemory/leases/release", http_method: "POST" },
});
@@ -3415,8 +3334,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::lease-renew",
config: { api_path: "/agentmemory/leases/renew", http_method: "POST" },
});
@@ -3435,8 +3353,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::routine-create",
config: { api_path: "/agentmemory/routines", http_method: "POST" },
});
@@ -3451,8 +3368,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::routine-list",
config: { api_path: "/agentmemory/routines", http_method: "GET" },
});
@@ -3470,8 +3386,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::routine-run",
config: { api_path: "/agentmemory/routines/run", http_method: "POST" },
});
@@ -3488,8 +3403,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::routine-status",
config: { api_path: "/agentmemory/routines/status", http_method: "GET" },
});
@@ -3513,8 +3427,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::signal-send",
config: { api_path: "/agentmemory/signals/send", http_method: "POST" },
});
@@ -3537,8 +3450,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::signal-read",
config: { api_path: "/agentmemory/signals", http_method: "GET" },
});
@@ -3562,8 +3474,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::checkpoint-create",
config: { api_path: "/agentmemory/checkpoints", http_method: "POST" },
});
@@ -3586,8 +3497,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::checkpoint-resolve",
config: { api_path: "/agentmemory/checkpoints/resolve", http_method: "POST" },
});
@@ -3603,8 +3513,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::checkpoint-list",
config: { api_path: "/agentmemory/checkpoints", http_method: "GET" },
});
@@ -3624,8 +3533,7 @@ export function registerApiTriggers(
return { status_code: 201, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::mesh-register",
config: { api_path: "/agentmemory/mesh/peers", http_method: "POST" },
});
@@ -3640,8 +3548,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::mesh-list",
config: { api_path: "/agentmemory/mesh/peers", http_method: "GET" },
});
@@ -3658,8 +3565,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::mesh-sync",
config: { api_path: "/agentmemory/mesh/sync", http_method: "POST" },
});
@@ -3674,8 +3580,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::mesh-receive",
config: { api_path: "/agentmemory/mesh/receive", http_method: "POST" },
});
@@ -3754,7 +3659,7 @@ export function registerApiTriggers(
for (const [name, rows] of collections) {
const unexportable = rows.some((row) => payloadByteLength(row) > SAFE_PAYLOAD_BYTES);
if (unexportable) {
- return { status_code: 413, body: oversizedPayloadError(SAFE_PAYLOAD_BYTES + 1, `use ?since, ?project, or ?collections to exclude the oversized ${name} record`) };
+ return { status_code: 413, body: oversizedPayloadError(SAFE_PAYLOAD_BYTES + 1, `use ?since or ?project to exclude the oversized ${name} record`) };
}
}
if (!paged) {
@@ -3813,8 +3718,7 @@ export function registerApiTriggers(
return { status_code: 200, body };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::mesh-export",
config: { api_path: "/agentmemory/mesh/export", http_method: "GET" },
});
@@ -3840,8 +3744,7 @@ export function registerApiTriggers(
}
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::flow-compress",
config: { api_path: "/agentmemory/flow/compress", http_method: "POST" },
});
@@ -3855,8 +3758,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::branch-detect",
config: { api_path: "/agentmemory/branch/detect", http_method: "GET" },
});
@@ -3870,8 +3772,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::branch-worktrees",
config: { api_path: "/agentmemory/branch/worktrees", http_method: "GET" },
});
@@ -3885,8 +3786,7 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::branch-sessions",
config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" },
});
@@ -3921,8 +3821,7 @@ export function registerApiTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::viewer",
config: { api_path: "/agentmemory/viewer", http_method: "GET" },
});
@@ -3935,7 +3834,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sentinel-create", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } });
sdk.registerFunction("api::sentinel-trigger", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -3945,7 +3844,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } });
sdk.registerFunction("api::sentinel-check", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -3953,7 +3852,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sentinel-check", payload: {} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } });
sdk.registerFunction("api::sentinel-cancel", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -3963,7 +3862,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sentinel-cancel", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } });
sdk.registerFunction("api::sentinel-list", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -3972,7 +3871,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sentinel-list", payload: { status: params.status, type: params.type } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } });
sdk.registerFunction("api::sketch-create", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -3982,7 +3881,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sketch-create", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } });
sdk.registerFunction("api::sketch-add", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -3992,7 +3891,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sketch-add", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } });
sdk.registerFunction("api::sketch-promote", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4002,7 +3901,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sketch-promote", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } });
sdk.registerFunction("api::sketch-discard", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4012,7 +3911,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sketch-discard", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } });
sdk.registerFunction("api::sketch-list", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4021,7 +3920,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sketch-list", payload: { status: params.status, project: params.project } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } });
sdk.registerFunction("api::sketch-gc", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4029,7 +3928,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::sketch-gc", payload: {} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } });
sdk.registerFunction("api::crystallize", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4039,7 +3938,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::crystallize", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } });
sdk.registerFunction("api::crystal-list", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4055,7 +3954,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::crystal-list", payload: { project: params.project, sessionId: params.sessionId, limit } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } });
sdk.registerFunction("api::auto-crystallize", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4064,7 +3963,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::auto-crystallize", payload: body || {} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } });
sdk.registerFunction("api::diagnose", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4073,7 +3972,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::diagnose", payload: body || {} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } });
sdk.registerFunction("api::heal", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4082,7 +3981,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::heal", payload: body || {} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } });
sdk.registerFunction("api::facet-tag", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4092,7 +3991,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::facet-tag", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } });
sdk.registerFunction("api::facet-untag", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4102,7 +4001,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::facet-untag", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } });
sdk.registerFunction("api::facet-query", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4111,7 +4010,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::facet-query", payload: body || {} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } });
sdk.registerFunction("api::facet-get", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4121,7 +4020,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::facet-get", payload: { targetId: params.targetId } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } });
sdk.registerFunction("api::facet-stats", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4130,7 +4029,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::facet-stats", payload: { targetType: params.targetType } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } });
sdk.registerFunction("api::verify", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4140,7 +4039,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::verify", payload: { id: body.id } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } });
sdk.registerFunction("api::cascade-update", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4152,7 +4051,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::cascade-update", payload: { supersededMemoryId: body.supersededMemoryId } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } });
sdk.registerFunction("api::lesson-save", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4179,7 +4078,7 @@ export function registerApiTriggers(
const statusCode = result?.action === "created" ? 201 : 200;
return { status_code: statusCode, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } });
sdk.registerFunction("api::lesson-list", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4207,7 +4106,7 @@ export function registerApiTriggers(
} });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } });
sdk.registerFunction("api::lesson-search", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4217,7 +4116,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::lesson-recall", payload: body });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } });
sdk.registerFunction("api::lesson-get", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4236,7 +4135,7 @@ export function registerApiTriggers(
}
return { status_code: 200, body: { success: true, lesson } };
});
- sdk.registerTrigger({ type: "http", function_id: "api::lesson-get", config: { api_path: "/agentmemory/lessons/get", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::lesson-get", config: { api_path: "/agentmemory/lessons/get", http_method: "POST" } });
sdk.registerFunction("api::lesson-strengthen", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4246,7 +4145,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: body.lessonId } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } });
sdk.registerFunction("api::lesson-delete", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4261,7 +4160,7 @@ export function registerApiTriggers(
}
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::lesson-delete", config: { api_path: "/agentmemory/lessons/delete", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::lesson-delete", config: { api_path: "/agentmemory/lessons/delete", http_method: "POST" } });
sdk.registerFunction("api::obsidian-export", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4278,7 +4177,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { vaultDir, types } });
return { status_code: 200, body: result };
});
- sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } });
sdk.registerFunction("api::reflect", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4290,7 +4189,7 @@ export function registerApiTriggers(
} });
return insightHttpResponse(result);
});
- sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } });
sdk.registerFunction("api::insight-list", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4317,7 +4216,7 @@ export function registerApiTriggers(
} });
return insightHttpResponse(result);
});
- sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } });
sdk.registerFunction("api::insight-search", async (req: HttpRequest) => {
const denied = checkAuth(req, secret);
@@ -4332,5 +4231,5 @@ export function registerApiTriggers(
} });
return insightHttpResponse(result);
});
- sdk.registerTrigger({ type: "http", function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } });
}
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index e11187cd75..d6f2f045f2 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -1,5 +1,5 @@
import { TriggerAction, type IIIClient } from "iii-sdk";
-import type { CompressedObservation, Memory, Session } from "../types.js";
+import type { Memory, Session } from "../types.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { emitLiveEvent } from "../viewer/live-events.js";
@@ -15,6 +15,8 @@ import { logger } from "../logger.js";
import { getSummaryTriggerTimeoutMs } from "../functions/summary-state.js";
import { noteMemoryChange, noteSessionChange } from "../state/viewer-counts.js";
+import { getBindings } from "../runtime/bindings.js";
+import { registerObserverTarget } from "../runtime/observed.js";
// Global marker recording when corpus consolidation last ran, used to debounce
// the per-turn session-stop fan-out.
const CONSOLIDATION_MARKER_KEY = "consolidation:lastRun";
@@ -37,7 +39,7 @@ async function consolidationDueUnserialized(kv: StateKV): Promise {
// check through an in-process chain so exactly one concurrent caller wins.
let consolidationCheckChain: Promise = Promise.resolve();
-function consolidationDue(kv: StateKV): Promise {
+export function consolidationDue(kv: StateKV): Promise {
const result = consolidationCheckChain.then(() =>
consolidationDueUnserialized(kv),
);
@@ -53,6 +55,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
timeoutMs: getSummaryTriggerTimeoutMs(),
});
if (summary?.unchanged === true) return summary;
+ const bindings = getBindings(sdk);
const fireVoid = (function_id: string, payload: unknown) =>
sdk
.trigger({ function_id, payload, action: TriggerAction.Void() })
@@ -62,23 +65,11 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
error: err instanceof Error ? err.message : String(err),
}),
);
- if (isReflectEnabled()) {
+ if (isReflectEnabled() && !bindings.observing("mem::post-session-reflect")) {
fireVoid("mem::slot-reflect", { sessionId: data.sessionId });
}
- // Unconditional: mem::graph-extract gates its LLM pass internally.
- try {
- const observations = await kv.list(
- KV.observations(data.sessionId),
- );
- const compressed = observations.filter((o) => o.title);
- if (compressed.length > 0) {
- fireVoid("mem::graph-extract", { observations: compressed });
- }
- } catch (err) {
- logger.warn("graph-extract trigger failed", {
- sessionId: data.sessionId,
- error: err instanceof Error ? err.message : String(err),
- });
+ if (!bindings.observing("mem::post-session-graph")) {
+ fireVoid("mem::post-session-graph", { sessionId: data.sessionId });
}
// Crystals + lessons consolidation. The stop lifecycle is the single
// source of truth: event::session::stopped fires for ALL agents (the
@@ -96,7 +87,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
// are full-corpus LLM work with no internal "nothing changed" guard, so
// firing them every turn is a cost/latency storm for connected agents.
// Bound the global corpus consolidation to once per cooldown window.
- if (isConsolidationEnabled() && !data.skipConsolidation) {
+ if (isConsolidationEnabled() && !data.skipConsolidation && !bindings.observing("mem::post-session-consolidate")) {
if (await consolidationDue(kv)) {
fireVoid("mem::consolidate-pipeline", { tier: "all", force: true });
fireVoid("mem::auto-crystallize", { olderThanDays: 0 });
@@ -108,8 +99,9 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
return summary;
});
// React to observation count changes and emit a lightweight live event for dashboards/viewer.
- sdk.registerFunction(
+ registerObserverTarget(sdk,
"event::session::observation-count-changed",
+ "input",
async (payload: {
key: string;
event_type: string;
@@ -145,14 +137,11 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
return { emitted: true };
},
);
- sdk.registerTrigger({
- type: "state",
- function_id: "event::session::observation-count-changed",
- config: { scope: KV.sessions },
- });
+ getBindings(sdk).state({ function_id: "event::session::observation-count-changed", scope: KV.sessions, maxInFlight: 1 });
- sdk.registerFunction(
+ registerObserverTarget(sdk,
"event::memory::changed",
+ "input",
async (payload: {
key: string;
event_type: string;
@@ -187,11 +176,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
return { emitted: true };
},
);
- sdk.registerTrigger({
- type: "state",
- function_id: "event::memory::changed",
- config: { scope: KV.memories },
- });
+ getBindings(sdk).state({ function_id: "event::memory::changed", scope: KV.memories, maxInFlight: 1 });
}
export function isStateDelete(payload: { event_type: string; new_value?: unknown }): boolean {
diff --git a/src/triggers/viewer-sse.ts b/src/triggers/viewer-sse.ts
index 574ca05589..b2780f0382 100644
--- a/src/triggers/viewer-sse.ts
+++ b/src/triggers/viewer-sse.ts
@@ -2,6 +2,7 @@ import { http } from "@iii-dev/helpers/http";
import type { IIIClient } from "iii-sdk";
import { liveEvents, type LiveEventWriter } from "../viewer/live-events.js";
+import { getBindings } from "../runtime/bindings.js";
export function registerViewerSse(sdk: IIIClient): void {
sdk.registerFunction(
"api::viewer-events",
@@ -17,8 +18,7 @@ export function registerViewerSse(sdk: IIIClient): void {
liveEvents.subscribe(res.stream as LiveEventWriter);
}),
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::viewer-events",
config: {
api_path: "/agentmemory/viewer/events",
diff --git a/src/triggers/viewer-streams.ts b/src/triggers/viewer-streams.ts
index 6e8fcfdc22..861692dd50 100644
--- a/src/triggers/viewer-streams.ts
+++ b/src/triggers/viewer-streams.ts
@@ -43,6 +43,8 @@ import { buildConfigFlags, checkAuth, createConsolidationStatusReader, createSta
import { isStateDelete, sendViewerEvent } from "./events.js";
import { setAuditRecordedListener } from "../functions/audit.js";
+import { getBindings } from "../runtime/bindings.js";
+import { registerObserverTarget } from "../runtime/observed.js";
type Response = {
status_code: number;
headers?: Record;
@@ -120,7 +122,7 @@ export function registerViewerStreamTriggers(
entity: string;
countKind?: CountedKind;
}): void {
- sdk.registerFunction(options.functionId, async (payload: StatePayload) => {
+ registerObserverTarget(sdk, options.functionId, "input", async (payload: StatePayload) => {
const deleted = isStateDelete(payload);
const row = deleted ? null : payload.new_value ?? null;
if (options.countKind) noteRowChange(options.countKind, payload.old_value, row);
@@ -133,11 +135,7 @@ export function registerViewerStreamTriggers(
});
return { emitted: true };
});
- sdk.registerTrigger({
- type: "state",
- function_id: options.functionId,
- config: { scope: options.scope },
- });
+ getBindings(sdk).state({ function_id: options.functionId, scope: options.scope, maxInFlight: 1 });
}
registerRowStream({ functionId: "event::viewer::lesson-changed", scope: KV.lessons, entity: "lesson", countKind: "lessons" });
@@ -178,8 +176,9 @@ export function registerViewerStreamTriggers(
throw error;
}
}
- sdk.registerFunction(
+ registerObserverTarget(sdk,
"event::viewer::graph-snapshot-changed",
+ "input",
async (payload: StatePayload) => withKeyedLock("graph:viewer-events", async () => {
if (payload.key !== GRAPH_SNAPSHOT_KEY) return { emitted: false };
if (!await isLegacyGraphState(kv)) return { emitted: false };
@@ -189,11 +188,7 @@ export function registerViewerStreamTriggers(
return { emitted: true };
}),
);
- sdk.registerTrigger({
- type: "state",
- function_id: "event::viewer::graph-snapshot-changed",
- config: { scope: KV.graphSnapshot },
- });
+ getBindings(sdk).state({ function_id: "event::viewer::graph-snapshot-changed", scope: KV.graphSnapshot, key: GRAPH_SNAPSHOT_KEY });
const pendingGraphItems = { nodes: 0, edges: 0, since: 0 };
let graphItemsTimer: ReturnType | null = null;
@@ -228,7 +223,7 @@ export function registerViewerStreamTriggers(
noteGraphItem(kind);
return { emitted: true };
}));
- sdk.registerTrigger({ type: "state", function_id: functionId, config: { scope } });
+ getBindings(sdk).state({ function_id: functionId, scope, maxInFlight: 1 });
}
setGraphGenerationListener(async (kind) => withKeyedLock("graph:viewer-events", async () => {
@@ -245,8 +240,9 @@ export function registerViewerStreamTriggers(
await publishGraphMetadata(kind === "reset");
}));
- sdk.registerFunction(
+ registerObserverTarget(sdk,
"event::viewer::consolidation-changed",
+ "input",
async (payload: StatePayload) => {
if (payload.key !== CONSOLIDATION_LAST_RUN_KEY || isStateDelete(payload)) {
return { emitted: false };
@@ -259,14 +255,11 @@ export function registerViewerStreamTriggers(
return { emitted: true };
},
);
- sdk.registerTrigger({
- type: "state",
- function_id: "event::viewer::consolidation-changed",
- config: { scope: KV.config },
- });
+ getBindings(sdk).state({ function_id: "event::viewer::consolidation-changed", scope: KV.config, key: CONSOLIDATION_LAST_RUN_KEY });
- sdk.registerFunction(
+ registerObserverTarget(sdk,
"event::viewer::health-changed",
+ "input",
async (payload: StatePayload) => {
if (payload.key !== HEALTH_LATEST_KEY || isStateDelete(payload)) {
return { emitted: false };
@@ -280,11 +273,7 @@ export function registerViewerStreamTriggers(
return { emitted: true };
},
);
- sdk.registerTrigger({
- type: "state",
- function_id: "event::viewer::health-changed",
- config: { scope: KV.health },
- });
+ getBindings(sdk).state({ function_id: "event::viewer::health-changed", scope: KV.health, key: HEALTH_LATEST_KEY });
const { restPort } = loadConfig();
@@ -318,8 +307,7 @@ export function registerViewerStreamTriggers(
};
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::viewer-snapshot",
config: {
api_path: "/agentmemory/viewer/snapshot",
@@ -335,8 +323,7 @@ export function registerViewerStreamTriggers(
return { status_code: 200, body: { counts: await getViewerCounts(kv) } };
},
);
- sdk.registerTrigger({
- type: "http",
+ getBindings(sdk).http({
function_id: "api::counts",
config: {
api_path: "/agentmemory/counts",
diff --git a/src/types.ts b/src/types.ts
index d4061c1d58..1f968033e2 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -1,3 +1,29 @@
+export interface RelationReactionMark {
+ targetId: string;
+ type: MemoryRelation["type"];
+ sources: Record;
+ isLatestBefore?: boolean;
+ strengthBefore?: number;
+ confidenceBefore?: number;
+ contradictBase?: number;
+ contradictPenalties?: Record;
+ relatedIdsAdded?: string[];
+ firstAppliedAt: string;
+ lastAppliedAt: string;
+ pending?: {
+ target: Pick;
+ removeMark: boolean;
+ };
+}
+
+export interface GraphExtractMark {
+ sessionId: string;
+ lastObservationTimestamp: string;
+ extractedCount: number;
+ updatedAt: string;
+ graphGeneration?: string | null;
+}
+
export interface Session {
id: string;
project: string;
@@ -145,6 +171,7 @@ export interface Memory {
files: string[];
sessionIds: string[];
strength: number;
+ confidence?: number;
version: number;
recurrence?: number;
parentId?: string;
@@ -732,6 +759,14 @@ export interface AuditEntry {
| "core_add"
| "core_remove"
| "auto_page"
+ | "compress-failed"
+ | "summarize-failed"
+ | "graph-extract-failed"
+ | "consolidate-failed"
+ | "reflect-failed"
+ | "skill-extract-failed"
+ | "cascade"
+ | "relation_reaction"
| "vision_embed"
| "slot_append"
| "slot_replace"
diff --git a/src/version.ts b/src/version.ts
index 7884e4517a..0b03a645a4 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1,2 +1,2 @@
export const VERSION = "0.9.33";
-export const III_PINNED_VERSION = "0.25.1";
+export const III_PINNED_VERSION = "0.26.0";
diff --git a/src/viewer/index.html b/src/viewer/index.html
index 407f02303c..74c93ca1a7 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -2557,6 +2557,17 @@ agentmemory
html += '';
}
+ if (!store.report && !statusReportRequest) {
+ ensureStatusReport().then(function() {
+ if (state.activeTab === 'dashboard' && store.report) renderTab('dashboard');
+ });
+ }
+ if (store.report && store.report.runtime && store.report.runtime.duplicateWorkers && store.report.runtime.duplicateWorkers.count > 1) {
+ html += 'Duplicate worker
';
+ html += '
' + esc(store.report.runtime.duplicateWorkers.count + ' agentmemory workers share this engine. Stop the extra daemon (agentmemory stop) and restart.') + '
';
+ html += '
';
+ }
+
html += '
What your agents remember updates live
';
html += '';
html += statCard({ label: 'Memories', help: 'memory', tab: 'memories', value: fmtNum(c.latestMemories), sub: fmtNum(c.memories) + ' incl. older versions' });
diff --git a/test/bindings.test.ts b/test/bindings.test.ts
new file mode 100644
index 0000000000..be99a04ca4
--- /dev/null
+++ b/test/bindings.test.ts
@@ -0,0 +1,348 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { Bindings, getBindings } from "../src/runtime/bindings.js";
+import { registerObserverTarget, unwrapObserved } from "../src/runtime/observed.js";
+import { KV } from "../src/state/schema.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+import { logger } from "../src/logger.js";
+
+type Observed = { source: Record
; target: string; options?: Record };
+
+function makeHandle(initial: "active" | "pending" = "active") {
+ const listeners = new Set<(state: string) => void>();
+ const handle = {
+ id: "obs-1",
+ state: initial as string,
+ reason: undefined,
+ ready: vi.fn(() => Promise.resolve()),
+ onStateChange: (listener: (state: string) => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; },
+ dispose: vi.fn(() => Promise.resolve()),
+ become(next: string) { handle.state = next; for (const listener of listeners) listener(next); },
+ };
+ return handle;
+}
+
+function fakeSdk(initial: "active" | "pending" = "active") {
+ const observed: Observed[] = [];
+ const handles: ReturnType[] = [];
+ const sdk = {
+ observed,
+ handles,
+ observe: vi.fn((source: Record, target: string, options?: Record) => {
+ observed.push({ source, target, options });
+ const handle = makeHandle(initial);
+ handles.push(handle);
+ return handle;
+ }),
+ };
+ return sdk;
+}
+
+const ROUTE = {
+ function_id: "api::x",
+ config: { api_path: "/agentmemory/x", http_method: "POST", middleware_function_ids: ["middleware::api-auth"] },
+};
+
+describe("Bindings", () => {
+ const env = process.env;
+ beforeEach(() => { vi.clearAllMocks(); env.AGENTMEMORY_BINDINGS = undefined; });
+ afterEach(() => { env.AGENTMEMORY_BINDINGS = undefined; });
+
+ it("observes http::on-request with the route as args right away", () => {
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ expect(sdk.observed).toHaveLength(1);
+ const route = sdk.observed[0];
+ expect(route.source).toEqual({
+ function_id: "http::on-request",
+ args: { method: "POST", path: "/agentmemory/x", middleware_function_ids: ["middleware::api-auth"] },
+ });
+ expect(route.target).toBe("api::x");
+ expect(route.options).toEqual({ id: "agentmemory:route:POST /agentmemory/x", max_in_flight: 1024 });
+ });
+
+ it("defaults the method to GET and passes public_webhook only when set", () => {
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ b.http({ type: "http", function_id: "api::y", config: { api_path: "/y", public_webhook: true } });
+ expect(sdk.observed[0].source.args).toEqual({ method: "GET", path: "/y", public_webhook: true });
+ });
+
+ it("refuses route config the http worker does not accept", () => {
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ const odd = { ...ROUTE, config: { ...ROUTE.config, condition_function_id: "x::y" } };
+ expect(() => b.http(odd as never)).toThrow(/condition_function_id/);
+ expect(sdk.observed).toHaveLength(0);
+ });
+
+ it("observes state::on-changed with capture input and a scope filter", () => {
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ b.state({ function_id: "ev::mem", scope: KV.memories, maxInFlight: 1 });
+ const st = sdk.observed[0];
+ expect(st.source).toEqual({
+ function_id: "state::on-changed",
+ filters: { "input.scope": { $eq: KV.memories } },
+ capture: ["input"],
+ });
+ expect(st.options).toEqual({ id: "agentmemory:state:ev::mem", max_in_flight: 1 });
+ expect(b.stateHandles).toHaveLength(1);
+ });
+
+ it("graph scopes produce an $or prefix filter and key filters are included", () => {
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ b.state({ function_id: "ev::g", scope: KV.graphNodes, key: "current" });
+ expect(sdk.observed[0].source.filters).toEqual({
+ $or: [
+ { "input.scope": { $eq: KV.graphNodes } },
+ { "input.scope": { $prefix: `${KV.graphNodes}:generation:` } },
+ ],
+ "input.key": { $eq: "current" },
+ });
+ });
+
+ it("no observer source carries the removed on or deliver fields", () => {
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ b.state({ function_id: "ev::x", scope: KV.sessions });
+ b.observeStateChanges({ "input.scope": { $eq: KV.relations } }, "ev::r");
+ for (const { source } of sdk.observed) {
+ expect(source).not.toHaveProperty("on");
+ expect(source).not.toHaveProperty("deliver");
+ }
+ });
+
+ it("activate resolves at once when every route and state observer is active", async () => {
+ const sdk = fakeSdk("active");
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ b.state({ function_id: "ev::x", scope: KV.memories });
+ expect(await b.activate()).toEqual({ state: "observe", http: "observe" });
+ expect(b.describe()).toMatchObject({ state: "observe", http: "observe", pipeline: "observe", failedObservers: 0, reasons: [] });
+ });
+
+ it("modes follow observer state changes and activate resolves when they settle", async () => {
+ const sdk = fakeSdk("pending");
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ b.state({ function_id: "ev::x", scope: KV.memories });
+ expect(b.modes).toEqual({ state: "pending", http: "pending" });
+ const settled = b.activate();
+ sdk.handles[1].become("active");
+ expect(b.modes).toEqual({ state: "observe", http: "pending" });
+ sdk.handles[0].become("active");
+ expect(await settled).toEqual({ state: "observe", http: "observe" });
+ });
+
+ it("observes a route again when an earlier connection still holds its observer id", async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = fakeSdk("active");
+ let first = true;
+ sdk.observe.mockImplementation((source: Record, target: string, options?: Record) => {
+ sdk.observed.push({ source, target, options });
+ const handle = makeHandle(first ? "error" : "active");
+ if (first) handle.ready.mockImplementation(() => Promise.reject(Object.assign(new Error("conflict"), { code: "OBSERVER_ID_CONFLICT" })));
+ first = false;
+ sdk.handles.push(handle);
+ return handle;
+ });
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sdk.observed).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(sdk.observed).toHaveLength(2);
+ expect(sdk.observed[1].options).toEqual(sdk.observed[0].options);
+ expect(sdk.handles[0].dispose).toHaveBeenCalled();
+ expect(b.handles).toEqual([sdk.handles[1]]);
+ expect(b.describe()).toMatchObject({ http: "observe", failedObservers: 0, reasons: [] });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("activate resolves when a retried route observer becomes active", async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = fakeSdk("active");
+ let first = true;
+ sdk.observe.mockImplementation((source: Record, target: string, options?: Record) => {
+ sdk.observed.push({ source, target, options });
+ const handle = makeHandle(first ? "pending" : "active");
+ if (first) handle.ready.mockImplementation(() => Promise.reject(Object.assign(new Error("conflict"), { code: "OBSERVER_ID_CONFLICT" })));
+ first = false;
+ sdk.handles.push(handle);
+ return handle;
+ });
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ let modes: unknown = null;
+ void b.activate().then((m) => { modes = m; });
+ sdk.handles[0].become("error");
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(modes).toEqual({ state: "pending", http: "observe" });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("reports a route as rejected after the id conflict retries run out", async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = fakeSdk("active");
+ sdk.observe.mockImplementation((source: Record, target: string, options?: Record) => {
+ sdk.observed.push({ source, target, options });
+ const handle = makeHandle("active");
+ handle.state = "error";
+ handle.ready.mockImplementation(() => Promise.reject(Object.assign(new Error("conflict"), { code: "OBSERVER_ID_CONFLICT" })));
+ sdk.handles.push(handle);
+ return handle;
+ });
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ await vi.advanceTimersByTimeAsync(200_000);
+ expect(sdk.observed).toHaveLength(5);
+ expect(b.describe().failedObservers).toBe(1);
+ expect(b.describe().reasons).toContain("route POST /agentmemory/x observer rejected: OBSERVER_ID_CONFLICT");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("reports a pipeline target as observed only while its own observer is active", () => {
+ const sdk = fakeSdk("pending");
+ const b = new Bindings(sdk as never);
+ b.observePipeline({ function_id: "mem::observe" }, "mem::compress");
+ b.observePipeline({ function_id: "event::session::stopped" }, "mem::post-session-graph");
+ expect(b.observing("mem::compress")).toBe(false);
+ sdk.handles[0].become("active");
+ expect(b.observing("mem::compress")).toBe(true);
+ expect(b.observing("mem::post-session-graph")).toBe(false);
+ expect(b.describe().reasons).toContain("1 pipeline observers are not active, so their work runs as direct calls: mem::post-session-graph");
+ sdk.handles[0].become("error");
+ expect(b.observing("mem::compress")).toBe(false);
+ });
+
+ it("never reports a pipeline target as observed in inline mode", () => {
+ process.env.AGENTMEMORY_BINDINGS = "inline";
+ const sdk = fakeSdk("active");
+ const b = new Bindings(sdk as never);
+ b.observePipeline({ function_id: "mem::observe" }, "mem::compress");
+ expect(b.observing("mem::compress")).toBe(false);
+ });
+
+ it("reports observers that stay inactive while others of the same provider are active", () => {
+ const sdk = fakeSdk("pending");
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ b.http({ ...ROUTE, config: { ...ROUTE.config, api_path: "/agentmemory/other" } });
+ sdk.handles[0].become("active");
+ expect(b.modes.http).toBe("observe");
+ expect(b.describe().reasons).toEqual(["1 of 2 http observers are not active (pending)"]);
+ sdk.handles[1].become("active");
+ expect(b.describe().reasons).toEqual([]);
+ });
+
+ it("activate resolves with pending modes after the deadline and reports why", async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = fakeSdk("pending");
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ const modes = b.activate();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(await modes).toEqual({ state: "pending", http: "pending" });
+ expect(b.describe().reasons).toEqual(["http::on-request observers pending until the http worker connects"]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("route observer max_in_flight honors AGENTMEMORY_ROUTE_MAX_IN_FLIGHT and falls back on invalid", () => {
+ process.env.AGENTMEMORY_ROUTE_MAX_IN_FLIGHT = "256";
+ let sdk = fakeSdk();
+ new Bindings(sdk as never).http(ROUTE);
+ expect(sdk.observed[0].options?.max_in_flight).toBe(256);
+ process.env.AGENTMEMORY_ROUTE_MAX_IN_FLIGHT = "abc";
+ sdk = fakeSdk();
+ new Bindings(sdk as never).http(ROUTE);
+ expect(sdk.observed[0].options?.max_in_flight).toBe(1024);
+ process.env.AGENTMEMORY_ROUTE_MAX_IN_FLIGHT = undefined;
+ });
+
+ it("logs and counts a rejected observer", async () => {
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ const handle = makeHandle();
+ handle.ready = vi.fn(() => Promise.reject(Object.assign(new Error("conflict"), { code: "HTTP_ROUTE_CONFLICT" })));
+ sdk.observe.mockReturnValueOnce(handle as never);
+ b.http(ROUTE);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(logger.error).toHaveBeenCalledWith(
+ expect.stringContaining("POST /agentmemory/x"),
+ expect.objectContaining({ error: "HTTP_ROUTE_CONFLICT" }),
+ );
+ const report = b.describe();
+ expect(report.failedObservers).toBe(1);
+ expect(report.observers).toBe(0);
+ expect(report.reasons.join("\n")).toContain("POST /agentmemory/x observer rejected: HTTP_ROUTE_CONFLICT");
+ });
+
+ it("skips bindings and runs the pipeline inline for a client without observe", () => {
+ const sdk = {};
+ const b = new Bindings(sdk as never);
+ b.http(ROUTE);
+ b.state({ function_id: "ev::x", scope: KV.memories });
+ expect(b.pipeline).toBe("inline");
+ expect(b.handles).toHaveLength(0);
+ expect(b.describe().reasons).toContain("client has no observe(); bindings skipped");
+ });
+
+ it("AGENTMEMORY_BINDINGS=trigger is treated as inline with a warning", () => {
+ env.AGENTMEMORY_BINDINGS = "trigger";
+ const sdk = fakeSdk();
+ const b = new Bindings(sdk as never);
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("AGENTMEMORY_BINDINGS=trigger"));
+ expect(b.pipeline).toBe("inline");
+ b.http(ROUTE);
+ expect(sdk.observed).toHaveLength(1);
+ });
+
+ it("per-sdk singleton", () => {
+ const sdk = {};
+ expect(getBindings(sdk as never)).toBe(getBindings(sdk as never));
+ });
+});
+
+describe("observed payloads", () => {
+ const activation = { observer_id: "o", activation_id: "a", function_id: "f", namespace: "agentmemory", invocation_id: "i", status: "success", started_at_ms: 1, duration_ms: 2 };
+
+ it("unwraps input and output from an Observed payload", () => {
+ expect(unwrapObserved({ ...activation, input: { key: "k" } }, "input")).toEqual({ key: "k" });
+ expect(unwrapObserved({ ...activation, output: { observationId: "o1" } }, "output")).toEqual({ observationId: "o1" });
+ });
+
+ it("passes a direct call payload through unchanged", () => {
+ const direct = { sessionId: "s1", observationId: "o1" };
+ expect(unwrapObserved(direct, "input")).toBe(direct);
+ expect(unwrapObserved(direct, "output")).toBe(direct);
+ expect(unwrapObserved(null, "input")).toBeNull();
+ });
+
+ it("registerObserverTarget hands the handler the captured field", async () => {
+ const handlers = new Map unknown>();
+ const sdk = { registerFunction: (id: string, fn: (payload: unknown) => unknown) => handlers.set(id, fn) };
+ registerObserverTarget(sdk as never, "t::in", "input", (payload: { key: string }) => payload.key);
+ registerObserverTarget(sdk as never, "t::out", "output", (payload: { id: string }) => payload.id);
+ expect(await handlers.get("t::in")!({ ...activation, input: { key: "k" } })).toBe("k");
+ expect(await handlers.get("t::out")!({ ...activation, output: { id: "o1" } })).toBe("o1");
+ expect(await handlers.get("t::in")!({ key: "direct" })).toBe("direct");
+ });
+});
diff --git a/test/cascade-audit.test.ts b/test/cascade-audit.test.ts
new file mode 100644
index 0000000000..0ba3facfc2
--- /dev/null
+++ b/test/cascade-audit.test.ts
@@ -0,0 +1,593 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { readFileSync } from "node:fs";
+import { registerCascadeFunctions, failureCounters, flushDeleteCascade } from "../src/functions/cascade-audit.js";
+import { registerPipelineObservers } from "../src/runtime/pipeline-observers.js";
+import { getBindings } from "../src/runtime/bindings.js";
+import { recordObservers } from "./helpers/mocks.js";
+import { KV } from "../src/state/schema.js";
+import type { Memory, MemoryRelation, Facet } from "../src/types.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+
+const audits: Array> = [];
+vi.mock("../src/functions/audit.js", () => ({
+ recordAudit: vi.fn(async (_kv: unknown, operation: string, functionId: string, targetIds: string[], details: Record) => {
+ audits.push({ operation, functionId, targetIds, details });
+ return { id: "aud_x" };
+ }),
+ safeAudit: vi.fn(async (_kv: unknown, operation: string, functionId: string, targetIds: string[], details: Record) => {
+ audits.push({ operation, functionId, targetIds, details });
+ return { id: "aud_x" };
+ }),
+}));
+
+const removedBm25: string[] = [];
+const removedVector: string[] = [];
+const addedBm25: string[] = [];
+const addedVector: string[] = [];
+const addedVectorCalls: unknown[][] = [];
+vi.mock("../src/functions/search.js", () => ({
+ getSearchIndex: () => ({ remove: (id: string) => removedBm25.push(id), add: (obs: { id: string }) => addedBm25.push(obs.id) }),
+ getVectorIndex: () => ({ size: 0 }),
+ vectorIndexRemove: (id: string) => { removedVector.push(id); },
+ vectorIndexAddGuarded: async (...args: unknown[]) => { addedVector.push(args[0] as string); addedVectorCalls.push(args); return true; },
+ scheduleIndexSave: () => {},
+ isMemoryIndexReady: () => true,
+}));
+
+function memoryKv(seed: Record> = {}) {
+ const store = seed;
+ return {
+ store,
+ get: vi.fn(async (scope: string, key: string) => store[scope]?.get(key) ?? null),
+ set: vi.fn(async (scope: string, key: string, v: unknown) => { (store[scope] ??= new Map()).set(key, v); }),
+ delete: vi.fn(async (scope: string, key: string) => { store[scope]?.delete(key); }),
+ update: vi.fn(async (scope: string, key: string, ops: Array<{ path: string; value: unknown }>) => {
+ const row = store[scope]?.get(key) as Record | undefined;
+ if (row) for (const op of ops) row[op.path] = op.value;
+ return row;
+ }),
+ list: vi.fn(async (scope: string) => [...(store[scope]?.values() ?? [])]),
+ listKeys: vi.fn(async (scope: string) => [...(store[scope]?.keys() ?? [])]),
+ iterate: async function* (scope: string) { yield [...(store[scope]?.values() ?? [])]; },
+ backend: "file",
+ };
+}
+
+function fakeFns() {
+ const fns = new Map Promise>();
+ return {
+ functions: fns,
+ registerFunction(id: string, h: (d: unknown) => Promise) { fns.set(id, h); },
+ };
+}
+
+describe("mem::record-failure", () => {
+ beforeEach(() => { audits.length = 0; });
+
+ it("classifies retryable vs permanent and writes the op audit", async () => {
+ const sdk = fakeFns();
+ const kv = memoryKv();
+ registerCascadeFunctions(sdk as never, kv as never);
+ const fn = sdk.functions.get("mem::record-failure")!;
+ await fn({ input: { observationId: "o1", sessionId: "s1" }, output: {}, error: { code: "circuit_breaker_open", message: "breaker" }, duration_ms: 12 }, { source_fn: "mem::compress" });
+ expect(audits[0].operation).toBe("compress-failed");
+ expect(audits[0].details).toMatchObject({ code: "circuit_breaker_open", retryable: true, durationMs: 12 });
+ expect(audits[0].targetIds).toEqual(["o1", "s1"]);
+ const c = failureCounters();
+ expect(c.transient).toBeGreaterThan(0);
+ audits.length = 0;
+ await fn({ observer_id: "agentmemory:pipeline:failure:mem::summarize:soft", input: {}, output: { success: false, error: "source_unavailable" } });
+ expect(audits[0].operation).toBe("summarize-failed");
+ expect(audits[0].details).toMatchObject({ code: "source_unavailable", retryable: false });
+ audits.length = 0;
+ await fn({ observer_id: "agentmemory:pipeline:failure:mem::graph-extract:partial", input: {}, output: { success: true, partial: true, error: "llm down" } });
+ expect(audits).toHaveLength(1);
+ expect(audits[0].operation).toBe("graph-extract-failed");
+ expect(audits[0].details).toMatchObject({ message: "llm down" });
+ });
+
+ it("dedupes by (function_id, code) in a fixed 60s window and counts every failure", async () => {
+ vi.useFakeTimers();
+ const sdk = fakeFns();
+ registerCascadeFunctions(sdk as never, memoryKv() as never);
+ const fn = sdk.functions.get("mem::record-failure")!;
+ const env = { input: {}, output: {}, error: { code: "parse_failed" } };
+ const meta = { source_fn: "mem::graph-extract" };
+ await fn(env, meta);
+ vi.advanceTimersByTime(30_000);
+ const r1 = await fn(env, meta);
+ expect(r1).toMatchObject({ deduped: true });
+ expect(audits.length).toBe(1);
+ vi.advanceTimersByTime(31_000);
+ const r2 = await fn(env, meta);
+ expect(r2).toMatchObject({ recorded: true });
+ expect(audits.length).toBe(2);
+ expect(audits[1].details).toMatchObject({ dedupedCount: 1 });
+ vi.useRealTimers();
+ });
+});
+
+describe("pipeline observer specs", () => {
+ it("failure observers: error + soft specs per function", async () => {
+ const bound = recordObservers();
+ const observed = bound.sources as Array<{ source: Record; target: string; options?: Record }>;
+ const sdk = { registerFunction: vi.fn(), observe: bound.observe };
+ const b = getBindings(sdk as never);
+ registerPipelineObservers(sdk as never);
+ await b.activate();
+ const compressErr = observed.find((o) => o.options?.id === "agentmemory:pipeline:failure:mem::compress:error")!;
+ expect(compressErr.source).toEqual({ function_id: "mem::compress", filters: { error: { $exists: true } }, capture: ["input", "error"] });
+ expect(compressErr.options?.max_in_flight).toBe(4);
+ const summarizeSoft = observed.find((o) => o.options?.id === "agentmemory:pipeline:failure:mem::summarize:soft")!;
+ expect(summarizeSoft.source).toEqual({ function_id: "mem::summarize", filters: { "output.success": { $eq: false } }, capture: ["input", "output"] });
+ const graphPartial = observed.find((o) => o.options?.id === "agentmemory:pipeline:failure:mem::graph-extract:partial")!;
+ expect(graphPartial.source).toEqual({ function_id: "mem::graph-extract", filters: { "output.partial": { $eq: true } }, capture: ["input", "output"] });
+ const deleted = observed.find((o) => o.options?.id === "agentmemory:cascade:deleted")!;
+ const or = deleted.source.filters as { $or: Array> };
+ expect(or.$or[0]).toMatchObject({ "input.event_type": { $eq: "state:deleted" }, "input.scope": { $prefix: "mem:obs:" } });
+ const rel = observed.find((o) => o.options?.id === "agentmemory:cascade:relation-reaction")!;
+ const or2 = rel.source.filters as { $or: Array> };
+ expect(or2.$or[0]["input.new_value.type"]).toEqual({ $in: ["supersedes", "contradicts", "extends"] });
+ expect(rel.options?.max_in_flight).toBe(1);
+ });
+});
+
+describe("mem::on-record-deleted", () => {
+ beforeEach(() => { audits.length = 0; removedBm25.length = 0; removedVector.length = 0; });
+
+ it("removes bm25/vector entries, facets (incl. lessons), reconciles observationCount, audits", async () => {
+ const sdk = fakeFns();
+ const facets = new Map([
+ ["f1", { id: "f1", targetId: "m1", targetType: "memory", dimension: "d", value: "v", createdAt: "t" }],
+ ["f2", { id: "f2", targetId: "l1", targetType: "memory", dimension: "d", value: "v", createdAt: "t" }],
+ ["f3", { id: "f3", targetId: "other", targetType: "memory", dimension: "d", value: "v", createdAt: "t" }],
+ ]);
+ const kv = memoryKv({
+ [KV.facets]: facets,
+ [KV.sessions]: new Map([["s1", { id: "s1", observationCount: 5 }]]),
+ "mem:obs:s1": new Map([["o1", {}], ["o2", {}]]),
+ });
+ registerCascadeFunctions(sdk as never, kv as never);
+ const fn = sdk.functions.get("mem::on-record-deleted")!;
+ kv.store[KV.observations("s1")]?.delete("o9");
+ await fn({ event_type: "state:deleted", scope: "mem:obs:s1", key: "o9" });
+ expect(removedBm25).toContain("o9");
+ expect(removedVector).toContain("o9");
+ kv.store[KV.lessons]?.set("l1", { deleted: true });
+ await fn({ scope: KV.lessons, key: "l1", event_type: "state:updated", new_value: { deleted: true }, old_value: { deleted: false } });
+ kv.store[KV.memories]?.delete("m1");
+ await fn({ event_type: "state:deleted", scope: KV.memories, key: "m1" });
+ const { flushDeleteCascade } = await import("../src/functions/cascade-audit.js");
+ await flushDeleteCascade();
+ expect(kv.update).toHaveBeenCalledWith(KV.sessions, "s1", [{ type: "set", path: "observationCount", value: 2 }]);
+ expect(audits.find((a) => a.operation === "cascade")).toBeTruthy();
+ expect(kv.store[KV.facets].has("f2")).toBe(false);
+ expect(kv.store[KV.facets].has("f3")).toBe(true);
+ expect(kv.store[KV.facets].has("f1")).toBe(false);
+ });
+
+ it("keeps index entries when the key was restored before the delete delivery ran", async () => {
+ const sdk = fakeFns();
+ const kv = memoryKv({
+ [KV.memories]: new Map([["m1", { id: "m1" }]]),
+ [KV.lessons]: new Map([["l1", { id: "l1", deleted: true }]]),
+ [KV.facets]: new Map(),
+ });
+ registerCascadeFunctions(sdk as never, kv as never);
+ const fn = sdk.functions.get("mem::on-record-deleted")!;
+ const r = await fn({ event_type: "state:deleted", scope: KV.memories, key: "m1" });
+ expect(r).toMatchObject({ restored: "m1" });
+ expect(removedBm25).not.toContain("m1");
+ expect(removedVector).not.toContain("m1");
+ await fn({ scope: KV.lessons, key: "l1", event_type: "state:updated", new_value: { deleted: true }, old_value: { deleted: false } });
+ expect(removedBm25).toContain("l1");
+ expect(removedVector).toContain("l1");
+ await flushDeleteCascade();
+ });
+
+ it("keeps index entries when the restoration read fails and removes them once the flush confirms the delete", async () => {
+ const sdk = fakeFns();
+ const kv = memoryKv({ [KV.memories]: new Map(), [KV.facets]: new Map() });
+ const realGet = kv.get.bind(kv);
+ let failNext = true;
+ kv.get = (async (scope: string, key: string) => {
+ if (failNext && scope === KV.memories && key === "m2") {
+ failNext = false;
+ throw new Error("state read failed");
+ }
+ return realGet(scope, key);
+ }) as typeof kv.get;
+ registerCascadeFunctions(sdk as never, kv as never);
+ const fn = sdk.functions.get("mem::on-record-deleted")!;
+ const r = await fn({ event_type: "state:deleted", scope: KV.memories, key: "m2" });
+ expect(r).toMatchObject({ deferred: "m2", queued: true });
+ expect(removedBm25).not.toContain("m2");
+ expect(removedVector).not.toContain("m2");
+ await flushDeleteCascade();
+ expect(removedBm25).toContain("m2");
+ expect(removedVector).toContain("m2");
+ });
+
+ it("worker shutdown drains queued delete cascades before the SDK shuts down", () => {
+ const src = readFileSync(new URL("../src/index.ts", import.meta.url), "utf8");
+ const body = src.slice(src.indexOf("const shutdown = async"));
+ const drain = body.indexOf("flushDeleteCascade()");
+ expect(drain).toBeGreaterThan(0);
+ expect(drain).toBeLessThan(body.indexOf("sdk.shutdown()"));
+ });
+});
+
+describe("event::graph::edge-reaction", () => {
+ const base: Memory = { id: "tgt", createdAt: "t", updatedAt: "t", type: "fact", title: "x", content: "c", concepts: [], files: [], sessionIds: [], strength: 1, version: 1, isLatest: true, confidence: 0.8, relatedIds: ["pre"] } as unknown as Memory;
+ const rel: MemoryRelation = { type: "supersedes", sourceId: "src", targetId: "tgt", createdAt: "2026-01-01T00:00:00Z", confidence: 0.6 };
+
+ function seeded(marks: Record = {}) {
+ const sdk = fakeFns();
+ const kv = memoryKv({
+ [KV.memories]: new Map([["tgt", { ...base }], ["src", { ...base, id: "src" }]]),
+ [KV.relations]: new Map(),
+ [KV.relationReactions]: new Map(Object.entries(marks)),
+ });
+ registerCascadeFunctions(sdk as never, kv as never);
+ return { kv, fn: sdk.functions.get("event::graph::edge-reaction")! };
+ }
+ const created = (key: string, r: Partial = {}) => ({ event_type: "state:created", scope: KV.relations, key, new_value: { ...rel, ...r } });
+ const deleted = (key: string, r: Partial = {}) => ({ event_type: "state:deleted", scope: KV.relations, key, old_value: { ...rel, ...r } });
+ const mem = (kv: ReturnType["kv"]) => kv.store[KV.memories].get("tgt") as Memory;
+ const mark = (kv: ReturnType["kv"], type = "supersedes") => kv.store[KV.relationReactions]?.get(`tgt:${type}`) as Record | undefined;
+
+ it("two supersedes: second adds contributor only; delete restores originals when empty", async () => {
+ const { kv, fn } = seeded();
+ await fn(created("rA"));
+ await fn(created("rB", { sourceId: "srcB" }));
+ expect(mem(kv).strength).toBeCloseTo(0.5);
+ const r1 = await fn(deleted("rA"));
+ expect(r1).toMatchObject({ unreacted: false, remaining: 1 });
+ expect(mem(kv).isLatest).toBe(false);
+ expect(mem(kv).strength).toBeCloseTo(0.5);
+ const r2 = await fn(deleted("rB", { sourceId: "srcB" }));
+ expect(r2).toMatchObject({ unreacted: true });
+ expect(mem(kv).isLatest).toBe(true);
+ expect(mem(kv).strength).toBeCloseTo(1);
+ expect(mark(kv)).toBeUndefined();
+ });
+
+ it("contradicts: cumulative floored decay, partial undo adds back per-relation delta", async () => {
+ const { kv, fn } = seeded();
+ await fn(created("rA", { type: "contradicts", confidence: 0.5 }));
+ await fn(created("rB", { type: "contradicts", sourceId: "srcB", confidence: 0.5 }));
+ expect(mem(kv).confidence).toBeCloseTo(0.5);
+ const mutual = await fn(created("rC", { type: "contradicts", sourceId: "tgt", targetId: "src", confidence: 0.5 }));
+ expect(mutual).toMatchObject({ reacted: true });
+ await fn(deleted("rA", { type: "contradicts" }));
+ expect(mem(kv).confidence).toBeCloseTo(0.65);
+ await fn(deleted("rB", { type: "contradicts", sourceId: "srcB" }));
+ expect(mem(kv).confidence).toBeCloseTo(0.8);
+ });
+
+ it("supersedes removes the target from search indexes and the final undo re-adds it", async () => {
+ const { kv, fn } = seeded();
+ removedBm25.length = 0; removedVector.length = 0;
+ await fn(created("rA"));
+ expect(removedBm25).toContain("tgt");
+ expect(removedVector).toContain("tgt");
+ addedBm25.length = 0; addedVector.length = 0;
+ await fn(deleted("rA"));
+ expect(mem(kv).isLatest).toBe(true);
+ expect(addedBm25).toContain("tgt");
+ expect(addedVector).toContain("tgt");
+ const call = addedVectorCalls.find((args) => args[0] === "tgt")!;
+ expect(call).toHaveLength(4);
+ expect(typeof call[1]).toBe("string");
+ expect(String(call[2])).toContain("c");
+ expect(call[3]).toEqual({ kind: "memory", logId: "tgt" });
+ });
+
+ it("contradicts on a memory without a stored confidence starts from the default salience and stays finite", async () => {
+ const { kv, fn } = seeded();
+ const plain = { ...base } as Record;
+ delete plain.confidence;
+ kv.store[KV.memories].set("tgt", plain);
+ await fn(created("rA", { type: "contradicts", confidence: 0.5 }));
+ expect(mem(kv).confidence).toBeCloseTo(0.35);
+ expect(mem(kv).confidence!).toBeLessThanOrEqual(0.5);
+ await fn(deleted("rA", { type: "contradicts" }));
+ expect(mem(kv).confidence).toBeCloseTo(0.5);
+ });
+
+ it("contradicts: undoing one relation keeps the floor a remaining relation still holds", async () => {
+ const { kv, fn } = seeded();
+ kv.store[KV.memories].set("tgt", { ...base, confidence: 0.2 });
+ await fn(created("rA", { type: "contradicts", confidence: 0.5 }));
+ await fn(created("rB", { type: "contradicts", sourceId: "srcB", confidence: 0.5 }));
+ expect(mem(kv).confidence).toBeCloseTo(0.05);
+ await fn(deleted("rA", { type: "contradicts" }));
+ expect(mem(kv).confidence).toBeCloseTo(0.05);
+ await fn(deleted("rB", { type: "contradicts", sourceId: "srcB" }));
+ expect(mem(kv).confidence).toBeCloseTo(0.2);
+ });
+
+ it("supersedes cycle guard via reverse mark", async () => {
+ const { kv, fn } = seeded();
+ await fn(created("rA"));
+ const r = await fn(created("rB", { sourceId: "tgt", targetId: "src" }));
+ expect(r).toMatchObject({ skipped: "cycle" });
+ expect(audits.find((a) => (a.details as { skipped?: string }).skipped === "cycle")).toBeTruthy();
+ });
+
+ it("supersedes cycle guard rejects a three-relation cycle", async () => {
+ const { kv, fn } = seeded();
+ kv.store[KV.memories].set("c", { ...base, id: "c" });
+ await fn(created("rA"));
+ await fn(created("rB", { sourceId: "c", targetId: "src" }));
+ const r = await fn(created("rC", { sourceId: "tgt", targetId: "c" }));
+ expect(r).toMatchObject({ skipped: "cycle" });
+ expect((kv.store[KV.memories].get("c") as Memory).isLatest).toBe(true);
+ });
+
+ it("a failed mark write after the memory write does not apply the reaction twice on retry", async () => {
+ const { kv, fn } = seeded();
+ const realSet = kv.set.getMockImplementation()!;
+ let armed = true;
+ kv.set.mockImplementation(async (scope: string, key: string, v: unknown) => {
+ if (armed && scope === KV.relationReactions && !(v as { pending?: unknown }).pending) {
+ armed = false;
+ throw new Error("state worker restarting");
+ }
+ return realSet(scope, key, v);
+ });
+ await expect(fn(created("rA"))).rejects.toThrow("state worker restarting");
+ const r = await fn(created("rA"));
+ expect(r).toMatchObject({ skipped: "already_applied" });
+ expect(mem(kv).strength).toBeCloseTo(0.5);
+ expect(mark(kv)).toMatchObject({ strengthBefore: 1, isLatestBefore: true });
+ expect(mark(kv)?.pending).toBeUndefined();
+ await fn(deleted("rA"));
+ expect(mem(kv).strength).toBeCloseTo(1);
+ expect(mem(kv).isLatest).toBe(true);
+ });
+
+ it("a pending mark whose memory write was lost is completed by the next delivery", async () => {
+ const { kv, fn } = seeded({
+ "tgt:supersedes": {
+ targetId: "tgt", type: "supersedes", sources: { rA: "src" }, isLatestBefore: true, strengthBefore: 1,
+ firstAppliedAt: rel.createdAt, lastAppliedAt: rel.createdAt,
+ pending: { target: { isLatest: false, strength: 0.5, confidence: 0.8, relatedIds: ["pre"] }, removeMark: false },
+ },
+ });
+ const r = await fn(created("rA"));
+ expect(r).toMatchObject({ skipped: "already_applied" });
+ expect(mem(kv).strength).toBeCloseTo(0.5);
+ expect(mem(kv).isLatest).toBe(false);
+ expect(mark(kv)?.pending).toBeUndefined();
+ expect(mark(kv)).toMatchObject({ strengthBefore: 1 });
+ });
+
+ it("extends: undo removes only the added ids", async () => {
+ const { kv, fn } = seeded();
+ await fn(created("rA", { type: "extends" }));
+ await fn(created("rB", { type: "extends", sourceId: "srcB" }));
+ expect(mem(kv).relatedIds).toEqual(["pre", "src", "srcB"]);
+ await fn(deleted("rA", { type: "extends" }));
+ await fn(deleted("rB", { type: "extends", sourceId: "srcB" }));
+ expect(mem(kv).relatedIds).toEqual(["pre"]);
+ });
+
+ it("replayed create applies once", async () => {
+ const { kv, fn } = seeded();
+ await fn(created("rA"));
+ const r = await fn(created("rA"));
+ expect(r).toMatchObject({ skipped: "already_applied" });
+ expect(mem(kv).strength).toBeCloseTo(0.5);
+ });
+
+ it("missing target audits and skips", async () => {
+ const { kv, fn } = seeded();
+ kv.store[KV.memories].delete("tgt");
+ const r = await fn(created("rA"));
+ expect(r).toMatchObject({ skipped: "missing_target" });
+ });
+});
+
+describe("mem::relate lock safety", () => {
+ it("resolves when sourceId === targetId and a follow-up relate resolves", async () => {
+ const { registerRelationsFunction } = await import("../src/functions/relations.js");
+ const sdk = fakeFns();
+ const kv = memoryKv({
+ [KV.memories]: new Map([["m1", { id: "m1", relatedIds: [], sessionIds: [], concepts: [], files: [] }]]),
+ [KV.relations]: new Map(),
+ });
+ registerRelationsFunction(sdk as never, kv as never);
+ const fn = sdk.functions.get("mem::relate")!;
+ const timed = (p: Promise) =>
+ Promise.race([p, new Promise((_, rj) => setTimeout(() => rj(new Error("deadlock")), 2000))]);
+ const r1 = await timed(fn({ sourceId: "m1", targetId: "m1", type: "extends" }));
+ expect(r1).toMatchObject({ success: true });
+ const r2 = await timed(fn({ sourceId: "m1", targetId: "m1", type: "contradicts" }));
+ expect(r2).toMatchObject({ success: true });
+ });
+});
+
+describe("delete cascade batcher resilience", () => {
+ function seededDelete() {
+ const sdk = fakeFns();
+ const kv = memoryKv({
+ [KV.sessions]: new Map([
+ ["s1", { id: "s1", observationCount: 5 }],
+ ["s2", { id: "s2", observationCount: 3 }],
+ ]),
+ [KV.observations("s1")]: new Map([["o1", {}], ["o2", {}]]),
+ [KV.observations("s2")]: new Map([["o3", {}]]),
+ [KV.facets]: new Map(),
+ });
+ registerCascadeFunctions(sdk as never, kv as never);
+ return { kv, fn: sdk.functions.get("mem::on-record-deleted")! };
+ }
+
+ it("scans the facet scope once per target type for a batch of deletes", async () => {
+ const { kv, fn } = seededDelete();
+ for (const id of ["m1", "m2", "m3"]) await fn({ event_type: "state:deleted", scope: KV.memories, key: id });
+ kv.list.mockClear();
+ await flushDeleteCascade();
+ expect(kv.list.mock.calls.filter((c) => c[0] === KV.facets)).toHaveLength(1);
+ });
+
+ it("retries facet cleanup for a target whose read failed", async () => {
+ const { kv, fn } = seededDelete();
+ kv.store[KV.facets].set("f1", { id: "f1", targetId: "m1", targetType: "memory", dimension: "d", value: "v", createdAt: "t" });
+ await fn({ event_type: "state:deleted", scope: KV.memories, key: "m1" });
+ kv.get.mockRejectedValueOnce(new Error("state worker restarting"));
+ await flushDeleteCascade();
+ expect(kv.store[KV.facets].has("f1")).toBe(true);
+ await flushDeleteCascade();
+ expect(kv.store[KV.facets].has("f1")).toBe(false);
+ });
+
+ it("a failed flush logs, requeues sessions, and reconciles on the next flush", async () => {
+ const { kv, fn } = seededDelete();
+ const rejections: unknown[] = [];
+ const onRej = (e: unknown) => { rejections.push(e); };
+ process.on("unhandledRejection", onRej);
+ try {
+ kv.listKeys.mockRejectedValueOnce(new Error("state worker restarting"));
+ await fn({ event_type: "state:deleted", scope: "mem:obs:s1", key: "o9" });
+ await flushDeleteCascade().catch(() => {});
+ expect(rejections).toEqual([]);
+ await flushDeleteCascade();
+ expect(kv.update).toHaveBeenCalledWith(KV.sessions, "s1", [
+ { type: "set", path: "observationCount", value: 2 },
+ ]);
+ } finally {
+ process.off("unhandledRejection", onRej);
+ }
+ });
+
+ it("items queued during an in-flight flush are drained by the next batch", async () => {
+ vi.useFakeTimers();
+ try {
+ const { kv, fn } = seededDelete();
+ let release!: () => void;
+ const gate = new Promise((r) => { release = r; });
+ kv.list.mockImplementationOnce(() => gate.then(() => []));
+ await fn({ event_type: "state:deleted", scope: "mem:obs:s1", key: "o1" });
+ await vi.advanceTimersByTimeAsync(600);
+ await fn({ event_type: "state:deleted", scope: "mem:obs:s2", key: "o3" });
+ release();
+ await vi.advanceTimersByTimeAsync(600);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(kv.update).toHaveBeenCalledWith(KV.sessions, "s2", [
+ { type: "set", path: "observationCount", value: 1 },
+ ]);
+ const cascades = audits.filter((a) => a.operation === "cascade");
+ expect(cascades.length).toBeGreaterThanOrEqual(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("memory delete vs relation writers", () => {
+ const memory = (id: string) => ({ id, createdAt: "t", updatedAt: "t", type: "fact", title: "x", content: "c", concepts: [], files: [], sessionIds: [], strength: 1, version: 1, isLatest: true, confidence: 0.8, relatedIds: [] });
+
+ function gateRead(kv: ReturnType, key: string, nth: number) {
+ let reached!: () => void;
+ let release!: () => void;
+ const reachedP = new Promise((r) => { reached = r; });
+ const releaseP = new Promise((r) => { release = r; });
+ const original = kv.get.getMockImplementation()!;
+ let seen = 0;
+ kv.get.mockImplementation(async (scope: string, k: string) => {
+ if (scope === KV.memories && k === key && ++seen === nth) {
+ const value = await original(scope, k);
+ reached();
+ await releaseP;
+ return value;
+ }
+ return original(scope, k);
+ });
+ return { reached: reachedP, release };
+ }
+
+ it("a delete that lands during an edge reaction is not undone by the reaction write", async () => {
+ const { deleteMemoryUnderLock } = await import("../src/state/memory-utils.js");
+ const sdk = fakeFns();
+ const kv = memoryKv({
+ [KV.memories]: new Map([["tgt", memory("tgt")], ["src", memory("src")]]),
+ [KV.relationReactions]: new Map(),
+ });
+ registerCascadeFunctions(sdk as never, kv as never);
+ const gate = gateRead(kv, "tgt", 1);
+ const reaction = sdk.functions.get("event::graph::edge-reaction")!({
+ event_type: "state:created", scope: KV.relations, key: "rRace",
+ new_value: { type: "supersedes", sourceId: "src", targetId: "tgt", createdAt: "2026-01-01T00:00:00Z", confidence: 0.6 },
+ });
+ await gate.reached;
+ const deletion = deleteMemoryUnderLock(kv as never, KV.memories, "tgt");
+ await new Promise((r) => setTimeout(r, 20));
+ gate.release();
+ await reaction;
+ await deletion;
+ expect(kv.store[KV.memories].has("tgt")).toBe(false);
+ });
+
+ it("a delete that lands during mem::relate is not undone by the relatedIds write", async () => {
+ const { deleteMemoryUnderLock } = await import("../src/state/memory-utils.js");
+ const { registerRelationsFunction } = await import("../src/functions/relations.js");
+ const sdk = fakeFns();
+ const kv = memoryKv({
+ [KV.memories]: new Map([["m1", memory("m1")], ["m2", memory("m2")]]),
+ [KV.relations]: new Map(),
+ });
+ registerRelationsFunction(sdk as never, kv as never);
+ const gate = gateRead(kv, "m1", 2);
+ const relate = sdk.functions.get("mem::relate")!({ sourceId: "m1", targetId: "m2", type: "related" });
+ await gate.reached;
+ const deletion = deleteMemoryUnderLock(kv as never, KV.memories, "m1");
+ await new Promise((r) => setTimeout(r, 20));
+ gate.release();
+ await relate;
+ await deletion;
+ expect(kv.store[KV.memories].has("m1")).toBe(false);
+ });
+});
+
+describe("delete cascade flush backoff", () => {
+ it("backs off retries while state reads fail and resets after a successful flush", async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = fakeFns();
+ const kv = memoryKv({ [KV.memories]: new Map(), [KV.facets]: new Map() });
+ registerCascadeFunctions(sdk as never, kv as never);
+ const onDeleted = sdk.functions.get("mem::on-record-deleted")!;
+ await onDeleted({ event_type: "state:deleted", scope: KV.memories, key: "mBackoff" });
+ let down = true;
+ const attempts: number[] = [];
+ const start = Date.now();
+ kv.get.mockImplementation(async (scope: string, key: string) => {
+ if (scope === KV.memories && key === "mBackoff") {
+ attempts.push(Date.now() - start);
+ if (down) throw new Error("state worker unreachable");
+ }
+ return kv.store[scope]?.get(key) ?? null;
+ });
+ await vi.advanceTimersByTimeAsync(120_000);
+ const gaps = attempts.slice(1).map((t, i) => t - attempts[i]);
+ expect(gaps.slice(0, 6)).toEqual([1000, 2000, 4000, 8000, 16000, 30000]);
+ expect(Math.max(...gaps)).toBe(30000);
+ down = false;
+ await vi.advanceTimersByTimeAsync(30_000);
+ const settled = attempts.length;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(attempts.length).toBe(settled);
+ const before = attempts.length;
+ await onDeleted({ event_type: "state:deleted", scope: KV.memories, key: "mBackoff" });
+ await vi.advanceTimersByTimeAsync(500);
+ expect(attempts.length).toBe(before + 2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/test/cli-data-dir.test.ts b/test/cli-data-dir.test.ts
index b60cd7ba68..d9ddac6dc8 100644
--- a/test/cli-data-dir.test.ts
+++ b/test/cli-data-dir.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { resolveDataDir } from "../src/cli-data-dir.js";
+import { managedRuntimeDirs, resolveDataDir } from "../src/cli-data-dir.js";
describe("resolveDataDir", () => {
it("prefers --data-dir over AGENTMEMORY_DATA_DIR", () => {
@@ -163,3 +163,33 @@ describe("resolveDataDir", () => {
}
});
});
+
+describe("managedRuntimeDirs", () => {
+ it("lists the default runtime dir and every instance dir regardless of the selected --instance", () => {
+ const home = "/home/alex";
+ const options = { env: {}, cwd: "/repo/project", home, platform: "linux" as const };
+ const fromDefault = managedRuntimeDirs({ ...options, args: ["upgrade"] });
+ const fromInstance = managedRuntimeDirs({ ...options, args: ["upgrade", "--instance", "3"] });
+ const fromInline = managedRuntimeDirs({ ...options, args: ["upgrade", "--instance=7"] });
+
+ expect(fromDefault).toHaveLength(51);
+ expect(fromDefault[0]).toBe(join(home, ".agentmemory"));
+ expect(fromDefault).toContain(join(home, ".local", "share", "agentmemory", "instance-1"));
+ expect(fromDefault).toContain(join(home, ".local", "share", "agentmemory", "instance-50"));
+ expect(fromInstance).toEqual(fromDefault);
+ expect(fromInline).toEqual(fromDefault);
+ });
+
+ it("keeps a --data-dir override for the instance dirs", () => {
+ const home = "/home/alex";
+ const dirs = managedRuntimeDirs({
+ args: ["doctor", "--data-dir", "~/state", "--instance", "2"],
+ env: {},
+ cwd: "/repo/project",
+ home,
+ platform: "linux",
+ });
+ expect(dirs).toContain(join(home, "state", "instance-1"));
+ expect(dirs).toContain(join(home, "state", "instance-2"));
+ });
+});
diff --git a/test/cli-doctor-fixes.test.ts b/test/cli-doctor-fixes.test.ts
index 50b09dc268..cce7d82040 100644
--- a/test/cli-doctor-fixes.test.ts
+++ b/test/cli-doctor-fixes.test.ts
@@ -44,6 +44,7 @@ function stubEffects(overrides: Partial = {}): DoctorEffects {
localBinIiiPath: () => "/Users/test/.local/bin/iii",
iiiBinaryVersion: () => III_PINNED_VERSION,
externalEngineRunning: async () => false,
+ managedEngineRunning: async () => false,
workerConnection: async () => "connected",
viewerReachable: async () => true,
runInit: async () => ({ ok: true, message: "wrote .env" }),
@@ -416,6 +417,26 @@ describe("doctor v2 diagnostic catalog", () => {
expect(after.ok).toBe(true);
});
+ it("refuses to run the installer while a managed engine is running", async () => {
+ const install = vi.fn(async () => ({ ok: true }));
+ const stop = vi.fn(async () => ({ ok: true }));
+ const start = vi.fn(async () => ({ ok: true }));
+ const diagnostics = buildDiagnostics(stubEffects({
+ managedEngineRunning: async () => true,
+ runIiiInstaller: install,
+ runStop: stop,
+ runStart: start,
+ }));
+ for (const id of ["engine-version-mismatch", "iii-on-path-not-local-bin"]) {
+ const result = await diagnostics.find((d) => d.id === id)!.fix(stubCtx({ targetArgs: " --port 3211" }));
+ expect(result.ok).toBe(false);
+ expect(result.message).toContain("agentmemory stop --port 3211 first");
+ }
+ expect(install).not.toHaveBeenCalled();
+ expect(stop).not.toHaveBeenCalled();
+ expect(start).not.toHaveBeenCalled();
+ });
+
it("does not infer an external engine version from a pinned private install", async () => {
const install = vi.fn(async () => ({ ok: true }));
const stop = vi.fn(async () => ({ ok: true }));
diff --git a/test/cli-engine-startup.test.ts b/test/cli-engine-startup.test.ts
index fc552a7583..71ca717912 100644
--- a/test/cli-engine-startup.test.ts
+++ b/test/cli-engine-startup.test.ts
@@ -150,4 +150,48 @@ describe("fresh native engine startup", () => {
'if (state.composePid && pidAlive(state.composePid) && composePidIdentity(state.composePid, state) !== "foreign")',
);
});
+
+ it("records the launched engine version next to the worker versions in the Compose state", () => {
+ const start = source.indexOf("async function startIiiBin");
+ const body = source.slice(start, source.indexOf("function pickCompatibleIii", start));
+ expect(body).toContain("const engineVersion = iiiBinVersion(iiiBin);");
+ expect(body).toContain("...(engineVersion ? { engineVersion } : {}),");
+ expect(body).toContain("workerVersions: workerBinDir ? { local: true } : COMPOSE_WORKER_VERSIONS,");
+ });
+
+ it("refuses to adopt a running Compose project whose persisted engine or workers are stale", () => {
+ const reconcileStart = source.indexOf("async function reconcilePersistedComposeEngine");
+ const reconcileBody = source.slice(reconcileStart, source.indexOf("async function main()", reconcileStart));
+ const staleCheck = reconcileBody.indexOf("const staleRuntime = composeRuntimeVersionMismatch(state, IIPINNED_VERSION);");
+ expect(staleCheck).toBeGreaterThan(-1);
+ expect(staleCheck).toBeLessThan(reconcileBody.indexOf("compose::status"));
+ expect(reconcileBody).toMatch(/if \(staleRuntime\) \{\s*p\.log\.error\(`The running managed Compose engine\/workers are an older version: \$\{staleRuntime\}\. Run agentmemory stop[^`]*`\);\s*process\.exit\(1\);/);
+ });
+
+ it("refuses to upgrade while a managed engine is running, before touching dependencies or the installer", () => {
+ const start = source.indexOf("async function runUpgrade");
+ const body = source.slice(start, source.indexOf("\nfunction pidAlive", start));
+ const guard = body.indexOf("if (await managedComposeEngineRunning()) {");
+ expect(guard).toBeGreaterThan(-1);
+ expect(guard).toBeLessThan(body.indexOf("runCommand("));
+ expect(guard).toBeLessThan(body.indexOf("await runIiiInstaller()"));
+ expect(body.slice(guard, body.indexOf("}", guard))).toContain("process.exit(1);");
+ expect(body.slice(guard, body.indexOf("}", guard))).toContain("run agentmemory stop first");
+ const helper = source.slice(source.indexOf("async function managedComposeEngineRunning"), source.indexOf("async function main()"));
+ expect(helper).toContain('if (state?.kind !== "compose") return false;');
+ expect(source).toContain("managedEngineRunning: managedComposeEngineRunning,");
+ });
+
+ it("checks the Compose state of every managed instance, not only the selected one, before replacing the shared engine", () => {
+ const helper = source.slice(source.indexOf("async function managedComposeEngineRunning"), source.indexOf("async function main()"));
+ expect(helper).toContain("for (const dir of managedRuntimeDirs({ args, env: baseEnv })) {");
+ expect(helper).toContain("AGENTMEMORY_DATA_DIR: unsuffixedDataDirEnv");
+ const capture = source.indexOf('const unsuffixedDataDirEnv = process.env["AGENTMEMORY_DATA_DIR"];');
+ const override = source.indexOf('process.env["AGENTMEMORY_DATA_DIR"] = dataDirResolution.dataDir;');
+ expect(capture).toBeGreaterThan(-1);
+ expect(capture).toBeLessThan(override);
+ expect(helper).toContain('runtimeMetadataPath("engine-state.json", { env: { AGENTMEMORY_RUNTIME_DIR: dir } })');
+ expect(helper).toContain("if (await composeStateRunning(readEngineState(path), false)) return true;");
+ expect(helper).toContain("probeEngine(`http://127.0.0.1:${state.restPort}`, signal)");
+ });
});
diff --git a/test/compose-control.test.ts b/test/compose-control.test.ts
index 63dda5450d..f082108e20 100644
--- a/test/compose-control.test.ts
+++ b/test/compose-control.test.ts
@@ -5,7 +5,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const temp = mkdtempSync(join(tmpdir(), "compose-state-error-"));
afterEach(() => rmSync(temp, { recursive: true, force: true }));
-import { composeCall, composeEnvironment, composeRegistryFailureMessage, composeStateRegistryFailure, composeWorkerFailureSummary, ownedComposeProject, readComposeLogFromOffset, startComposeDaemon, withQuietSdkDebug, type ComposeStatus } from "../src/cli/compose-control.js";
+import { composeCall, composeEnvironment, composeRegistryFailureMessage, composeRuntimeVersionMismatch, composeStateRegistryFailure, composeWorkerFailureSummary, ownedComposeProject, readComposeLogFromOffset, startComposeDaemon, withQuietSdkDebug, type ComposeStatus } from "../src/cli/compose-control.js";
+import { COMPOSE_WORKER_VERSIONS } from "../src/cli/compose-project.js";
describe("Compose control plane", () => {
it("does not leak arbitrary machine credentials to the Compose daemon", () => {
@@ -164,3 +165,27 @@ describe("Compose control client output", () => {
expect(console.debug).toBe(original);
});
});
+
+describe("Compose runtime version reconciliation", () => {
+ it("reports an older launched engine and older workers from the persisted state", () => {
+ const stale = composeRuntimeVersionMismatch({ engineVersion: "0.25.1", workerVersions: { state: "0.22.22", http: "0.22.8" } }, "0.26.0");
+ expect(stale).toContain("engine 0.25.1 (expected 0.26.0)");
+ expect(stale).toContain(`state worker 0.22.22 (expected ${COMPOSE_WORKER_VERSIONS.state})`);
+ expect(stale).toContain(`http worker 0.22.8 (expected ${COMPOSE_WORKER_VERSIONS.http})`);
+ });
+
+ it("detects a stale runtime from workerVersions when an older CLI did not record engineVersion", () => {
+ expect(composeRuntimeVersionMismatch({ workerVersions: { state: "0.22.22", http: "0.22.8" } }, "0.26.0")).toContain("state worker 0.22.22");
+ });
+
+ it("returns null when the persisted runtime matches the pins or cannot decide", () => {
+ expect(composeRuntimeVersionMismatch({ engineVersion: "0.26.0", workerVersions: { ...COMPOSE_WORKER_VERSIONS } }, "0.26.0")).toBeNull();
+ expect(composeRuntimeVersionMismatch({ workerVersions: { ...COMPOSE_WORKER_VERSIONS } }, "0.26.0")).toBeNull();
+ expect(composeRuntimeVersionMismatch({}, "0.26.0")).toBeNull();
+ expect(composeRuntimeVersionMismatch({ workerVersions: { local: true } }, "0.26.0")).toBeNull();
+ });
+
+ it("still checks the launched engine when the workers are local binaries", () => {
+ expect(composeRuntimeVersionMismatch({ engineVersion: "0.25.1", workerVersions: { local: true } }, "0.26.0")).toBe("engine 0.25.1 (expected 0.26.0)");
+ });
+});
diff --git a/test/duplicate-workers.test.ts b/test/duplicate-workers.test.ts
new file mode 100644
index 0000000000..282a3badc5
--- /dev/null
+++ b/test/duplicate-workers.test.ts
@@ -0,0 +1,39 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { readFileSync } from "node:fs";
+import { checkDuplicateWorkers, resetDuplicateWorkersForTest } from "../src/runtime/duplicates.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+
+describe("duplicate worker detection", () => {
+ beforeEach(() => resetDuplicateWorkersForTest());
+
+ it("reports engine worker ids from the id field", async () => {
+ const sdk = {
+ trigger: vi.fn(async () => ({ workers: [
+ { id: "w-1", name: "agentmemory" },
+ { id: "w-2", name: "agentmemory" },
+ { id: "w-3", name: "state" },
+ ] })),
+ };
+ const info = await checkDuplicateWorkers(sdk as never);
+ expect(info).toEqual({ count: 2, workerIds: ["w-1", "w-2"] });
+ });
+
+ it("doctor authenticates its status request against the daemon base URL", () => {
+ const cli = readFileSync("src/cli.ts", "utf-8");
+ const daemonStatus = cli.slice(cli.indexOf("daemonStatus: async () =>"), cli.indexOf("runInit: async () =>"));
+ expect(daemonStatus).toContain("headers: bearerHeaders(base)");
+ expect(daemonStatus).not.toContain("bearerHeaders(resolveClientSecret(");
+ const timeout = Number(/AbortSignal\.timeout\((\d+)\)/.exec(daemonStatus)?.[1]);
+ expect(timeout).toBeGreaterThan(5000);
+ });
+});
+
+describe("route bindings in api.ts", () => {
+ it("registers every HTTP route through Bindings", () => {
+ const api = readFileSync("src/triggers/api.ts", "utf-8");
+ expect(api).not.toMatch(/sdk\.registerTrigger\(\{\s*type:\s*"http"/);
+ });
+});
diff --git a/test/engine-config.test.ts b/test/engine-config.test.ts
index f70aa418eb..e2adc76048 100644
--- a/test/engine-config.test.ts
+++ b/test/engine-config.test.ts
@@ -3,7 +3,7 @@ import { COMPOSE_WORKER_VERSIONS, renderWorkerCompose } from "../src/cli/compose
describe("native Worker Compose runtime configuration", () => {
it("pins state/http workers at the reviewed registry versions", () => {
- expect(COMPOSE_WORKER_VERSIONS).toEqual({ state: "0.22.22", http: "0.22.8" });
+ expect(COMPOSE_WORKER_VERSIONS).toEqual({ state: "0.23.1", http: "0.23.2" });
});
it("renders instance-specific worker ports and persistent state storage", () => {
@@ -16,9 +16,9 @@ describe("native Worker Compose runtime configuration", () => {
linux: false,
});
expect(rendered).toContain("worker: 'package://api.workers.iii.dev/state'");
- expect(rendered).toContain("version: '0.22.22'");
+ expect(rendered).toContain("version: '0.23.1'");
expect(rendered).toContain("worker: 'package://api.workers.iii.dev/http'");
- expect(rendered).toContain("version: '0.22.8'");
+ expect(rendered).toContain("version: '0.23.2'");
expect(rendered).toContain("port: 3211");
expect(rendered).toContain("port: 49234");
expect(rendered).toContain("file_path: '/tmp/agentmemory/state_store.db'");
diff --git a/test/engine-install.test.ts b/test/engine-install.test.ts
index bbee8c1c53..47698686e0 100644
--- a/test/engine-install.test.ts
+++ b/test/engine-install.test.ts
@@ -98,6 +98,15 @@ describe("iii engine auto-installer", () => {
expect(cmd).toContain(`--max-time ${III_INSTALL_MAX_TIME_S}`);
});
+ it("lists each engine release once in the checksum table", () => {
+ const source = readFileSync("src/cli/engine-install.ts", "utf8");
+ const table = source.slice(source.indexOf("III_RELEASE_SHA256"));
+ const versions = [...table.matchAll(/^ {2}"(\d+\.\d+\.\d+)": \{$/gm)].map((match) => match[1]);
+ expect(versions.length).toBeGreaterThan(0);
+ expect(new Set(versions).size).toBe(versions.length);
+ expect(versions).toEqual(Object.keys(III_RELEASE_SHA256));
+ });
+
it("pins a SHA-256 for every auto-installable asset of the pinned engine release", () => {
const pinned = III_RELEASE_SHA256[III_PINNED_VERSION];
expect(pinned).toBeDefined();
diff --git a/test/engine-launch-hardening.test.ts b/test/engine-launch-hardening.test.ts
index 207ffa15be..adf08328b9 100644
--- a/test/engine-launch-hardening.test.ts
+++ b/test/engine-launch-hardening.test.ts
@@ -30,8 +30,8 @@ describe("Worker Compose runtime configuration", () => {
homeDir: "/home/u",
linux: false,
});
- expect(rendered).toContain("version: '0.22.22'");
- expect(rendered).toContain("version: '0.22.8'");
+ expect(rendered).toContain("version: '0.23.1'");
+ expect(rendered).toContain("version: '0.23.2'");
expect(rendered).toContain("save_interval_ms: 2000");
expect(rendered).toContain("file_path: '/var/lib/agentmemory/state_store.db'");
expect(rendered).not.toContain("iii-config.yaml");
diff --git a/test/events-consolidation.test.ts b/test/events-consolidation.test.ts
index b4c337d4c9..6d04cb331b 100644
--- a/test/events-consolidation.test.ts
+++ b/test/events-consolidation.test.ts
@@ -114,6 +114,20 @@ describe("event::session::stopped consolidation fan-out", () => {
});
});
+ it("runs the marker-aware post-session graph function when the graph observer is inactive", async () => {
+ const { sdk, handlers, trigger } = mockSdk();
+ const kv = mockKV();
+ kv.list.mockResolvedValue([{ id: "o1", title: "t" }] as never);
+ registerEventTriggers(sdk as never, kv as never);
+ await handlers.get("event::session::stopped")!({ sessionId: "ses_1" });
+ const ids = functionIds(trigger);
+ expect(ids).not.toContain("mem::graph-extract");
+ const call = trigger.mock.calls.find(
+ (c) => (c[0] as { function_id: string }).function_id === "mem::post-session-graph",
+ );
+ expect((call![0] as { payload: unknown }).payload).toEqual({ sessionId: "ses_1" });
+ });
+
it("waits on mem::summarize for longer than the configured summary budget", async () => {
const previous = process.env.AGENTMEMORY_SUMMARY_TIMEOUT_MS;
process.env.AGENTMEMORY_SUMMARY_TIMEOUT_MS = "600000";
@@ -221,6 +235,23 @@ describe("event::session::stopped consolidation fan-out", () => {
expect.objectContaining({ sessionId: "ses_1" }),
);
});
+
+ it("runs consolidation directly while its observer is not active and leaves it to the observer once active", async () => {
+ vi.mocked(isConsolidationEnabled).mockReturnValue(true);
+ const { getBindings } = await import("../src/runtime/bindings.js");
+ const handle = { state: "pending", ready: () => Promise.resolve(), onStateChange: () => () => {}, dispose: () => Promise.resolve() };
+ const run = async () => {
+ const { sdk, handlers, trigger } = mockSdk();
+ const observed = Object.assign(sdk, { observe: () => handle });
+ getBindings(observed as never).observePipeline({ function_id: "event::session::stopped" }, "mem::post-session-consolidate");
+ registerEventTriggers(observed as never, mockKV() as never);
+ await handlers.get("event::session::stopped")!({ sessionId: "ses_1" });
+ return functionIds(trigger);
+ };
+ expect(await run()).toContain("mem::consolidate-pipeline");
+ handle.state = "active";
+ expect(await run()).not.toContain("mem::consolidate-pipeline");
+ });
});
// The client session-end hook is bundled into a standalone binary that reads
diff --git a/test/graph-heuristic-extract.test.ts b/test/graph-heuristic-extract.test.ts
index f3bfec805b..5819424f06 100644
--- a/test/graph-heuristic-extract.test.ts
+++ b/test/graph-heuristic-extract.test.ts
@@ -92,11 +92,11 @@ describe("extractGraphHeuristics", () => {
// mem::graph-extract, and the function itself gates only the LLM pass
// on the flag plus a real provider.
describe("keyless graph extraction wiring", () => {
- it("event::session::stopped fires graph-extract without the flag gate", () => {
+ it("event::session::stopped fires post-session graph extraction without the flag gate", () => {
const events = readFileSync("src/triggers/events.ts", "utf-8");
const stopped = events.slice(events.indexOf("event::session::stopped"));
const gate = stopped.indexOf("isGraphExtractionEnabled()");
- const fire = stopped.indexOf('fireVoid("mem::graph-extract"');
+ const fire = stopped.indexOf('fireVoid("mem::post-session-graph"');
expect(fire).toBeGreaterThan(-1);
expect(gate === -1 || gate > fire).toBe(true);
});
diff --git a/test/graph.test.ts b/test/graph.test.ts
index 1556a59023..56885b3a0b 100644
--- a/test/graph.test.ts
+++ b/test/graph.test.ts
@@ -201,6 +201,17 @@ describe("Graph Functions", () => {
expect(result.edgesByType.uses).toBe(1);
});
+ it("graph-extract reports a partial result when the LLM pass fails after structural extraction", async () => {
+ mockProvider.compress.mockRejectedValueOnce(new Error("llm down"));
+ const result = (await sdk.trigger("mem::graph-extract", {
+ observations: [{ ...testObs, files: ["src/auth.ts"], concepts: ["jwt"] }],
+ })) as { success: boolean; partial?: boolean; error?: string; nodesAdded: number };
+ expect(result.success).toBe(true);
+ expect(result.nodesAdded).toBeGreaterThan(0);
+ expect(result.partial).toBe(true);
+ expect(result.error).toBe("llm down");
+ });
+
it("graph-extract returns error for empty observations", async () => {
const result = (await sdk.trigger("mem::graph-extract", {
observations: [],
diff --git a/test/helpers/mocks.ts b/test/helpers/mocks.ts
index 7b3fd335c9..afa0a0e6fd 100644
--- a/test/helpers/mocks.ts
+++ b/test/helpers/mocks.ts
@@ -53,7 +53,6 @@ export function mockSdk(opts?: { looseTrigger?: boolean }) {
const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
functions.set(id, handler);
},
- registerTrigger: vi.fn(),
trigger: async (
idOrInput:
| string
@@ -76,3 +75,48 @@ export function mockSdk(opts?: { looseTrigger?: boolean }) {
},
};
}
+
+export function fakeHandle(id = "h", state: "active" | "pending" = "active") {
+ return {
+ id,
+ state,
+ ready: () => Promise.resolve(),
+ onStateChange: (_listener: (state: string) => void) => () => {},
+ dispose: () => Promise.resolve(),
+ };
+}
+
+export type BoundRoute = { function_id: string; method: string; path: string; middleware_function_ids?: string[] };
+export type BoundState = { function_id: string; scope?: string; key?: string };
+type ObservedSource = { function_id: string; args?: Record; filters?: Record; capture?: string[] };
+
+function filterValue(filters: Record | undefined, field: string): string | undefined {
+ if (!filters) return undefined;
+ const direct = (filters[field] as { $eq?: string } | undefined)?.$eq;
+ if (direct !== undefined) return direct;
+ const branches = filters.$or as Array> | undefined;
+ return branches ? filterValue(branches[0], field) : undefined;
+}
+
+export function recordObservers() {
+ const routes: BoundRoute[] = [];
+ const states: BoundState[] = [];
+ const sources: Array<{ source: ObservedSource; target: string; options?: Record }> = [];
+ const observe = (source: ObservedSource, target: string, options?: Record) => {
+ sources.push({ source, target, options });
+ if (source.function_id === "http::on-request" && source.args) {
+ routes.push({
+ function_id: target,
+ method: String(source.args.method),
+ path: String(source.args.path),
+ ...(source.args.middleware_function_ids ? { middleware_function_ids: source.args.middleware_function_ids as string[] } : {}),
+ });
+ } else if (source.function_id === "state::on-changed") {
+ const scope = filterValue(source.filters, "input.scope");
+ const key = filterValue(source.filters, "input.key");
+ states.push({ function_id: target, ...(scope !== undefined ? { scope } : {}), ...(key !== undefined ? { key } : {}) });
+ }
+ return fakeHandle(String(options?.id ?? target));
+ };
+ return { observe, routes, states, sources };
+}
diff --git a/test/import-replace-rebuild.test.ts b/test/import-replace-rebuild.test.ts
new file mode 100644
index 0000000000..6d317358ed
--- /dev/null
+++ b/test/import-replace-rebuild.test.ts
@@ -0,0 +1,56 @@
+import { describe, it, expect, vi } from "vitest";
+
+const { warn, rebuilt } = vi.hoisted(() => ({ warn: vi.fn(), rebuilt: [] as unknown[] }));
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn, error: vi.fn() },
+}));
+
+vi.mock("../src/functions/search.js", async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, rebuildKeywordIndex: vi.fn(async (kv: unknown) => { rebuilt.push(kv); return {}; }) };
+});
+
+import { registerExportImportFunction } from "../src/functions/export-import.js";
+import type { ExportData } from "../src/types.js";
+
+function mockKV() {
+ const store = new Map>();
+ return {
+ get: async (scope: string, key: string) => store.get(scope)?.get(key) ?? null,
+ set: async (scope: string, key: string, data: unknown) => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ delete: async (scope: string, key: string) => { store.get(scope)?.delete(key); },
+ list: async (scope: string) => Array.from(store.get(scope)?.values() ?? []),
+ };
+}
+
+describe("replace import keyword rebuild", () => {
+ it("rebuilds the keyword index from the imported store after a replace import", async () => {
+ const functions = new Map Promise>();
+ const sdk = {
+ registerFunction: (id: string | { id: string }, handler: (payload: unknown) => Promise) => {
+ functions.set(typeof id === "string" ? id : id.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (input: { function_id: string; payload: unknown }) => functions.get(input.function_id)?.(input.payload),
+ };
+ const kv = mockKV();
+ registerExportImportFunction(sdk as never, kv as never);
+ const exportData: ExportData = {
+ version: "0.3.0",
+ exportedAt: new Date().toISOString(),
+ sessions: [{ id: "ses_new", project: "p", cwd: "/tmp/p", startedAt: "2026-03-01T00:00:00Z", status: "active", observationCount: 0 }],
+ observations: {},
+ memories: [],
+ summaries: [],
+ };
+ const result = (await functions.get("mem::import")!({ exportData, strategy: "replace" })) as { success: boolean };
+ expect(result.success).toBe(true);
+ await vi.waitFor(() => expect(rebuilt).toHaveLength(1));
+ expect(rebuilt[0]).toBe(kv);
+ expect(warn).not.toHaveBeenCalledWith("Post-replace index rebuild failed", expect.anything());
+ });
+});
diff --git a/test/mesh-export-project-scope.test.ts b/test/mesh-export-project-scope.test.ts
index c177fdae23..bec327ce59 100644
--- a/test/mesh-export-project-scope.test.ts
+++ b/test/mesh-export-project-scope.test.ts
@@ -126,6 +126,9 @@ describe("api::mesh-export project scoping", () => {
const unscoped = await meshExport(sdk);
expect(unscoped.status_code).toBe(413);
expect((unscoped.body as { oversized?: boolean }).oversized).toBe(true);
+ const hint = String((unscoped.body as { error?: string }).error);
+ expect(hint).toContain("?project");
+ expect(hint).not.toContain("?collections");
});
});
diff --git a/test/observer-pipeline.test.ts b/test/observer-pipeline.test.ts
new file mode 100644
index 0000000000..4be57a980e
--- /dev/null
+++ b/test/observer-pipeline.test.ts
@@ -0,0 +1,383 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { Bindings, getBindings } from "../src/runtime/bindings.js";
+import { registerPipelineObservers } from "../src/runtime/pipeline-observers.js";
+import { KV } from "../src/state/schema.js";
+import type { GraphExtractMark } from "../src/types.js";
+import { fakeHandle as handle } from "./helpers/mocks.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+vi.mock("../src/config.js", async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, isAutoCompressEnabled: () => envFlags.autoCompress, isReflectEnabled: () => envFlags.reflect, isGraphExtractionEnabled: () => envFlags.graphLlm, isConsolidationEnabled: () => envFlags.consolidation, compressMaxConcurrent: () => envFlags.maxConcurrent, isGraphStructuralEnabled: () => envFlags.structural };
+});
+vi.mock("../src/functions/slots.js", async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, isReflectEnabled: () => envFlags.reflect };
+});
+
+const envFlags = { autoCompress: true, reflect: false, graphLlm: false, consolidation: true, maxConcurrent: 3, structural: true };
+
+
+function fakeSdk(functions: string[] = ["state::get", "http::x", "state::on-changed", "http::on-request"]) {
+ const observed: Array<{ source: Record; target: string; options?: Record }> = [];
+ const triggers: Array<{ function_id: string; payload: unknown }> = [];
+ const sdk = {
+ observed,
+ triggers,
+ registerFunction: vi.fn((id: string, handler: unknown) => {
+ (sdk as Record)[`fn:${id}`] = handler;
+ }),
+ observe: vi.fn((source: Record, target: string, options?: Record) => {
+ observed.push({ source, target, options });
+ return handle();
+ }),
+ trigger: vi.fn(async (req: { function_id: string; payload: unknown }) => {
+ triggers.push({ function_id: req.function_id, payload: req.payload });
+ if (req.function_id === "engine::functions::list") return { functions };
+ return {};
+ }),
+ };
+ return sdk;
+}
+
+async function activatedBindings(sdk: ReturnType) {
+ const b = new Bindings(sdk as never);
+ await b.activate();
+ return b;
+}
+
+describe("observer pipeline", () => {
+ beforeEach(() => {
+ envFlags.autoCompress = true; envFlags.reflect = false; envFlags.graphLlm = false;
+ envFlags.consolidation = true; envFlags.maxConcurrent = 3; envFlags.structural = true;
+ process.env.AGENTMEMORY_BINDINGS = undefined;
+ });
+ afterEach(() => { process.env.AGENTMEMORY_BINDINGS = undefined; });
+
+ it("pipeline is observe with an observe-capable sdk and inline otherwise", () => {
+ expect(new Bindings(fakeSdk() as never).pipeline).toBe("observe");
+ expect(new Bindings({ trigger: vi.fn() } as never).pipeline).toBe("inline");
+ process.env.AGENTMEMORY_BINDINGS = "inline";
+ expect(new Bindings(fakeSdk() as never).pipeline).toBe("inline");
+ });
+
+ it("observePipeline creates the observer right away", () => {
+ const sdk = fakeSdk();
+ const b = getBindings(sdk as never);
+ b.observePipeline({ function_id: "x::y" }, "mem::z", { id: "agentmemory:pipeline:test" });
+ expect(sdk.observed).toHaveLength(1);
+ expect(sdk.observed[0].target).toBe("mem::z");
+ expect(b.handles).toHaveLength(1);
+ });
+
+ it("observePipeline is a no-op in inline mode", () => {
+ process.env.AGENTMEMORY_BINDINGS = "inline";
+ const sdk = fakeSdk();
+ const b = getBindings(sdk as never);
+ expect(b.observePipeline({ function_id: "x::y" }, "mem::z", {})).toBeNull();
+ expect(sdk.observed).toHaveLength(0);
+ });
+
+ it("registers the delete-cascade and relation-reaction observers in inline mode", () => {
+ process.env.AGENTMEMORY_BINDINGS = "inline";
+ const sdk = fakeSdk();
+ registerPipelineObservers(sdk as never);
+ const ids = sdk.observed.map((o) => o.options?.id);
+ expect(ids).toContain("agentmemory:cascade:deleted");
+ expect(ids).toContain("agentmemory:cascade:relation-reaction");
+ expect(ids.filter((id) => String(id).startsWith("agentmemory:pipeline:"))).toEqual([]);
+ });
+
+ it("registerPipelineObservers issues the compress observer spec", async () => {
+ const sdk = fakeSdk();
+ const b = getBindings(sdk as never);
+ registerPipelineObservers(sdk as never);
+ await b.activate();
+ const compress = sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:compress-on-capture")!;
+ expect(compress.source).toEqual({
+ function_id: "mem::observe",
+ filters: { "output.observationId": { $exists: true }, "output.deduplicated": { $ne: true } },
+ capture: ["output"],
+ });
+ expect(compress.target).toBe("mem::compress");
+ expect(compress.options?.max_in_flight).toBe(3);
+ });
+
+ it("compress observer absent when auto-compress disabled", async () => {
+ envFlags.autoCompress = false;
+ const sdk = fakeSdk();
+ const b = getBindings(sdk as never);
+ registerPipelineObservers(sdk as never);
+ await b.activate();
+ expect(sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:compress-on-capture")).toBeUndefined();
+ });
+
+ it("post-session observers: graph always, reflect gated, consolidate filtered", async () => {
+ envFlags.reflect = true;
+ const sdk = fakeSdk();
+ const b = getBindings(sdk as never);
+ registerPipelineObservers(sdk as never);
+ await b.activate();
+ const graph = sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:post-session-graph")!;
+ expect(graph.source).toEqual({ function_id: "event::session::stopped", filters: { "output.unchanged": { $ne: true } }, capture: ["input", "output"] });
+ expect(graph.options?.max_in_flight).toBe(1);
+ const reflect = sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:post-session-reflect");
+ expect(reflect).toBeTruthy();
+ const consolidate = sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:post-session-consolidate")!;
+ expect((consolidate.source.filters as Record)["input.skipConsolidation"]).toEqual({ $ne: true });
+ const remember = sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:post-remember-graph");
+ expect(remember).toBeUndefined();
+ });
+
+ it("reflect observer absent when reflect disabled; remember observer present when graph extraction enabled", async () => {
+ envFlags.reflect = false;
+ envFlags.graphLlm = true;
+ const sdk = fakeSdk();
+ const b = getBindings(sdk as never);
+ registerPipelineObservers(sdk as never);
+ await b.activate();
+ expect(sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:post-session-reflect")).toBeUndefined();
+ const remember = sdk.observed.find((o) => o.options?.id === "agentmemory:pipeline:post-remember-graph")!;
+ expect(remember).toBeTruthy();
+ expect(remember.source).toMatchObject({ function_id: "mem::remember", capture: ["input", "output"] });
+ expect(remember.options?.max_in_flight).toBe(1);
+ });
+});
+
+describe("post-session-graph delta marker", () => {
+ it("only extracts new observations and advances marker on success", async () => {
+ const { registerPostSessionFunctions } = await import("../src/functions/post-session.js");
+ const sdk = { functions: new Map Promise>(), trigger: vi.fn(async (req: { function_id: string; payload: unknown }) => {
+ if (req.function_id === "mem::graph-extract") return { nodes: 1 };
+ return {};
+ }), registerFunction: function (id: string, h: (d: unknown) => Promise) { this.functions.set(id, h); } };
+ const marks = new Map();
+ const obs = [
+ { id: "o1", title: "old", timestamp: "2026-01-01T00:00:00Z" },
+ { id: "o2", title: "new1", timestamp: "2026-02-01T00:00:00Z" },
+ { id: "o3", title: "new2", timestamp: "2026-03-01T00:00:00Z" },
+ { id: "o4", title: "", timestamp: "2026-04-01T00:00:00Z" },
+ ];
+ const kv = {
+ get: vi.fn(async (_s: string, k: string) => marks.get(k) ?? null),
+ set: vi.fn(async (_s: string, k: string, v: GraphExtractMark) => { marks.set(k, v); }),
+ iterate: async function* () { yield obs; },
+ backend: "file",
+ };
+ marks.set("s1", { sessionId: "s1", lastObservationTimestamp: "2026-01-15T00:00:00Z", extractedCount: 1, updatedAt: "2026-01-15T00:00:00Z" });
+ registerPostSessionFunctions(sdk as never, kv as never);
+ const result = await sdk.functions.get("mem::post-session-graph")!({ sessionId: "s1" });
+ const call = sdk.trigger.mock.calls.find((c) => c[0].function_id === "mem::graph-extract")!;
+ expect((call[0].payload as { observations: Array<{ id: string }> }).observations.map((o) => o.id)).toEqual(["o2", "o3"]);
+ expect(marks.get("s1")!.lastObservationTimestamp).toBe("2026-03-01T00:00:00Z");
+ expect(marks.get("s1")!.extractedCount).toBe(3);
+ expect(result).toEqual({ extracted: 2 });
+ });
+
+ it("reads the session from an Observed payload delivered by the stop observer", async () => {
+ const { registerPostSessionFunctions } = await import("../src/functions/post-session.js");
+ const sdk = { functions: new Map Promise>(), trigger: vi.fn(async () => ({ success: true })), registerFunction: function (id: string, h: (d: unknown) => Promise) { this.functions.set(id, h); } };
+ const kv = {
+ get: vi.fn(async () => null),
+ set: vi.fn(async () => {}),
+ iterate: async function* () { yield [{ id: "o1", title: "x", timestamp: "2026-02-01T00:00:00Z" }]; },
+ backend: "file",
+ };
+ registerPostSessionFunctions(sdk as never, kv as never);
+ const result = await sdk.functions.get("mem::post-session-graph")!({
+ observer_id: "agentmemory:pipeline:post-session-graph", activation_id: "a1", function_id: "event::session::stopped",
+ namespace: "agentmemory", invocation_id: "i1", status: "success", started_at_ms: 1, duration_ms: 1,
+ input: { sessionId: "s1" }, output: { unchanged: false },
+ });
+ expect(result).toEqual({ extracted: 1 });
+ expect(kv.set).toHaveBeenCalledWith(KV.graphExtractMarks, "s1", expect.objectContaining({ sessionId: "s1" }));
+ });
+
+ it("marker does not advance when extract fails", async () => {
+ const { registerPostSessionFunctions } = await import("../src/functions/post-session.js");
+ const sdk = { functions: new Map Promise>(), trigger: vi.fn(async () => { throw new Error("boom"); }), registerFunction: function (id: string, h: (d: unknown) => Promise) { this.functions.set(id, h); } };
+ const marks = new Map();
+ const kv = {
+ get: vi.fn(async (_s: string, k: string) => marks.get(k) ?? null),
+ set: vi.fn(async (_s: string, k: string, v: GraphExtractMark) => { marks.set(k, v); }),
+ iterate: async function* () { yield [{ id: "o1", title: "x", timestamp: "2026-02-01T00:00:00Z" }]; },
+ backend: "file",
+ };
+ marks.set("s1", { sessionId: "s1", lastObservationTimestamp: "2026-01-01T00:00:00Z", extractedCount: 0, updatedAt: "2026-01-01T00:00:00Z" });
+ registerPostSessionFunctions(sdk as never, kv as never);
+ await expect(sdk.functions.get("mem::post-session-graph")!({ sessionId: "s1" })).rejects.toThrow("boom");
+ expect(marks.get("s1")!.lastObservationTimestamp).toBe("2026-01-01T00:00:00Z");
+ });
+});
+
+describe("post-session-graph marker validity", () => {
+ async function setup(opts: { extract?: unknown; generation?: string | null; obs: Array>; mark?: GraphExtractMark }) {
+ const { registerPostSessionFunctions } = await import("../src/functions/post-session.js");
+ const functions = new Map Promise>();
+ const sdk = {
+ trigger: vi.fn(async (req: { function_id: string; payload: unknown }) => (req.function_id === "mem::graph-extract" ? opts.extract ?? { success: true } : {})),
+ registerFunction: (id: string, h: (d: unknown) => Promise) => { functions.set(id, h); },
+ };
+ const marks = new Map();
+ if (opts.mark) marks.set("s1", opts.mark);
+ const kv = {
+ get: vi.fn(async (scope: string, k: string) => (scope === KV.graphExtractMarks ? marks.get(k) ?? null : opts.generation ?? null)),
+ set: vi.fn(async (_s: string, k: string, v: GraphExtractMark) => { marks.set(k, v); }),
+ iterate: async function* () { yield opts.obs; },
+ backend: "file",
+ };
+ registerPostSessionFunctions(sdk as never, kv as never);
+ const extracted = () => sdk.trigger.mock.calls
+ .filter((c) => c[0].function_id === "mem::graph-extract")
+ .flatMap((c) => (c[0].payload as { observations: Array<{ id: string; files?: string[] }> }).observations);
+ return { functions, marks, extracted };
+ }
+ const mark = (graphGeneration?: string | null): GraphExtractMark => ({
+ sessionId: "s1", lastObservationTimestamp: "2026-02-01T00:00:00Z", extractedCount: 1, updatedAt: "2026-02-01T00:00:00Z",
+ ...(graphGeneration !== undefined ? { graphGeneration } : {}),
+ });
+
+ it("keeps the marker when graph extraction reports success false", async () => {
+ const t = await setup({ extract: { success: false, error: "llm down" }, obs: [{ id: "o2", title: "x", timestamp: "2026-03-01T00:00:00Z" }], mark: mark() });
+ const result = await t.functions.get("mem::post-session-graph")!({ sessionId: "s1" });
+ expect(result).toEqual({ extracted: 0, error: "llm down" });
+ expect(t.marks.get("s1")!.lastObservationTimestamp).toBe("2026-02-01T00:00:00Z");
+ });
+
+ it("keeps the marker when graph extraction reports a partial LLM failure", async () => {
+ const t = await setup({ extract: { success: true, partial: true, error: "llm down", nodesAdded: 2 }, obs: [{ id: "o2", title: "x", timestamp: "2026-03-01T00:00:00Z" }], mark: mark() });
+ const result = await t.functions.get("mem::post-session-graph")!({ sessionId: "s1" });
+ expect(result).toEqual({ extracted: 0, error: "llm down" });
+ expect(t.marks.get("s1")!.lastObservationTimestamp).toBe("2026-02-01T00:00:00Z");
+ });
+
+ it("re-extracts the whole session after a graph reset changes the generation", async () => {
+ const t = await setup({
+ generation: "22222222-2222-4222-8222-222222222222",
+ obs: [{ id: "o1", title: "old", timestamp: "2026-01-01T00:00:00Z" }, { id: "o2", title: "new", timestamp: "2026-03-01T00:00:00Z" }],
+ mark: mark("11111111-1111-4111-8111-111111111111"),
+ });
+ await t.functions.get("mem::post-session-graph")!({ sessionId: "s1" });
+ expect(t.extracted().map((o) => o.id)).toEqual(["o1", "o2"]);
+ expect(t.marks.get("s1")!.graphGeneration).toBe("22222222-2222-4222-8222-222222222222");
+ });
+
+ it("re-extracts an observation compressed after the marker", async () => {
+ const t = await setup({
+ obs: [{ id: "o1", title: "late", timestamp: "2026-01-01T00:00:00Z", compressedAt: "2026-04-01T00:00:00Z" }],
+ mark: mark(),
+ });
+ await t.functions.get("mem::post-session-graph")!({ sessionId: "s1" });
+ expect(t.extracted().map((o) => o.id)).toEqual(["o1"]);
+ expect(t.marks.get("s1")!.lastObservationTimestamp).toBe("2026-04-01T00:00:00Z");
+ });
+
+ it("passes a saved memory's files to graph extraction", async () => {
+ const t = await setup({ obs: [] });
+ await t.functions.get("mem::post-remember-graph")!({
+ input: { content: "uses the parser" },
+ output: { success: true, memory: { id: "m1", title: "t", type: "fact", createdAt: "2026-01-01T00:00:00Z", concepts: [], files: ["src/parser.ts"] } },
+ });
+ expect(t.extracted()[0].files).toEqual(["src/parser.ts"]);
+ });
+});
+
+describe("compression sweep", () => {
+ it("selects only old pending/failed observations, bounded, single-flight", async () => {
+ const { createCompressionSweep } = await import("../src/functions/compression-sweep.js");
+ const sent: unknown[] = [];
+ const sdk = { trigger: vi.fn(async (req: { function_id: string; payload: unknown }) => { sent.push(req.payload); return {}; }) };
+ const sessions = [{ id: "s1" }];
+ const now = Date.now();
+ const obs = Array.from({ length: 60 }, (_, i) => ({
+ id: `o${i}`,
+ title: "t",
+ timestamp: new Date(now - (i < 55 ? 10 * 60_000 : 60_000)).toISOString(),
+ compression: { status: "pending", attempts: 0, revision: "r" },
+ }));
+ const kv = {
+ list: vi.fn(async () => sessions),
+ iterate: async function* () { yield obs; },
+ backend: "file",
+ };
+ const run = createCompressionSweep(sdk as never, kv as never);
+ const [r1, r2] = await Promise.all([run(), run()]);
+ expect(r1.dispatched).toBe(50);
+ expect(r2.dispatched).toBe(50);
+ expect(sent).toHaveLength(50);
+ });
+
+ it("sends pending rows before failed rows and stops retrying failures that cannot succeed", async () => {
+ const { createCompressionSweep, MAX_SWEEP_ATTEMPTS } = await import("../src/functions/compression-sweep.js");
+ const sent: Array<{ observationId: string }> = [];
+ const sdk = { trigger: vi.fn(async (req: { payload: { observationId: string } }) => { sent.push(req.payload); return {}; }) };
+ const old = new Date(Date.now() - 10 * 60_000).toISOString();
+ const failedRow = (id: string, attempts: number, error = "llm_error") => ({ id, title: "t", timestamp: old, compression: { status: "failed", attempts, revision: "r", error } });
+ const obs = [
+ ...Array.from({ length: 60 }, (_, i) => failedRow(`f${i}`, 1)),
+ failedRow("exhausted", MAX_SWEEP_ATTEMPTS),
+ failedRow("no-source", 0, "source_unavailable"),
+ ...Array.from({ length: 10 }, (_, i) => ({ id: `p${i}`, title: "t", timestamp: old, compression: { status: "pending", attempts: 0, revision: "r" } })),
+ ];
+ const kv = { list: vi.fn(async () => [{ id: "s1" }]), iterate: async function* () { yield obs; }, backend: "file" };
+ const result = await createCompressionSweep(sdk as never, kv as never)();
+ const ids = sent.map((p) => p.observationId);
+ expect(result.dispatched).toBe(50);
+ expect(new Set(ids.slice(0, 10))).toEqual(new Set(Array.from({ length: 10 }, (_, i) => `p${i}`)));
+ expect(ids).not.toContain("exhausted");
+ expect(ids).not.toContain("no-source");
+ });
+});
+
+describe("post-remember-graph", () => {
+ it("builds an observation-shaped extract payload from the saved memory", async () => {
+ const { registerPostSessionFunctions } = await import("../src/functions/post-session.js");
+ const sdk = { functions: new Map Promise>(), trigger: vi.fn(async () => ({ ok: true })), registerFunction: function (id: string, h: (d: unknown) => Promise) { this.functions.set(id, h); } };
+ registerPostSessionFunctions(sdk as never, { get: vi.fn(), set: vi.fn(), iterate: async function* () {}, backend: "file" } as never);
+ await sdk.functions.get("mem::post-remember-graph")!({
+ input: { content: "prefer pnpm over npm", type: "preference", concepts: ["tooling"] },
+ output: { success: true, memory: { id: "m1", title: "use pnpm", content: "prefer pnpm over npm", type: "preference", createdAt: "2026-01-01T00:00:00Z", concepts: ["tooling"] } },
+ });
+ const call = sdk.trigger.mock.calls.find((c) => c[0].function_id === "mem::graph-extract")!;
+ const obs = (call[0].payload as { observations: Array> }).observations;
+ expect(obs).toHaveLength(1);
+ expect(obs[0]).toMatchObject({ id: "m1", title: "use pnpm", narrative: "prefer pnpm over npm", hookType: "remember" });
+ });
+
+ it("skips when remember output has no memory", async () => {
+ const { registerPostSessionFunctions } = await import("../src/functions/post-session.js");
+ const sdk = { functions: new Map Promise>(), trigger: vi.fn(async () => ({})), registerFunction: function (id: string, h: (d: unknown) => Promise) { this.functions.set(id, h); } };
+ registerPostSessionFunctions(sdk as never, { get: vi.fn(), set: vi.fn(), backend: "file" } as never);
+ const result = await sdk.functions.get("mem::post-remember-graph")!({ output: { success: false } });
+ expect(result).toEqual({ skipped: "no_memory" });
+ expect(sdk.trigger).not.toHaveBeenCalled();
+ });
+});
+
+describe("env parsing", () => {
+ it("compressMaxConcurrent default and strict integer", async () => {
+ envFlags.maxConcurrent = 7;
+ const mod = await import("../src/config.js");
+ expect(mod.compressMaxConcurrent()).toBe(7);
+ });
+
+ it("compressionSweepMs treats an empty value as unset and keeps 0 as disabled", async () => {
+ const mod = await import("../src/config.js");
+ const saved = process.env.AGENTMEMORY_COMPRESSION_SWEEP_MS;
+ try {
+ process.env.AGENTMEMORY_COMPRESSION_SWEEP_MS = "";
+ expect(mod.compressionSweepMs()).toBe(600_000);
+ process.env.AGENTMEMORY_COMPRESSION_SWEEP_MS = " ";
+ expect(mod.compressionSweepMs()).toBe(600_000);
+ process.env.AGENTMEMORY_COMPRESSION_SWEEP_MS = "0";
+ expect(mod.compressionSweepMs()).toBe(0);
+ process.env.AGENTMEMORY_COMPRESSION_SWEEP_MS = "120000";
+ expect(mod.compressionSweepMs()).toBe(120_000);
+ } finally {
+ if (saved === undefined) delete process.env.AGENTMEMORY_COMPRESSION_SWEEP_MS;
+ else process.env.AGENTMEMORY_COMPRESSION_SWEEP_MS = saved;
+ }
+ });
+});
diff --git a/test/skills-rest-endpoints.test.ts b/test/skills-rest-endpoints.test.ts
index 20967cd982..3b928e95fd 100644
--- a/test/skills-rest-endpoints.test.ts
+++ b/test/skills-rest-endpoints.test.ts
@@ -29,11 +29,11 @@ describe("generated REST endpoint methods", () => {
const source = `
// api_path: "/comment", http_method: "DELETE"
const example = 'api_path: "/string", http_method: "DELETE"';
- sdk.registerTrigger({ type: "http", config: { http_method: "GET", api_path: "/first" } });
- sdk.registerTrigger({ type: "http", config: { api_path: "/second", metadata: { http_method: "DELETE" },
+ getBindings(sdk).http({ function_id: "f", config: { http_method: "GET", api_path: "/first" } });
+ getBindings(sdk).http({ function_id: "f", config: { api_path: "/second", metadata: { http_method: "DELETE" },
/* ${"spacing".repeat(40)} */ http_method: "POST" } });
- sdk.registerTrigger({ type: "http", config: { "api_path": '/third', "http_method": 'PATCH' } });
- sdk.registerTrigger({ type: "cron", config: { api_path: "/not-http", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "f", config: { "api_path": '/third', "http_method": 'PATCH' } });
+ getBindings(sdk).state({ function_id: "x", config: { api_path: "/not-http", http_method: "GET" } });
`;
expect(collectRestEndpoints(source)).toEqual([
{ path: "/first", method: "GET" },
@@ -44,9 +44,9 @@ describe("generated REST endpoint methods", () => {
it("deduplicates method/path pairs while preserving multiple methods for the same route", () => {
const source = `
- sdk.registerTrigger({ type: "http", config: { api_path: "/shared", http_method: "POST" } });
- sdk.registerTrigger({ type: "http", config: { api_path: "/shared", http_method: "GET" } });
- sdk.registerTrigger({ type: "http", config: { api_path: "/shared", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "f", config: { api_path: "/shared", http_method: "POST" } });
+ getBindings(sdk).http({ function_id: "f", config: { api_path: "/shared", http_method: "GET" } });
+ getBindings(sdk).http({ function_id: "f", config: { api_path: "/shared", http_method: "POST" } });
`;
expect(collectRestEndpoints(source)).toEqual([
{ path: "/shared", method: "GET" },
diff --git a/test/state-worker-return.test.ts b/test/state-worker-return.test.ts
new file mode 100644
index 0000000000..72d66b2a29
--- /dev/null
+++ b/test/state-worker-return.test.ts
@@ -0,0 +1,400 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { onStateWorkerReturn, stateWorkerStatus } from "../src/runtime/state-worker.js";
+import { IndexPersistence } from "../src/state/index-persistence.js";
+import { VectorIndex } from "../src/state/vector-index.js";
+import { rearmIndexRecovery, shouldRearmIndex, backfillFailedOutright } from "../src/runtime/recovery.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+
+function fakeHandle(initial: "active" | "pending") {
+ const listeners: Array<(next: string) => void> = [];
+ return {
+ id: "h1",
+ state: initial,
+ onStateChange: (l: (next: string) => void) => { listeners.push(l); return () => {}; },
+ emit: (next: "active" | "pending" | "suspended") => { for (const l of listeners) l(next); },
+ ready: () => Promise.resolve(),
+ dispose: () => Promise.resolve(),
+ };
+}
+
+function fakeBindings(handle: ReturnType, stateMode = "observe") {
+ return { stateHandles: [handle], handles: [handle], modes: { http: stateMode, state: stateMode } };
+}
+
+function fakeSdk() {
+ return {
+ trigger: vi.fn(async () => ({ ok: true })),
+ observe: vi.fn(() => fakeHandle("active")),
+ registerFunction: vi.fn(),
+ };
+}
+
+describe("onStateWorkerReturn", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ stateWorkerStatus.ready = true;
+ stateWorkerStatus.waitedMs = 0;
+ stateWorkerStatus.lastReturnAt = undefined;
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ stateWorkerStatus.ready = true;
+ });
+
+ it("probeReady seeds from stateWorkerStatus.ready; first successful probeTick fires the callback", async () => {
+ stateWorkerStatus.ready = false;
+ const cb = vi.fn();
+ const sdk = fakeSdk();
+ const rearm = onStateWorkerReturn(sdk as never, fakeBindings(fakeHandle("active"), "trigger") as never, cb);
+ expect(rearm.state.probeReady).toBe(false);
+ await rearm.probeTick();
+ expect(rearm.state.probeReady).toBe(true);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+
+ it("runs recovery for a state handle bound later, such as an id conflict replacement", async () => {
+ const cb = vi.fn();
+ const original = fakeHandle("pending");
+ let bindLater: ((handle: ReturnType) => void) | undefined;
+ const bindings = { ...fakeBindings(original), onStateHandle: (listener: (handle: ReturnType) => void) => { bindLater = listener; return () => {}; } };
+ stateWorkerStatus.ready = false;
+ const rearm = onStateWorkerReturn(fakeSdk() as never, bindings as never, cb);
+ const replacement = fakeHandle("pending");
+ bindLater!(replacement);
+ replacement.emit("active");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(cb).toHaveBeenCalledTimes(1);
+ expect(stateWorkerStatus.ready).toBe(true);
+ const activeAlready = fakeHandle("active");
+ stateWorkerStatus.ready = false;
+ await vi.advanceTimersByTimeAsync(1000);
+ bindLater!(activeAlready);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(cb).toHaveBeenCalledTimes(2);
+ rearm.stop();
+ });
+
+ it("two returns within the throttle window fire the callback twice, second after retry delay", async () => {
+ const cb = vi.fn();
+ const handle = fakeHandle("pending");
+ const rearm = onStateWorkerReturn(fakeSdk() as never, fakeBindings(handle) as never, cb);
+ handle.emit("active");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(cb).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(100);
+ handle.emit("pending");
+ handle.emit("active");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(cb).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(cb).toHaveBeenCalledTimes(2);
+ rearm.stop();
+ });
+
+ it("probeTick retries pending recovery while the state worker stays reachable", async () => {
+ const cb = vi.fn();
+ let pending = true;
+ const rearm = onStateWorkerReturn(fakeSdk() as never, fakeBindings(fakeHandle("active"), "trigger") as never, cb, { pending: () => pending });
+ await rearm.probeTick();
+ expect(cb).toHaveBeenCalledTimes(1);
+ pending = false;
+ await vi.advanceTimersByTimeAsync(2000);
+ await rearm.probeTick();
+ expect(cb).toHaveBeenCalledTimes(1);
+ rearm.stop();
+ });
+
+ it("probeTick retries pending recovery in observe mode while the observer stays active", async () => {
+ const cb = vi.fn();
+ const rearm = onStateWorkerReturn(fakeSdk() as never, fakeBindings(fakeHandle("active")) as never, cb, { pending: () => true });
+ await rearm.probeTick();
+ expect(cb).toHaveBeenCalledTimes(1);
+ stateWorkerStatus.ready = false;
+ await vi.advanceTimersByTimeAsync(2000);
+ await rearm.probeTick();
+ expect(cb).toHaveBeenCalledTimes(1);
+ rearm.stop();
+ });
+
+ it("stop() cancels a pending throttle retry", async () => {
+ const cb = vi.fn();
+ const handle = fakeHandle("pending");
+ const rearm = onStateWorkerReturn(fakeSdk() as never, fakeBindings(handle) as never, cb);
+ handle.emit("active");
+ await vi.advanceTimersByTimeAsync(0);
+ handle.emit("pending");
+ handle.emit("active");
+ rearm.stop();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+});
+
+function memoryKv() {
+ const store = new Map();
+ return {
+ get: async (scope: string, key: string) => store.get(`${scope}/${key}`) ?? null,
+ set: async (scope: string, key: string, value: unknown) => { store.set(`${scope}/${key}`, value); },
+ delete: async (scope: string, key: string) => { store.delete(`${scope}/${key}`); },
+ list: async () => [],
+ count: async () => 0,
+ listKeys: async function* () {},
+ backend: "file",
+ };
+}
+
+describe("IndexPersistence.resumeAfterUnavailable", () => {
+ it("resumes only the unavailable-checkpoint pause", async () => {
+ const kv = memoryKv();
+ const p = new IndexPersistence(kv as never, new VectorIndex(), { requireRecoveryPlan: true });
+ await p.prepareBackfill(null);
+ expect(p.isRecoveryPaused()).toBe(true);
+ expect(p.resumeAfterUnavailable()).toBe(true);
+ expect(p.isRecoveryPaused()).toBe(true);
+ expect(p.resumeAfterUnavailable()).toBe(false);
+ });
+
+ it("keeps checkpoint writes paused until the reloaded checkpoint is prepared", async () => {
+ const kv = memoryKv();
+ const sets: string[] = [];
+ const tracked = { ...kv, set: async (scope: string, key: string, value: unknown) => { sets.push(`${scope}/${key}`); await kv.set(scope, key, value); } };
+ const vector = new VectorIndex();
+ const p = new IndexPersistence(tracked as never, vector, { requireRecoveryPlan: true });
+ await p.prepareBackfill(null);
+ expect(p.resumeAfterUnavailable()).toBe(true);
+ vector.add("live", "s", new Float32Array([1, 2, 3]));
+ p.scheduleSave();
+ await p.save();
+ expect(sets).toEqual([]);
+ expect(vector.pendingChanges).toBeGreaterThan(0);
+ });
+
+ it("clears the unavailable-checkpoint error so a restored checkpoint can complete backfill", async () => {
+ const kv = memoryKv();
+ const p = new IndexPersistence(kv as never, new VectorIndex(), { requireRecoveryPlan: true });
+ await p.prepareBackfill(null);
+ expect(p.status().vector?.lastError).toMatch(/unavailable/);
+ expect(p.resumeAfterUnavailable()).toBe(true);
+ expect(p.status().vector?.lastError).toBeNull();
+ await kv.set("mem:index:bm25", "vectors:meta", { v: 3, bucketCount: 0, savedAt: new Date().toISOString(), count: 0, backfillSince: null });
+ const loaded = await p.load();
+ await p.prepareBackfill(loaded);
+ expect(await p.completeBackfill()).toBe(true);
+ });
+
+ it("does not resume pauses from other causes", async () => {
+ const failingKv = {
+ ...memoryKv(),
+ set: async () => { throw new Error("write_denied"); },
+ };
+ const vector = new VectorIndex();
+ const loaded = { state: "none" as const, vector, savedAt: new Date().toISOString() };
+ const p = new IndexPersistence(failingKv as never, vector, { requireRecoveryPlan: true });
+ await p.prepareBackfill(loaded);
+ expect(p.isRecoveryPaused()).toBe(true);
+ expect(p.resumeAfterUnavailable()).toBe(false);
+ expect(p.isRecoveryPaused()).toBe(true);
+ });
+
+ it("re-arm after unavailable boot restores the checkpoint and resumes backfill planning", async () => {
+ const kv = memoryKv();
+ const p = new IndexPersistence(kv as never, new VectorIndex(), { requireRecoveryPlan: true });
+ await p.prepareBackfill(null);
+ expect(p.isRecoveryPaused()).toBe(true);
+ expect(p.resumeAfterUnavailable()).toBe(true);
+ const checkpoint = new VectorIndex();
+ checkpoint.add("obs1", "session", new Float32Array([1, 0, 0]));
+ checkpoint.add("obs2", "session", new Float32Array([0, 1, 0]));
+ const since = await p.prepareBackfill({
+ state: "buckets",
+ vector: checkpoint,
+ savedAt: new Date(Date.now() - 60_000).toISOString(),
+ expectedCount: 2,
+ });
+ expect(since).not.toBeUndefined();
+ expect(p.isRecoveryPaused()).toBe(false);
+ });
+});
+
+describe("state-worker re-arm order", () => {
+ it("rebuilds the index after a checkpoint retry even when the index looked complete", async () => {
+ const order: string[] = [];
+ await rearmIndexRecovery({
+ retryCheckpoint: async () => { order.push("checkpoint"); return true; },
+ indexNeedsRearm: () => false,
+ runIndexRecovery: async () => { order.push("index"); },
+ });
+ expect(order).toEqual(["checkpoint", "index"]);
+ });
+
+ it("skips index recovery when no checkpoint was retried and the index is complete", async () => {
+ const run = vi.fn(async () => {});
+ await rearmIndexRecovery({ retryCheckpoint: async () => false, indexNeedsRearm: () => false, runIndexRecovery: run });
+ expect(run).not.toHaveBeenCalled();
+ });
+});
+
+describe("VectorIndex.mergeMissingFrom", () => {
+ it("keeps vectors embedded after boot and adds only missing checkpoint entries", () => {
+ const live = new VectorIndex();
+ live.add("fresh", "s", new Float32Array([9, 9, 9]));
+ live.add("both", "s", new Float32Array([7, 7, 7]));
+ const checkpoint = new VectorIndex();
+ checkpoint.add("both", "s", new Float32Array([1, 1, 1]));
+ checkpoint.add("old", "s", new Float32Array([2, 2, 2]));
+ expect(live.mergeMissingFrom(checkpoint)).toBe(1);
+ expect(Array.from(live.get("fresh")!.embedding)).toEqual([9, 9, 9]);
+ expect(Array.from(live.get("both")!.embedding)).toEqual([7, 7, 7]);
+ expect(Array.from(live.get("old")!.embedding)).toEqual([2, 2, 2]);
+ });
+
+ it("does not restore a checkpoint vector deleted while it was absent from the live index", () => {
+ const live = new VectorIndex();
+ live.trackLiveChanges();
+ live.remove("deleted-early");
+ const checkpoint = new VectorIndex();
+ checkpoint.add("deleted-early", "s", new Float32Array([3]));
+ expect(live.mergeMissingFrom(checkpoint)).toBe(0);
+ expect(live.has("deleted-early")).toBe(false);
+ expect(live.pendingChanges).toBe(0);
+ });
+
+ it("does not bring back a vector removed after boot", () => {
+ const live = new VectorIndex();
+ live.add("gone", "s", new Float32Array([1]));
+ live.remove("gone");
+ const checkpoint = new VectorIndex();
+ checkpoint.add("gone", "s", new Float32Array([1]));
+ expect(live.mergeMissingFrom(checkpoint)).toBe(0);
+ expect(live.has("gone")).toBe(false);
+ });
+});
+
+describe("reported state-worker readiness", () => {
+ afterEach(() => { stateWorkerStatus.ready = true; });
+
+ it("follows trigger-mode probe outcomes", async () => {
+ stateWorkerStatus.ready = true;
+ const sdk = fakeSdk();
+ const rearm = onStateWorkerReturn(sdk as never, fakeBindings(fakeHandle("active"), "trigger") as never, vi.fn());
+ sdk.trigger.mockRejectedValueOnce(new Error("function_not_found"));
+ await rearm.probeTick();
+ expect(stateWorkerStatus.ready).toBe(false);
+ await rearm.probeTick();
+ expect(stateWorkerStatus.ready).toBe(true);
+ rearm.stop();
+ });
+
+ it("follows observer state changes in observe mode", () => {
+ stateWorkerStatus.ready = true;
+ const handle = fakeHandle("active");
+ const rearm = onStateWorkerReturn(fakeSdk() as never, fakeBindings(handle) as never, vi.fn());
+ handle.emit("pending");
+ expect(stateWorkerStatus.ready).toBe(false);
+ handle.emit("active");
+ expect(stateWorkerStatus.ready).toBe(true);
+ rearm.stop();
+ });
+});
+
+describe("shouldRearmIndex", () => {
+ it("does not re-run recovery for a backfill paused at its per-start cap", () => {
+ expect(shouldRearmIndex({ bm25Incomplete: false, persistencePaused: false, lastRecoveryFailed: false, checkpointSaveFailed: false })).toBe(false);
+ });
+
+ it("re-runs recovery after an incomplete keyword rebuild, a paused checkpoint or a failed run", () => {
+ const none = { bm25Incomplete: false, persistencePaused: false, lastRecoveryFailed: false, checkpointSaveFailed: false };
+ expect(shouldRearmIndex({ ...none, bm25Incomplete: true })).toBe(true);
+ expect(shouldRearmIndex({ ...none, persistencePaused: true })).toBe(true);
+ expect(shouldRearmIndex({ ...none, lastRecoveryFailed: true })).toBe(true);
+ expect(shouldRearmIndex({ ...none, checkpointSaveFailed: true })).toBe(true);
+ });
+});
+
+describe("checkpoint retry keeps live vectors", () => {
+ it("pending-log replay leaves vectors added or deleted live during the outage alone", () => {
+ const live = new VectorIndex();
+ live.trackLiveChanges();
+ live.add("fresh", "s", new Float32Array([9]));
+ live.remove("gone");
+ live.beginReplay();
+ live.add("fresh", "s", new Float32Array([1]));
+ live.add("gone", "s", new Float32Array([4]));
+ live.add("other", "s", new Float32Array([5]));
+ live.endReplay();
+ expect(Array.from(live.get("fresh")!.embedding)).toEqual([9]);
+ expect(live.has("gone")).toBe(false);
+ expect(live.has("other")).toBe(true);
+ });
+
+ it("keeps a vector re-added after a live delete", () => {
+ const live = new VectorIndex();
+ live.trackLiveChanges();
+ live.add("x", "s", new Float32Array([1]));
+ live.remove("x");
+ live.add("x", "s", new Float32Array([2]));
+ live.beginReplay();
+ live.remove("x");
+ live.endReplay();
+ expect(Array.from(live.get("x")!.embedding)).toEqual([2]);
+ });
+
+ it("a replayed clear keeps live-changed vectors", () => {
+ const live = new VectorIndex();
+ live.trackLiveChanges();
+ live.add("live", "s", new Float32Array([1]));
+ live.loadPersisted("old", "s", new Float32Array([2]));
+ live.beginReplay();
+ live.clear();
+ live.endReplay();
+ expect(live.has("live")).toBe(true);
+ expect(live.has("old")).toBe(false);
+ });
+
+ it("queues live deletions for persistence and drops the tracking set when tracking ends", () => {
+ const live = new VectorIndex();
+ live.trackLiveChanges();
+ live.remove("absent");
+ live.takeChanges();
+ live.finishLiveTracking();
+ expect(live.takeChanges().get("absent")).toBe(false);
+ const checkpoint = new VectorIndex();
+ checkpoint.add("later", "s", new Float32Array([1]));
+ live.remove("later");
+ expect(live.mergeMissingFrom(checkpoint)).toBe(1);
+ });
+});
+
+describe("backfillFailedOutright", () => {
+ it("re-arms only when a batch embedded nothing and some embeddings failed", () => {
+ expect(backfillFailedOutright({ added: 0, failed: 2 })).toBe(true);
+ expect(backfillFailedOutright({ added: 1, failed: 1 })).toBe(false);
+ expect(backfillFailedOutright({ added: 2, failed: 0 })).toBe(false);
+ });
+});
+
+describe("boot checkpoint load with live writes", () => {
+ it("keeps vectors written live while the boot checkpoint was loading", () => {
+ const live = new VectorIndex();
+ live.trackLiveChanges();
+ live.add("obs_a", "s", new Float32Array([9]));
+ live.remove("obs_b");
+ const checkpoint = new VectorIndex();
+ checkpoint.add("obs_a", "s", new Float32Array([1]));
+ checkpoint.add("obs_b", "s", new Float32Array([2]));
+ checkpoint.add("obs_c", "s", new Float32Array([3]));
+ live.restoreFrom(checkpoint);
+ live.beginReplay();
+ live.add("obs_a", "s", new Float32Array([1]));
+ live.endReplay();
+ expect(Array.from(live.get("obs_a")!.embedding)).toEqual([9]);
+ expect(live.has("obs_b")).toBe(false);
+ expect(live.has("obs_c")).toBe(true);
+ const pending = live.takeChanges();
+ expect(pending.get("obs_a")).toBe(true);
+ expect(pending.get("obs_b")).toBe(false);
+ });
+});
diff --git a/test/viewer-dashboard-reliability.test.ts b/test/viewer-dashboard-reliability.test.ts
index 2ba8fa69ec..46f2e4363e 100644
--- a/test/viewer-dashboard-reliability.test.ts
+++ b/test/viewer-dashboard-reliability.test.ts
@@ -321,3 +321,15 @@ describe("viewer navigation and shared components", () => {
expect(reload).toMatch(/loadGraph\(\{ quiet: true \}\)/);
});
});
+
+describe("dashboard duplicate-worker alert", () => {
+ it("requests the status report when the dashboard renders without one", () => {
+ const body = extractFunction("renderDashboard");
+ const request = body.indexOf("if (!store.report && !statusReportRequest)");
+ const alert = body.indexOf("store.report.runtime.duplicateWorkers.count > 1");
+ expect(request).toBeGreaterThan(-1);
+ expect(alert).toBeGreaterThan(request);
+ expect(body).toContain("ensureStatusReport().then(");
+ expect(body).toContain("renderTab('dashboard')");
+ });
+});
diff --git a/test/viewer-live-events.test.ts b/test/viewer-live-events.test.ts
index a3d4972546..ddaeee2e13 100644
--- a/test/viewer-live-events.test.ts
+++ b/test/viewer-live-events.test.ts
@@ -1,24 +1,25 @@
import { onLiveEvent } from "../src/viewer/live-events.js";
import { describe, it, expect, vi } from "vitest";
import { registerEventTriggers } from "../src/triggers/events.js";
+import { recordObservers } from "./helpers/mocks.js";
import type { StateKV } from "../src/state/kv.js";
type Handler = (payload: unknown) => Promise;
function setup() {
const handlers = new Map();
- const triggers: Array<{ type: string; function_id: string; config: Record }> = [];
+ const bound = recordObservers();
const sent: Array<{ type: string; id: string; data: Record }> = [];
const sdk = {
registerFunction: (id: string, fn: Handler) => handlers.set(id, fn),
- registerTrigger: (t: { type: string; function_id: string; config: Record }) => triggers.push(t),
+ observe: bound.observe,
trigger: vi.fn(async (req: { function_id: string; payload: Record }) => {
return {};
}),
};
onLiveEvent((event) => sent.push(event));
registerEventTriggers(sdk as never, {} as StateKV);
- return { handlers, triggers, sent };
+ return { handlers, bound, sent };
}
describe("viewer live events", () => {
@@ -79,10 +80,8 @@ describe("viewer live events", () => {
});
it("pushes memory.created, memory.updated and memory.deleted with the full row", async () => {
- const { handlers, triggers, sent } = setup();
- expect(triggers).toContainEqual(
- expect.objectContaining({ type: "state", function_id: "event::memory::changed", config: { scope: "mem:memories" } }),
- );
+ const { handlers, bound, sent } = setup();
+ expect(bound.states).toContainEqual({ function_id: "event::memory::changed", scope: "mem:memories" });
const handler = handlers.get("event::memory::changed")!;
const row = { id: "m1", type: "fact", title: "t", content: "long body", isLatest: true, updatedAt: "2026-09-24T00:00:00Z" };
await handler({ key: "m1", event_type: "state:created", new_value: row });
diff --git a/test/viewer-sse.test.ts b/test/viewer-sse.test.ts
index bfed9e1006..03c35ff3fa 100644
--- a/test/viewer-sse.test.ts
+++ b/test/viewer-sse.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { registerViewerSse } from "../src/triggers/viewer-sse.js";
+import { recordObservers } from "./helpers/mocks.js";
const viewerSource = readFileSync("src/viewer/index.html", "utf8");
function extractFunction(name: string): string {
@@ -16,13 +17,12 @@ function extractFunction(name: string): string {
describe("viewer SSE endpoint", () => {
it("registers the authenticated GET route and streams with the required headers", async () => {
const functions = new Map Promise>();
- const triggers: any[] = [];
- const sdk = { registerFunction: (id: string, fn: any) => functions.set(id, fn), registerTrigger: (trigger: any) => triggers.push(trigger) };
+ const bound = recordObservers();
+ const sdk = { registerFunction: (id: string, fn: any) => functions.set(id, fn), observe: bound.observe };
registerViewerSse(sdk as never);
- expect(triggers).toContainEqual(expect.objectContaining({
- type: "http", function_id: "api::viewer-events",
- config: expect.objectContaining({ api_path: "/agentmemory/viewer/events", http_method: "GET", middleware_function_ids: ["middleware::api-auth"] }),
- }));
+ expect(bound.routes).toContainEqual({
+ function_id: "api::viewer-events", method: "GET", path: "/agentmemory/viewer/events", middleware_function_ids: ["middleware::api-auth"],
+ });
const parts: string[] = [];
const emitted: any[] = [];
const response = { sendMessage: (raw: string) => { const message = JSON.parse(raw); emitted.push(message.type === "set_status" ? ["status", message.status_code] : ["headers", message.headers]); }, stream: { write: (s: string) => parts.push(s), once(event: string, cb: () => void) { if (event === "close") queueMicrotask(cb); }, off() {}, writableLength: 0, destroyed: false }, close() {} };
diff --git a/test/viewer-streams.test.ts b/test/viewer-streams.test.ts
index a767f85414..8ea648fa24 100644
--- a/test/viewer-streams.test.ts
+++ b/test/viewer-streams.test.ts
@@ -4,6 +4,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { registerEventTriggers } from "../src/triggers/events.js";
import { getViewerCounts, resetViewerCounts } from "../src/state/viewer-counts.js";
import { KV } from "../src/state/schema.js";
+import { recordObservers } from "./helpers/mocks.js";
import { recordAudit, setAuditRecordedListener } from "../src/functions/audit.js";
const cleanupListeners: Array<() => void> = [];
@@ -33,11 +34,11 @@ function mockKV(seed: Record> = {}) {
function setup(kv = mockKV(), deps: Record = {}) {
const handlers = new Map();
- const triggers: Array<{ type: string; function_id: string; config: Record }> = [];
+ const bound = recordObservers();
const sent: Sent[] = [];
const sdk = {
registerFunction: (id: string, fn: Handler) => handlers.set(id, fn),
- registerTrigger: (t: (typeof triggers)[number]) => triggers.push(t),
+ observe: bound.observe,
trigger: vi.fn(async (req: { function_id: string; payload: Record }) => {
return {};
}),
@@ -45,7 +46,7 @@ function setup(kv = mockKV(), deps: Record = {}) {
cleanupListeners.push(onLiveEvent((event) => sent.push(event)));
registerEventTriggers(sdk as never, kv as never);
registerViewerStreamTriggers(sdk as never, kv as never, deps);
- return { handlers, triggers, sent, kv };
+ return { handlers, bound, sent, kv };
}
const graphControl = (nodes: number, edges = 0) => ({ schema: 2, buildId: "test", status: "ready", revision: 0, nodes, edges, historyEdges: 0, incompleteRecords: 0, nodesByType: {}, edgesByType: {}, otherTypes: 0, updatedAt: "now" });
@@ -81,8 +82,8 @@ describe("viewer stream triggers", () => {
});
it("registers a state trigger for every scope the viewer shows", () => {
- const { triggers } = setup();
- const scopes = triggers.filter((t) => t.type === "state").map((t) => t.config.scope);
+ const { bound } = setup();
+ const scopes = bound.states.map((s) => s.scope);
for (const scope of [
KV.sessions,
KV.memories,
@@ -99,7 +100,7 @@ describe("viewer stream triggers", () => {
]) {
expect(scopes).toContain(scope);
}
- const http = triggers.filter((t) => t.type === "http").map((t) => t.config.api_path);
+ const http = bound.routes.map((r) => r.path);
expect(http).toEqual(expect.arrayContaining(["/agentmemory/viewer/snapshot", "/agentmemory/counts"]));
});
diff --git a/website/app/security/page.tsx b/website/app/security/page.tsx
index 6db67e6a46..0b95f9b44d 100644
--- a/website/app/security/page.tsx
+++ b/website/app/security/page.tsx
@@ -127,7 +127,7 @@ export default function SecurityPage() {
Supply chain
- The iii engine is pinned to one version (0.25.1) and runs workers under Worker Compose; registry workers state@0.22.22 and http@0.22.8 provide state and REST. The installer checks the downloaded archive
+ The iii engine is pinned to one version (0.26.0) and runs workers under Worker Compose; registry workers state@0.23.1 and http@0.23.2 provide state and REST. The installer checks the downloaded archive
against a SHA-256 recorded in the package before it extracts it.