#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix: retention scoring (#119) + npx agentmemory-mcp 404 (#120), release 0.8.3 (#123)
Rohit Ghumare8a36fe7867cb
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex a8b2fb5c..782b1c2f 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -23,6 +23,53 @@ jobs:- run: npm run build- run: npm test- - run: npm publish --provenance --access public+ - name: Publish @agentmemory/agentmemory+ run: |+ if npm view "@agentmemory/agentmemory@$(node -p "require('./package.json').version")" version >/dev/null 2>&1; then+ echo "Version already published, skipping"+ else+ npm publish --provenance --access public+ fienv:NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}++ - name: Wait for npm registry propagation+ run: |+ VERSION=$(node -p "require('./package.json').version")+ for i in $(seq 1 24); do+ if npm view "@agentmemory/agentmemory@$VERSION" version >/dev/null 2>&1; then+ echo "Registry propagated after ${i} attempt(s)"+ exit 0+ fi+ echo "Attempt $i: not yet available, sleeping 5s..."+ sleep 5+ done+ echo "ERROR: registry never propagated after 2 minutes" >&2+ exit 1++ - name: Publish agentmemory-mcp shim+ working-directory: packages/agentmemory-mcp+ run: |+ SHIM_VERSION=$(node -p "require('./package.json').version")+ if npm view "agentmemory-mcp@$SHIM_VERSION" version >/dev/null 2>&1; then+ echo "Shim version already published, skipping"+ else+ npm publish --provenance --access public+ fi+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}++ - name: Wait for agentmemory-mcp registry propagation+ working-directory: packages/agentmemory-mcp+ run: |+ SHIM_VERSION=$(node -p "require('./package.json').version")+ for i in $(seq 1 24); do+ if npm view "agentmemory-mcp@$SHIM_VERSION" version >/dev/null 2>&1; then+ echo "Shim propagated after ${i} attempt(s)"+ exit 0+ fi+ echo "Attempt $i: not yet available, sleeping 5s..."+ sleep 5+ done+ echo "ERROR: shim never propagated after 2 minutes" >&2+ exit 1diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bcae7c90..6a3ae114 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,25 @@ All notable changes to agentmemory will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.8.3] — 2026-04-13++Two bug fixes reported in the public issue tracker.++### Fixed++- **Retention score now reflects real agent-side reads** ([#119](https://github.com/rohitg00/agentmemory/issues/119)) — `mem::retention-score` previously hardcoded `accessCount = 0` and `accessTimestamps = []` for episodic memories, and only used a single-sample `lastAccessedAt` for semantic memories. Reads from `mem::search`, `mem::smart-search`, `mem::context`, `mem::timeline`, `mem::file-context`, and the matching MCP tools (`memory_recall`, `memory_smart_search`, `memory_timeline`, `memory_file_history`) were never recorded, so the time-frequency decay formula was a dead path. The reinforcement boost is now driven by a real per-memory access log persisted at `mem:access`, written by every read endpoint (fire-and-forget, so reads never block on tracker writes), with a bounded ring buffer of the last 20 access timestamps. Pre-0.8.3 semantic memories that only have the legacy `lastAccessedAt` field still score correctly via a backwards-compat fallback.+- **`npx agentmemory-mcp` 404** ([#120](https://github.com/rohitg00/agentmemory/issues/120)) — the README told users to run `npx agentmemory-mcp` for MCP client setup, but `agentmemory-mcp` was only a `bin` entry inside `@agentmemory/agentmemory`, not a real package, so `npx` returned 404 from the npm registry. Two fixes:+ - Published a new sibling package `agentmemory-mcp` (in `packages/agentmemory-mcp/`) that is a thin shim over `@agentmemory/agentmemory/dist/standalone.mjs`. `npx agentmemory-mcp` now works as documented.+ - Added a canonical `npx @agentmemory/agentmemory mcp` subcommand to the main CLI for users who already have `@agentmemory/agentmemory` installed and don't want a second package on disk. Both commands do the same thing.+ - README install snippets now use `npx -y agentmemory-mcp` so first-time users skip the install confirmation prompt.++### Added++- **Concurrent access tracking is race-safe** — the access log RMW is wrapped in the existing `withKeyedLock` keyed mutex, so two parallel reads of the same memory don't lose increments. `recordAccessBatch` uses `Promise.allSettled` so a slow keyed-lock acquisition on one id doesn't block the rest of the batch.+- **`mem::export` / `mem::import` now round-trip the access log** — the new `mem:access` namespace is included in dumps and restored on import, so backup/restore cycles no longer silently zero out reinforcement signals.+- **`exports` field in `package.json`** — explicitly exposes `./dist/standalone.mjs` as a subpath so the shim package and external consumers have a stable contract.+- **CI publishes both packages on release** — `.github/workflows/publish.yml` now publishes `@agentmemory/agentmemory` first, then the `agentmemory-mcp` shim from `packages/agentmemory-mcp/` so `npx agentmemory-mcp` works on the live release.+## [0.8.2] — 2026-04-12This release ships 6 security fixes, growth features, and a visual redesign of the README. Users on v0.8.1 should upgrade as soon as possible — the security fixes address vulnerabilities in default deployments.@@ -66,6 +85,7 @@ See GitHub Security Advisories for CVSS scores and affected version ranges.---+[0.8.3]: https://github.com/rohitg00/agentmemory/compare/v0.8.2...v0.8.3[0.8.2]: https://github.com/rohitg00/agentmemory/compare/v0.8.1...v0.8.2[0.8.1]: https://github.com/rohitg00/agentmemory/compare/v0.8.0...v0.8.1[0.8.0]: https://github.com/rohitg00/agentmemory/releases/tag/v0.8.0diff --git a/README.md b/README.mdindex 27469e85..72b820da 100644--- a/README.md+++ b/README.md@@ -317,7 +317,7 @@ Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separa"mcpServers": {"agentmemory": {"command": "npx",- "args": ["agentmemory-mcp"]+ "args": ["-y", "agentmemory-mcp"]}}}@@ -338,7 +338,7 @@ Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separatemcp_servers:agentmemory:command: npx- args: ["agentmemory-mcp"]+ args: ["-y", "agentmemory-mcp"]Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper 6-hook memory provider integration (pre-LLM context injection, turn capture, MEMORY.md mirroring, system prompt block), copy integrations/hermes from the agentmemory repo to ~/.hermes/plugins/memory/agentmemory.```@@ -355,14 +355,14 @@ Then add the MCP config for your agent:| Agent | Setup ||---|---|-| **Cursor** | Add to `~/.cursor/mcp.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["agentmemory-mcp"]}}}` |-| **OpenClaw** | Add to MCP config: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["agentmemory-mcp"]}}}` or use the [gateway plugin](integrations/openclaw/) |-| **Gemini CLI** | `gemini mcp add agentmemory -- npx agentmemory-mcp` |-| **Codex CLI** | Add to `.codex/config.yaml`: `mcp_servers: {agentmemory: {command: npx, args: ["agentmemory-mcp"]}}` |-| **OpenCode** | Add to `.opencode/config.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["agentmemory-mcp"]}}}` |+| **Cursor** | Add to `~/.cursor/mcp.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "agentmemory-mcp"]}}}` |+| **OpenClaw** | Add to MCP config: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "agentmemory-mcp"]}}}` or use the [gateway plugin](integrations/openclaw/) |+| **Gemini CLI** | `gemini mcp add agentmemory -- npx -y agentmemory-mcp` |+| **Codex CLI** | Add to `.codex/config.yaml`: `mcp_servers: {agentmemory: {command: npx, args: ["-y", "agentmemory-mcp"]}}` |+| **OpenCode** | Add to `.opencode/config.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "agentmemory-mcp"]}}}` || **Hermes Agent** | Add to `~/.hermes/config.yaml` or use the [memory provider plugin](integrations/hermes/) || **Cline / Goose / Kilo Code** | Add MCP server in settings |-| **Claude Desktop** | Add to `claude_desktop_config.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["agentmemory-mcp"]}}}` |+| **Claude Desktop** | Add to `claude_desktop_config.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "agentmemory-mcp"]}}}` || **Aider** | REST API: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'` || **Any agent (32+)** | `npx skillkit install agentmemory` |@@ -586,10 +586,11 @@ npm install @xenova/transformers### Standalone MCP-Run without the full server — for any MCP client:+Run without the full server — for any MCP client. Either of these works:```bash-npx agentmemory-mcp+npx -y @agentmemory/agentmemory mcp # canonical (always available)+npx -y agentmemory-mcp # shim package alias```Or add to your agent's MCP config:@@ -599,7 +600,7 @@ Or add to your agent's MCP config:"mcpServers": {"agentmemory": {"command": "npx",- "args": ["agentmemory-mcp"]+ "args": ["-y", "agentmemory-mcp"]}}}diff --git a/integrations/hermes/README.md b/integrations/hermes/README.mdindex dcec3646..fa7b658d 100644--- a/integrations/hermes/README.md+++ b/integrations/hermes/README.md@@ -35,7 +35,7 @@ an MCP server with all 43 memory tools:mcp_servers:agentmemory:command: npx- args: ["agentmemory-mcp"]+ args: ["-y", "agentmemory-mcp"]Verify it's working with`curl http://localhost:3111/agentmemory/health` — it should return@@ -61,7 +61,7 @@ Add to `~/.hermes/config.yaml`:mcp_servers:agentmemory:command: npx- args: ["agentmemory-mcp"]+ args: ["-y", "agentmemory-mcp"]```This gives Hermes access to all 43 MCP tools. Start the server separately:diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.mdindex 83947af7..e3958ed1 100644--- a/integrations/openclaw/README.md+++ b/integrations/openclaw/README.md@@ -37,7 +37,7 @@ memory_smart_search, memory_timeline, memory_profile, etc.):"mcpServers": {"agentmemory": {"command": "npx",- "args": ["agentmemory-mcp"]+ "args": ["-y", "agentmemory-mcp"]}}}@@ -81,7 +81,7 @@ Then add to your OpenClaw MCP config:"mcpServers": {"agentmemory": {"command": "npx",- "args": ["agentmemory-mcp"]+ "args": ["-y", "agentmemory-mcp"]}}}diff --git a/package-lock.json b/package-lock.jsonindex fd461afb..4fd11630 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@agentmemory/agentmemory",- "version": "0.8.2",+ "version": "0.8.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@agentmemory/agentmemory",- "version": "0.8.2",+ "version": "0.8.3","license": "Apache-2.0","dependencies": {"@anthropic-ai/claude-agent-sdk": "^0.2.56",diff --git a/package.json b/package.jsonindex 48dbb0b4..cae9252c 100644--- a/package.json+++ b/package.json@@ -1,13 +1,20 @@{"name": "@agentmemory/agentmemory",- "version": "0.8.2",+ "version": "0.8.3","description": "Persistent memory for AI coding agents, powered by iii-engine's three primitives","type": "module","main": "dist/index.mjs","types": "dist/index.d.mts",+ "exports": {+ ".": {+ "types": "./dist/index.d.mts",+ "import": "./dist/index.mjs"+ },+ "./dist/standalone.mjs": "./dist/standalone.mjs",+ "./package.json": "./package.json"+ },"bin": {- "agentmemory": "dist/cli.mjs",- "agentmemory-mcp": "dist/standalone.mjs"+ "agentmemory": "dist/cli.mjs"},"scripts": {"build": "tsdown && (cp iii-config.yaml dist/ 2>/dev/null || true) && (cp iii-config.docker.yaml dist/ 2>/dev/null || true) && (cp docker-compose.yml dist/ 2>/dev/null || true) && mkdir -p dist/viewer && cp src/viewer/index.html dist/viewer/",diff --git a/packages/agentmemory-mcp/LICENSE b/packages/agentmemory-mcp/LICENSEnew file mode 100644index 00000000..cb13c728--- /dev/null+++ b/packages/agentmemory-mcp/LICENSE@@ -0,0 +1,190 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to the Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by the Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding any notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ Copyright 2026 Rohit Ghumare++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/agentmemory-mcp/README.md b/packages/agentmemory-mcp/README.mdnew file mode 100644index 00000000..d40e7328--- /dev/null+++ b/packages/agentmemory-mcp/README.md@@ -0,0 +1,51 @@+# agentmemory-mcp++Standalone MCP server for [agentmemory](https://github.com/rohitg00/agentmemory).++This is a thin shim package that re-exposes the standalone MCP entrypoint from+[`@agentmemory/agentmemory`](https://www.npmjs.com/package/@agentmemory/agentmemory),+so MCP client configs that say `npx agentmemory-mcp` work out of the box.++## Usage++```bash+npx agentmemory-mcp+```++Or wire it into your MCP client (Claude Desktop, OpenClaw, Cursor, Codex, etc.):++```json+{+ "mcpServers": {+ "agentmemory": {+ "command": "npx",+ "args": ["-y", "agentmemory-mcp"]+ }+ }+}+```++This package depends on `@agentmemory/agentmemory` and forwards to its+`dist/standalone.mjs` entrypoint. If you already have `@agentmemory/agentmemory`+installed, you can call the same entrypoint directly:++```bash+npx @agentmemory/agentmemory mcp+```++Both commands do the same thing.++## Why does this package exist?++The README for `@agentmemory/agentmemory` documented `npx agentmemory-mcp`+because the package exposes a `bin` of that name. But `npx <name>` resolves+`<name>` against the npm registry, not against installed binaries, so users got+a 404. This shim publishes a real `agentmemory-mcp` package whose only job is+to forward to the canonical entrypoint.++See [issue #120](https://github.com/rohitg00/agentmemory/issues/120) for the+full story.++## License++Apache-2.0diff --git a/packages/agentmemory-mcp/bin.mjs b/packages/agentmemory-mcp/bin.mjsnew file mode 100755index 00000000..8b02e9f3--- /dev/null+++ b/packages/agentmemory-mcp/bin.mjs@@ -0,0 +1,11 @@+#!/usr/bin/env node+import("@agentmemory/agentmemory/dist/standalone.mjs").catch((err) => {+ console.error(+ "[agentmemory-mcp] Failed to load standalone entrypoint from @agentmemory/agentmemory.",+ );+ console.error(+ "[agentmemory-mcp] Try installing manually: npm i -g @agentmemory/agentmemory",+ );+ console.error(err instanceof Error ? err.stack || err.message : String(err));+ process.exit(1);+});diff --git a/packages/agentmemory-mcp/package.json b/packages/agentmemory-mcp/package.jsonnew file mode 100644index 00000000..ef479802--- /dev/null+++ b/packages/agentmemory-mcp/package.json@@ -0,0 +1,40 @@+{+ "name": "agentmemory-mcp",+ "version": "0.8.3",+ "description": "Standalone MCP server for agentmemory — thin shim that re-exposes @agentmemory/agentmemory's MCP entrypoint",+ "type": "module",+ "bin": {+ "agentmemory-mcp": "./bin.mjs"+ },+ "files": [+ "bin.mjs",+ "README.md",+ "LICENSE"+ ],+ "keywords": [+ "ai",+ "agent",+ "memory",+ "mcp",+ "agentmemory"+ ],+ "author": "Rohit Ghumare <[email protected]>",+ "license": "Apache-2.0",+ "repository": {+ "type": "git",+ "url": "https://github.com/rohitg00/agentmemory",+ "directory": "packages/agentmemory-mcp"+ },+ "homepage": "https://github.com/rohitg00/agentmemory#readme",+ "bugs": "https://github.com/rohitg00/agentmemory/issues",+ "dependencies": {+ "@agentmemory/agentmemory": "~0.8.3"+ },+ "publishConfig": {+ "access": "public",+ "provenance": true+ },+ "engines": {+ "node": ">=20.0.0"+ }+}diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.jsonindex 86da1a13..cba4019e 100644--- a/plugin/.claude-plugin/plugin.json+++ b/plugin/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "agentmemory",- "version": "0.8.2",+ "version": "0.8.3","description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 43 MCP tools, 4 skills, real-time viewer.","author": {"name": "Rohit Ghumare",diff --git a/src/cli.ts b/src/cli.tsindex 807f9668..48de10ed 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -20,6 +20,7 @@ Commands:(default) Start agentmemory workerstatus Show connection status, memory count, and healthdemo Seed sample sessions and show recall in action+ mcp Start standalone MCP server (no engine required)Options:--help, -h Show this help@@ -31,7 +32,8 @@ Quick start:npx @agentmemory/agentmemory # start with local iii-engine or Dockernpx @agentmemory/agentmemory status # check healthnpx @agentmemory/agentmemory demo # try it in 30 seconds (needs server running)- npx agentmemory-mcp # standalone MCP server (no engine)+ npx @agentmemory/agentmemory mcp # standalone MCP server (no engine)+ npx agentmemory-mcp # same as above (shim package)`);process.exit(0);}@@ -506,9 +508,14 @@ async function runDemo() {p.log.success("agentmemory is working. Point your agent at it and get back to coding.");}+async function runMcp(): Promise<void> {+ await import("./mcp/standalone.js");+}+const commands: Record<string, () => Promise<void>> = {status: runStatus,demo: runDemo,+ mcp: runMcp,};const handler = commands[args[0] ?? ""] ?? main;diff --git a/src/functions/access-tracker.ts b/src/functions/access-tracker.tsnew file mode 100644index 00000000..f7cf8dda--- /dev/null+++ b/src/functions/access-tracker.ts@@ -0,0 +1,105 @@+import { getContext } from "iii-sdk";+import { KV } from "../state/schema.js";+import type { StateKV } from "../state/kv.js";+import { withKeyedLock } from "../state/keyed-mutex.js";++const RECENT_CAP = 20;++export interface AccessLog {+ memoryId: string;+ count: number;+ lastAt: string;+ recent: number[];+}++export function emptyAccessLog(memoryId: string): AccessLog {+ return { memoryId, count: 0, lastAt: "", recent: [] };+}++export function normalizeAccessLog(raw: unknown): AccessLog {+ const r = (raw ?? {}) as Partial<AccessLog>;+ const rawCount =+ typeof r.count === "number" && Number.isFinite(r.count) ? r.count : 0;+ const count = Math.max(0, Math.floor(rawCount));+ const rawRecent = Array.isArray(r.recent)+ ? r.recent.filter(+ (x): x is number => typeof x === "number" && Number.isFinite(x),+ )+ : [];+ const recent =+ rawRecent.length > RECENT_CAP ? rawRecent.slice(-RECENT_CAP) : rawRecent;+ return {+ memoryId: typeof r.memoryId === "string" ? r.memoryId : "",+ count: Math.max(count, recent.length),+ lastAt: typeof r.lastAt === "string" ? r.lastAt : "",+ recent,+ };+}++export async function getAccessLog(+ kv: StateKV,+ memoryId: string,+): Promise<AccessLog> {+ try {+ const raw = await kv.get<AccessLog>(KV.accessLog, memoryId);+ if (!raw) return emptyAccessLog(memoryId);+ const normalized = normalizeAccessLog(raw);+ if (!normalized.memoryId) normalized.memoryId = memoryId;+ return normalized;+ } catch {+ return emptyAccessLog(memoryId);+ }+}++export async function recordAccess(+ kv: StateKV,+ memoryId: string,+ timestampMs?: number,+): Promise<void> {+ if (!memoryId) return;+ const ts = timestampMs ?? Date.now();+ try {+ await withKeyedLock(`mem:access:${memoryId}`, async () => {+ const existing = await getAccessLog(kv, memoryId);+ existing.count += 1;+ existing.lastAt = new Date(ts).toISOString();+ existing.recent.push(ts);+ if (existing.recent.length > RECENT_CAP) {+ existing.recent = existing.recent.slice(-RECENT_CAP);+ }+ await kv.set(KV.accessLog, memoryId, existing);+ });+ } catch (err) {+ try {+ const ctx = getContext();+ ctx.logger.warn("recordAccess failed", {+ memoryId,+ error: err instanceof Error ? err.message : String(err),+ });+ } catch {}+ }+}++export async function recordAccessBatch(+ kv: StateKV,+ memoryIds: string[],+ timestampMs?: number,+): Promise<void> {+ if (!memoryIds || memoryIds.length === 0) return;+ const ts = timestampMs ?? Date.now();+ const unique = Array.from(new Set(memoryIds.filter(Boolean)));+ await Promise.allSettled(unique.map((id) => recordAccess(kv, id, ts)));+}++export async function deleteAccessLog(+ kv: StateKV,+ memoryId: string,+): Promise<void> {+ if (!memoryId) return;+ try {+ await withKeyedLock(`mem:access:${memoryId}`, async () => {+ await kv.delete(KV.accessLog, memoryId);+ });+ } catch {}+}+diff --git a/src/functions/auto-forget.ts b/src/functions/auto-forget.tsindex ed33f823..a4009ca9 100644--- a/src/functions/auto-forget.ts+++ b/src/functions/auto-forget.ts@@ -3,6 +3,7 @@ import { getContext } from "iii-sdk";import type { Memory, CompressedObservation, Session } from "../types.js";import { KV, jaccardSimilarity } from "../state/schema.js";import { StateKV } from "../state/kv.js";+import { deleteAccessLog } from "./access-tracker.js";const MS_PER_DAY = 24 * 60 * 60 * 1000;const CONTRADICTION_THRESHOLD = 0.9;@@ -47,6 +48,7 @@ export function registerAutoForgetFunction(sdk: ISdk, kv: StateKV): void {deletedIds.add(mem.id);if (!dryRun) {await kv.delete(KV.memories, mem.id);+ await deleteAccessLog(kv, mem.id);}}}diff --git a/src/functions/context.ts b/src/functions/context.tsindex 804f1577..19063a76 100644--- a/src/functions/context.ts+++ b/src/functions/context.ts@@ -9,6 +9,7 @@ import type {} from "../types.js";import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";+import { recordAccessBatch } from "./access-tracker.js";function estimateTokens(text: string): number {return Math.ceil(text.length / 3);@@ -124,9 +125,10 @@ export function registerContextFunction();if (important.length > 0) {- const items = important+ const top = important.sort((a, b) => b.importance - a.importance)- .slice(0, 5)+ .slice(0, 5);+ const items = top.map((o) => `- [${o.type}] ${o.title}: ${o.narrative}`).join("\n");const content = `## Session ${sessions[i].id.slice(0, 8)} (${sessions[i].startedAt})\n${items}`;@@ -135,6 +137,7 @@ export function registerContextFunction(content,tokens: estimateTokens(content),recency: new Date(sessions[i].startedAt).getTime(),+ sourceIds: top.map((o) => o.id),});}}@@ -143,6 +146,7 @@ export function registerContextFunction(let usedTokens = 0;const selected: string[] = [];+ const accessedIds: string[] = [];const header = `<agentmemory-context project="${escapeXmlAttr(data.project)}">`;const footer = `</agentmemory-context>`;usedTokens += estimateTokens(header) + estimateTokens(footer);@@ -151,6 +155,13 @@ export function registerContextFunction(if (usedTokens + block.tokens > budget) break;selected.push(block.content);usedTokens += block.tokens;+ if (block.sourceIds && block.sourceIds.length > 0) {+ accessedIds.push(...block.sourceIds);+ }+ }++ if (accessedIds.length > 0) {+ void recordAccessBatch(kv, accessedIds);}if (selected.length === 0) {diff --git a/src/functions/evict.ts b/src/functions/evict.tsindex 905a6a55..c50ac353 100644--- a/src/functions/evict.ts+++ b/src/functions/evict.ts@@ -8,6 +8,7 @@ import type {} from "../types.js";import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";+import { deleteAccessLog } from "./access-tracker.js";interface EvictionConfig {staleSessionDays: number;@@ -137,6 +138,7 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {evictedMemIds.add(mem.id);if (!dryRun) {await kv.delete(KV.memories, mem.id).catch(() => {});+ await deleteAccessLog(kv, mem.id);}}}@@ -151,6 +153,7 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {stats.nonLatestMemories++;if (!dryRun) {await kv.delete(KV.memories, mem.id).catch(() => {});+ await deleteAccessLog(kv, mem.id);}}}diff --git a/src/functions/export-import.ts b/src/functions/export-import.tsindex bfc7c90a..3960bfa8 100644--- a/src/functions/export-import.ts+++ b/src/functions/export-import.ts@@ -23,7 +23,9 @@ import type {Lesson,Insight,ExportPagination,+ AccessLogExport,} from "../types.js";+import { normalizeAccessLog } from "./access-tracker.js";import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";import { VERSION } from "../version.js";@@ -87,6 +89,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {routines,signals,checkpoints,+ accessLogs,] = await Promise.all([kv.list<GraphNode>(KV.graphNodes).catch(() => []),kv.list<GraphEdge>(KV.graphEdges).catch(() => []),@@ -103,6 +106,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {kv.list<Routine>(KV.routines).catch(() => []),kv.list<Signal>(KV.signals).catch(() => []),kv.list<Checkpoint>(KV.checkpoints).catch(() => []),+ kv.list<AccessLogExport>(KV.accessLog).catch(() => []),]);const exportData: ExportData = {@@ -130,6 +134,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {routines: routines.length > 0 ? routines : undefined,signals: signals.length > 0 ? signals : undefined,checkpoints: checkpoints.length > 0 ? checkpoints : undefined,+ accessLogs: accessLogs.length > 0 ? accessLogs : undefined,};if (maxSessions !== undefined) {@@ -170,7 +175,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {const strategy = data.strategy || "merge";const importData = data.exportData;- const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2"]);+ const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3"]);if (!supportedVersions.has(importData.version)) {return {success: false,@@ -183,6 +188,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {const MAX_SUMMARIES = 10_000;const MAX_OBS_PER_SESSION = 5_000;const MAX_TOTAL_OBSERVATIONS = 500_000;+ const MAX_ACCESS_LOGS = 50_000;if (!Array.isArray(importData.sessions)) {return { success: false, error: "sessions must be an array" };@@ -320,6 +326,9 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {for (const p of await kv.list<{ id: string }>(KV.procedural).catch(() => [])) {await kv.delete(KV.procedural, p.id);}+ for (const a of await kv.list<AccessLogExport>(KV.accessLog).catch(() => [])) {+ await kv.delete(KV.accessLog, a.memoryId);+ }}for (const session of importData.sessions) {@@ -516,6 +525,34 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {await kv.set(KV.insights, insight.id, insight);}}+ if (importData.accessLogs) {+ if (!Array.isArray(importData.accessLogs)) {+ return { success: false, error: "accessLogs must be an array" };+ }+ if (importData.accessLogs.length > MAX_ACCESS_LOGS) {+ return {+ success: false,+ error: `Too many access logs (max ${MAX_ACCESS_LOGS})`,+ };+ }+ const memoryIds = new Set<string>(+ importData.memories.map((m) => m.id),+ );+ for (const raw of importData.accessLogs) {+ const log = normalizeAccessLog(raw);+ if (!log.memoryId || !memoryIds.has(log.memoryId)) continue;+ if (strategy === "skip") {+ const existing = await kv+ .get(KV.accessLog, log.memoryId)+ .catch(() => null);+ if (existing) {+ stats.skipped++;+ continue;+ }+ }+ await kv.set(KV.accessLog, log.memoryId, log);+ }+ }ctx.logger.info("Import complete", { strategy, ...stats });return { success: true, strategy, ...stats };diff --git a/src/functions/file-index.ts b/src/functions/file-index.tsindex 00509406..7143ee9a 100644--- a/src/functions/file-index.ts+++ b/src/functions/file-index.ts@@ -3,6 +3,7 @@ import { getContext } from "iii-sdk";import type { CompressedObservation, Session } from "../types.js";import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";+import { recordAccessBatch } from "./access-tracker.js";interface FileHistory {file: string;@@ -95,6 +96,12 @@ export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void {}lines.push("</agentmemory-file-context>");+ const accessedIds: string[] = [];+ for (const fh of results) {+ for (const obs of fh.observations) accessedIds.push(obs.obsId);+ }+ void recordAccessBatch(kv, accessedIds);+const context = lines.join("\n");ctx.logger.info("File context generated", {files: data.files.length,diff --git a/src/functions/governance.ts b/src/functions/governance.tsindex f3b1673a..f6450741 100644--- a/src/functions/governance.ts+++ b/src/functions/governance.ts@@ -4,6 +4,7 @@ import type { Memory, GovernanceFilter, AuditEntry } from "../types.js";import { KV } from "../state/schema.js";import type { StateKV } from "../state/kv.js";import { recordAudit, queryAudit } from "./audit.js";+import { deleteAccessLog } from "./access-tracker.js";export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void {sdk.registerFunction(@@ -23,6 +24,7 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void {const mem = await kv.get<Memory>(KV.memories, id);if (mem) {await kv.delete(KV.memories, id);+ await deleteAccessLog(kv, id);deleted++;}}@@ -102,6 +104,7 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void {for (const mem of candidates) {await kv.delete(KV.memories, mem.id);+ await deleteAccessLog(kv, mem.id);}await recordAudit(diff --git a/src/functions/relations.ts b/src/functions/relations.tsindex d2958253..1ae5c25a 100644--- a/src/functions/relations.ts+++ b/src/functions/relations.ts@@ -4,6 +4,7 @@ import type { Memory, MemoryRelation } from "../types.js";import { KV, generateId } from "../state/schema.js";import { StateKV } from "../state/kv.js";import { withKeyedLock } from "../state/keyed-mutex.js";+import { recordAccessBatch } from "./access-tracker.js";function computeConfidence(source: Memory,@@ -227,6 +228,11 @@ export function registerRelationsFunction(sdk: ISdk, kv: StateKV): void {result.sort((a, b) => b.confidence - a.confidence);+ void recordAccessBatch(+ kv,+ result.map((r) => r.memory.id),+ );+ctx.logger.info("Related memories retrieved", {memoryId: data.memoryId,found: result.length,diff --git a/src/functions/remember.ts b/src/functions/remember.tsindex dced14e1..c6b9bf47 100644--- a/src/functions/remember.ts+++ b/src/functions/remember.ts@@ -4,6 +4,7 @@ import type { Memory } from "../types.js";import { KV, generateId, jaccardSimilarity } from "../state/schema.js";import { StateKV } from "../state/kv.js";import { withKeyedLock } from "../state/keyed-mutex.js";+import { deleteAccessLog } from "./access-tracker.js";export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {sdk.registerFunction(@@ -124,6 +125,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {if (data.memoryId) {await kv.delete(KV.memories, data.memoryId);+ await deleteAccessLog(kv, data.memoryId);deleted++;}diff --git a/src/functions/retention.ts b/src/functions/retention.tsindex 27753fdc..178fc584 100644--- a/src/functions/retention.ts+++ b/src/functions/retention.ts@@ -8,6 +8,12 @@ import type {} from "../types.js";import { KV } from "../state/schema.js";import type { StateKV } from "../state/kv.js";+import type { AccessLog } from "./access-tracker.js";+import {+ emptyAccessLog,+ deleteAccessLog,+ normalizeAccessLog,+} from "./access-tracker.js";const DEFAULT_DECAY: DecayConfig = {lambda: 0.01,@@ -19,27 +25,35 @@ const DEFAULT_DECAY: DecayConfig = {},};-function computeRetention(- salience: number,- createdAt: string,+function computeReinforcementBoost(accessTimestamps: number[],- config: DecayConfig,+ sigma: number,): number {const now = Date.now();- const deltaT = (now - new Date(createdAt).getTime()) / (1000 * 60 * 60 * 24);-- const temporalDecay = Math.exp(-config.lambda * deltaT);-- let reinforcementBoost = 0;+ let boost = 0;for (const tAccess of accessTimestamps) {- const daysSinceAccess =- (now - tAccess) / (1000 * 60 * 60 * 24);+ if (!Number.isFinite(tAccess)) continue;+ const daysSinceAccess = (now - tAccess) / (1000 * 60 * 60 * 24);if (daysSinceAccess > 0) {- reinforcementBoost += 1 / daysSinceAccess;+ boost += 1 / daysSinceAccess;}}- reinforcementBoost *= config.sigma;+ return boost * sigma;+}+function computeRetention(+ salience: number,+ createdAt: string,+ accessTimestamps: number[],+ config: DecayConfig,+): number {+ const deltaT =+ (Date.now() - new Date(createdAt).getTime()) / (1000 * 60 * 60 * 24);+ const temporalDecay = Math.exp(-config.lambda * deltaT);+ const reinforcementBoost = computeReinforcementBoost(+ accessTimestamps,+ config.sigma,+ );return Math.min(1, salience * temporalDecay + reinforcementBoost);}@@ -83,33 +97,48 @@ export function registerRetentionFunctions(const ctx = getContext();const config = { ...DEFAULT_DECAY, ...data.config };- const memories = await kv.list<Memory>(KV.memories);- const semanticMems = await kv.list<SemanticMemory>(KV.semantic);+ const [memories, semanticMems, allLogs] = await Promise.all([+ kv.list<Memory>(KV.memories),+ kv.list<SemanticMemory>(KV.semantic),+ kv.list<unknown>(KV.accessLog).catch(() => [] as unknown[]),+ ]);+ const logsById = new Map<string, AccessLog>();+ for (const raw of allLogs) {+ const log = normalizeAccessLog(raw);+ if (log.memoryId) logsById.set(log.memoryId, log);+ }const scores: RetentionScore[] = [];+ const computeDecay = (createdAt: string): number =>+ Math.exp(+ -config.lambda *+ ((Date.now() - new Date(createdAt).getTime()) /+ (1000 * 60 * 60 * 24)),+ );+for (const mem of memories) {if (!mem.isLatest) continue;- const salience = computeSalience(mem, 0);- const score = computeRetention(- salience,- mem.createdAt,- [],- config,+ const log = logsById.get(mem.id) ?? emptyAccessLog(mem.id);+ const salience = computeSalience(mem, log.count);+ const temporalDecay = computeDecay(mem.createdAt);+ const reinforcementBoost = computeReinforcementBoost(+ log.recent,+ config.sigma,+ );+ const score = Math.min(+ 1,+ salience * temporalDecay + reinforcementBoost,);const entry: RetentionScore = {memoryId: mem.id,score,salience,- temporalDecay: Math.exp(- -config.lambda *- ((Date.now() - new Date(mem.createdAt).getTime()) /- (1000 * 60 * 60 * 24)),- ),- reinforcementBoost: 0,- lastAccessed: mem.updatedAt,- accessCount: 0,+ temporalDecay,+ reinforcementBoost,+ lastAccessed: log.lastAt || mem.updatedAt,+ accessCount: log.count,};scores.push(entry);@@ -117,34 +146,42 @@ export function registerRetentionFunctions(}for (const sem of semanticMems) {- const accessTimestamps = sem.lastAccessedAt- ? [new Date(sem.lastAccessedAt).getTime()]- : [];- const salience = computeSalience(sem, sem.accessCount);- const score = computeRetention(- salience,- sem.createdAt,+ const log = logsById.get(sem.id) ?? emptyAccessLog(sem.id);++ // Pre-0.8.3 fallback: use sem.lastAccessedAt only when mem:access is empty.+ let accessTimestamps: number[];+ let effectiveCount: number;+ if (log.recent.length > 0 || log.count > 0) {+ accessTimestamps = log.recent;+ effectiveCount = log.count;+ } else if (sem.lastAccessedAt) {+ const legacyTs = Date.parse(sem.lastAccessedAt);+ accessTimestamps = Number.isFinite(legacyTs) ? [legacyTs] : [];+ effectiveCount = sem.accessCount;+ } else {+ accessTimestamps = [];+ effectiveCount = sem.accessCount;+ }++ const salience = computeSalience(sem, effectiveCount);+ const temporalDecay = computeDecay(sem.createdAt);+ const reinforcementBoost = computeReinforcementBoost(accessTimestamps,- config,+ config.sigma,+ );+ const score = Math.min(+ 1,+ salience * temporalDecay + reinforcementBoost,);const entry: RetentionScore = {memoryId: sem.id,score,salience,- temporalDecay: Math.exp(- -config.lambda *- ((Date.now() - new Date(sem.createdAt).getTime()) /- (1000 * 60 * 60 * 24)),- ),- reinforcementBoost:- score - salience * Math.exp(- -config.lambda *- ((Date.now() - new Date(sem.createdAt).getTime()) /- (1000 * 60 * 60 * 24)),- ),- lastAccessed: sem.lastAccessedAt,- accessCount: sem.accessCount,+ temporalDecay,+ reinforcementBoost,+ lastAccessed: log.lastAt || sem.lastAccessedAt,+ accessCount: effectiveCount,};scores.push(entry);@@ -218,6 +255,7 @@ export function registerRetentionFunctions(try {await kv.delete(KV.memories, candidate.memoryId);await kv.delete(KV.retentionScores, candidate.memoryId);+ await deleteAccessLog(kv, candidate.memoryId);evicted++;} catch {continue;diff --git a/src/functions/search.ts b/src/functions/search.tsindex 404d681d..298f829f 100644--- a/src/functions/search.ts+++ b/src/functions/search.ts@@ -4,6 +4,7 @@ import type { CompressedObservation, SearchResult, Session } from '../types.js'import { KV } from '../state/schema.js'import { StateKV } from '../state/kv.js'import { SearchIndex } from '../state/search-index.js'+import { recordAccessBatch } from './access-tracker.js'let index: SearchIndex | null = null@@ -125,6 +126,11 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {}}+ void recordAccessBatch(+ kv,+ enriched.map((r) => r.observation.id),+ )+// Avoid logging raw cwd/project (host paths). Log only that filters were active.ctx.logger.info('Search completed', {query,diff --git a/src/functions/smart-search.ts b/src/functions/smart-search.tsindex 5460c082..fb614db2 100644--- a/src/functions/smart-search.ts+++ b/src/functions/smart-search.ts@@ -7,6 +7,7 @@ import type {} from "../types.js";import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";+import { recordAccessBatch } from "./access-tracker.js";export function registerSmartSearchFunction(sdk: ISdk,@@ -53,6 +54,11 @@ export function registerSmartSearchFunction(if (r) expanded.push(r);}+ void recordAccessBatch(+ kv,+ expanded.map((e) => e.observation.id),+ );+const truncated = data.expandIds.length > raw.length;ctx.logger.info("Smart search expanded", {requested: data.expandIds.length,@@ -79,6 +85,11 @@ export function registerSmartSearchFunction(timestamp: r.observation.timestamp,}));+ void recordAccessBatch(+ kv,+ compact.map((r) => r.obsId),+ );+ctx.logger.info("Smart search compact", {query: data.query,results: compact.length,diff --git a/src/functions/snapshot.ts b/src/functions/snapshot.tsindex ba85bc70..cfd84f8f 100644--- a/src/functions/snapshot.ts+++ b/src/functions/snapshot.ts@@ -4,7 +4,13 @@ import { execFile } from "node:child_process";import { promisify } from "node:util";import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";import { join } from "node:path";-import type { SnapshotMeta, Session, Memory, GraphNode } from "../types.js";+import type {+ SnapshotMeta,+ Session,+ Memory,+ GraphNode,+ AccessLogExport,+} from "../types.js";import { KV, generateId } from "../state/schema.js";import type { StateKV } from "../state/kv.js";import { recordAudit } from "./audit.js";@@ -46,6 +52,9 @@ export function registerSnapshotFunction(const sessions = await kv.list<Session>(KV.sessions);const memories = await kv.list<Memory>(KV.memories);const graphNodes = await kv.list<GraphNode>(KV.graphNodes);+ const accessLogs = await kv+ .list<AccessLogExport>(KV.accessLog)+ .catch(() => [] as AccessLogExport[]);const observations: Record<string, unknown[]> = {};for (const session of sessions) {@@ -64,6 +73,7 @@ export function registerSnapshotFunction(memories,graphNodes,observations,+ accessLogs,};writeFileSync(@@ -171,6 +181,7 @@ export function registerSnapshotFunction(string,Array<{ id: string } & Record<string, unknown>>>;+ accessLogs?: AccessLogExport[];};if (state.sessions) {@@ -195,6 +206,11 @@ export function registerSnapshotFunction(}}}+ if (state.accessLogs) {+ for (const log of state.accessLogs) {+ await kv.set(KV.accessLog, log.memoryId, log);+ }+ }await gitExec(snapshotDir, ["checkout", "HEAD", "--", "state.json"]);diff --git a/src/functions/timeline.ts b/src/functions/timeline.tsindex b3f89902..0071155e 100644--- a/src/functions/timeline.ts+++ b/src/functions/timeline.ts@@ -7,6 +7,7 @@ import type {} from "../types.js";import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";+import { recordAccessBatch } from "./access-tracker.js";export function registerTimelineFunction(sdk: ISdk, kv: StateKV): void {sdk.registerFunction(@@ -95,6 +96,11 @@ export function registerTimelineFunction(sdk: ISdk, kv: StateKV): void {});}+ void recordAccessBatch(+ kv,+ entries.map((e) => e.observation.id),+ );+ctx.logger.info("Timeline retrieved", {anchor: data.anchor,entries: entries.length,diff --git a/src/functions/working-memory.ts b/src/functions/working-memory.tsindex fcb6b707..aa5fa170 100644--- a/src/functions/working-memory.ts+++ b/src/functions/working-memory.ts@@ -4,6 +4,7 @@ import type { Memory, CompressedObservation, ContextBlock } from "../types.js";import { KV, generateId } from "../state/schema.js";import { StateKV } from "../state/kv.js";import { recordAudit } from "./audit.js";+import { recordAccessBatch } from "./access-tracker.js";const CORE_SCOPE = "mem:core-memory";@@ -160,13 +161,17 @@ export function registerWorkingMemoryFunctions();});+ const archivalIds: string[] = [];for (const mem of active) {const tokens = estimateTokens(mem.content);if (usedTokens + tokens > budget) continue;archivalLines.push(`- [${mem.type}] ${mem.title}: ${mem.content}`);+ archivalIds.push(mem.id);usedTokens += tokens;}+ void recordAccessBatch(kv, archivalIds);+const pagedOut = active.length - archivalLines.length;const sections: string[] = [];diff --git a/src/state/schema.ts b/src/state/schema.tsindex 3571e010..a39077aa 100644--- a/src/state/schema.ts+++ b/src/state/schema.ts@@ -40,6 +40,7 @@ export const KV = {enrichedChunks: (sessionId: string) => `mem:enriched:${sessionId}`,latentEmbeddings: (obsId: string) => `mem:latent:${obsId}`,retentionScores: "mem:retention",+ accessLog: "mem:access",} as const;export const STREAM = {diff --git a/src/types.ts b/src/types.tsindex a364c2de..88dcdc16 100644--- a/src/types.ts+++ b/src/types.ts@@ -147,6 +147,7 @@ export interface ContextBlock {content: string;tokens: number;recency: number;+ sourceIds?: string[];}export interface EvalResult {@@ -251,7 +252,7 @@ export interface ExportPagination {}export interface ExportData {- version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2";+ version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2" | "0.8.3";exportedAt: string;sessions: Session[];observations: Record<string, CompressedObservation[]>;@@ -273,9 +274,17 @@ export interface ExportData {facets?: Facet[];lessons?: Lesson[];insights?: Insight[];+ accessLogs?: AccessLogExport[];pagination?: ExportPagination;}+export interface AccessLogExport {+ memoryId: string;+ count: number;+ lastAt: string;+ recent: number[];+}+export interface EmbeddingConfig {provider?: string;bm25Weight: number;diff --git a/src/version.ts b/src/version.tsindex a1198883..8a6e33a2 100644--- a/src/version.ts+++ b/src/version.ts@@ -1 +1 @@-export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.8.1" | "0.8.2" = "0.8.2";+export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.8.1" | "0.8.2" | "0.8.3" = "0.8.3";diff --git a/test/access-tracker.test.ts b/test/access-tracker.test.tsnew file mode 100644index 00000000..00fd6caa--- /dev/null+++ b/test/access-tracker.test.ts@@ -0,0 +1,249 @@+import { describe, it, expect, vi } from "vitest";++vi.mock("iii-sdk", () => ({+ getContext: () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ }),+}));++function mockKV() {+ const store = new Map<string, Map<string, unknown>>();+ return {+ store,+ get: async <T>(scope: string, key: string): Promise<T | null> =>+ (store.get(scope)?.get(key) as T) ?? null,+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {+ if (!store.has(scope)) store.set(scope, new Map());+ store.get(scope)!.set(key, data);+ return data;+ },+ delete: async (scope: string, key: string) => {+ store.get(scope)?.delete(key);+ },+ list: async <T>(scope: string): Promise<T[]> => {+ const m = store.get(scope);+ return m ? (Array.from(m.values()) as T[]) : [];+ },+ };+}++describe("access-tracker", () => {+ it("getAccessLog returns empty log for unknown id", async () => {+ const { getAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ const log = await getAccessLog(kv as never, "mem_xyz");+ expect(log).toEqual({ memoryId: "mem_xyz", count: 0, lastAt: "", recent: [] });+ });++ it("recordAccess increments count and lastAt", async () => {+ const { recordAccess, getAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ await recordAccess(kv as never, "mem_a", 1_000_000);+ await recordAccess(kv as never, "mem_a", 2_000_000);+ await recordAccess(kv as never, "mem_a", 3_000_000);++ const log = await getAccessLog(kv as never, "mem_a");+ expect(log.count).toBe(3);+ expect(log.recent).toEqual([1_000_000, 2_000_000, 3_000_000]);+ expect(log.lastAt).toBe(new Date(3_000_000).toISOString());+ });++ it("recent[] is bounded to last 20 entries", async () => {+ const { recordAccess, getAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ for (let i = 1; i <= 50; i++) {+ await recordAccess(kv as never, "mem_b", i * 1000);+ }+ const log = await getAccessLog(kv as never, "mem_b");+ expect(log.count).toBe(50);+ expect(log.recent.length).toBe(20);+ // Should be the LAST 20: 31_000..50_000+ expect(log.recent[0]).toBe(31_000);+ expect(log.recent[19]).toBe(50_000);+ });++ it("recordAccessBatch deduplicates and writes once per id", async () => {+ const { recordAccessBatch, getAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ await recordAccessBatch(+ kv as never,+ ["mem_a", "mem_b", "mem_a", "mem_b", "mem_c"],+ 5_000_000,+ );+ expect((await getAccessLog(kv as never, "mem_a")).count).toBe(1);+ expect((await getAccessLog(kv as never, "mem_b")).count).toBe(1);+ expect((await getAccessLog(kv as never, "mem_c")).count).toBe(1);+ });++ it("recordAccess swallows kv.set errors (must not break reads)", async () => {+ const { recordAccess } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ kv.set = (async () => {+ throw new Error("boom");+ }) as never;+ await expect(recordAccess(kv as never, "mem_a")).resolves.toBeUndefined();+ });++ it("concurrent recordAccess calls do not lose increments (keyed mutex)", async () => {+ const { recordAccess, getAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ await Promise.all(+ Array.from({ length: 25 }, (_, i) =>+ recordAccess(kv as never, "mem_race", i * 100),+ ),+ );+ const log = await getAccessLog(kv as never, "mem_race");+ expect(log.count).toBe(25);+ });++ it("recordAccessBatch: a single failing id does not block siblings", async () => {+ const { recordAccessBatch, getAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ const realSet = kv.set.bind(kv);+ kv.set = (async (scope: string, key: string, val: unknown) => {+ if (key === "mem_slow") throw new Error("write failed");+ return realSet(scope, key, val);+ }) as never;++ await recordAccessBatch(+ kv as never,+ ["mem_slow", "mem_fast_a", "mem_fast_b"],+ 1_000_000,+ );+ expect((await getAccessLog(kv as never, "mem_fast_a")).count).toBe(1);+ expect((await getAccessLog(kv as never, "mem_fast_b")).count).toBe(1);+ expect((await getAccessLog(kv as never, "mem_slow")).count).toBe(0);+ });++ it("ignores empty / falsy memory ids", async () => {+ const { recordAccess, recordAccessBatch } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ await recordAccess(kv as never, "");+ await recordAccessBatch(kv as never, ["", "mem_x", ""]);+ expect(kv.store.get("mem:access")?.has("")).toBeFalsy();+ expect(kv.store.get("mem:access")?.get("mem_x")).toBeTruthy();+ });++ it("deleteAccessLog removes the target entry and leaves siblings intact", async () => {+ const { recordAccess, deleteAccessLog, getAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ await recordAccess(kv as never, "mem_a");+ await recordAccess(kv as never, "mem_b");++ await deleteAccessLog(kv as never, "mem_a");++ expect(kv.store.get("mem:access")?.has("mem_a")).toBe(false);+ expect((await getAccessLog(kv as never, "mem_b")).count).toBe(1);+ });++ it("deleteAccessLog is a no-op for unknown ids and empty ids", async () => {+ const { deleteAccessLog, recordAccess } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ await recordAccess(kv as never, "mem_keep");++ await deleteAccessLog(kv as never, "");+ await deleteAccessLog(kv as never, "mem_unknown");++ expect(kv.store.get("mem:access")?.has("mem_keep")).toBe(true);+ });++ it("deleteAccessLog swallows kv.delete errors", async () => {+ const { deleteAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const kv = mockKV();+ kv.delete = (async () => {+ throw new Error("boom");+ }) as never;++ await expect(+ deleteAccessLog(kv as never, "mem_x"),+ ).resolves.toBeUndefined();+ });+});++describe("normalizeAccessLog", () => {+ it("returns a well-formed empty log for nullish / non-object input", async () => {+ const { normalizeAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const log = normalizeAccessLog(null);+ expect(log).toEqual({+ memoryId: "",+ count: 0,+ lastAt: "",+ recent: [],+ });+ expect(normalizeAccessLog(undefined).count).toBe(0);+ expect(normalizeAccessLog("garbage").count).toBe(0);+ });++ it("coerces count to a non-negative integer", async () => {+ const { normalizeAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ expect(normalizeAccessLog({ count: -5 }).count).toBe(0);+ expect(normalizeAccessLog({ count: 3.7 }).count).toBe(3);+ expect(normalizeAccessLog({ count: NaN }).count).toBe(0);+ expect(normalizeAccessLog({ count: "123" }).count).toBe(0);+ });++ it("preserves large lifetime counts (NOT capped at ring buffer size)", async () => {+ const { normalizeAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const log = normalizeAccessLog({ memoryId: "m", count: 500, recent: [1] });+ expect(log.count).toBe(500);+ });++ it("truncates recent[] to the last 20 entries and drops non-finite values", async () => {+ const { normalizeAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const input = Array.from({ length: 40 }, (_, i) => i * 1000);+ const withGarbage = [...input, NaN, Infinity, "bad" as unknown as number];+ const log = normalizeAccessLog({ recent: withGarbage });+ expect(log.recent.length).toBe(20);+ expect(log.recent[0]).toBe(20_000);+ expect(log.recent[19]).toBe(39_000);+ });++ it("count is at least recent.length when count < recent.length", async () => {+ const { normalizeAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ const log = normalizeAccessLog({+ count: 2,+ recent: [1, 2, 3, 4, 5],+ });+ expect(log.count).toBeGreaterThanOrEqual(5);+ });++ it("fills in memoryId only when field is a string", async () => {+ const { normalizeAccessLog } = await import(+ "../src/functions/access-tracker.js"+ );+ expect(normalizeAccessLog({ memoryId: "mem_x" }).memoryId).toBe("mem_x");+ expect(normalizeAccessLog({ memoryId: 42 }).memoryId).toBe("");+ });+});diff --git a/test/export-import.test.ts b/test/export-import.test.tsindex 22794d5c..cc156c50 100644--- a/test/export-import.test.ts+++ b/test/export-import.test.ts@@ -118,7 +118,7 @@ describe("Export/Import Functions", () => {it("export produces valid ExportData structure", async () => {const result = (await sdk.trigger("mem::export", {})) as ExportData;- expect(result.version).toBe("0.8.2");+ expect(result.version).toBe("0.8.3");expect(result.exportedAt).toBeDefined();expect(result.sessions.length).toBe(1);expect(result.sessions[0].id).toBe("ses_1");diff --git a/test/retention-access.test.ts b/test/retention-access.test.tsnew file mode 100644index 00000000..d27728e9--- /dev/null+++ b/test/retention-access.test.ts@@ -0,0 +1,310 @@+import { describe, it, expect, vi } from "vitest";+import type { Memory, SemanticMemory } from "../src/types.js";++vi.mock("iii-sdk", () => ({+ getContext: () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ }),+}));++function mockKV(+ memories: Memory[] = [],+ semanticMems: SemanticMemory[] = [],+) {+ const store = new Map<string, Map<string, unknown>>();+ const memMap = new Map<string, unknown>();+ for (const m of memories) memMap.set(m.id, m);+ store.set("mem:memories", memMap);+ const semMap = new Map<string, unknown>();+ for (const s of semanticMems) semMap.set(s.id, s);+ store.set("mem:semantic", semMap);+ store.set("mem:retention", new Map());+ store.set("mem:access", new Map());++ return {+ get: async <T>(scope: string, key: string): Promise<T | null> =>+ (store.get(scope)?.get(key) as T) ?? null,+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {+ if (!store.has(scope)) store.set(scope, new Map());+ store.get(scope)!.set(key, data);+ return data;+ },+ delete: async (scope: string, key: string) => {+ store.get(scope)?.delete(key);+ },+ list: async <T>(scope: string): Promise<T[]> => {+ const m = store.get(scope);+ return m ? (Array.from(m.values()) as T[]) : [];+ },+ };+}++function mockSdk() {+ const fns = new Map<string, Function>();+ return {+ registerFunction: (opts: { id: string }, fn: Function) => {+ fns.set(opts.id, fn);+ },+ trigger: async (id: string, data: unknown) => {+ const fn = fns.get(id);+ if (fn) return fn(data);+ return null;+ },+ };+}++function makeMemory(id: string, daysOld = 30): Memory {+ const created = new Date(+ Date.now() - daysOld * 86_400_000,+ ).toISOString();+ return {+ id,+ createdAt: created,+ updatedAt: created,+ type: "fact",+ title: `Memory ${id}`,+ content: `Content ${id}`,+ concepts: [],+ files: [],+ sessionIds: ["ses_1"],+ strength: 1,+ version: 1,+ isLatest: true,+ };+}++function makeSemantic(+ id: string,+ daysOld: number,+ accessCount = 0,+): SemanticMemory {+ const created = new Date(+ Date.now() - daysOld * 86_400_000,+ ).toISOString();+ return {+ id,+ fact: `Fact ${id}`,+ confidence: 0.8,+ sourceSessionIds: ["ses_1"],+ sourceMemoryIds: [],+ accessCount,+ lastAccessedAt: created,+ strength: 0.8,+ createdAt: created,+ updatedAt: created,+ };+}++describe("RetentionScoring with access log (issue #119)", () => {+ it("episodic memories with recorded reads get higher reinforcementBoost than untouched ones", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );+ const { recordAccess } = await import(+ "../src/functions/access-tracker.js"+ );++ const memories = [+ makeMemory("mem_hot", 30),+ makeMemory("mem_cold", 30),+ ];+ const sdk = mockSdk();+ const kv = mockKV(memories);+ registerRetentionFunctions(sdk as never, kv as never);++ // Simulate 5 agent reads of mem_hot in the past 24h+ const now = Date.now();+ for (let i = 0; i < 5; i++) {+ await recordAccess(kv as never, "mem_hot", now - i * 60_000);+ }++ const result = (await sdk.trigger("mem::retention-score", {})) as any;++ const hot = result.scores.find((s: any) => s.memoryId === "mem_hot");+ const cold = result.scores.find((s: any) => s.memoryId === "mem_cold");++ expect(hot.accessCount).toBe(5);+ expect(cold.accessCount).toBe(0);+ expect(hot.reinforcementBoost).toBeGreaterThan(0);+ expect(cold.reinforcementBoost).toBe(0);+ expect(hot.score).toBeGreaterThan(cold.score);+ });++ it("recent reads contribute more to reinforcement than ancient reads", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );+ const { recordAccess } = await import(+ "../src/functions/access-tracker.js"+ );++ const memories = [+ makeMemory("mem_recent_read", 60),+ makeMemory("mem_old_read", 60),+ ];+ const sdk = mockSdk();+ const kv = mockKV(memories);+ registerRetentionFunctions(sdk as never, kv as never);++ const now = Date.now();+ // mem_recent_read: 1 access yesterday+ await recordAccess(kv as never, "mem_recent_read", now - 86_400_000);+ // mem_old_read: 1 access 60 days ago+ await recordAccess(kv as never, "mem_old_read", now - 60 * 86_400_000);++ const result = (await sdk.trigger("mem::retention-score", {})) as any;+ const recent = result.scores.find(+ (s: any) => s.memoryId === "mem_recent_read",+ );+ const old = result.scores.find(+ (s: any) => s.memoryId === "mem_old_read",+ );++ expect(recent.reinforcementBoost).toBeGreaterThan(old.reinforcementBoost);+ });++ it("backwards-compat: semantic memories with only legacy lastAccessedAt still score", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ // Pre-0.8.3 data: semantic memory has lastAccessedAt set by the+ // consolidation pipeline, but no entry in mem:access. The merge in+ // retention.ts must inject lastAccessedAt into accessTimestamps so+ // the boost is non-zero. Compare against an identical sem with NO+ // lastAccessedAt to prove the merge actually contributes.+ const semWith = makeSemantic("sem_with_legacy", 30, 3);+ semWith.lastAccessedAt = new Date(Date.now() - 86_400_000).toISOString();+ const semWithout = makeSemantic("sem_without_legacy", 30, 3);+ semWithout.lastAccessedAt = "";++ const sdk = mockSdk();+ const kv = mockKV([], [semWith, semWithout]);+ registerRetentionFunctions(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::retention-score", {})) as any;+ const withEntry = result.scores.find(+ (s: any) => s.memoryId === "sem_with_legacy",+ );+ const withoutEntry = result.scores.find(+ (s: any) => s.memoryId === "sem_without_legacy",+ );++ expect(withEntry.accessCount).toBe(3);+ expect(withEntry.reinforcementBoost).toBeGreaterThan(0);+ expect(withoutEntry.reinforcementBoost).toBe(0);+ // The merged legacy timestamp must produce a meaningful delta.+ expect(withEntry.reinforcementBoost).toBeGreaterThan(+ withoutEntry.reinforcementBoost + 0.1,+ );+ });++ it("corrupted lastAccessedAt does not propagate NaN into the score", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );+ const sem = makeSemantic("sem_corrupt", 30, 1);+ sem.lastAccessedAt = "<script>alert(1)</script>";++ const sdk = mockSdk();+ const kv = mockKV([], [sem]);+ registerRetentionFunctions(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::retention-score", {})) as any;+ const entry = result.scores.find((s: any) => s.memoryId === "sem_corrupt");++ expect(Number.isFinite(entry.score)).toBe(true);+ expect(Number.isFinite(entry.reinforcementBoost)).toBe(true);+ });++ it("retention scoring normalizes malformed mem:access rows", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );+ const memories = [+ makeMemory("mem_corrupt", 10),+ makeMemory("mem_clean", 10),+ ];+ const sdk = mockSdk();+ const kv = mockKV(memories);++ // Seed the access namespace directly with garbage rows.+ await kv.set("mem:access", "mem_corrupt", {+ memoryId: "mem_corrupt",+ count: "not-a-number" as unknown as number,+ lastAt: 42 as unknown as string,+ recent: [NaN, "bad" as unknown as number, 5_000, Infinity, -1_000],+ });+ await kv.set("mem:access", "mem_clean", {+ memoryId: "mem_clean",+ count: -7,+ lastAt: "",+ recent: Array.from({ length: 50 }, (_, i) => i * 1000),+ });++ registerRetentionFunctions(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::retention-score", {})) as any;+ const corrupt = result.scores.find(+ (s: any) => s.memoryId === "mem_corrupt",+ );+ const clean = result.scores.find((s: any) => s.memoryId === "mem_clean");++ expect(Number.isFinite(corrupt.score)).toBe(true);+ expect(Number.isFinite(corrupt.reinforcementBoost)).toBe(true);+ expect(corrupt.accessCount).toBeGreaterThanOrEqual(0);+ expect(Number.isFinite(clean.score)).toBe(true);+ // recent[] was 50 entries; normalization should have capped at 20.+ expect(clean.accessCount).toBeGreaterThanOrEqual(20);+ });++ it("retention scoring survives kv.list(mem:access) failures", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );+ const memories = [makeMemory("mem_resilient", 10)];+ const sdk = mockSdk();+ const kv = mockKV(memories);+ const realList = kv.list.bind(kv);+ kv.list = (async (scope: string) => {+ if (scope === "mem:access") throw new Error("namespace missing");+ return realList(scope);+ }) as never;++ registerRetentionFunctions(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::retention-score", {})) as any;+ expect(result.success).toBe(true);+ const entry = result.scores.find(+ (s: any) => s.memoryId === "mem_resilient",+ );+ expect(entry.accessCount).toBe(0);+ });++ it("fresh access log overrides legacy single-sample for semantic memories", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );+ const { recordAccess } = await import(+ "../src/functions/access-tracker.js"+ );++ const sem = makeSemantic("sem_active", 30, 1);+ const sdk = mockSdk();+ const kv = mockKV([], [sem]);+ registerRetentionFunctions(sdk as never, kv as never);++ const now = Date.now();+ for (let i = 0; i < 10; i++) {+ await recordAccess(kv as never, "sem_active", now - i * 30_000);+ }++ const result = (await sdk.trigger("mem::retention-score", {})) as any;+ const entry = result.scores.find(+ (s: any) => s.memoryId === "sem_active",+ );++ // effectiveCount = max(log=10, sem.accessCount=1) = 10+ expect(entry.accessCount).toBe(10);+ });+});diff --git a/test/smart-search.test.ts b/test/smart-search.test.tsindex 0c58fc4d..ba5bc6e4 100644--- a/test/smart-search.test.ts+++ b/test/smart-search.test.ts@@ -166,4 +166,30 @@ describe("Smart Search Function", () => {expect(result.mode).toBe("expanded");expect(result.results.length).toBe(0);});++ it("compact mode records access for every returned observation id (#119)", async () => {+ await sdk.trigger("mem::smart-search", { query: "auth" });+ // recordAccessBatch is fire-and-forget — let the microtask queue drain.+ await new Promise((r) => setImmediate(r));++ const log1 = (await kv.get("mem:access", "obs_1")) as {+ count: number;+ } | null;+ const log2 = (await kv.get("mem:access", "obs_2")) as {+ count: number;+ } | null;++ expect(log1?.count).toBe(1);+ expect(log2?.count).toBe(1);+ });++ it("expand mode records access for expanded observation ids (#119)", async () => {+ await sdk.trigger("mem::smart-search", { expandIds: ["obs_1"] });+ await new Promise((r) => setImmediate(r));++ const log = (await kv.get("mem:access", "obs_1")) as {+ count: number;+ } | null;+ expect(log?.count).toBe(1);+ });});