diff --git a/AGENTS.md b/AGENTS.md index c4ffbc28fb..2822cc25a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -110,7 +110,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). ## Current Stats (v0.9.33) - 54 MCP tools visible by default; `AGENTMEMORY_TOOLS=core` selects 8 essentials -- 147 REST endpoints +- 148 REST endpoints - 6 MCP resources, 3 MCP prompts - 12 hooks, 17 skills - 322+ iii functions diff --git a/CHANGELOG.md b/CHANGELOG.md index 16a6992fab..042b5872a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Fixed + +- **The Claude Agent SDK fallback no longer overrides a provider key.** With `AGENTMEMORY_ALLOW_AGENT_SDK=true`, a provider key such as `OPENAI_API_KEY`, and no `AGENTMEMORY_LLM_PROVIDER`, 0.9.33 silently spawned Claude Agent SDK sessions. agentmemory now runs zero-LLM in that case and boot, `doctor`, `status` and the viewer name both choices. `AGENTMEMORY_LLM_PROVIDER=agent-sdk` selects the fallback explicitly. A key claimed by `EMBEDDING_PROVIDER` does not count (#1762). +- **Capture keeps observations through a stop or restart.** Hooks, `agentmemory capture --drain`, the shared capture client, the DSH plugin and the Orca worker treated every 4xx as a permanent rejection, so a `404 ` from the HTTP worker during a stop deleted the live observation and the whole spool. Only agentmemory's own rejection body (400 or 422 with `status: "rejected"`) and 413 are now permanent; 401, 403 and 404 keep the record for a later retry (#1808). +- **Hooks no longer write the capture spool into the project.** The spool folder skips the legacy `/data` adoption that the CLI uses for migration, so a project with an old `data/state_store.db` keeps its files clean. A failed rename no longer leaves `*.tmp` stats files behind (#1810). +- **The boot drain finds the hooks' default spool.** The Worker Compose environment now passes `APPDATA` on Windows and `XDG_DATA_HOME` elsewhere, so a daemon with a custom data dir drains the folder hooks write to (#1809). +- **A stale Compose PID no longer blocks startup after a reboot.** When the recorded PID belongs to a process whose command line cannot be read (a Windows service, for example) and `engine-state.json` predates the current boot, agentmemory clears the stale state and starts (#1805). +- **Consolidation reinforces restated facts.** The semantic tier shows the model the known facts with their ids, accepts `ref=""` for a restatement, and falls back to a token-overlap match, so re-running consolidation over the same summaries no longer stores reworded copies (#1793). +- **Function health follows recent calls.** `status` judges failures over the last 10 calls. `POST /agentmemory/metrics/reset` (optional `functionId`) clears the counters (#1794). +- The pi extension falls back to the previous working directory when a host omits `ctx.cwd` (#1807). + ## [0.9.33] — 2026-11-09 ### Upgrade notes diff --git a/README.md b/README.md index be25d9645f..5501a82830 100644 --- a/README.md +++ b/README.md @@ -1097,7 +1097,7 @@ agentmemory sends session content to an LLM only after you select a provider wit | OpenRouter | `AGENTMEMORY_LLM_PROVIDER=openrouter` + `OPENROUTER_API_KEY` | Any model | | OpenAI API | `AGENTMEMORY_LLM_PROVIDER=openai` + `OPENAI_API_KEY` | Default `gpt-5.6-luna`, override with `OPENAI_MODEL` | | **Local (Ollama / LM Studio / vLLM / llama.cpp)** | `AGENTMEMORY_LLM_PROVIDER=openai` + `OPENAI_API_KEY=local` + `OPENAI_BASE_URL=http://localhost:11434/v1` (Ollama) or `http://localhost:1234/v1` (LM Studio) + `OPENAI_MODEL=` | Anything OpenAI-API-compatible. Zero cost, runs on your hardware. See [Local models](#local-models-ollama--lm-studio--vllm) below. | -| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in only. Spawns `@anthropic-ai/claude-agent-sdk` sessions; it used to cause unbounded Stop-hook recursion, so it is no longer the default. | +| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in only. Spawns `@anthropic-ai/claude-agent-sdk` sessions; it used to cause unbounded Stop-hook recursion, so it is no longer the default. If an LLM provider key is also present and `AGENTMEMORY_LLM_PROVIDER` is unset, agentmemory does not pick either one and runs zero-LLM until you add `AGENTMEMORY_LLM_PROVIDER=` or `AGENTMEMORY_LLM_PROVIDER=agent-sdk`. A key claimed by `EMBEDDING_PROVIDER` does not count. | ### Local models (Ollama / LM Studio / vLLM) @@ -1261,7 +1261,7 @@ The complete reference is [`.env.example`](.env.example), including provider cre

API

-147 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer `, and mesh sync endpoints require an explicitly set `AGENTMEMORY_SECRET` on both peers. +148 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer `, and mesh sync endpoints require an explicitly set `AGENTMEMORY_SECRET` on both peers. **Authentication is on by default.** When `AGENTMEMORY_SECRET` is not set (in the shell or in `~/.agentmemory/.env`), the CLI generates a random secret on first start and stores it at `~/.agentmemory/secret`, mirrored to the selected data directory as `secret`, with mode `0600` (the platform-specific default data directory is described above). Bundled clients read the canonical secret first when they talk to a local server: the CLI, the viewer, the hooks under `plugin/scripts`, the MCP server and the `@agentmemory/mcp` shim, the configs written by `agentmemory connect`, and the bundled OpenCode, Pi, OpenClaw, Hermes and filesystem-watcher integrations. The stored secret is only sent to loopback URLs (`localhost`, `127.0.0.0/8`, `::1`). An explicit `AGENTMEMORY_SECRET` always wins, and remote clients need the secret set in their environment. Repository-based Docker self-host deployments and the `deploy/` entrypoints generate and export their own secret. To call the API by hand: diff --git a/READMEs/README.ar-SA.md b/READMEs/README.ar-SA.md index 1cd7f0ab07..8002fc4e34 100644 --- a/READMEs/README.ar-SA.md +++ b/READMEs/README.ar-SA.md @@ -1163,7 +1163,7 @@ EMBEDDING_PROVIDER=local

API

-147 نقطة نهاية على المنفذ `3111`. ترتبط REST API بـ `127.0.0.1` افتراضيًا. تتطلب نقاط النهاية المحمية ترويسة `Authorization: Bearer `، وتتطلب نقاط نهاية مزامنة mesh ضبط `AGENTMEMORY_SECRET` صريحًا على كلا الطرفين. +148 نقطة نهاية على المنفذ `3111`. ترتبط REST API بـ `127.0.0.1` افتراضيًا. تتطلب نقاط النهاية المحمية ترويسة `Authorization: Bearer `، وتتطلب نقاط نهاية مزامنة mesh ضبط `AGENTMEMORY_SECRET` صريحًا على كلا الطرفين. **المصادقة مُفعّلة افتراضيًا.** إذا لم يُضبط `AGENTMEMORY_SECRET`، ينشئ CLI عند التشغيل الأول سرًا عشوائيًا في `~/.agentmemory/secret` بصلاحيات `0600` وينسخه أيضًا إلى مجلد البيانات المحدد. يقرأ كل عميل مضمّن هذا السر عند الاتصال بخادم محلي: CLI والعارض والخطافات تحت `plugin/scripts` وخادم MCP ووسيط `@agentmemory/mcp` والإعدادات التي يكتبها `agentmemory connect` وتكاملات OpenCode وPi وOpenClaw وHermes ومراقب نظام الملفات المضمّنة. لا يُرسل السر المحفوظ إلا إلى عناوين loopback (`localhost` و`127.0.0.0/8` و`::1`). وتكون الأولوية دائمًا لقيمة `AGENTMEMORY_SECRET` الصريحة، كما يجب ضبط السر في بيئة العملاء البعيدين. تنشئ عمليات الاستضافة الذاتية عبر Docker من المستودع ونقاط دخول [`deploy/`](../deploy/) سرها وتصدّره. لاستدعاء API يدويًا: diff --git a/READMEs/README.bn-BD.md b/READMEs/README.bn-BD.md index 5a0df4e07e..20ff70a5eb 100644 --- a/READMEs/README.bn-BD.md +++ b/READMEs/README.bn-BD.md @@ -1176,7 +1176,7 @@ EMBEDDING_PROVIDER=local

API

-`3111` পোর্টে 147 এন্ডপয়েন্ট। REST API ডিফল্টভাবে `127.0.0.1`-এ বাইন্ড করে। প্রোটেক্টেড এন্ডপয়েন্টে `Authorization: Bearer ` লাগে, এবং mesh sync এন্ডপয়েন্টে দুই পিয়ারেই স্পষ্টভাবে সেট করা `AGENTMEMORY_SECRET` লাগে। +`3111` পোর্টে 148 এন্ডপয়েন্ট। REST API ডিফল্টভাবে `127.0.0.1`-এ বাইন্ড করে। প্রোটেক্টেড এন্ডপয়েন্টে `Authorization: Bearer ` লাগে, এবং mesh sync এন্ডপয়েন্টে দুই পিয়ারেই স্পষ্টভাবে সেট করা `AGENTMEMORY_SECRET` লাগে। প্রমাণীকরণ ডিফল্টভাবে চালু। `AGENTMEMORY_SECRET` নির্ধারিত না থাকলে CLI প্রথমবার একটি random secret `~/.agentmemory/secret`-এ রাখে এবং নির্বাচিত ডেটা ডিরেক্টরির `secret`-এ কপি করে; অনুমতি `0600`। সঙ্গে থাকা ক্লায়েন্ট লোকাল সংযোগে মূল ফাইলটিকে অগ্রাধিকার দেয় এবং সংরক্ষিত secret শুধু loopback URL-এ পাঠায়। স্পষ্ট `AGENTMEMORY_SECRET` অগ্রাধিকার পায়; রিমোট ক্লায়েন্টকে environment-এ সেট করতে হয়। Docker নিজস্ব secret তৈরি করে। diff --git a/READMEs/README.cs-CZ.md b/READMEs/README.cs-CZ.md index d072aec821..8c78b8d7cb 100644 --- a/READMEs/README.cs-CZ.md +++ b/READMEs/README.cs-CZ.md @@ -1162,7 +1162,7 @@ EMBEDDING_PROVIDER=local

API

-147 endpointů na portu `3111`. REST API se ve výchozím stavu váže na `127.0.0.1`. Chráněné endpointy vyžadují `Authorization: Bearer `, a endpointy pro mesh sync vyžadují explicitně nastavené `AGENTMEMORY_SECRET` na obou stranách. +148 endpointů na portu `3111`. REST API se ve výchozím stavu váže na `127.0.0.1`. Chráněné endpointy vyžadují `Authorization: Bearer `, a endpointy pro mesh sync vyžadují explicitně nastavené `AGENTMEMORY_SECRET` na obou stranách. **Autentizace je ve výchozím stavu zapnutá.** Pokud `AGENTMEMORY_SECRET` není nastaveno, CLI při prvním spuštění vygeneruje náhodný secret v `~/.agentmemory/secret` s oprávněním `0600` a zkopíruje jej také do vybraného datového adresáře. Všichni zabalení klienti jej načítají odtud při komunikaci s lokálním serverem: CLI, viewer, hooks v `plugin/scripts`, server MCP a shim `@agentmemory/mcp`, konfigurace zapsané pomocí `agentmemory connect` a zabalené integrace OpenCode, Pi, OpenClaw, Hermes a filesystem-watcher. Uložený secret se odesílá pouze na loopback URL (`localhost`, `127.0.0.0/8`, `::1`). Výslovně nastavená `AGENTMEMORY_SECRET` má vždy přednost a vzdálení klienti ji musí mít ve svém prostředí. Self-host nasazení Dockeru z repozitáře a entrypointy `deploy/` generují a exportují vlastní secret. Pro ruční volání API: diff --git a/READMEs/README.da-DK.md b/READMEs/README.da-DK.md index da82729e8d..47418f4e6c 100644 --- a/READMEs/README.da-DK.md +++ b/READMEs/README.da-DK.md @@ -1170,7 +1170,7 @@ Den fulde reference er [`.env.example`](../.env.example) med legitimationsoplysn

API

-147 endpoints på port `3111`. REST API'et binder til `127.0.0.1` som standard. Beskyttede endpoints kræver `Authorization: Bearer `, og mesh-sync-endpoints kræver en eksplicit sat `AGENTMEMORY_SECRET` på begge peers. +148 endpoints på port `3111`. REST API'et binder til `127.0.0.1` som standard. Beskyttede endpoints kræver `Authorization: Bearer `, og mesh-sync-endpoints kræver en eksplicit sat `AGENTMEMORY_SECRET` på begge peers. **Autentificering er slået til som standard.** Hvis `AGENTMEMORY_SECRET` hverken er sat i shellen eller i `~/.agentmemory/.env`, opretter CLI’en en tilfældig hemmelighed ved første start i `~/.agentmemory/secret` og en kopi med navnet `secret` i den valgte datamappe, med filtilstanden `0600`. Alle medfølgende klienter læser den derfra, når de taler med en lokal server: CLI’en, viewer, hooks under `plugin/scripts`, MCP-serveren og `@agentmemory/mcp`-shimmen, konfigurationerne skrevet af `agentmemory connect`, og de medfølgende OpenCode-, Pi-, OpenClaw-, Hermes- og filesystem-watcher-integrationer. Den lagrede secret sendes kun til loopback-URL’er (`localhost`, `127.0.0.0/8`, `::1`). En eksplicit `AGENTMEMORY_SECRET` vinder altid, og eksterne klienter skal have den i deres miljø. Docker-self-hosting fra repositoryet og `deploy/`-entrypoints genererer og eksporterer deres egen secret. Sådan kaldes API’et manuelt: diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md index e85c8c3484..1ec2983559 100644 --- a/READMEs/README.de-DE.md +++ b/READMEs/README.de-DE.md @@ -1168,7 +1168,7 @@ Die vollständige Referenz steht in [`.env.example`](../.env.example), einschlie

API

-147 Endpunkte auf Port `3111`. Die REST API bindet sich standardmäßig an `127.0.0.1`. Geschützte Endpunkte verlangen `Authorization: Bearer `, und Mesh-Sync-Endpunkte erfordern ein explizit gesetztes `AGENTMEMORY_SECRET` auf beiden Peers. +148 Endpunkte auf Port `3111`. Die REST API bindet sich standardmäßig an `127.0.0.1`. Geschützte Endpunkte verlangen `Authorization: Bearer `, und Mesh-Sync-Endpunkte erfordern ein explizit gesetztes `AGENTMEMORY_SECRET` auf beiden Peers. **Authentifizierung ist standardmäßig aktiv.** Wenn `AGENTMEMORY_SECRET` weder in der Shell noch in `~/.agentmemory/.env` gesetzt ist, erzeugt die CLI beim ersten Start ein zufälliges Secret unter `~/.agentmemory/secret` und spiegelt es als `secret` in das ausgewählte Datenverzeichnis, jeweils mit Dateimodus `0600`. Jeder mitgelieferte Client liest es von dort, wenn er mit einem lokalen Server spricht: die CLI, der Viewer, die Hooks unter `plugin/scripts`, der MCP-Server und das `@agentmemory/mcp`-Shim, die von `agentmemory connect` geschriebenen Konfigs sowie die mitgelieferten Integrationen für OpenCode, Pi, OpenClaw, Hermes und den Filesystem-Watcher. Das gespeicherte Secret wird nur an Loopback-URLs gesendet (`localhost`, `127.0.0.0/8`, `::1`). Ein explizites `AGENTMEMORY_SECRET` gewinnt immer, und Remote-Clients benötigen es trotzdem gesetzt. Docker und die `deploy/`-Entrypoints erzeugen und exportieren bereits ihr eigenes Secret. Um die API von Hand aufzurufen: diff --git a/READMEs/README.el-GR.md b/READMEs/README.el-GR.md index 70b8978d19..1770cbd802 100644 --- a/READMEs/README.el-GR.md +++ b/READMEs/README.el-GR.md @@ -1162,7 +1162,7 @@ EMBEDDING_PROVIDER=local

API

-147 endpoints στη θύρα `3111`. Το REST API συνδέεται στο `127.0.0.1` από προεπιλογή. Τα προστατευμένα endpoints απαιτούν `Authorization: Bearer `, και τα endpoints mesh sync απαιτούν ένα ρητά ρυθμισμένο `AGENTMEMORY_SECRET` και στους δύο peers. +148 endpoints στη θύρα `3111`. Το REST API συνδέεται στο `127.0.0.1` από προεπιλογή. Τα προστατευμένα endpoints απαιτούν `Authorization: Bearer `, και τα endpoints mesh sync απαιτούν ένα ρητά ρυθμισμένο `AGENTMEMORY_SECRET` και στους δύο peers. **Η πιστοποίηση είναι ενεργή από προεπιλογή.** Όταν δεν ορίζεται `AGENTMEMORY_SECRET`, στην πρώτη εκκίνηση το CLI δημιουργεί τυχαίο μυστικό στο `~/.agentmemory/secret` με δικαιώματα `0600` και το αντιγράφει και στον επιλεγμένο κατάλογο δεδομένων. Κάθε ενσωματωμένος client το διαβάζει από εκεί όταν μιλά με έναν τοπικό διακομιστή: το CLI, το viewer, τα hooks κάτω από το `plugin/scripts`, ο διακομιστής MCP και το shim `@agentmemory/mcp`, οι ρυθμίσεις που γράφει το `agentmemory connect`, και οι ενσωματωμένες ενσωματώσεις OpenCode, Pi, OpenClaw, Hermes, και filesystem-watcher. Το αποθηκευμένο secret αποστέλλεται μόνο σε loopback URLs (`localhost`, `127.0.0.0/8`, `::1`). Ένα ρητό `AGENTMEMORY_SECRET` υπερισχύει πάντα, και οι απομακρυσμένοι clients εξακολουθούν να το χρειάζονται ρυθμισμένο. Το Docker και τα entrypoints του `deploy/` δημιουργούν και εξάγουν ήδη το δικό τους secret. Για να καλέσετε το API χειροκίνητα: diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md index 230c598b9b..6b42419d64 100644 --- a/READMEs/README.es-ES.md +++ b/READMEs/README.es-ES.md @@ -1164,7 +1164,7 @@ La referencia completa está en [`.env.example`](../.env.example): credenciales,

API

-147 endpoints en el puerto `3111`. La REST API se enlaza a `127.0.0.1` por defecto. Los endpoints protegidos requieren `Authorization: Bearer `, y los endpoints de mesh sync requieren un `AGENTMEMORY_SECRET` definido explícitamente en ambos peers. +148 endpoints en el puerto `3111`. La REST API se enlaza a `127.0.0.1` por defecto. Los endpoints protegidos requieren `Authorization: Bearer `, y los endpoints de mesh sync requieren un `AGENTMEMORY_SECRET` definido explícitamente en ambos peers. **La autenticación está activada por defecto.** Si `AGENTMEMORY_SECRET` no está definida en la shell ni en `~/.agentmemory/.env`, la CLI genera un secreto aleatorio en el primer inicio en `~/.agentmemory/secret` y lo copia como `secret` en el directorio de datos seleccionado, con permisos `0600`. Todos los clientes incluidos lo leen desde allí al comunicarse con un servidor local: la CLI, el visor, los hooks de `plugin/scripts`, el servidor MCP y el shim `@agentmemory/mcp`, las configuraciones escritas por `agentmemory connect` y las integraciones incluidas de OpenCode, Pi, OpenClaw, Hermes y filesystem-watcher. El secreto guardado solo se envía a URL de loopback (`localhost`, `127.0.0.0/8`, `::1`). Un `AGENTMEMORY_SECRET` explícito siempre tiene prioridad, y los clientes remotos necesitan que el secreto esté definido en su entorno. Los despliegues Docker alojados por cuenta propia desde el repositorio y los entrypoints de `deploy/` generan y exportan su propio secreto. Para llamar a la API manualmente: diff --git a/READMEs/README.fi-FI.md b/READMEs/README.fi-FI.md index c0dbc4d478..fe7a2a108a 100644 --- a/READMEs/README.fi-FI.md +++ b/READMEs/README.fi-FI.md @@ -1162,7 +1162,7 @@ Täydellinen [`.env.example`](../.env.example) kattaa palveluntarjoajat, tallenn

API

-147 endpointia portissa `3111`. REST-rajapinta sitoutuu oletuksena osoitteeseen `127.0.0.1`. Suojatut endpointit vaativat `Authorization: Bearer `, ja mesh-synkronointiendpointit vaativat nimenomaisesti asetetun `AGENTMEMORY_SECRET`-arvon molemmilla vertaisilla. +148 endpointia portissa `3111`. REST-rajapinta sitoutuu oletuksena osoitteeseen `127.0.0.1`. Suojatut endpointit vaativat `Authorization: Bearer `, ja mesh-synkronointiendpointit vaativat nimenomaisesti asetetun `AGENTMEMORY_SECRET`-arvon molemmilla vertaisilla. **Autentikointi on oletuksena päällä.** Jos `AGENTMEMORY_SECRET` puuttuu, CLI luo ensimmäisellä käynnistyksellä satunnaisen salaisuuden tiedostoon `~/.agentmemory/secret` oikeuksilla `0600` ja kopioi sen myös valittuun datahakemistoon. Kaikki mukana toimitetut asiakkaat lukevat salaisuuden sieltä käyttäessään paikallista palvelinta: CLI, katseluohjelma, `plugin/scripts`-hakemiston hookit, MCP-palvelin ja `@agentmemory/mcp`-shim, `agentmemory connect` -komennon luomat asetukset sekä mukana toimitetut OpenCode-, Pi-, OpenClaw-, Hermes- ja filesystem-watcher-integraatiot. Tallennettu salaisuus lähetetään vain loopback-osoitteisiin (`localhost`, `127.0.0.0/8`, `::1`). Nimenomainen `AGENTMEMORY_SECRET` voittaa aina, ja etäasiakkaiden on asetettava salaisuus ympäristöönsä. Repositorion Docker-itseylläpitokäyttöönotot ja `deploy/`-entrypointit luovat ja vievät oman salaisuutensa. Rajapinnan manuaalinen kutsu: diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md index b783f2f903..47e726ee3a 100644 --- a/READMEs/README.fr-FR.md +++ b/READMEs/README.fr-FR.md @@ -1171,7 +1171,7 @@ La référence complète est [`.env.example`](../.env.example) : identifiants de

API

-147 endpoints sur le port `3111`. L'API REST se lie à `127.0.0.1` par défaut. Les endpoints protégés requièrent `Authorization: Bearer `, et les endpoints de mesh sync requièrent un `AGENTMEMORY_SECRET` explicitement défini sur les deux pairs. +148 endpoints sur le port `3111`. L'API REST se lie à `127.0.0.1` par défaut. Les endpoints protégés requièrent `Authorization: Bearer `, et les endpoints de mesh sync requièrent un `AGENTMEMORY_SECRET` explicitement défini sur les deux pairs. **L'authentification est activée par défaut.** Si `AGENTMEMORY_SECRET` n'est défini ni dans le shell ni dans `~/.agentmemory/.env`, la CLI génère un secret aléatoire au premier lancement dans `~/.agentmemory/secret` et en conserve une copie nommée `secret` dans le répertoire de données choisi, avec les permissions `0600`. Chaque client embarqué le lit depuis là quand il parle à un serveur local : la CLI, le visualiseur, les hooks sous `plugin/scripts`, le serveur MCP et le shim `@agentmemory/mcp`, les configs écrites par `agentmemory connect`, et les intégrations embarquées OpenCode, Pi, OpenClaw, Hermes et filesystem-watcher. Le secret stocké n'est envoyé qu'à des URLs loopback (`localhost`, `127.0.0.0/8`, `::1`). Un `AGENTMEMORY_SECRET` explicite prime toujours, et les clients distants en ont toujours besoin. Docker et les points d'entrée `deploy/` génèrent et exportent déjà leur propre secret. Pour appeler l'API à la main : diff --git a/READMEs/README.he-IL.md b/READMEs/README.he-IL.md index e46d6ca37a..8c64024135 100644 --- a/READMEs/README.he-IL.md +++ b/READMEs/README.he-IL.md @@ -1163,7 +1163,7 @@ EMBEDDING_PROVIDER=local

API

-147 endpoints בפורט `3111`. ה-REST API נקשר ל-`127.0.0.1` כברירת מחדל. endpoints מוגנים דורשים `Authorization: Bearer `, ו-endpoints של mesh sync דורשים `AGENTMEMORY_SECRET` מוגדר באופן מפורש בשני ה-peers. +148 endpoints בפורט `3111`. ה-REST API נקשר ל-`127.0.0.1` כברירת מחדל. endpoints מוגנים דורשים `Authorization: Bearer `, ו-endpoints של mesh sync דורשים `AGENTMEMORY_SECRET` מוגדר באופן מפורש בשני ה-peers. **אימות (Authentication) פעיל כברירת מחדל.** אם `AGENTMEMORY_SECRET` לא מוגדר, בהפעלה הראשונה ה-CLI יוצר סוד אקראי ב-`~/.agentmemory/secret` עם הרשאות `0600`, ומעתיק אותו גם לתיקיית הנתונים שנבחרה. כל לקוח מצורף קורא אותו משם כשהוא מדבר עם שרת מקומי: ה-CLI, המציג, ה-hooks תחת `plugin/scripts`, שרת ה-MCP וה-shim `@agentmemory/mcp`, התצורות שנכתבות על ידי `agentmemory connect`, והאינטגרציות המצורפות של OpenCode, Pi, OpenClaw, Hermes וה-filesystem-watcher. ה-secret המאוחסן נשלח רק ל-URLs של loopback (`localhost`, `127.0.0.0/8`, `::1`). `AGENTMEMORY_SECRET` מפורש גובר תמיד, ולקוחות מרוחקים עדיין צריכים אותו מוגדר. Docker וה-entrypoints של `deploy/` כבר מייצרים ומייצאים את ה-secret שלהם. כדי לקרוא ל-API ביד: diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md index 413fe9e772..5caa041c6d 100644 --- a/READMEs/README.hi-IN.md +++ b/READMEs/README.hi-IN.md @@ -1177,7 +1177,7 @@ EMBEDDING_PROVIDER=local

API

-Port `3111` पर 147 endpoints। REST API default रूप से `127.0.0.1` से bind होता है। Protected endpoints `Authorization: Bearer ` की आवश्यकता रखते हैं, और mesh sync endpoints दोनों peers पर एक explicitly set `AGENTMEMORY_SECRET` की आवश्यकता रखते हैं। +Port `3111` पर 148 endpoints। REST API default रूप से `127.0.0.1` से bind होता है। Protected endpoints `Authorization: Bearer ` की आवश्यकता रखते हैं, और mesh sync endpoints दोनों peers पर एक explicitly set `AGENTMEMORY_SECRET` की आवश्यकता रखते हैं। प्रमाणीकरण डिफ़ॉल्ट रूप से चालू है। `AGENTMEMORY_SECRET` सेट न होने पर CLI पहली बार एक random secret `~/.agentmemory/secret` में रखता है और चुनी हुई डेटा डायरेक्टरी के `secret` में उसकी प्रति बनाता है; permissions `0600` होती हैं। साथ आए क्लाइंट लोकल कनेक्शन में इस मूल फ़ाइल को प्राथमिकता देते हैं और सेव किया secret सिर्फ loopback URL को भेजते हैं। स्पष्ट `AGENTMEMORY_SECRET` प्राथमिकता रखता है; रिमोट क्लाइंट को इसे environment में सेट करना होता है। Docker अपना secret बनाता है। diff --git a/READMEs/README.hu-HU.md b/READMEs/README.hu-HU.md index 3508e743c1..364ec66216 100644 --- a/READMEs/README.hu-HU.md +++ b/READMEs/README.hu-HU.md @@ -1160,7 +1160,7 @@ A teljes [`.env.example`](../.env.example) leírja a szolgáltatókat, rögzít

API

-147 endpoint a `3111`-es porton. A REST API alapértelmezetten a `127.0.0.1`-hez kötődik. A védett végpontok `Authorization: Bearer `-et igényelnek, és a mesh-sync végpontok mindkét oldalon explicit módon beállított `AGENTMEMORY_SECRET`-et igényelnek. +148 endpoint a `3111`-es porton. A REST API alapértelmezetten a `127.0.0.1`-hez kötődik. A védett végpontok `Authorization: Bearer `-et igényelnek, és a mesh-sync végpontok mindkét oldalon explicit módon beállított `AGENTMEMORY_SECRET`-et igényelnek. **A hitelesítés alapértelmezetten be van kapcsolva.** Ha az `AGENTMEMORY_SECRET` nincs beállítva, a CLI első indításkor véletlen titkot hoz létre a `~/.agentmemory/secret` fájlban `0600` jogosultsággal, és a kiválasztott adatkönyvtárba is átmásolja. Minden becsomagolt kliens onnan olvassa, amikor egy lokális szerverrel beszél: a CLI, a megjelenítő, a `plugin/scripts` alatti hookok, az MCP szerver és a `@agentmemory/mcp` shim, az `agentmemory connect` által írt konfigurációk, és a becsomagolt OpenCode, Pi, OpenClaw, Hermes és fájlrendszer-figyelő integrációk. A tárolt secret csak loopback URL-eknek kerül elküldésre (`localhost`, `127.0.0.0/8`, `::1`). Egy explicit `AGENTMEMORY_SECRET` mindig elsőbbséget kap, és a távoli klienseknek továbbra is be kell állítaniuk. A Docker és a `deploy/` entrypointok már generálnak és exportálnak egy saját secretet. Az API kézi hívásához: diff --git a/READMEs/README.id-ID.md b/READMEs/README.id-ID.md index 19a052fde3..457fd787bb 100644 --- a/READMEs/README.id-ID.md +++ b/READMEs/README.id-ID.md @@ -1177,7 +1177,7 @@ Referensi lengkap ada di [`.env.example`](../.env.example), termasuk penyedia, f

API

-147 endpoint di port `3111`. REST API terbind ke `127.0.0.1` secara default. Endpoint yang terlindungi membutuhkan `Authorization: Bearer `, dan endpoint mesh sync membutuhkan `AGENTMEMORY_SECRET` yang diset secara eksplisit di kedua peer. +148 endpoint di port `3111`. REST API terbind ke `127.0.0.1` secara default. Endpoint yang terlindungi membutuhkan `Authorization: Bearer `, dan endpoint mesh sync membutuhkan `AGENTMEMORY_SECRET` yang diset secara eksplisit di kedua peer. Autentikasi aktif secara default. Jika `AGENTMEMORY_SECRET` tidak disetel, CLI membuat rahasia acak saat pertama dijalankan di `~/.agentmemory/secret` dan menyalinnya ke `secret` dalam direktori data terpilih, dengan mode `0600`. Klien bawaan mengutamakan file kanonis ini untuk koneksi lokal dan hanya mengirim rahasia tersimpan ke URL loopback. `AGENTMEMORY_SECRET` eksplisit selalu diutamakan; klien remote harus mengaturnya melalui environment. Deployment Docker membuat rahasianya sendiri. diff --git a/READMEs/README.it-IT.md b/READMEs/README.it-IT.md index ec565f5eeb..9f1adccbde 100644 --- a/READMEs/README.it-IT.md +++ b/READMEs/README.it-IT.md @@ -1170,7 +1170,7 @@ La documentazione completa è in [`.env.example`](../.env.example): credenziali,

API

-147 endpoint sulla porta `3111`. L'API REST si collega a `127.0.0.1` per impostazione predefinita. Gli endpoint protetti richiedono `Authorization: Bearer `, e gli endpoint di sincronizzazione mesh richiedono un `AGENTMEMORY_SECRET` impostato esplicitamente su entrambi i peer. +148 endpoint sulla porta `3111`. L'API REST si collega a `127.0.0.1` per impostazione predefinita. Gli endpoint protetti richiedono `Authorization: Bearer `, e gli endpoint di sincronizzazione mesh richiedono un `AGENTMEMORY_SECRET` impostato esplicitamente su entrambi i peer. **L'autenticazione è attiva per default.** Se `AGENTMEMORY_SECRET` non è impostato nella shell o in `~/.agentmemory/.env`, al primo avvio la CLI genera un segreto casuale in `~/.agentmemory/secret` e ne conserva una copia chiamata `secret` nella directory dati selezionata, con permessi `0600`. Ogni client incluso lo legge da lì quando parla con un server locale: la CLI, il viewer, gli hook sotto `plugin/scripts`, il server MCP e lo shim `@agentmemory/mcp`, le configurazioni scritte da `agentmemory connect`, e le integrazioni incluse OpenCode, Pi, OpenClaw, Hermes e filesystem-watcher. Il secret memorizzato viene inviato solo a URL loopback (`localhost`, `127.0.0.0/8`, `::1`). Un `AGENTMEMORY_SECRET` esplicito vince sempre, e i client remoti devono comunque averlo impostato. Docker e gli entrypoint di `deploy/` generano ed esportano già il proprio secret. Per chiamare l'API a mano: diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md index 31180870ec..f7502c7659 100644 --- a/READMEs/README.ja-JP.md +++ b/READMEs/README.ja-JP.md @@ -1176,7 +1176,7 @@ EMBEDDING_PROVIDER=local

API

-ポート `3111` 上の 147 エンドポイント。REST API はデフォルトで `127.0.0.1` にバインドします。保護されたエンドポイントは `Authorization: Bearer ` を要求し、mesh sync エンドポイントは両ピアで明示的に設定された `AGENTMEMORY_SECRET` を要求します。 +ポート `3111` 上の 148 エンドポイント。REST API はデフォルトで `127.0.0.1` にバインドします。保護されたエンドポイントは `Authorization: Bearer ` を要求し、mesh sync エンドポイントは両ピアで明示的に設定された `AGENTMEMORY_SECRET` を要求します。 認証はデフォルトで有効です。`AGENTMEMORY_SECRET` が未設定なら、CLI は初回起動時にランダムなシークレットを `~/.agentmemory/secret` に保存し、選択したデータディレクトリの `secret` にも複製します。権限は `0600` です。同梱クライアントはローカル接続時にこの共通ファイルを優先し、保存されたシークレットを送るのはループバック URL だけです。明示的な `AGENTMEMORY_SECRET` が優先され、リモート接続には環境変数で指定します。Docker デプロイは独自のシークレットを生成します。 diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md index ae1f96e09f..686e992514 100644 --- a/READMEs/README.ko-KR.md +++ b/READMEs/README.ko-KR.md @@ -1175,7 +1175,7 @@ EMBEDDING_PROVIDER=local

API

-포트 `3111`의 엔드포인트 147개. REST API는 기본적으로 `127.0.0.1`에 바인딩됩니다. 보호된 엔드포인트는 `Authorization: Bearer `을 요구하며, mesh sync 엔드포인트는 양쪽 피어 모두에 `AGENTMEMORY_SECRET`이 명시적으로 설정되어 있어야 합니다. +포트 `3111`의 엔드포인트 148개. REST API는 기본적으로 `127.0.0.1`에 바인딩됩니다. 보호된 엔드포인트는 `Authorization: Bearer `을 요구하며, mesh sync 엔드포인트는 양쪽 피어 모두에 `AGENTMEMORY_SECRET`이 명시적으로 설정되어 있어야 합니다. 인증은 기본적으로 활성화됩니다. `AGENTMEMORY_SECRET`이 없으면 CLI가 처음 시작할 때 임의의 비밀값을 `~/.agentmemory/secret`에 저장하고 선택한 데이터 디렉터리의 `secret`에도 복사합니다. 권한은 `0600`입니다. 번들 클라이언트는 로컬 연결 시 이 공통 파일을 우선하며 저장된 비밀값은 루프백 URL에만 보냅니다. 명시적인 `AGENTMEMORY_SECRET`이 우선하고 원격 클라이언트는 환경 변수로 설정해야 합니다. Docker 배포는 자체 비밀값을 생성합니다. diff --git a/READMEs/README.nb-NO.md b/READMEs/README.nb-NO.md index 3c61b500e9..c43a641e32 100644 --- a/READMEs/README.nb-NO.md +++ b/READMEs/README.nb-NO.md @@ -1168,7 +1168,7 @@ Den fullstendige referansen er [`.env.example`](../.env.example), med legitimasj

API

-147 endepunkter på port `3111`. REST-API-en bindes til `127.0.0.1` som standard. Beskyttede endepunkter krever `Authorization: Bearer `, og mesh-synkroniseringsendepunkter krever en uttrykkelig satt `AGENTMEMORY_SECRET` på begge sider. +148 endepunkter på port `3111`. REST-API-en bindes til `127.0.0.1` som standard. Beskyttede endepunkter krever `Authorization: Bearer `, og mesh-synkroniseringsendepunkter krever en uttrykkelig satt `AGENTMEMORY_SECRET` på begge sider. **Autentisering er på som standard.** Hvis `AGENTMEMORY_SECRET` verken er satt i skallet eller i `~/.agentmemory/.env`, oppretter CLI-en en tilfeldig hemmelighet ved første start i `~/.agentmemory/secret` og en kopi kalt `secret` i den valgte datamappen, med filmodus `0600`. Alle medfølgende klienter leser den derfra når de snakker med en lokal server: CLI-en, viewer, hookene under `plugin/scripts`, MCP-serveren og `@agentmemory/mcp`-shimmen, konfigurasjonene skrevet av `agentmemory connect` og de medfølgende OpenCode-, Pi-, OpenClaw-, Hermes- og filsystemovervåker-integrasjonene. Den lagrede hemmeligheten sendes bare til loopback-URL-er (`localhost`, `127.0.0.0/8`, `::1`). En uttrykkelig `AGENTMEMORY_SECRET` vinner alltid, og eksterne klienter trenger hemmeligheten i miljøet sitt. Docker-basert selvhosting fra repoet og `deploy/`-entrypointene genererer og eksporterer sin egen hemmelighet. Slik kaller du API-et manuelt: diff --git a/READMEs/README.nl-NL.md b/READMEs/README.nl-NL.md index 7eaf3fa71b..2dfd79b9dc 100644 --- a/READMEs/README.nl-NL.md +++ b/READMEs/README.nl-NL.md @@ -1164,7 +1164,7 @@ De volledige referentie staat in [`.env.example`](../.env.example), met provider

API

-147 endpoints op poort `3111`. De REST API bindt standaard aan `127.0.0.1`. Beschermde endpoints vereisen `Authorization: Bearer `, en mesh-sync-endpoints vereisen een expliciet ingestelde `AGENTMEMORY_SECRET` op beide peers. +148 endpoints op poort `3111`. De REST API bindt standaard aan `127.0.0.1`. Beschermde endpoints vereisen `Authorization: Bearer `, en mesh-sync-endpoints vereisen een expliciet ingestelde `AGENTMEMORY_SECRET` op beide peers. **Authenticatie staat standaard aan.** Als `AGENTMEMORY_SECRET` niet in de shell of in `~/.agentmemory/.env` staat, maakt de CLI bij de eerste start een willekeurig secret in `~/.agentmemory/secret` en een kopie met de naam `secret` in de geselecteerde gegevensmap, met bestandsmodus `0600`. Elke gebundelde client leest het daar wanneer die met een lokale server communiceert: de CLI, viewer, hooks onder `plugin/scripts`, MCP-server en `@agentmemory/mcp`-shim, configs geschreven door `agentmemory connect`, en de gebundelde OpenCode-, Pi-, OpenClaw-, Hermes- en filesystem-watcher-integraties. Het opgeslagen secret wordt alleen verstuurd naar loopback-URL's (`localhost`, `127.0.0.0/8`, `::1`). Een expliciete `AGENTMEMORY_SECRET` wint altijd, en externe clients hebben het secret in hun omgeving nodig. Docker self-host deployments vanuit de repository en de `deploy/`-entrypoints genereren en exporteren hun eigen secret. Zo roep je de API handmatig aan: diff --git a/READMEs/README.pl-PL.md b/READMEs/README.pl-PL.md index 18bce09522..4de384b1af 100644 --- a/READMEs/README.pl-PL.md +++ b/READMEs/README.pl-PL.md @@ -1160,7 +1160,7 @@ Pełny opis w [`.env.example`](../.env.example) obejmuje dostawców, filtry prze

API

-147 endpointów na porcie `3111`. REST API domyślnie wiąże się z `127.0.0.1`. Chronione endpointy wymagają `Authorization: Bearer `, a endpointy synchronizacji mesh wymagają wyraźnie ustawionego `AGENTMEMORY_SECRET` na obu peerach. +148 endpointów na porcie `3111`. REST API domyślnie wiąże się z `127.0.0.1`. Chronione endpointy wymagają `Authorization: Bearer `, a endpointy synchronizacji mesh wymagają wyraźnie ustawionego `AGENTMEMORY_SECRET` na obu peerach. **Autoryzacja jest domyślnie włączona.** Gdy `AGENTMEMORY_SECRET` nie jest ustawiony, CLI przy pierwszym uruchomieniu generuje losowy sekret w `~/.agentmemory/secret` z uprawnieniami `0600` i kopiuje go także do wybranego katalogu danych. Wszystkie dołączone klienty odczytują go stamtąd, gdy łączą się z lokalnym serwerem: CLI, podgląd, hooki w `plugin/scripts`, serwer MCP i shim `@agentmemory/mcp`, konfiguracje tworzone przez `agentmemory connect` oraz dołączone integracje OpenCode, Pi, OpenClaw, Hermes i obserwator systemu plików. Zapisany sekret jest wysyłany tylko na adresy loopback (`localhost`, `127.0.0.0/8`, `::1`). Jawnie ustawione `AGENTMEMORY_SECRET` ma zawsze pierwszeństwo, a zdalni klienci muszą mieć sekret w swoim środowisku. Wdrożenia self-hosted Docker oparte na repozytorium i punkty wejścia `deploy/` generują i eksportują własny sekret. Aby ręcznie wywołać API: diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md index faf3585631..d622977c4d 100644 --- a/READMEs/README.pt-BR.md +++ b/READMEs/README.pt-BR.md @@ -1168,7 +1168,7 @@ A referência completa está em [`.env.example`](../.env.example): credenciais,

API

-147 endpoints na porta `3111`. A REST API faz bind em `127.0.0.1` por padrão. Endpoints protegidos exigem `Authorization: Bearer `, e endpoints de mesh sync exigem um `AGENTMEMORY_SECRET` explicitamente definido em ambos os peers. +148 endpoints na porta `3111`. A REST API faz bind em `127.0.0.1` por padrão. Endpoints protegidos exigem `Authorization: Bearer `, e endpoints de mesh sync exigem um `AGENTMEMORY_SECRET` explicitamente definido em ambos os peers. **A autenticação vem ativada por padrão.** Quando `AGENTMEMORY_SECRET` não está definida na shell nem em `~/.agentmemory/.env`, a CLI gera um segredo aleatório na primeira execução em `~/.agentmemory/secret` e grava uma cópia chamada `secret` no diretório de dados selecionado, com permissões `0600`. Todos os clientes empacotados o leem de lá ao falar com um servidor local: CLI, viewer, hooks em `plugin/scripts`, servidor MCP e shim `@agentmemory/mcp`, configurações escritas por `agentmemory connect` e integrações empacotadas de OpenCode, Pi, OpenClaw, Hermes e filesystem-watcher. O secret armazenado só é enviado para URLs de loopback (`localhost`, `127.0.0.0/8`, `::1`). Um `AGENTMEMORY_SECRET` explícito sempre prevalece, e clientes remotos precisam ter o secret definido em seu ambiente. Deploys self-hosted com Docker baseados no repositório e os entrypoints de `deploy/` geram e exportam seu próprio secret. Para chamar a API manualmente: diff --git a/READMEs/README.pt-PT.md b/READMEs/README.pt-PT.md index 8f2d384d46..b5e484f6de 100644 --- a/READMEs/README.pt-PT.md +++ b/READMEs/README.pt-PT.md @@ -1164,7 +1164,7 @@ A referência completa está em [`.env.example`](../.env.example): credenciais,

API

-147 endpoints na porta `3111`. A REST API faz bind em `127.0.0.1` por predefinição. Os endpoints protegidos exigem `Authorization: Bearer `, e os endpoints de sincronização mesh exigem uma `AGENTMEMORY_SECRET` explicitamente definida em ambos os pares. +148 endpoints na porta `3111`. A REST API faz bind em `127.0.0.1` por predefinição. Os endpoints protegidos exigem `Authorization: Bearer `, e os endpoints de sincronização mesh exigem uma `AGENTMEMORY_SECRET` explicitamente definida em ambos os pares. **A autenticação está ativa por predefinição.** Quando `AGENTMEMORY_SECRET` não está definida na shell nem em `~/.agentmemory/.env`, o CLI gera um segredo aleatório no primeiro arranque em `~/.agentmemory/secret` e guarda uma cópia chamada `secret` no diretório de dados selecionado, com permissões `0600`. Todos os clientes incluídos o leem daí quando comunicam com um servidor local: o CLI, o visualizador, os hooks em `plugin/scripts`, o servidor MCP e o shim `@agentmemory/mcp`, as configurações escritas por `agentmemory connect`, e as integrações incluídas de OpenCode, Pi, OpenClaw, Hermes e filesystem-watcher. O segredo guardado só é enviado para URLs de loopback (`localhost`, `127.0.0.0/8`, `::1`). Uma `AGENTMEMORY_SECRET` explícita prevalece sempre, e os clientes remotos precisam de ter o segredo definido no seu ambiente. As implementações Docker self-host a partir do repositório e os entrypoints de `deploy/` geram e exportam o seu próprio segredo. Para chamar a API manualmente: diff --git a/READMEs/README.ro-RO.md b/READMEs/README.ro-RO.md index a305986973..cb2325bb23 100644 --- a/READMEs/README.ro-RO.md +++ b/READMEs/README.ro-RO.md @@ -1156,7 +1156,7 @@ Referința completă [`.env.example`](../.env.example) include furnizori, filtre

API

-147 de endpoint-uri pe portul `3111`. API-ul REST se leagă implicit la `127.0.0.1`. Endpoint-urile protejate necesită `Authorization: Bearer `, iar endpoint-urile de sincronizare mesh necesită un `AGENTMEMORY_SECRET` setat explicit pe ambii parteneri (peers). +148 de endpoint-uri pe portul `3111`. API-ul REST se leagă implicit la `127.0.0.1`. Endpoint-urile protejate necesită `Authorization: Bearer `, iar endpoint-urile de sincronizare mesh necesită un `AGENTMEMORY_SECRET` setat explicit pe ambii parteneri (peers). **Autentificarea este activată implicit.** Dacă `AGENTMEMORY_SECRET` nu este setat, CLI-ul generează la prima pornire un secret aleatoriu în `~/.agentmemory/secret`, cu permisiuni `0600`, și îl copiază și în directorul de date selectat. Toți clienții incluși îl citesc de acolo când comunică cu un server local: CLI-ul, vizualizatorul, hook-urile din `plugin/scripts`, serverul MCP și shim-ul `@agentmemory/mcp`, configurațiile scrise de `agentmemory connect` și integrările incluse OpenCode, Pi, OpenClaw, Hermes și filesystem-watcher. Secretul stocat este trimis doar către URL-uri loopback (`localhost`, `127.0.0.0/8`, `::1`). Un `AGENTMEMORY_SECRET` explicit are întotdeauna prioritate, iar clienții la distanță trebuie să seteze secretul în mediul lor. Implementările Docker self-host pornite din repository și entrypoint-urile `deploy/` își generează și exportă propriul secret. Pentru a apela API-ul manual: diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md index 52f937c423..07de4ee9da 100644 --- a/READMEs/README.ru-RU.md +++ b/READMEs/README.ru-RU.md @@ -1162,7 +1162,7 @@ EMBEDDING_PROVIDER=local

API

-147 эндпоинтов на порту `3111`. REST API по умолчанию слушает на `127.0.0.1`. Защищённые эндпоинты требуют `Authorization: Bearer `, а эндпоинты mesh-синхронизации требуют явно заданного `AGENTMEMORY_SECRET` на обоих узлах. +148 эндпоинтов на порту `3111`. REST API по умолчанию слушает на `127.0.0.1`. Защищённые эндпоинты требуют `Authorization: Bearer `, а эндпоинты mesh-синхронизации требуют явно заданного `AGENTMEMORY_SECRET` на обоих узлах. **Аутентификация включена по умолчанию.** Если `AGENTMEMORY_SECRET` не задан, при первом запуске CLI создаёт случайный секрет в `~/.agentmemory/secret` с правами `0600` и копирует его также в выбранный каталог данных. Каждый встроенный клиент читает его оттуда, когда говорит с локальным сервером: CLI, просмотрщик, хуки из `plugin/scripts`, MCP-сервер и shim `@agentmemory/mcp`, конфиги, записанные `agentmemory connect`, и встроенные интеграции OpenCode, Pi, OpenClaw, Hermes и filesystem-watcher. Сохранённый секрет отправляется только на loopback-адреса (`localhost`, `127.0.0.0/8`, `::1`). Явно заданный `AGENTMEMORY_SECRET` всегда выигрывает, и удалённым клиентам он всё равно нужен. Docker и entrypoint'ы `deploy/` уже генерируют и экспортируют собственный секрет. Чтобы вызвать API вручную: diff --git a/READMEs/README.sv-SE.md b/READMEs/README.sv-SE.md index dece59a678..8eabcf4efc 100644 --- a/READMEs/README.sv-SE.md +++ b/READMEs/README.sv-SE.md @@ -1170,7 +1170,7 @@ Den fullständiga referensen finns i [`.env.example`](../.env.example): autentis

API

-147 endpoints på port `3111`. REST API:et binder till `127.0.0.1` som standard. Skyddade endpoints kräver `Authorization: Bearer `, och mesh-synk-endpoints kräver en explicit satt `AGENTMEMORY_SECRET` på båda parterna. +148 endpoints på port `3111`. REST API:et binder till `127.0.0.1` som standard. Skyddade endpoints kräver `Authorization: Bearer `, och mesh-synk-endpoints kräver en explicit satt `AGENTMEMORY_SECRET` på båda parterna. **Autentisering är aktiverad som standard.** Om `AGENTMEMORY_SECRET` inte är angiven i skalet eller i `~/.agentmemory/.env` skapar CLI:n en slumpmässig hemlighet vid första starten i `~/.agentmemory/secret` och en kopia med namnet `secret` i den valda datamappen, med filbehörigheten `0600`. Alla medföljande klienter läser den därifrån när de ansluter till en lokal server: CLI:n, viewern, hookarna under `plugin/scripts`, MCP-servern och `@agentmemory/mcp`-shimmen, konfigurationerna skrivna av `agentmemory connect` samt de medföljande integrationerna för OpenCode, Pi, OpenClaw, Hermes och filsystemsbevakaren. Den lagrade hemligheten skickas bara till loopback-URL:er (`localhost`, `127.0.0.0/8`, `::1`). En explicit `AGENTMEMORY_SECRET` har alltid företräde; fjärrklienter behöver hemligheten i sin miljö. Docker-baserad self-hosting från repot och startpunkterna i `deploy/` genererar och exporterar en egen hemlighet. För att anropa API:et för hand: diff --git a/READMEs/README.th-TH.md b/READMEs/README.th-TH.md index 47868c8b97..1b82c6328f 100644 --- a/READMEs/README.th-TH.md +++ b/READMEs/README.th-TH.md @@ -1163,7 +1163,7 @@ EMBEDDING_PROVIDER=local

API

-147 endpoint บนพอร์ต `3111` REST API จะ bind กับ `127.0.0.1` โดย default endpoint ที่ป้องกันไว้ต้องมี `Authorization: Bearer ` และ endpoint ของ mesh sync ต้องตั้งค่า `AGENTMEMORY_SECRET` ไว้อย่างชัดเจนทั้งสองฝั่ง +148 endpoint บนพอร์ต `3111` REST API จะ bind กับ `127.0.0.1` โดย default endpoint ที่ป้องกันไว้ต้องมี `Authorization: Bearer ` และ endpoint ของ mesh sync ต้องตั้งค่า `AGENTMEMORY_SECRET` ไว้อย่างชัดเจนทั้งสองฝั่ง เปิดการยืนยันตัวตนตามค่าเริ่มต้น หากไม่ตั้ง `AGENTMEMORY_SECRET` CLI จะสร้างรหัสลับสุ่มครั้งแรกที่ `~/.agentmemory/secret` และคัดลอกไปยัง `secret` ในไดเรกทอรีข้อมูลที่เลือก โดยใช้สิทธิ์ `0600` ไคลเอนต์ที่รวมมาจะอ่านไฟล์หลักนี้ก่อนเมื่อเชื่อมต่อในเครื่อง และส่งรหัสลับที่บันทึกไว้เฉพาะ URL แบบ loopback ค่า `AGENTMEMORY_SECRET` ที่ระบุเองมีลำดับความสำคัญสูงกว่า ไคลเอนต์ระยะไกลต้องตั้งผ่าน environment ส่วน Docker สร้างรหัสลับของตนเอง diff --git a/READMEs/README.tl-PH.md b/READMEs/README.tl-PH.md index 46e8525e75..8d23b86781 100644 --- a/READMEs/README.tl-PH.md +++ b/READMEs/README.tl-PH.md @@ -1172,7 +1172,7 @@ Nasa [`.env.example`](../.env.example) ang buong reference, kasama ang provider,

API

-147 na endpoint sa port `3111`. Nagbibind ang REST API sa `127.0.0.1` bilang default. Kinakailangan ng mga protected endpoint ang `Authorization: Bearer `, at kinakailangan ng mga mesh sync endpoint ang tahasang naka-set na `AGENTMEMORY_SECRET` sa dalawang peer. +148 na endpoint sa port `3111`. Nagbibind ang REST API sa `127.0.0.1` bilang default. Kinakailangan ng mga protected endpoint ang `Authorization: Bearer `, at kinakailangan ng mga mesh sync endpoint ang tahasang naka-set na `AGENTMEMORY_SECRET` sa dalawang peer. Naka-on ang authentication bilang default. Kapag walang `AGENTMEMORY_SECRET`, gumagawa ang CLI ng random secret sa unang start sa `~/.agentmemory/secret` at kinokopya sa `secret` ng napiling data directory, na may mode `0600`. Inuuna ng bundled clients ang canonical file sa local connection at ipinapadala lang ang naka-save na secret sa loopback URL. Mas mataas ang prayoridad ng explicit na `AGENTMEMORY_SECRET`; dapat itong itakda ng remote clients sa environment. Gumagawa ang Docker deployment ng sarili nitong secret. diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md index 9449a9fcc4..e2e33d3edf 100644 --- a/READMEs/README.tr-TR.md +++ b/READMEs/README.tr-TR.md @@ -1161,7 +1161,7 @@ Tam [`.env.example`](../.env.example) sağlayıcıları, kayıt filtrelerini, sa

API

-`3111` portunda 147 endpoint. REST API, varsayılan olarak `127.0.0.1`'e bağlanır. Korumalı endpoint'ler `Authorization: Bearer ` gerektirir ve mesh sync endpoint'leri her iki peer'da da açıkça ayarlanmış bir `AGENTMEMORY_SECRET` gerektirir. +`3111` portunda 148 endpoint. REST API, varsayılan olarak `127.0.0.1`'e bağlanır. Korumalı endpoint'ler `Authorization: Bearer ` gerektirir ve mesh sync endpoint'leri her iki peer'da da açıkça ayarlanmış bir `AGENTMEMORY_SECRET` gerektirir. **Kimlik doğrulama varsayılan olarak açıktır.** `AGENTMEMORY_SECRET` ayarlanmamışsa CLI ilk başlatmada `~/.agentmemory/secret` dosyasında `0600` izinleriyle rastgele bir sır oluşturur ve seçilen veri dizinine de kopyalar. Paketli istemciler yerel sunucuya bağlanırken buradan okur; secret yalnız loopback URL’lerine (`localhost`, `127.0.0.0/8`, `::1`) gönderilir. Uzak istemciler secret’ı kendi ortamında sağlamalıdır. Docker self-host ve `deploy/` kendi secret’larını üretir. API’yi elle çağırmak için: diff --git a/READMEs/README.uk-UA.md b/READMEs/README.uk-UA.md index d8724f82b5..0c8498f512 100644 --- a/READMEs/README.uk-UA.md +++ b/READMEs/README.uk-UA.md @@ -1162,7 +1162,7 @@ EMBEDDING_PROVIDER=local

API

-147 ендпоінтів на порту `3111`. REST API за замовчуванням прив'язується до `127.0.0.1`. Захищені ендпоінти вимагають `Authorization: Bearer `, а ендпоінти синхронізації mesh вимагають явно встановленого `AGENTMEMORY_SECRET` на обох сторонах. +148 ендпоінтів на порту `3111`. REST API за замовчуванням прив'язується до `127.0.0.1`. Захищені ендпоінти вимагають `Authorization: Bearer `, а ендпоінти синхронізації mesh вимагають явно встановленого `AGENTMEMORY_SECRET` на обох сторонах. **Автентифікацію ввімкнено типово.** Якщо `AGENTMEMORY_SECRET` не задано, під час першого запуску CLI створює випадковий секрет у `~/.agentmemory/secret` з правами `0600` і копіює його також у вибраний каталог даних. Вбудовані клієнти читають його звідти для локального сервера; secret надсилається лише на loopback URL (`localhost`, `127.0.0.0/8`, `::1`). Віддалені клієнти мають отримати secret через власне середовище. Docker self-host і `deploy/` створюють власні секрети. Щоб викликати API вручну: diff --git a/READMEs/README.ur-PK.md b/READMEs/README.ur-PK.md index 79984684a2..b130d5e0de 100644 --- a/READMEs/README.ur-PK.md +++ b/READMEs/README.ur-PK.md @@ -1167,7 +1167,7 @@ EMBEDDING_PROVIDER=local

API

-پورٹ `3111` پر 147 اینڈ پوائنٹس۔ REST API ڈیفالٹ کے طور پر `127.0.0.1` سے bind ہوتا ہے۔ محفوظ اینڈ پوائنٹس کو `Authorization: Bearer ` درکار ہے، اور mesh sync اینڈ پوائنٹس کو دونوں peers پر واضح طور پر سیٹ کیا گیا `AGENTMEMORY_SECRET` درکار ہے۔ +پورٹ `3111` پر 148 اینڈ پوائنٹس۔ REST API ڈیفالٹ کے طور پر `127.0.0.1` سے bind ہوتا ہے۔ محفوظ اینڈ پوائنٹس کو `Authorization: Bearer ` درکار ہے، اور mesh sync اینڈ پوائنٹس کو دونوں peers پر واضح طور پر سیٹ کیا گیا `AGENTMEMORY_SECRET` درکار ہے۔ توثیق بطور طے شدہ فعال ہے۔ `AGENTMEMORY_SECRET` مقرر نہ ہو تو CLI پہلی بار بے ترتیب راز `~/.agentmemory/secret` میں محفوظ کرتا ہے اور منتخب ڈیٹا ڈائریکٹری کے `secret` میں اس کی نقل رکھتا ہے؛ اجازت `0600` ہوتی ہے۔ ساتھ آنے والے کلائنٹس مقامی رابطے میں اس اصل فائل کو ترجیح دیتے ہیں اور محفوظ راز صرف loopback URL کو بھیجتے ہیں۔ واضح `AGENTMEMORY_SECRET` مقدم ہے؛ دور کے کلائنٹس اسے environment میں مقرر کریں۔ Docker اپنا راز بناتا ہے۔ diff --git a/READMEs/README.vi-VN.md b/READMEs/README.vi-VN.md index 144f2433c6..9a25dc1a57 100644 --- a/READMEs/README.vi-VN.md +++ b/READMEs/README.vi-VN.md @@ -1172,7 +1172,7 @@ Tham chiếu đầy đủ ở [`.env.example`](../.env.example), gồm nhà cung

API

-147 endpoint trên port `3111`. REST API bind vào `127.0.0.1` theo mặc định. Các endpoint được bảo vệ cần `Authorization: Bearer `, và các endpoint mesh sync cần `AGENTMEMORY_SECRET` được đặt rõ ràng trên cả hai phía. +148 endpoint trên port `3111`. REST API bind vào `127.0.0.1` theo mặc định. Các endpoint được bảo vệ cần `Authorization: Bearer `, và các endpoint mesh sync cần `AGENTMEMORY_SECRET` được đặt rõ ràng trên cả hai phía. Xác thực bật mặc định. Nếu chưa đặt `AGENTMEMORY_SECRET`, CLI tạo bí mật ngẫu nhiên lần đầu tại `~/.agentmemory/secret` và sao chép vào `secret` trong thư mục dữ liệu đã chọn, với quyền `0600`. Client đi kèm ưu tiên tệp chính này khi kết nối cục bộ và chỉ gửi bí mật đã lưu đến URL loopback. `AGENTMEMORY_SECRET` đặt tường minh luôn được ưu tiên; client từ xa phải đặt qua biến môi trường. Triển khai Docker tạo bí mật riêng. diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md index 5791cf5ce7..b720797c52 100644 --- a/READMEs/README.zh-CN.md +++ b/READMEs/README.zh-CN.md @@ -1173,7 +1173,7 @@ EMBEDDING_PROVIDER=local

API

-端口 `3111` 上有 147 个端点。REST API 默认绑定到 `127.0.0.1`。受保护的端点需要 `Authorization: Bearer `,mesh 同步端点则需要双方都显式设置 `AGENTMEMORY_SECRET`。 +端口 `3111` 上有 148 个端点。REST API 默认绑定到 `127.0.0.1`。受保护的端点需要 `Authorization: Bearer `,mesh 同步端点则需要双方都显式设置 `AGENTMEMORY_SECRET`。 认证默认开启。未设置 `AGENTMEMORY_SECRET` 时,CLI 首次启动会将随机密钥保存到 `~/.agentmemory/secret`,并镜像到所选数据目录的 `secret`,权限为 `0600`。内置客户端连接本地服务器时优先读取该公共文件,只向回环 URL 发送保存的密钥。显式设置的 `AGENTMEMORY_SECRET` 优先;远程客户端需通过环境变量设置密钥。Docker 部署生成自己的密钥。 diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md index f22939d49b..22f786fed3 100644 --- a/READMEs/README.zh-TW.md +++ b/READMEs/README.zh-TW.md @@ -1165,7 +1165,7 @@ EMBEDDING_PROVIDER=local

API

-連接埠 `3111` 上有 147 個端點。REST API 預設綁定 `127.0.0.1`。受保護的端點需要 `Authorization: Bearer `,而網狀同步端點要求兩端都明確設定 `AGENTMEMORY_SECRET`。 +連接埠 `3111` 上有 148 個端點。REST API 預設綁定 `127.0.0.1`。受保護的端點需要 `Authorization: Bearer `,而網狀同步端點要求兩端都明確設定 `AGENTMEMORY_SECRET`。 驗證預設開啟。未設定 `AGENTMEMORY_SECRET` 時,CLI 首次啟動會將隨機密鑰儲存到 `~/.agentmemory/secret`,並鏡像到所選資料目錄的 `secret`,權限為 `0600`。內建客戶端連接本機伺服器時優先讀取此共用檔案,只向回環 URL 傳送儲存的密鑰。明確設定的 `AGENTMEMORY_SECRET` 優先;遠端客戶端需透過環境變數設定密鑰。Docker 部署會產生自己的密鑰。 diff --git a/assets/diagrams/architecture.svg b/assets/diagrams/architecture.svg index 14316203d9..52d3b672f7 100644 --- a/assets/diagrams/architecture.svg +++ b/assets/diagrams/architecture.svg @@ -83,7 +83,7 @@ agentmemory server :3111 -REST · 147 endpoints · MCP · 54 tools, 6 resources, 3 prompts +REST · 148 endpoints · MCP · 54 tools, 6 resources, 3 prompts Privacy filter on every write · per-agent scope · audit log · circuit breaker diff --git a/assets/diagrams/stack.svg b/assets/diagrams/stack.svg index 8bc91e8f77..89204585d8 100644 --- a/assets/diagrams/stack.svg +++ b/assets/diagrams/stack.svg @@ -44,7 +44,7 @@ Captureprivacy filterCompresssyntheticRecallhybrid searchConsolidatedecay, TTL -Hooks12 lifecycle eventsMCP54 toolsREST147 endpoints +Hooks12 lifecycle eventsMCP54 toolsREST148 endpoints Claude CodeCodexCursorCopilot CLIOpenCodeGemini CLIPiHermesOpenClawOrca diff --git a/integrations/omp/README.md b/integrations/omp/README.md index 9517e1dcee..1f3127f8ac 100644 --- a/integrations/omp/README.md +++ b/integrations/omp/README.md @@ -48,9 +48,9 @@ Automatic capture uses AgentMemory's privacy scrubber before sending or queueing ## Offline behavior -Failed captures from network errors, timeouts, HTTP 408/429 and server errors enter the bounded local capture spool. OMP retries at session start, before prompts, every ten seconds and on `/agentmemory-status`. Event IDs prevent duplicate storage across retries. Acknowledgements are retained through the daemon's durability window to cover restarts. +Failed captures enter the bounded local capture spool unless the daemon rejected the payload itself (HTTP 400 or 422 with `status: "rejected"`, or 413). Network errors, timeouts, authentication errors, a `404` while the daemon restarts and server errors all keep the capture. OMP retries at session start, before prompts, every ten seconds and on `/agentmemory-status`. Event IDs prevent duplicate storage across retries. Acknowledgements are retained through the daemon's durability window to cover restarts. -The conversation continues when the daemon is unavailable. Explicit save/search tools report failure and are not queued. Authentication and other non-retryable client errors are reported instead of retried forever. Queue limits, disabled spooling or disk failures can still drop captures; inspect `/agentmemory-status`. Session finalization is best effort within OMP's two-second shutdown budget. Summary generation and consolidation run on the server. +The conversation continues when the daemon is unavailable. Explicit save/search tools report failure and are not queued. A replay pass stops at the first failure, so a wrong secret costs one request per pass while the capture stays queued. Queue limits, disabled spooling or disk failures can still drop captures; inspect `/agentmemory-status`. Session finalization is best effort within OMP's two-second shutdown budget. Summary generation and consolidation run on the server. ## Configuration diff --git a/integrations/orca/src/worker.ts b/integrations/orca/src/worker.ts index 049fba2f9a..80611afd01 100644 --- a/integrations/orca/src/worker.ts +++ b/integrations/orca/src/worker.ts @@ -122,15 +122,15 @@ async function openViewer(orca: OrcaWorkerApi): Promise { const pendingCaptures: Array> = [] let flushing = false -function retryable(status: number): boolean { - return status === 0 || status === 408 || status === 429 || status >= 500 +function isFinal(status: number, body: unknown): boolean { + if (status === -1 || status === 413) return true + const rejection = body as { status?: unknown; retryable?: unknown } | null + return (status === 400 || status === 422) && rejection?.status === 'rejected' && rejection.retryable !== true } async function sendCapture(url: string, body: Record): Promise { const reply = await callServer(url, 'observe', { method: 'POST', body, timeoutMs: 5000 }) - if (reply.status >= 200 && reply.status < 300) return true - if (retryable(reply.status)) return false - return true + return (reply.status >= 200 && reply.status < 300) || isFinal(reply.status, reply.body) } async function flushCaptures(url: string): Promise { diff --git a/integrations/pi/index.ts b/integrations/pi/index.ts index 92c5c6c49c..6e4575235a 100644 --- a/integrations/pi/index.ts +++ b/integrations/pi/index.ts @@ -127,6 +127,11 @@ export default function agentmemoryExtension(pi: ExtensionAPI) { // override, git repository basename, cwd basename) so Pi sessions share a // project bucket with every other agent instead of scoping on a raw path. const projectCache = new Map(); + function syncCwd(cwd: unknown): void { + if (typeof cwd === "string" && cwd) currentCwd = cwd; + currentProject = resolveProjectName(currentCwd); + } + function resolveProjectName(dir: string): string { const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]?.trim(); if (explicit) return explicit; @@ -330,8 +335,7 @@ export default function agentmemoryExtension(pi: ExtensionAPI) { pi.on("session_start", async (_event, ctx) => { sessionId = ctx.sessionManager.getSessionId(); - currentCwd = ctx.cwd; - currentProject = resolveProjectName(currentCwd); + syncCwd(ctx.cwd); lastPrompt = ""; seenEvents.clear(); fileStash.clear(); @@ -342,8 +346,7 @@ export default function agentmemoryExtension(pi: ExtensionAPI) { }); pi.on("before_agent_start", async (event, ctx) => { - currentCwd = ctx.cwd; - currentProject = resolveProjectName(currentCwd); + syncCwd(ctx.cwd); lastPrompt = "prompt" in event ? event.prompt.trim() : ""; if (!lastPrompt) return; turnId = generateId("turn"); diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index a3d4b60f59..3d69405dab 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -1,5 +1,5 @@ import { spawn } from "node:child_process"; -import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs"; +import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs"; import { createHash } from "node:crypto"; import { homedir, platform } from "node:os"; import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; @@ -272,7 +272,7 @@ function resolveDataDir(options = {}) { }; const legacyDir = resolve(cwd, "data"); const hasLegacyStore = existsSync(join(legacyDir, "state_store.db")) || existsSync(join(legacyDir, "iii-config.yaml")); - if (instance === 0 && hasLegacyStore) return { + if (options.adoptLegacy !== false && instance === 0 && hasLegacyStore) return { dataDir: legacyDir, source: "default" }; @@ -372,6 +372,22 @@ function scrubRecord(value, options = {}) { } //#endregion //#region src/capture/spool.ts +function rejectionBody(body) { + let value = body; + if (typeof value === "string") try { + value = JSON.parse(value); + } catch { + return false; + } + if (!value || typeof value !== "object") return false; + const record = value; + return record.status === "rejected" && record.retryable !== true; +} +function sendOutcome(status, body) { + if (status >= 200 && status < 300) return status === 200 || body?.status === "duplicate" ? "duplicate" : "delivered"; + if (status === 413) return "rejected"; + return (status === 400 || status === 422) && rejectionBody(body) ? "rejected" : "retry"; +} const DEFAULT_MAX_BYTES = 5 * 1024 * 1024; const MIN_MAX_BYTES = 64 * 1024; const DEFAULT_MAX_AGE_HOURS = 168; @@ -415,7 +431,8 @@ function spoolDir(env = process.env) { if (explicit && explicit.trim()) return resolve(explicit.trim()); return join(resolveDataDir({ args: [], - env + env, + adoptLegacy: false }).dataDir, "capture-spool"); } const LOOPBACK = new Set([ @@ -500,13 +517,15 @@ function readSpoolStats(paths) { } } function writeStats(paths, patch) { + const tmp = `${paths.stats}.${process.pid}.tmp`; try { const stats = readSpoolStats(paths); patch(stats); - const tmp = `${paths.stats}.${process.pid}.tmp`; writeFileSync(tmp, JSON.stringify(stats), { mode: 384 }); renameSync(tmp, paths.stats); - } catch {} + } catch { + rmSync(tmp, { force: true }); + } } function fileSize(path) { try { @@ -562,7 +581,12 @@ function rewriteLocked(paths, records) { } finally { closeSync(fd); } - renameSync(tmp, paths.file); + try { + renameSync(tmp, paths.file); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } } function pruneExpiredLocked(paths, policy) { if (!existsSync(paths.file)) return 0; @@ -969,11 +993,6 @@ function withEventId(body, host, content, options = {}) { eventId: deriveEventId(body.hookType, body.sessionId, source, content ?? body.data) }; } -function classify(status) { - if (status >= 200 && status < 300) return status === 200 ? "duplicate" : "delivered"; - if (status === 408 || status === 429 || status >= 500) return "retry"; - return "rejected"; -} async function post(body, timeoutMs) { if (transportBlocked()) throw new Error("insecure transport"); const res = await fetch(`${REST_URL}/agentmemory/observe`, { @@ -983,22 +1002,16 @@ async function post(body, timeoutMs) { signal: AbortSignal.timeout(timeoutMs) }); const text = await res.text().catch(() => ""); - const outcome = classify(res.status); - if (outcome !== "delivered" && outcome !== "duplicate") return { + const outcome = sendOutcome(res.status, text); + let mark = null; + if (outcome === "delivered" || outcome === "duplicate") try { + mark = parseSentMark(JSON.parse(text)); + } catch {} + return { outcome, - mark: null + mark, + status: res.status }; - try { - return { - outcome, - mark: parseSentMark(JSON.parse(text)) - }; - } catch { - return { - outcome, - mark: null - }; - } } function keepUntilDurable(eventId, body, mark) { const { requeued } = reconcileSent(REST_URL, mark.bootId); @@ -1031,12 +1044,12 @@ async function captureObservation(body, timeoutMs) { }; let reason; try { - const { outcome, mark } = await post(payload, timeoutMs); + const { outcome, mark, status } = await post(payload, timeoutMs); if (outcome !== "retry") { if ((mark ? keepUntilDurable(eventId, payload, mark) : 0) > 0 || spoolHasRecords(REST_URL)) startDrainChild(); return outcome; } - reason = "server-error"; + reason = status >= 500 ? "server-error" : `http-${status}`; } catch (err) { const name = err instanceof Error ? err.name : ""; reason = name === "TimeoutError" || name === "AbortError" ? "timeout" : "unreachable"; diff --git a/plugin/skills/agentmemory-rest-api/REFERENCE.md b/plugin/skills/agentmemory-rest-api/REFERENCE.md index 0ec4695388..624f1a6693 100644 --- a/plugin/skills/agentmemory-rest-api/REFERENCE.md +++ b/plugin/skills/agentmemory-rest-api/REFERENCE.md @@ -5,7 +5,7 @@ Generated from `src/triggers/api.ts`. Do not edit the block below by hand; run ` The REST API is the primary surface. All paths are under `http://localhost:3111` (override with `--port`). Send `Authorization: Bearer `: the value of `AGENTMEMORY_SECRET`, or the one generated into `~/.agentmemory/secret` on first start when it is unset. Writes must use `Content-Type: application/json`. -147 registered endpoints: +148 registered endpoints: | Method | Path | | --- | --- | @@ -93,6 +93,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111` | POST | `/agentmemory/mesh/peers` | | POST | `/agentmemory/mesh/receive` | | POST | `/agentmemory/mesh/sync` | +| POST | `/agentmemory/metrics/reset` | | POST | `/agentmemory/migrate` | | GET | `/agentmemory/next` | | GET | `/agentmemory/observations` | diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json index fa2e64735b..71a4122d76 100644 --- a/scripts/docs-sync.state.json +++ b/scripts/docs-sync.state.json @@ -11,7 +11,7 @@ "7" ], "restEndpoints": [ - "147" + "148" ], "skills": [ "17" @@ -23,7 +23,7 @@ "5000+" ], "functions": [ - "323" + "324" ], "sourceFiles": [ "263" diff --git a/src/capture/client.ts b/src/capture/client.ts index 334a35b537..0ed19d2438 100644 --- a/src/capture/client.ts +++ b/src/capture/client.ts @@ -1,4 +1,4 @@ -import { appendSpool, drainSpool, parseSentMark, reconcileSent, retainSent, spoolSummary, type SendOutcome, type SpoolRecord } from "./spool.js"; +import { appendSpool, drainSpool, parseSentMark, reconcileSent, retainSent, sendOutcome, spoolSummary, type SendOutcome, type SpoolRecord } from "./spool.js"; import { scrubRecord, stripPrivateData } from "../functions/privacy.js"; export function cleanCapture(value: unknown): unknown { @@ -22,15 +22,15 @@ export function createCapture(url: string, post: (body: Record) async function send(record: Pick): Promise { const result = await post(record.body); - if (result.status >= 200 && result.status < 300) { + const outcome = sendOutcome(result.status, result.body); + if (outcome === "delivered" || outcome === "duplicate") { const mark = parseSentMark(result.body); if (mark) { reconcileSent(url, mark.bootId); retainSent(url, record.eventId, record.body, mark); } - return (result.body as { status?: string })?.status === "duplicate" ? "duplicate" : "delivered"; } - return result.status === 0 || result.status === 408 || result.status === 429 || result.status >= 500 ? "retry" : "rejected"; + return outcome; } function track(work: Promise) { const safe = work.catch(() => { error = "Capture spool is unavailable; check disk space and permissions."; }); diff --git a/src/capture/spool.ts b/src/capture/spool.ts index f1c802cf2e..a7c8455792 100644 --- a/src/capture/spool.ts +++ b/src/capture/spool.ts @@ -8,6 +8,7 @@ import { readFileSync, readdirSync, renameSync, + rmSync, statSync, unlinkSync, utimesSync, @@ -91,6 +92,24 @@ export interface SpoolSummary { export type SendOutcome = "delivered" | "duplicate" | "rejected" | "retry"; +function rejectionBody(body: unknown): boolean { + let value = body; + if (typeof value === "string") { + try { value = JSON.parse(value); } catch { return false; } + } + if (!value || typeof value !== "object") return false; + const record = value as Record; + return record.status === "rejected" && record.retryable !== true; +} + +export function sendOutcome(status: number, body: unknown): SendOutcome { + if (status >= 200 && status < 300) { + return status === 200 || (body as { status?: unknown } | null)?.status === "duplicate" ? "duplicate" : "delivered"; + } + if (status === 413) return "rejected"; + return (status === 400 || status === 422) && rejectionBody(body) ? "rejected" : "retry"; +} + export interface DrainResult { claimed: number; delivered: number; @@ -142,7 +161,7 @@ export function spoolPolicy(env: NodeJS.ProcessEnv = process.env): SpoolPolicy { export function spoolDir(env: NodeJS.ProcessEnv = process.env): string { const explicit = env["AGENTMEMORY_CAPTURE_SPOOL_DIR"]; if (explicit && explicit.trim()) return resolve(explicit.trim()); - return join(resolveDataDir({ args: [], env }).dataDir, "capture-spool"); + return join(resolveDataDir({ args: [], env, adoptLegacy: false }).dataDir, "capture-spool"); } const LOOPBACK = new Set(["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"]); @@ -226,13 +245,15 @@ export function readSpoolStats(paths: SpoolPaths): SpoolStats { } function writeStats(paths: SpoolPaths, patch: (stats: SpoolStats) => void): void { + const tmp = `${paths.stats}.${process.pid}.tmp`; try { const stats = readSpoolStats(paths); patch(stats); - const tmp = `${paths.stats}.${process.pid}.tmp`; writeFileSync(tmp, JSON.stringify(stats), { mode: 0o600 }); renameSync(tmp, paths.stats); - } catch {} + } catch { + rmSync(tmp, { force: true }); + } } function fileSize(path: string): number { @@ -285,7 +306,12 @@ function rewriteLocked(paths: SpoolPaths, records: SpoolRecord[]): void { } finally { closeSync(fd); } - renameSync(tmp, paths.file); + try { + renameSync(tmp, paths.file); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } } function pruneExpiredLocked(paths: SpoolPaths, policy: SpoolPolicy): number { diff --git a/src/cli-data-dir.ts b/src/cli-data-dir.ts index e27fc60a90..60a344ecaf 100644 --- a/src/cli-data-dir.ts +++ b/src/cli-data-dir.ts @@ -16,6 +16,7 @@ type ResolveDataDirOptions = { cwd?: string; home?: string; platform?: NodeJS.Platform; + adoptLegacy?: boolean; }; function argValue(args: string[], name: string): string | undefined { @@ -115,7 +116,7 @@ export function resolveDataDir(options: ResolveDataDirOptions = {}): ResolvedDat const hasLegacyStore = existsSync(join(legacyDir, "state_store.db")) || existsSync(join(legacyDir, "iii-config.yaml")); - if (instance === 0 && hasLegacyStore) { + if (options.adoptLegacy !== false && instance === 0 && hasLegacyStore) { return { dataDir: legacyDir, source: "default" }; } diff --git a/src/cli.ts b/src/cli.ts index 8a6479e733..944a7f693e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -19,7 +19,7 @@ import { } from "node:fs"; import { join, dirname, resolve, delimiter as PATH_DELIMITER } from "node:path"; import { fileURLToPath } from "node:url"; -import { homedir, platform } from "node:os"; +import { homedir, platform, uptime } from "node:os"; import * as p from "@clack/prompts"; import pc from "picocolors"; @@ -86,7 +86,7 @@ import { } from "./cli/engine-config.js"; import { SHUTDOWN_HARD_EXIT_MS, registerStartupCleanup, runStartupCleanup } from "./shutdown.js"; import { processStatIsRunning } from "./cli/process-state.js"; -import { classifyComposeProcess, readUnixProcessExecutable, type ComposeProcessIdentity } from "./cli/compose-process.js"; +import { classifyComposeProcess, readUnixProcessExecutable, writtenBeforeBoot, type ComposeProcessIdentity } from "./cli/compose-process.js"; import { renderSplash } from "./cli/splash.js"; import { isFirstRun, readPrefs, resetPrefs, writePrefs } from "./cli/preferences.js"; import { runOnboarding } from "./cli/onboarding.js"; @@ -1567,11 +1567,20 @@ function printReadyHint(): void { process.stdout.write(`\n${c.dim("Try:")} ${c.cmd(demoCommand)}\n`); } +function engineStateFromPreviousBoot(): boolean { + try { + return writtenBeforeBoot(statSync(engineStatePath()).mtimeMs, Date.now(), uptime()); + } catch { + return false; + } +} + async function reconcilePersistedComposeEngine(): Promise { const state = readEngineState(); if (state?.kind !== "compose") return false; if (!(await isEngineRunning())) { - if (state.composePid && pidAlive(state.composePid) && composePidIdentity(state.composePid, state) !== "foreign") { + const identity = state.composePid && pidAlive(state.composePid) ? composePidIdentity(state.composePid, state) : "foreign"; + if (identity === "match" || (identity === "unknown" && !engineStateFromPreviousBoot())) { p.log.error(`Worker Compose daemon ${state.composePid} is alive but REST ${state.restPort} is not ready. Inspect ${state.logFile}; use agentmemory stop to reconcile.`); process.exit(1); } diff --git a/src/cli/capture.ts b/src/cli/capture.ts index ceb89d3b65..ea6e719d7e 100644 --- a/src/cli/capture.ts +++ b/src/cli/capture.ts @@ -1,4 +1,4 @@ -import { drainSpool, parseSentMark, retainSent, spoolSummary, type SendOutcome, type SpoolRecord } from "../capture/spool.js"; +import { drainSpool, parseSentMark, retainSent, sendOutcome, spoolSummary, type SpoolRecord } from "../capture/spool.js"; import { CURL_AUTH_HEADER } from "../functions/status.js"; interface CaptureCommandOptions { @@ -14,13 +14,6 @@ function headers(secret?: string): Record { return h; } -function classify(status: number): SendOutcome { - if (status === 200) return "duplicate"; - if (status >= 200 && status < 300) return "delivered"; - if (status === 408 || status === 429 || status >= 500) return "retry"; - return "rejected"; -} - async function serverCapture(base: string, secret?: string): Promise { try { const res = await fetch(`${base}/agentmemory/capture?limit=20`, { @@ -49,7 +42,7 @@ export async function runCaptureCommand(options: CaptureCommandOptions): Promise signal: AbortSignal.timeout(10_000), }); const text = await res.text().catch(() => ""); - const outcome = classify(res.status); + const outcome = sendOutcome(res.status, text); if (outcome === "delivered" || outcome === "duplicate") { let mark = null; try { diff --git a/src/cli/compose-process.ts b/src/cli/compose-process.ts index bb5139fd7f..643469a935 100644 --- a/src/cli/compose-process.ts +++ b/src/cli/compose-process.ts @@ -46,6 +46,13 @@ export function sameResolvedExecutable(actual: string, expected: string, windows export type ComposeProcessIdentity = "match" | "foreign" | "unknown"; +export const BOOT_TOLERANCE_MS = 120_000; + +export function writtenBeforeBoot(stateMtimeMs: number, nowMs: number, uptimeSeconds: number): boolean { + if (!Number.isFinite(stateMtimeMs) || !Number.isFinite(uptimeSeconds) || uptimeSeconds <= 0) return false; + return stateMtimeMs < nowMs - uptimeSeconds * 1000 - BOOT_TOLERANCE_MS; +} + export function classifyComposeProcess( inspected: { command: string; executable: string } | null, expected: { namespace: string; file: string; binPath: string }, diff --git a/src/cli/compose-project.ts b/src/cli/compose-project.ts index 57e510544b..66b020522f 100644 --- a/src/cli/compose-project.ts +++ b/src/cli/compose-project.ts @@ -367,9 +367,12 @@ export function renderWorkerCompose(options: ComposeProjectOptions): string { const explicitWorkerEnvironment = Object.entries(options.workerEnvironmentOverrides ?? options.workerEnvironment ?? {}) .filter(([key, value]) => value !== undefined && AGENTMEMORY_WORKER_ENV_ALLOWLIST.has(key) && !COMPOSE_RESERVED_ENV.has(key)) .sort(([left], [right]) => left.localeCompare(right)); + const dataRootKey = windows ? "APPDATA" : "XDG_DATA_HOME"; + const dataRoot = (options.workerEnvironment ?? process.env)[dataRootKey]; lines.push( " environment:", ...explicitWorkerEnvironment.map(([key, value]) => ` ${key}: ${yamlString(value!)}`), + ...(dataRoot ? [` ${dataRootKey}: ${yamlString(dataRoot)}`] : []), ...(windows ? [` NoDefaultCurrentDirectoryInExePath: ${yamlString("1")}`] : []), ` HOME: ${yamlString(options.homeDir)}`, ` PATH: ${yamlString(windows ? windowsWorkerPath(options.nodeBin, options.workerEnvironment?.PATH ?? process.env.PATH) : `${dirname(options.nodeBin)}:/usr/local/bin:/usr/bin:/bin`)}`, diff --git a/src/config.ts b/src/config.ts index 8cc3da2d1b..f9d97bb2f7 100644 --- a/src/config.ts +++ b/src/config.ts @@ -194,22 +194,57 @@ export function envFileLabel(path: string = ENV_FILE): string { return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path; } -export function llmOptInHint(env: Record = getMergedEnv()): string | null { +function keyedLlmProviders(env: Record): LlmProviderName[] { + return LLM_PROVIDER_NAMES.filter((name) => llmProviderHasKey(env, name)); +} + +function presentProviderKeys(env: Record, names: LlmProviderName[]): string[] { + return names.flatMap((name) => LLM_PROVIDER_KEYS[name].filter((k) => isRealProviderKey(env, k))); +} + +type LlmChoice = + | { kind: "provider"; name: LlmProviderName } + | { kind: "agent-sdk" } + | { kind: "noop"; hint: string | null; warn?: boolean }; + +function resolveLlmChoice(env: Record): LlmChoice { const selected = selectedLlmProviderValue(env); + const allowed = env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true"; + if (selected === "agent-sdk") { + return allowed + ? { kind: "agent-sdk" } + : { kind: "noop", hint: `AGENTMEMORY_LLM_PROVIDER=agent-sdk also needs AGENTMEMORY_ALLOW_AGENT_SDK=true in ${envFileLabel()}.` }; + } if (selected) { if (!isLlmProviderName(selected)) { - return `AGENTMEMORY_LLM_PROVIDER=${selected} is not a known provider. Use one of: ${LLM_PROVIDER_NAMES.join(", ")}.`; + return { kind: "noop", hint: `AGENTMEMORY_LLM_PROVIDER=${selected} is not a known provider. Use one of: ${LLM_PROVIDER_NAMES.join(", ")}.` }; } if (!llmProviderHasKey(env, selected)) { - return `AGENTMEMORY_LLM_PROVIDER=${selected} is set, but ${LLM_PROVIDER_KEYS[selected].join(" or ")} is not. Add the key to ${envFileLabel()}.`; + return { kind: "noop", hint: `AGENTMEMORY_LLM_PROVIDER=${selected} is set, but ${LLM_PROVIDER_KEYS[selected].join(" or ")} is not. Add the key to ${envFileLabel()}.` }; } - return null; + return { kind: "provider", name: selected }; } - if (env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true") return null; - const withKey = LLM_PROVIDER_NAMES.filter((name) => llmProviderHasKey(env, name)); - if (withKey.length === 0) return null; - const keys = withKey.flatMap((name) => LLM_PROVIDER_KEYS[name].filter((k) => isRealProviderKey(env, k))); - return `Found ${keys.join(", ")}, but agentmemory sends nothing to an LLM provider until you choose one for it. To turn on LLM summaries and compression, add AGENTMEMORY_LLM_PROVIDER=${withKey[0]} to ${envFileLabel()}.`; + const embedding = (env["EMBEDDING_PROVIDER"] || "").trim().toLowerCase(); + const keyed = keyedLlmProviders(env).filter((name) => !allowed || name !== embedding); + if (allowed && keyed.length === 0) return { kind: "agent-sdk" }; + if (keyed.length === 0) return { kind: "noop", hint: null }; + const keys = presentProviderKeys(env, keyed).join(", "); + if (allowed) { + return { + kind: "noop", + warn: true, + hint: `Found ${keys} and AGENTMEMORY_ALLOW_AGENT_SDK=true, but no AGENTMEMORY_LLM_PROVIDER, so agentmemory does not guess which one to use and sends nothing to an LLM. Add AGENTMEMORY_LLM_PROVIDER=${keyed[0]} to ${envFileLabel()} to use that key, or AGENTMEMORY_LLM_PROVIDER=agent-sdk to keep the Claude Agent SDK fallback.`, + }; + } + return { + kind: "noop", + hint: `Found ${keys}, but agentmemory sends nothing to an LLM provider until you choose one for it. To turn on LLM summaries and compression, add AGENTMEMORY_LLM_PROVIDER=${keyed[0]} to ${envFileLabel()}.`, + }; +} + +export function llmOptInHint(env: Record = getMergedEnv()): string | null { + const choice = resolveLlmChoice(env); + return choice.kind === "noop" ? choice.hint : null; } export function embeddingOptInHint(env: Record = getMergedEnv()): string | null { @@ -230,15 +265,21 @@ export function embeddingOptInHint(env: Record = get function detectProvider(env: Record): ProviderConfig { const maxTokens = parseInt(env["MAX_TOKENS"] || "4096", 10); - const noop: ProviderConfig = { provider: "noop", model: "noop", maxTokens }; - const selected = selectedLlmProviderValue(env); - - if (selected) { - if (!isLlmProviderName(selected) || !llmProviderHasKey(env, selected)) { - writeProviderNoticeOnce(`[agentmemory] ${llmOptInHint(env)} Running zero-LLM.\n`); - return noop; - } - switch (selected) { + const choice = resolveLlmChoice(env); + if (choice.kind === "noop") { + writeProviderNoticeOnce( + choice.hint + ? `[agentmemory] ${choice.warn ? "WARNING: " : ""}${choice.hint} Running zero-LLM.\n` + : pc.dim( + "[agentmemory] No LLM provider chosen, so agentmemory runs zero-LLM: no LLM compression or summaries, and no session content leaves this machine for an LLM. " + + "Search uses BM25 plus any embedding provider you set with EMBEDDING_PROVIDER (EMBEDDING_PROVIDER=local runs on-device). " + + "To turn on LLM summaries, set AGENTMEMORY_LLM_PROVIDER (anthropic, openai, gemini, openrouter or minimax) and that provider's key in ~/.agentmemory/.env.\n", + ), + ); + return { provider: "noop", model: "noop", maxTokens }; + } + if (choice.kind === "provider") { + switch (choice.name) { case "openai": { const model = env["OPENAI_MODEL"] || "gpt-5.6-luna"; warnIfPremiumModel(env, "OPENAI_MODEL", model); @@ -269,21 +310,6 @@ function detectProvider(env: Record): ProviderConfig { } } - const allowAgentSdk = env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true"; - if (!allowAgentSdk) { - const hint = llmOptInHint(env); - writeProviderNoticeOnce( - hint - ? `[agentmemory] ${hint}\n` - : pc.dim( - "[agentmemory] No LLM provider chosen, so agentmemory runs zero-LLM: no LLM compression or summaries, and no session content leaves this machine for an LLM. " + - "Search uses BM25 plus any embedding provider you set with EMBEDDING_PROVIDER (EMBEDDING_PROVIDER=local runs on-device). " + - "To turn on LLM summaries, set AGENTMEMORY_LLM_PROVIDER (anthropic, openai, gemini, openrouter or minimax) and that provider's key in ~/.agentmemory/.env.\n", - ), - ); - return noop; - } - writeProviderNoticeOnce( "[agentmemory] WARNING: agent-sdk fallback enabled via AGENTMEMORY_ALLOW_AGENT_SDK=true. " + "This spawns @anthropic-ai/claude-agent-sdk child sessions that can trigger the Stop-hook " + @@ -433,12 +459,7 @@ export function getAuditMigrateMaxBytes(): number { export function detectLlmProviderKind( env: Record = getMergedEnv(), ): "llm" | "noop" { - const selected = selectedLlmProviderValue(env); - if (selected && isLlmProviderName(selected) && llmProviderHasKey(env, selected)) { - return "llm"; - } - if (!selected && env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true") return "llm"; - return "noop"; + return resolveLlmChoice(env).kind === "noop" ? "noop" : "llm"; } export function describeLlmRoute(provider: ProviderConfig): string | null { diff --git a/src/eval/metrics-store.ts b/src/eval/metrics-store.ts index 1d381ff95b..e36d890610 100644 --- a/src/eval/metrics-store.ts +++ b/src/eval/metrics-store.ts @@ -2,6 +2,8 @@ import type { FunctionMetrics } from "../types.js"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; +export const RECENT_WINDOW = 10; + export class MetricsStore { private cache = new Map(); private qualityCallCounts = new Map(); @@ -34,6 +36,7 @@ export class MetricsStore { } else { m.failureCount += 1; } + m.recent = `${m.recent ?? ""}${success ? "1" : "0"}`.slice(-RECENT_WINDOW); if (qualityScore !== undefined) { const prevQualityCalls = this.qualityCallCounts.get(functionId) || 0; m.avgQualityScore = @@ -46,6 +49,16 @@ export class MetricsStore { await this.kv.set(KV.metrics, functionId, m).catch(() => {}); } + async reset(functionId?: string): Promise { + const ids = functionId ? [functionId] : (await this.getAll()).map((m) => m.functionId); + for (const id of ids) { + this.cache.delete(id); + this.qualityCallCounts.delete(id); + } + await Promise.all(ids.map((id) => this.kv.delete(KV.metrics, id))); + return ids; + } + async get(functionId: string): Promise { return ( this.cache.get(functionId) ?? diff --git a/src/functions/consolidation-pipeline.ts b/src/functions/consolidation-pipeline.ts index 37df1159f0..350bc7daaa 100644 --- a/src/functions/consolidation-pipeline.ts +++ b/src/functions/consolidation-pipeline.ts @@ -6,7 +6,7 @@ import type { Memory, MemoryProvider, } from "../types.js"; -import { KV, generateId } from "../state/schema.js"; +import { KV, generateId, jaccardSimilarity } from "../state/schema.js"; import type { StateKV } from "../state/kv.js"; import { collectAll } from "../state/kv.js"; import { @@ -50,6 +50,27 @@ function applyDecay( } const DECAY_STRENGTH_EPSILON = 1e-9; +const KNOWN_FACTS_IN_PROMPT = 40; +const SEMANTIC_DUPLICATE_SIMILARITY = 0.8; + +export function matchSemanticFact(existing: SemanticMemory[], fact: string, ref?: string): SemanticMemory | undefined { + const referenced = ref ? existing.find((s) => s.id === ref) : undefined; + if (referenced) return referenced; + const lower = fact.toLowerCase(); + let best: SemanticMemory | undefined; + let bestScore = SEMANTIC_DUPLICATE_SIMILARITY; + for (const s of existing) { + if (typeof s.fact !== "string") continue; + const candidate = s.fact.toLowerCase(); + if (candidate === lower) return s; + const score = jaccardSimilarity(candidate, lower); + if (score >= bestScore) { + best = s; + bestScore = score; + } + } + return best; +} function strengthChanged(before: number, after: number): boolean { return Math.abs(after - before) > DECAY_STRENGTH_EPSILON; @@ -105,12 +126,18 @@ export function registerConsolidationPipelineFunction( ) .slice(0, 20); + const known = existingSemantic + .filter((s) => s && typeof s.id === "string" && typeof s.fact === "string") + .sort((a, b) => (b.strength ?? 0) - (a.strength ?? 0) || (b.updatedAt ?? "").localeCompare(a.updatedAt ?? "")) + .slice(0, KNOWN_FACTS_IN_PROMPT) + .map((s) => ({ id: s.id, fact: s.fact.slice(0, 300) })); const prompt = buildSemanticMergePrompt( recentSummaries.map((s) => ({ title: s.title, narrative: s.narrative, concepts: s.concepts, })), + known, ); try { @@ -119,19 +146,19 @@ export function registerConsolidationPipelineFunction( prompt, ); - const factRegex = /([^<]+)<\/fact>/g; + const factRegex = /]*)>([^<]+)<\/fact>/g; let match; let newFacts = 0; const now = new Date().toISOString(); while ((match = factRegex.exec(response)) !== null) { - const parsedConf = parseFloat(match[1]); - const confidence = Number.isNaN(parsedConf) ? 0.5 : parsedConf; + const attrs = match[1]; + const parsedConf = parseFloat(/confidence="([^"]*)"/.exec(attrs)?.[1] ?? ""); + const confidence = Number.isNaN(parsedConf) ? 0.5 : Math.min(1, Math.max(0, parsedConf)); const fact = match[2].trim(); + if (!fact) continue; - const existing = existingSemantic.find( - (s) => s.fact.toLowerCase() === fact.toLowerCase(), - ); + const existing = matchSemanticFact(existingSemantic, fact, /ref="([^"]*)"/.exec(attrs)?.[1]); if (existing) { existing.accessCount++; existing.lastAccessedAt = now; @@ -152,6 +179,7 @@ export function registerConsolidationPipelineFunction( updatedAt: now, }; await kv.set(KV.semantic, sem.id, sem); + existingSemantic.push(sem); newFacts++; } } diff --git a/src/functions/status.ts b/src/functions/status.ts index c072a95cfc..1422fec5f9 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 { RECENT_WINDOW } from "../eval/metrics-store.js"; export type StatusLevel = "ok" | "info" | "warn" | "error"; @@ -19,6 +20,7 @@ export interface FunctionMetricInput { successCount: number; failureCount: number; avgLatencyMs: number; + recent?: string; } export interface StatusFlag { @@ -137,6 +139,17 @@ export interface StatusReport { } const FAILURE_RATE_THRESHOLD = 0.2; + +function failureWindow(m: FunctionMetricInput): { calls: number; failures: number } { + if (!m.recent) return { calls: m.totalCalls, failures: m.failureCount }; + return { calls: m.recent.length, failures: m.recent.split("").filter((c) => c === "0").length }; +} + +function isFailing(m: FunctionMetricInput & { offWithoutLlm: boolean }): boolean { + if (m.offWithoutLlm) return false; + const { calls, failures } = failureWindow(m); + return calls >= FAILURE_MIN_CALLS && failures / calls >= FAILURE_RATE_THRESHOLD; +} const FAILURE_MIN_CALLS = 5; const GRAPH_SNAPSHOT_STALE_SECONDS = 24 * 60 * 60; const LEVEL_RANK: Record = { ok: 0, info: 1, warn: 2, error: 3 }; @@ -315,18 +328,18 @@ export function evaluateStatus(input: StatusInputs): StatusReport { } const noLlm = input.provider === "noop"; - const functions = markLlmFunctions(input.functionMetrics, input.provider).map((m) => ({ - ...m, - failureRate: m.totalCalls > 0 ? m.failureCount / m.totalCalls : 0, - })); + const functions = markLlmFunctions(input.functionMetrics, input.provider).map((m) => { + const { calls, failures } = failureWindow(m); + return { ...m, failureRate: calls > 0 ? failures / calls : 0 }; + }); for (const fn of functions) { - if (fn.offWithoutLlm) continue; - if (fn.totalCalls < FAILURE_MIN_CALLS || fn.failureRate < FAILURE_RATE_THRESHOLD) continue; + if (!isFailing(fn)) continue; + const { calls, failures } = failureWindow(fn); problems.push({ level: "warn", code: "function-failing", - message: `${fn.functionId} failed ${fn.failureCount} of ${fn.totalCalls} calls (${Math.round(fn.failureRate * 100)}%).`, - fix: FUNCTION_FIXES[fn.functionId] ?? "Look for this function id in the server log to see the error.", + message: `${fn.functionId} failed ${failures} of ${fn.recent ? "the last " : ""}${calls} calls (${Math.round(fn.failureRate * 100)}%).`, + fix: `${FUNCTION_FIXES[fn.functionId] ?? "Look for this function id in the server log to see the error."} The check uses the last ${RECENT_WINDOW} calls; POST /agentmemory/metrics/reset clears the counters after a fix.`, }); } @@ -844,7 +857,7 @@ export function renderStatusHtml( .sort((a, b) => b.totalCalls - a.totalCalls) .map( (f) => - `= FAILURE_RATE_THRESHOLD && f.totalCalls >= FAILURE_MIN_CALLS ? ' class="bad"' : ""}>` + + `` + `${escapeHtml(f.functionId)}${f.totalCalls}${f.offWithoutLlm ? "-" : f.failureCount}` + `${f.offWithoutLlm ? "off, no LLM provider" : `${Math.round(f.failureRate * 100)}%`}${Math.round(f.avgLatencyMs)} ms`, ) diff --git a/src/hooks/_capture.ts b/src/hooks/_capture.ts index d5108a55e7..a4910b9671 100644 --- a/src/hooks/_capture.ts +++ b/src/hooks/_capture.ts @@ -8,6 +8,7 @@ import { parseSentMark, reconcileSent, retainSent, + sendOutcome, spoolHasRecords, type SendOutcome, type SentMark, @@ -56,13 +57,7 @@ export function withEventId( }; } -function classify(status: number): SendOutcome { - if (status >= 200 && status < 300) return status === 200 ? "duplicate" : "delivered"; - if (status === 408 || status === 429 || status >= 500) return "retry"; - return "rejected"; -} - -async function post(body: Record, timeoutMs: number): Promise<{ outcome: SendOutcome; mark: SentMark | null }> { +async function post(body: Record, timeoutMs: number): Promise<{ outcome: SendOutcome; mark: SentMark | null; status: number }> { if (transportBlocked()) throw new Error("insecure transport"); const res = await fetch(`${REST_URL}/agentmemory/observe`, { method: "POST", @@ -71,13 +66,12 @@ async function post(body: Record, timeoutMs: number): Promise<{ signal: AbortSignal.timeout(timeoutMs), }); const text = await res.text().catch(() => ""); - const outcome = classify(res.status); - if (outcome !== "delivered" && outcome !== "duplicate") return { outcome, mark: null }; - try { - return { outcome, mark: parseSentMark(JSON.parse(text)) }; - } catch { - return { outcome, mark: null }; + const outcome = sendOutcome(res.status, text); + let mark: SentMark | null = null; + if (outcome === "delivered" || outcome === "duplicate") { + try { mark = parseSentMark(JSON.parse(text)); } catch {} } + return { outcome, mark, status: res.status }; } function keepUntilDurable(eventId: string, body: Record, mark: SentMark): number { @@ -107,13 +101,13 @@ export async function captureObservation(body: ObserveBody, timeoutMs: number): const payload = { ...body, eventId } as unknown as Record; let reason: string; try { - const { outcome, mark } = await post(payload, timeoutMs); + const { outcome, mark, status } = await post(payload, timeoutMs); if (outcome !== "retry") { const requeued = mark ? keepUntilDurable(eventId, payload, mark) : 0; if (requeued > 0 || spoolHasRecords(REST_URL)) startDrainChild(); return outcome; } - reason = "server-error"; + reason = status >= 500 ? "server-error" : `http-${status}`; } catch (err) { const name = err instanceof Error ? err.name : ""; reason = name === "TimeoutError" || name === "AbortError" ? "timeout" : "unreachable"; diff --git a/src/index.ts b/src/index.ts index c254cb4bf4..d56947c2b4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -644,7 +644,7 @@ async function main() { `Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`, ); bootLog( - `REST API: 147 endpoints at http://localhost:${config.restPort}/agentmemory/*`, + `REST API: 148 endpoints at http://localhost:${config.restPort}/agentmemory/*`, ); bootLog( `MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`, diff --git a/src/integrations/dsh.ts b/src/integrations/dsh.ts index ce5cceaf63..7fb014acb8 100644 --- a/src/integrations/dsh.ts +++ b/src/integrations/dsh.ts @@ -4,7 +4,7 @@ import { captureOutputMax, shouldCaptureTool, truncateCaptureOutput } from "../h import { resolveProject } from "../hooks/_project.js"; import { stripPrivateData } from "../functions/privacy.js"; import { deriveEventId } from "../capture/event-id.js"; -import { appendSpool, drainSpool, parseSentMark, reconcileSent, retainSent, type SendOutcome } from "../capture/spool.js"; +import { appendSpool, drainSpool, parseSentMark, reconcileSent, retainSent, sendOutcome, type SendOutcome } from "../capture/spool.js"; interface Session { id: string; header?: { cwd?: string } } interface Event { type: string; seq: number; time?: number; data: Record } @@ -93,15 +93,15 @@ export function apply(ctx: Context, config: { url?: string; secret?: string } = async function deliver(body: Record): Promise { const result = await post("/observe", body); - if (result.status >= 200 && result.status < 300) { + const outcome = sendOutcome(result.status, result.body); + if (outcome === "delivered" || outcome === "duplicate") { const mark = parseSentMark(result.body); if (mark && typeof body.eventId === "string") { reconcileSent(url, mark.bootId); retainSent(url, body.eventId, body, mark); } - return result.status === 200 ? "duplicate" : "delivered"; } - return !result.status || result.status >= 500 || [408, 429].includes(result.status) ? "retry" : "rejected"; + return outcome; } function enqueue(state: State, task: () => Promise) { diff --git a/src/prompts/consolidation.ts b/src/prompts/consolidation.ts index 76580b8add..ebb85bee1d 100644 --- a/src/prompts/consolidation.ts +++ b/src/prompts/consolidation.ts @@ -9,10 +9,12 @@ Rules: - Extract only facts that appear in 2+ episodes or are highly confident - Confidence reflects how well-supported the fact is across episodes - Combine overlapping information into single concise facts -- Skip ephemeral details (specific error messages, temporary states)`; +- Skip ephemeral details (specific error messages, temporary states) +- When a fact restates one of the known facts, add ref="" to it instead of writing a new fact: ...`; export function buildSemanticMergePrompt( episodes: Array<{ title: string; narrative: string; concepts: string[] }>, + known: Array<{ id: string; fact: string }> = [], ): string { const items = episodes .map( @@ -20,7 +22,10 @@ export function buildSemanticMergePrompt( `[Episode ${i + 1}]\nTitle: ${e.title}\nNarrative: ${e.narrative}\nConcepts: ${e.concepts.join(", ")}`, ) .join("\n\n"); - return `Consolidate these episodic memories into stable facts:\n\n${items}`; + const knownBlock = known.length + ? `\n\nKnown facts (reuse with ref instead of restating):\n${known.map((k) => `[${k.id}] ${k.fact}`).join("\n")}` + : ""; + return `Consolidate these episodic memories into stable facts:\n\n${items}${knownBlock}`; } export const PROCEDURAL_EXTRACTION_SYSTEM = `You are a procedural memory extractor. Given repeated patterns and workflows observed across sessions, extract reusable procedures. diff --git a/src/triggers/api.ts b/src/triggers/api.ts index dabdd4f154..9720c4eaf3 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -696,6 +696,30 @@ export function registerApiTriggers( }, }); + sdk.registerFunction("api::metrics-reset", + async (req: HttpRequest<{ functionId?: unknown }>): Promise => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const raw = req.body?.functionId; + const functionId = raw === undefined ? undefined : asNonEmptyString(raw); + if (functionId === null || (functionId && functionId.length > 256)) { + return { status_code: 400, body: { error: "functionId must be a non-empty string" } }; + } + if (!metricsStore) return { status_code: 503, body: { error: "metrics unavailable" } }; + const reset = await metricsStore.reset(functionId); + return { status_code: 200, body: { success: true, reset } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::metrics-reset", + config: { + api_path: "/agentmemory/metrics/reset", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + const statusReport = createStatusReporter(sdk, kv, { metricsStore, provider }); sdk.registerFunction("api::status", @@ -738,6 +762,7 @@ export function registerApiTriggers( return { status_code: 400, body: { + status: "rejected", error: "hookType, sessionId, project, cwd, and timestamp are required strings", }, diff --git a/src/types.ts b/src/types.ts index d4061c1d58..c97436abd5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -268,6 +268,7 @@ export interface FunctionMetrics { failureCount: number; avgLatencyMs: number; avgQualityScore: number; + recent?: string; } export interface HealthSnapshot { diff --git a/test/capture-hook.test.ts b/test/capture-hook.test.ts index 2e79517c5b..ef8c5945f9 100644 --- a/test/capture-hook.test.ts +++ b/test/capture-hook.test.ts @@ -63,7 +63,7 @@ describe("hooks capture when the server is unavailable", () => { server = undefined; }); - async function startServer(status: number, received: Array>): Promise { + async function startServer(status: number, received: Array>, reply?: string): Promise { server = createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); @@ -72,7 +72,7 @@ describe("hooks capture when the server is unavailable", () => { received.push(JSON.parse(body)); } catch {} res.writeHead(status, { "content-type": "application/json" }); - res.end(JSON.stringify({ status: status === 201 ? "accepted" : "x" })); + res.end(reply ?? JSON.stringify({ status: status === 201 ? "accepted" : "x" })); }); }); await new Promise((resolve) => server!.listen(0, "127.0.0.1", () => resolve())); @@ -117,7 +117,7 @@ describe("hooks capture when the server is unavailable", () => { expect(recs[0]!.eventId).not.toBe(recs[1]!.eventId); }); - it("spools on a 5xx answer but not on a 4xx rejection", async () => { + it("spools on a 5xx answer but not on agentmemory's own rejection", async () => { const dir = mkdtempSync(join(tmpdir(), "am-hook-spool-")); const received: Array> = []; const port = await startServer(500, received); @@ -129,12 +129,20 @@ describe("hooks capture when the server is unavailable", () => { server = undefined; const dir2 = mkdtempSync(join(tmpdir(), "am-hook-spool-")); - const port2 = await startServer(400, []); + const port2 = await startServer(400, [], JSON.stringify({ status: "rejected", error: "invalid eventId" })); const env2 = { AGENTMEMORY_URL: `http://127.0.0.1:${port2}`, AGENTMEMORY_CAPTURE_SPOOL_DIR: dir2 }; expect((await runHook("post-tool-use.mjs", toolPayload("four-hundred"), env2)).exitCode).toBe(0); expect(spoolLines(dir2, port2)).toHaveLength(0); }); + it("spools when the HTTP worker answers 404 because the route is not registered", async () => { + const dir = mkdtempSync(join(tmpdir(), "am-hook-spool-")); + const port = await startServer(404, [], ""); + const env = { AGENTMEMORY_URL: `http://127.0.0.1:${port}`, AGENTMEMORY_CAPTURE_SPOOL_DIR: dir }; + expect((await runHook("post-tool-use.mjs", toolPayload("no-route"), env)).exitCode).toBe(0); + expect(spoolLines(dir, port)).toHaveLength(1); + }); + it("does not spool when the spool is turned off", async () => { const dir = mkdtempSync(join(tmpdir(), "am-hook-spool-")); const port = await closedPort(); diff --git a/test/cli-doctor-fixes.test.ts b/test/cli-doctor-fixes.test.ts index 50b09dc268..f512d0cc8c 100644 --- a/test/cli-doctor-fixes.test.ts +++ b/test/cli-doctor-fixes.test.ts @@ -263,7 +263,26 @@ describe("doctor v2 diagnostic catalog", () => { it("keeps the agent-sdk label when the only key is reserved for embeddings", async () => { expect( await statusFor( - { OPENAI_API_KEY: "sk-real-openai-key", OPENAI_API_KEY_FOR_LLM: "false" }, + { OPENAI_API_KEY: "sk-real-openai-key", EMBEDDING_PROVIDER: "openai" }, + { AGENTMEMORY_ALLOW_AGENT_SDK: "true" }, + ), + ).toEqual({ ok: true, detail: "agent-sdk fallback, no API key" }); + }); + + it("refuses to pick agent-sdk over an unclaimed LLM key and names both choices", async () => { + const result = await statusFor( + { OPENAI_API_KEY: "sk-real-openai-key", OPENAI_BASE_URL: "https://api.deepseek.com" }, + { AGENTMEMORY_ALLOW_AGENT_SDK: "true" }, + ); + expect(result.ok).toBe(false); + expect(result.detail).toContain("AGENTMEMORY_LLM_PROVIDER=openai"); + expect(result.detail).toContain("AGENTMEMORY_LLM_PROVIDER=agent-sdk"); + }); + + it("uses agent-sdk when it is selected explicitly next to another key", async () => { + expect( + await statusFor( + { OPENAI_API_KEY: "sk-real-openai-key", AGENTMEMORY_LLM_PROVIDER: "agent-sdk" }, { AGENTMEMORY_ALLOW_AGENT_SDK: "true" }, ), ).toEqual({ ok: true, detail: "agent-sdk fallback, no API key" }); diff --git a/test/cli-engine-startup.test.ts b/test/cli-engine-startup.test.ts index fc552a7583..4479b585b0 100644 --- a/test/cli-engine-startup.test.ts +++ b/test/cli-engine-startup.test.ts @@ -142,12 +142,12 @@ describe("fresh native engine startup", () => { expect(windowsBranch).toBeLessThan(body.indexOf("p.select(")); }); - it("clears unready Compose state only for a PID positively identified as foreign", () => { + it("keeps unready Compose state only for a matching PID or an unknown PID from the current boot", () => { const reconcileStart = source.indexOf("async function reconcilePersistedComposeEngine"); const reconcileEnd = source.indexOf("async function main()", reconcileStart); const reconcileBody = source.slice(reconcileStart, reconcileEnd); expect(reconcileBody).toContain( - 'if (state.composePid && pidAlive(state.composePid) && composePidIdentity(state.composePid, state) !== "foreign")', + 'if (identity === "match" || (identity === "unknown" && !engineStateFromPreviousBoot()))', ); }); }); diff --git a/test/consolidation-pipeline.test.ts b/test/consolidation-pipeline.test.ts index 19b6af7ab6..62252bfeda 100644 --- a/test/consolidation-pipeline.test.ts +++ b/test/consolidation-pipeline.test.ts @@ -201,6 +201,33 @@ describe("Consolidation Pipeline", () => { expect(stored[0].confidence).toBe(0.9); }); + it("reinforces a restated semantic fact instead of storing a reworded copy", async () => { + const replies = [ + `Redis was chosen over Memcached for session storage because Redis persists to disk with RDB snapshots`, + `Decision recorded: Redis was chosen over Memcached for session storage because Redis persists to disk with RDB snapshots`, + "", + `Payments run through the billing queue`, + ]; + const provider = { name: "test", compress: vi.fn(), summarize: vi.fn(async () => replies.shift() ?? "") }; + registerConsolidationPipelineFunction(sdk as never, kv as never, provider as never); + for (let i = 0; i < 6; i++) await kv.set("mem:summaries", `ses_${i}`, makeSummary(i)); + + await sdk.trigger("mem::consolidate-pipeline", { tier: "semantic" }); + await sdk.trigger("mem::consolidate-pipeline", { tier: "semantic" }); + const [first] = await kv.list("mem:semantic"); + replies[0] = `Decision recorded in notes.md: use Redis over Memcached for sessions`; + await sdk.trigger("mem::consolidate-pipeline", { tier: "semantic" }); + + const stored = await kv.list("mem:semantic"); + expect(stored).toHaveLength(1); + expect(stored[0].accessCount).toBe(3); + expect(stored[0].confidence).toBe(0.95); + expect(provider.summarize.mock.calls[2][1]).toContain(`[${first.id}] Redis was chosen over Memcached`); + + await sdk.trigger("mem::consolidate-pipeline", { tier: "semantic" }); + expect(await kv.list("mem:semantic")).toHaveLength(2); + }); + it("with enough patterns, creates procedural memories from provider response", async () => { const provider = { name: "test", diff --git a/test/directory-review-privacy.test.ts b/test/directory-review-privacy.test.ts index 011d223344..7689082165 100644 --- a/test/directory-review-privacy.test.ts +++ b/test/directory-review-privacy.test.ts @@ -47,7 +47,18 @@ describe("LLM provider opt-in", () => { }); it("gives no opt-in hint while the agent-sdk route is active", () => { - expect(llmOptInHint({ AGENTMEMORY_ALLOW_AGENT_SDK: "true", ANTHROPIC_API_KEY: "k" })).toBeNull(); + expect(llmOptInHint({ AGENTMEMORY_ALLOW_AGENT_SDK: "true" })).toBeNull(); + expect(llmOptInHint({ AGENTMEMORY_ALLOW_AGENT_SDK: "true", AGENTMEMORY_LLM_PROVIDER: "agent-sdk", ANTHROPIC_API_KEY: "k" })).toBeNull(); + }); + + it("does not let the agent-sdk fallback win over an unselected provider key", () => { + const env = { AGENTMEMORY_ALLOW_AGENT_SDK: "true", OPENAI_API_KEY: "sk-real-openai-key" }; + expect(detectLlmProviderKind(env)).toBe("noop"); + expect(llmOptInHint(env)).toContain("AGENTMEMORY_LLM_PROVIDER=openai"); + expect(detectLlmProviderKind({ ...env, AGENTMEMORY_LLM_PROVIDER: "openai" })).toBe("llm"); + expect(detectLlmProviderKind({ ...env, AGENTMEMORY_LLM_PROVIDER: "agent-sdk" })).toBe("llm"); + expect(detectLlmProviderKind({ AGENTMEMORY_LLM_PROVIDER: "agent-sdk" })).toBe("noop"); + expect(detectLlmProviderKind({ ...env, EMBEDDING_PROVIDER: "openai" })).toBe("llm"); }); it("points the hints at the env file the daemon reads", () => { diff --git a/test/dsh-plugin.test.ts b/test/dsh-plugin.test.ts index d548b7a7e3..d4fc19b249 100644 --- a/test/dsh-plugin.test.ts +++ b/test/dsh-plugin.test.ts @@ -235,14 +235,22 @@ describe("bundled DSH plugin", () => { expect(observations().slice(2)).toEqual(original); }); - it.each([400, 401, 403])("does not retry permanent HTTP %s failures", async status => { - reply = async () => Response.json({}, { status }); + it.each([400, 422])("does not retry an agentmemory rejection with HTTP %s", async status => { + reply = async () => Response.json({ status: "rejected", error: "invalid" }, { status }); const h = harness(); h.emit("user/message", 1, { content: "prompt" }); await h.stop(); expect(spoolSummary(url).records).toBe(0); }); + it.each([401, 403, 404])("keeps the capture for a later retry on HTTP %s", async status => { + reply = async () => Response.json({}, { status }); + const h = harness(); + h.emit("user/message", 1, { content: "prompt" }); + await h.stop(); + expect(spoolSummary(url).records).toBeGreaterThan(0); + }); + it("bounds shutdown even when the daemon hangs with queued observations", async () => { reply = (_path, _body, signal) => new Promise((_resolve, reject) => { if (signal.aborted) reject(signal.reason); diff --git a/test/omp-capture.test.ts b/test/omp-capture.test.ts index fe1dadf127..a67095c12f 100644 --- a/test/omp-capture.test.ts +++ b/test/omp-capture.test.ts @@ -21,11 +21,22 @@ describe("OMP capture recovery", () => { expect(send).toHaveBeenCalledWith(body); expect(online.status().records).toBe(0); }); - it.each([400, 401, 403])("does not endlessly retry a rejected capture (%i)", async status => { - const capture = createCapture(url, async () => ({ status, body: null })); + it.each([400, 422])("does not retry an agentmemory rejection (%i)", async status => { + const capture = createCapture(url, async () => ({ status, body: { status: "rejected", error: "invalid" } })); capture.enqueue(body); await capture.flush(); capture.stop(); expect(capture.status().records).toBe(0); expect(capture.status().error).toContain("rejected"); }); + it.each([401, 403, 404])("keeps a capture the server did not reject itself (%i) and replays it one request at a time", async status => { + const send = vi.fn(async () => ({ status, body: null })); + const capture = createCapture(url, send); + capture.enqueue(body); await capture.flush(); + capture.enqueue({ ...body, eventId: "event-34567890" }); await capture.flush(); + expect(capture.status().records).toBe(2); + send.mockClear(); + await capture.replay(); capture.stop(); + expect(send).toHaveBeenCalledTimes(1); + expect(capture.status().records).toBe(2); + }); it("bounds replay of slow successful requests and leaves the remaining events queued", async () => { for (let i = 0; i < 10; i++) appendSpool(url, `event-${i}`, { ...body, eventId: `event-${i}` }, "offline"); let now = Date.now(); diff --git a/test/skills-rest-endpoints.test.ts b/test/skills-rest-endpoints.test.ts index 20967cd982..f0fe3dbb2f 100644 --- a/test/skills-rest-endpoints.test.ts +++ b/test/skills-rest-endpoints.test.ts @@ -15,7 +15,7 @@ describe("generated REST endpoint methods", () => { it("documents HTTP routes from every trigger module", () => { const rows = collectRestEndpointsInDirectory(fileURLToPath(new URL("../src/triggers", import.meta.url))); - expect(rows).toHaveLength(147); + expect(rows).toHaveLength(148); expect(rows).toEqual(expect.arrayContaining([ { path: "/agentmemory/viewer/events", method: "GET" }, { path: "/agentmemory/viewer/snapshot", method: "GET" }, diff --git a/test/status.test.ts b/test/status.test.ts index b5e58ab104..f98d27074d 100644 --- a/test/status.test.ts +++ b/test/status.test.ts @@ -97,6 +97,16 @@ describe("evaluateStatus", () => { expect(failing[0].fix).toMatch(/LLM provider/); }); + it("judges failures by the recent window so a fixed provider clears the warning", () => { + const stale = { functionId: "mem::summarize", totalCalls: 25, successCount: 10, failureCount: 15, avgLatencyMs: 900 }; + const recovered = evaluateStatus(inputs({ functionMetrics: [{ ...stale, recent: "0111111111" }] })); + expect(recovered.problems.filter((p) => p.code === "function-failing")).toHaveLength(0); + const failing = evaluateStatus(inputs({ functionMetrics: [{ ...stale, recent: "1111100000" }] })); + const [problem] = failing.problems.filter((p) => p.code === "function-failing"); + expect(problem.message).toBe("mem::summarize failed 5 of the last 10 calls (50%)."); + expect(problem.fix).toContain("/agentmemory/metrics/reset"); + }); + it("escalates to error when the provider circuit breaker is open or health is critical", () => { expect(evaluateStatus(inputs({ circuitBreaker: { state: "open", failures: 5 } })).status).toBe("error"); expect(codes(evaluateStatus(inputs({ circuitBreaker: { state: "open", failures: 5 } })))).toContain( diff --git a/test/user-reported-0934.test.ts b/test/user-reported-0934.test.ts new file mode 100644 index 0000000000..531274ae69 --- /dev/null +++ b/test/user-reported-0934.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "vitest"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { parse } from "yaml"; +import { appendSpool, drainSpool, sendOutcome, spoolDir, spoolSummary } from "../src/capture/spool.js"; +import { resolveDataDir } from "../src/cli-data-dir.js"; +import { BOOT_TOLERANCE_MS, writtenBeforeBoot } from "../src/cli/compose-process.js"; +import { renderWorkerCompose } from "../src/cli/compose-project.js"; +import { MetricsStore, RECENT_WINDOW } from "../src/eval/metrics-store.js"; +import { KV } from "../src/state/schema.js"; +import { mockKV } from "./helpers/mocks.js"; + +const URL = "http://localhost:4977"; + +function record(id: string) { + return { hookType: "post_tool_use", sessionId: "ses_1", project: "p", cwd: "/w", timestamp: new Date().toISOString(), data: { id } }; +} + +describe("capture send classification", () => { + it("drops only agentmemory's own permanent rejection", () => { + expect(sendOutcome(201, { status: "accepted" })).toBe("delivered"); + expect(sendOutcome(200, "")).toBe("duplicate"); + expect(sendOutcome(202, { status: "duplicate" })).toBe("duplicate"); + expect(sendOutcome(422, { status: "rejected", error: "invalid" })).toBe("rejected"); + expect(sendOutcome(400, JSON.stringify({ status: "rejected" }))).toBe("rejected"); + expect(sendOutcome(413, "")).toBe("rejected"); + expect(sendOutcome(422, { status: "rejected", retryable: true })).toBe("retry"); + expect(sendOutcome(400, "bad gateway")).toBe("retry"); + for (const status of [0, 401, 403, 404, 408, 429, 500, 503]) expect(sendOutcome(status, "")).toBe("retry"); + }); + + it("keeps spooled records when the drain gets 404 from an unregistered route", async () => { + const dir = mkdtempSync(join(tmpdir(), "am-404-drain-")); + for (const id of ["evt-00000001", "evt-00000002", "evt-00000003"]) appendSpool(URL, id, record(id), "unreachable", { dir }); + const result = await drainSpool(URL, async () => sendOutcome(404, ""), { dir }); + expect(result.rejected).toBe(0); + expect(spoolSummary(URL, { dir }).records).toBe(3); + }); +}); + +describe("capture spool folder", () => { + it("does not adopt a legacy data folder in the hook's working directory", () => { + const project = mkdtempSync(join(tmpdir(), "am-project-")); + mkdirSync(join(project, "data")); + writeFileSync(join(project, "data", "state_store.db"), ""); + const home = mkdtempSync(join(tmpdir(), "am-home-")); + const env = { HOME: home, XDG_DATA_HOME: join(home, "xdg") }; + expect(resolveDataDir({ args: [], env, cwd: project, home, platform: "linux" }).dataDir).toBe(join(project, "data")); + const cwd = process.cwd(); + process.chdir(project); + try { + expect(spoolDir(env)).not.toContain(join(project, "data")); + } finally { + process.chdir(cwd); + } + }); +}); + +describe("Worker Compose environment", () => { + const base = { + ports: { restPort: 3511, viewerPort: 3513, enginePort: 49534 }, + dataDir: "/srv/am/data", + projectRoot: "/srv/am/pkg", + nodeBin: "/opt/node/bin/node", + homeDir: "/home/u", + startupTimeoutMs: 300_000, + linux: true, + }; + + it("passes the data root the hooks resolve their default spool from", () => { + const linux = parse(renderWorkerCompose({ ...base, workerEnvironment: { XDG_DATA_HOME: "/home/u/.data" } })); + expect(linux.containers.agentmemory.environment.XDG_DATA_HOME).toBe("/home/u/.data"); + const windows = parse(renderWorkerCompose({ ...base, windows: true, nodeBin: "C:\\node\\node.exe", workerEnvironment: { APPDATA: "C:\\Users\\u\\AppData\\Roaming", PATH: "C:\\node" } })); + expect(windows.containers.agentmemory.environment.APPDATA).toBe("C:\\Users\\u\\AppData\\Roaming"); + const unset = parse(renderWorkerCompose({ ...base, workerEnvironment: {} })); + expect(unset.containers.agentmemory.environment.XDG_DATA_HOME).toBeUndefined(); + }); +}); + +describe("Compose state from an earlier boot", () => { + it("treats state written before the current boot as stale", () => { + const now = Date.parse("2026-11-18T10:00:00Z"); + const uptimeSeconds = 3600; + const bootAt = now - uptimeSeconds * 1000; + expect(writtenBeforeBoot(bootAt - BOOT_TOLERANCE_MS - 1, now, uptimeSeconds)).toBe(true); + expect(writtenBeforeBoot(bootAt + 1000, now, uptimeSeconds)).toBe(false); + expect(writtenBeforeBoot(bootAt - 1000, now, uptimeSeconds)).toBe(false); + expect(writtenBeforeBoot(Number.NaN, now, uptimeSeconds)).toBe(false); + expect(writtenBeforeBoot(0, now, 0)).toBe(false); + }); +}); + +describe("function metrics", () => { + it("keeps a bounded recent window and resets on request", async () => { + const kv = mockKV(); + const store = new MetricsStore(kv as never); + for (let i = 0; i < 30; i++) await store.record("mem::summarize", 10, i >= 25); + const metrics = await store.get("mem::summarize"); + expect(metrics?.totalCalls).toBe(30); + expect(metrics?.recent).toHaveLength(RECENT_WINDOW); + expect(metrics?.recent?.endsWith("0000011111")).toBe(true); + await store.record("mem::compress", 10, true); + expect(await store.reset("mem::summarize")).toEqual(["mem::summarize"]); + expect(await kv.get(KV.metrics, "mem::summarize")).toBeNull(); + expect(await store.get("mem::summarize")).toBeNull(); + expect((await store.reset()).sort()).toEqual(["mem::compress"]); + expect(await store.getAll()).toEqual([]); + }); +});