diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..73b5a39 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,43 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + name: Tests (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: ["22.16", "22.x", "24.x"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + - run: npm ci + - run: npm run lint + # Uses the deterministic hash embedder: no model download. + - run: npm test + + retrieval-quality: + name: Retrieval quality (real model) + runs-on: ubuntu-latest + needs: test + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24.x + cache: npm + - run: npm ci + - uses: actions/cache@v4 + with: + path: ~/.cache/agent-memory-store + key: hf-${{ hashFiles('src/embeddings.js', 'package-lock.json') }} + - run: AMS_MODEL_TESTS=1 node --no-warnings --test test/e2e-model.test.js + - run: npm run bench diff --git a/.gitignore b/.gitignore index ec4bc7c..b565153 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules .agent-memory-store .claude -benchmarks/.cache \ No newline at end of file +benchmarks/.cache +.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ab54473 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing + +## Setup + +```bash +git clone https://github.com/vbfs/agent-memory-store +cd agent-memory-store +npm install +npm test # unit + end-to-end (stdio) + multi-process tests, no model download +AMS_MODEL_TESTS=1 npm test # also end-to-end with the real embedding model +``` + +Requires Node.js >= 22.16 (built-in `node:sqlite`). + +## Layout + +``` +src/ + index.js MCP server: tool schemas, formatting, errors + embeddings.js Embedder interface, local models, HashEmbedder (tests) + migrate.js One-time import of the legacy markdown file store + store/ + memory-store.js MemoryStore: schema + migrations, write/search/list/state + fts-query.js Safe FTS5 query builder (never a syntax error) + vector-index.js In-memory exact vector index + secrets.js Credential detection on write +test/ node:test suites (run with `npm test`) +benchmarks/ bench (quality + speed), golden set, LongMemEval — all use MemoryStore +``` + +There is one implementation of storage and ranking (`MemoryStore`). The MCP +server, the tests and every benchmark use it — never copy search logic into a +benchmark. + +## Changing ranking or the embedding model + +Run before and after, and include both outputs in the PR: + +```bash +npm run bench # quality + speed, ~30 s +npm run bench:tune-fusion # if you touched fusion or ranking +``` + +Report the metrics exactly as printed. Do not compare against numbers from +other systems unless they use the same dataset, granularity and metric. + +## Schema changes + +Bump `SCHEMA_VERSION` in `src/store/memory-store.js`, add a migration step +that runs inside the existing transaction, and add a test that opens a +database created with the previous schema. + +## Commits + +[Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, +`docs:`, `test:`, `perf:`, `refactor:`. + +## Reporting issues + +Include the Node.js version, OS, `AGENT_MEMORY_MODEL` (if set), the tool call +and arguments, and the server's stderr output. diff --git a/Contributing.md b/Contributing.md deleted file mode 100644 index b4d8b74..0000000 --- a/Contributing.md +++ /dev/null @@ -1,65 +0,0 @@ -# Contributing - -Thank you for your interest in contributing to context-store! - -## Getting started - -```bash -git clone https://github.com/YOUR_USERNAME/context-store -cd context-store -npm install -``` - -## Running locally - -```bash -# Start the MCP server (stdio mode) -npm start - -# Run tests -npm test -``` - -## Project structure - -``` -src/ - bm25.js — BM25 ranking engine (pure JS, no dependencies) - store.js — File-based persistence layer (chunks + state) - index.js — MCP server and tool definitions -``` - -## Adding a new tool - -1. Add the business logic in `src/store.js` -2. Register the tool in `src/index.js` with a `server.tool()` call -3. Add a test in `src/__tests__/store.test.js` -4. Document the tool in the README Tools table - -## Commit conventions - -This project uses [Conventional Commits](https://www.conventionalcommits.org/): - -``` -feat: add expiry-based chunk pruning tool -fix: handle missing frontmatter gracefully -docs: add opencode configuration example -test: add BM25 score regression test -``` - -## Pull request checklist - -- [ ] All existing tests pass (`npm test`) -- [ ] New functionality has tests -- [ ] README is updated if tools or configuration changed -- [ ] CHANGELOG entry added under `[Unreleased]` -- [ ] Code is in English (comments, variable names, tool descriptions) - -## Reporting issues - -Please include: - -- Node.js version (`node --version`) -- `CONTEXT_STORE_PATH` value (if customized) -- The tool call and input that caused the issue -- Error message or unexpected output diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0947fc0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Vinícius Barreto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.MD b/README.MD deleted file mode 100644 index d38a227..0000000 --- a/README.MD +++ /dev/null @@ -1,556 +0,0 @@ -# agent-memory-store - -[![npm version](https://img.shields.io/npm/v/agent-memory-store.svg)](https://www.npmjs.com/package/agent-memory-store) -[![npm downloads](https://img.shields.io/npm/dm/agent-memory-store.svg)](https://www.npmjs.com/package/agent-memory-store) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Node.js](https://img.shields.io/badge/node-%3E%3D22.5-green.svg)](https://nodejs.org) - -> 92.1% Recall@5 on LongMemEval — without any LLM calls. Persistent, searchable memory for multi-agent AI systems, powered by SQLite and local embeddings. Zero configuration. Zero external services. - -
-Competitive retrieval quality — no LLM overhead - -| System | Recall@5 | LLM Required | -| --- | --- | --- | -| MemPalace hybrid+LLM | 100.0% | Haiku | -| MemPalace raw | 96.6% | None | -| Mastra (GPT-4o-mini) | 94.87% | Yes | -| **agent-memory-store (hybrid)** | **92.1%** | **None** | -| Hindsight (Gemini) | 91.4% | Yes | -| Stella (dense baseline) | ~85% | None | - -Outperforms LLM-assisted Hindsight. Within 4.7 points of Mastra — with no API calls. Full benchmark details [below](#longmemeval-benchmark). - -
- ---- - -## Table of Contents - -- [Why this exists](#why-this-exists) -- [How agents use memory](#how-agents-use-memory) -- [Features](#features) -- [Quick start in 60 seconds](#quick-start-in-60-seconds) -- [Configuration](#configuration) -- [Teach your agent to use memory](#teach-your-agent-to-use-memory) -- [Tools](#tools) -- [Architecture](#architecture) -- [Performance](#performance) -- [LongMemEval Benchmark](#longmemeval-benchmark) -- [Documentation](#documentation) -- [Development](#development) -- [License](#license) - ---- - -## Why this exists - -Every time you start a new session with Claude Code, Cursor, or any MCP-compatible agent, it starts from zero. It doesn't know your project uses Fastify instead of Express. It doesn't know you decided on JWT two weeks ago. It doesn't know the staging deploy is on ECS. - -`agent-memory-store` gives agents a shared, searchable memory that survives across sessions. Agents write what they learn, search what they need, and build on each other's work — just like a team with good documentation, except it happens automatically. - -`agent-memory-store` is that shared memory. Agents write what they learn, search what they need, and build on each other's work — across sessions, across agents, without any orchestration overhead. - ---- - -Agents read and write **chunks** through MCP tools. Search combines **BM25 ranking** (via SQLite FTS5) with **semantic vector similarity** (via local embeddings), merged through Reciprocal Rank Fusion for best-of-both-worlds retrieval. - -``` - ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ - │ Agent A │ │ Agent B │ │ Agent C │ - └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ - │ │ │ - └────────────────┬──────────────────┘ - │ MCP tools - ┌──────────▼──────────┐ - │ agent-memory-store │ - │ hybrid search │ - │ BM25 + semantic │ - └──────────┬──────────┘ - │ - ┌──────────▼──────────┐ - │ .agent-memory-store/ │ - │ └── store.db │ - └───────────────────────┘ -``` - ---- - -## How agents use memory - -Every agent action follows the same loop: - -``` - ┌──────────────────────────────────────────────────────────────────┐ - │ AGENT MEMORY LOOP │ - │ │ - │ ┌──────────┐ search_context ┌──────────────────────────┐ │ - │ │ New │ ────────────────► │ Memory store (store.db) │ │ - │ │ task │ ◄──────────────── │ prior decisions/outputs │ │ - │ └──────────┘ prior context └──────────────────────────┘ │ - │ │ │ - │ ▼ │ - │ ┌──────────┐ │ - │ │ Act │ (generate, decide, build) │ - │ └──────────┘ │ - │ │ │ - │ ▼ │ - │ ┌──────────┐ write_context ┌──────────────────────────┐ │ - │ │ Result │ ────────────────► │ Memory store (store.db) │ │ - │ │ │ │ persisted for future │ │ - │ └──────────┘ └──────────────────────────┘ │ - └──────────────────────────────────────────────────────────────────┘ - - Multi-agent handoff: - - Agent A ──write_context──► store.db ◄──search_context── Agent B - ──set_state──────► store.db ◄──get_state─────── - ── HANDOFF message (lightweight pointer) ──────► -``` - ---- - -## Features - -- **Zero-install usage** via `npx` -- **Hybrid search** — BM25 full-text (FTS5) + semantic vector similarity + Reciprocal Rank Fusion -- **SQLite-backed** — single `store.db` file, WAL mode, native performance -- **Local embeddings** — 384-dim vectors via `all-MiniLM-L6-v2`, no API keys needed -- **Tag and agent filtering** — find chunks by who wrote them or what they cover -- **TTL-based expiry** — chunks auto-delete after a configurable number of days -- **Session state** — key/value store for pipeline progress, flags, and counters -- **Pagination support** — `list_context` supports limit/offset for large stores -- **MCP-native** — works with Claude Code, opencode, Cursor, and any MCP-compatible client -- **Zero external database dependencies** — uses Node.js built-in SQLite (`node:sqlite`) -- **Automatic migration** — upgrades legacy filesystem stores to SQLite on first run - -## Requirements - -- Node.js >= 22.5 (required for native `node:sqlite` with FTS5 support) - ---- - -## Quick start in 60 seconds - -No installation. No account. No API key. One command: - -```bash -npx agent-memory-store -``` - -By default, memory is stored in `.agent-memory-store/store.db` inside the directory where the server starts — so each project gets its own isolated store automatically. - -The first run downloads the embedding model (~23MB) once and caches it at `~/.cache/huggingface/`. Every subsequent start is instant. - -To use a custom path: - -```bash -AGENT_STORE_PATH=/your/project/.agent-memory-store npx agent-memory-store -``` - ---- - -## Configuration - -### Claude Code - -Add to your project's `claude.mcp.json` (or `~/.claude/claude.mcp.json` for global): - -```json -{ - "mcpServers": { - "agent-memory-store": { - "command": "npx", - "args": ["-y", "agent-memory-store"] - } - } -} -``` - -Or using the Claude Code CLI: - -```bash -claude mcp add agent-memory-store --command "npx" --args "-y agent-memory-store" -``` - -### opencode - -Add to your `opencode.json`: - -```json -{ - "$schema": "https://opencode.ai/config.json", - "mcp": { - "agent-memory-store": { - "type": "local", - "command": ["npx", "-y", "agent-memory-store"], - "enabled": true - } - } -} -``` - -### Cursor / VS Code (MCP extension) - -Add to your MCP settings file: - -```json -{ - "servers": { - "agent-memory-store": { - "command": "npx", - "args": ["-y", "agent-memory-store"] - } - } -} -``` - -### Custom storage path - -If you need to store memory outside the project directory, set `AGENT_STORE_PATH` in the environment block. - -**Claude Code:** - -```json -{ - "mcpServers": { - "agent-memory-store": { - "command": "npx", - "args": ["-y", "agent-memory-store"], - "env": { - "AGENT_STORE_PATH": "/absolute/path/to/.agent-memory-store" - } - } - } -} -``` - -**opencode:** - -```json -{ - "$schema": "https://opencode.ai/config.json", - "mcp": { - "agent-memory-store": { - "type": "local", - "command": ["npx", "-y", "agent-memory-store"], - "enabled": true, - "environment": { - "AGENT_STORE_PATH": "/absolute/path/to/.agent-memory-store" - } - } - } -} -``` - -### Environment variables - -| Variable | Default | Description | -| --- | --- | --- | -| `AGENT_STORE_PATH` | `./.agent-memory-store` | Custom path to the storage directory. Omit to use project default. | - ---- - -## Teach your agent to use memory - -Add this to your agent's system prompt (or `CLAUDE.md` / `AGENTS.md`): - -```markdown -## Memory - -You have persistent memory via agent-memory-store MCP tools. - -**Before acting on any task:** - -1. `search_context` with 2–3 queries related to the task. Check for prior decisions, conventions, and relevant outputs. -2. `get_state("project_tags")` to load the tag vocabulary. If empty, this is a new project — ask the user about stack, conventions, and structure, then persist them with `write_context` and `set_state`. - -**After completing work:** - -1. `write_context` to persist decisions (with rationale), outputs (with file paths), and discoveries (with impact). -2. Use short, lowercase tags consistent with the vocabulary: `auth`, `config`, `decision`, `output`, `discovery`. -3. Set `importance: "critical"` for decisions other agents depend on, `"high"` for outputs, `"medium"` for background context. - -**Before every write:** - -1. `search_context` for the same topic first. If a chunk exists, `delete_context` it, then write the updated version. One chunk per topic. - -**Rules:** - -- Never guess a fact that might be in memory — search first, it costs <10ms. -- Never store secrets — write references to where they live, not the values. -- `set_state` is for mutable values (current phase, counters). `write_context` is for searchable knowledge (decisions, outputs). Don't mix them. -- Use `search_mode: "semantic"` when exact terms don't match (e.g., searching "autenticação" when the chunk says "auth"). -``` - -Copy, paste, done. This is enough for any agent to use memory effectively. - -> **Advanced agent workflows:** The [`skills/SKILL.MD`](./skills/SKILL.MD) file is a comprehensive governance skill covering cold-start bootstrap, multi-agent pipeline handoffs, tag vocabulary management, deduplication workflows, performance budgets, and when to use each search mode. See the [full documentation](./docs/DOCUMENTATION.md) for a detailed walkthrough of all patterns. - ---- - -## Tools - -| Tool | When to use | -| --- | --- | -| `search_context` | **Start of every task** — retrieve relevant prior knowledge before acting | -| `write_context` | After decisions, discoveries, or outputs that other agents will need | -| `read_context` | Read a specific chunk by ID | -| `list_context` | Inventory the memory store (metadata only, no body) | -| `delete_context` | Remove outdated or incorrect chunks | -| `get_state` | Read a pipeline variable (progress, flags, counters) | -| `set_state` | Write a pipeline variable | - -### `search_context` - -``` -query string Search query. Use specific, canonical terms. -tags string[] (optional) Narrow to chunks matching any of these tags. -agent string (optional) Narrow to chunks written by a specific agent. -top_k number (optional) Max results to return. Range: 1–20. Default: 6. -min_score number (optional) Minimum relevance score. Default: 0.1. -search_mode string (optional) "hybrid" (default), "bm25", or "semantic". -``` - -**Search modes:** - -| Mode | How it works | Best for | -| --- | --- | --- | -| `hybrid` | BM25 + semantic similarity merged via Reciprocal Rank Fusion | General use (default) | -| `bm25` | FTS5 keyword matching only | Exact term lookups, canonical tags | -| `semantic` | Vector cosine similarity only | Finding conceptually related chunks | - -**Response format:** - -``` -### [score: 0.85] Auth service — JWT decision -**id:** `a1b2c3d4e5` | **agent:** pm-agent | **tags:** auth, decision | **importance:** critical | **updated:** 2025-06-01T14:00:00.000Z - -[chunk content in markdown] - ---- - -### [score: 0.71] ... -``` - -### `write_context` - -``` -topic string Short, specific title. ("Auth — JWT decision", not "decision") -content string Chunk body in markdown. Include rationale, not just conclusions. -agent string (optional) Agent ID writing this chunk. -tags string[] (optional) Canonical tags for future retrieval. -importance string (optional) low | medium | high | critical. Default: medium. -ttl_days number (optional) Auto-expiry in days. Omit for permanent storage. -``` - -Embeddings are computed asynchronously after the chunk is saved. The chunk is immediately searchable via BM25; semantic search results may lag by ~200ms. - -### `read_context` - -``` -id string Chunk ID (10-char hex string from write_context or list_context). -``` - -Returns the full chunk including header metadata and body content. - -### `list_context` - -``` -agent string (optional) Filter by agent ID. -tags string[] (optional) Filter by tags. -limit number (optional) Max results. Range: 1–500. Default: 100. -offset number (optional) Results to skip for pagination. Default: 0. -``` - -Returns metadata only (no body). Use for store inventory and curation. - -### `delete_context` - -``` -id string Chunk ID to permanently delete. -``` - -### `get_state` / `set_state` - -``` -key string State variable name. -value any (set_state only) Any JSON-serializable value. -``` - -`get_state` returns `null` (not an error) for keys that don't exist yet. - ---- - -## Architecture - -``` -src/ - index.js MCP server — tool registration and transport - store.js Public API — searchChunks, writeChunk, readChunk, etc. - db.js SQLite layer — node:sqlite with FTS5, WAL mode - search.js Hybrid search — FTS5 BM25 + vector similarity + RRF - embeddings.js Local embeddings — @huggingface/transformers (all-MiniLM-L6-v2) - bm25.js Pure JS BM25 — reference implementation (not on hot path) - migrate.js Filesystem → SQLite migration (automatic, one-time) -``` - -### Storage format - -All data lives in a single SQLite database at `.agent-memory-store/store.db`: - -- **chunks table** — id, topic, agent, tags (JSON), importance, content, embedding (BLOB), timestamps, expiry -- **chunks_fts** — FTS5 virtual table synced via triggers for full-text search -- **state table** — key/value pairs for pipeline variables - -WAL mode is enabled for concurrent read performance. No manual flush needed. - -### How hybrid search works - -1. **BM25 (FTS5)** — SQLite's native full-text search ranks chunks by term frequency and inverse document frequency. Fast, deterministic, great for exact keyword matches. - -2. **Semantic similarity** — Query and chunks are embedded into 384-dimensional vectors using `all-MiniLM-L6-v2` (runs locally via ONNX Runtime). Cosine similarity finds conceptually related chunks even when exact terms don't match. - -3. **Reciprocal Rank Fusion** — Both ranked lists are merged using RRF with weights (BM25: 0.4, semantic: 0.6). Documents appearing in both lists get boosted. The fusion formula is: `score = 0.4 / (60 + rank_bm25) + 0.6 / (60 + rank_semantic)`. - -The embedding model (~23MB) is downloaded automatically on first use and cached in `~/.cache/huggingface/`. If the model fails to load, the system falls back to BM25-only search transparently. - ---- - -## Performance - -Benchmarked on Apple Silicon (Node v25, darwin arm64, BM25 mode): - -| Operation | 1K chunks | 10K chunks | 50K chunks | 100K chunks | 250K chunks | -| --- | --- | --- | --- | --- | --- | -| **write** | 0.17 ms | 0.19 ms | 0.23 ms | 0.21 ms | 0.25 ms | -| **read** | 0.01 ms | 0.05 ms | 0.21 ms | 0.22 ms | 0.85 ms | -| **search (BM25)** | ~5 ms† | ~10 ms† | ~60 ms† | ~110 ms† | ~390 ms† | -| **list** | 0.2 ms | 0.3 ms | 0.3 ms | 0.3 ms | 1.1 ms | -| **state get/set** | 0.03 ms | 0.03 ms | 0.07 ms | 0.05 ms | 0.03 ms | - -† Search times from isolated run (no model loading interference). During warmup, first queries may be slower. - -**Key insights:** - -- **write is stable at ~0.2 ms/op** — FTS5 triggers and embedding backfill are non-blocking; inserts stay constant -- **read is a single index lookup** — sub-millisecond up to 50K chunks, still <1 ms at 250K -- **search scales linearly with FTS5 corpus** — for typical agent memory usage (≤25K chunks), search stays under 30 ms -- **list is O(1) in practice** — pagination caps results at 100 rows by default, so list time stays flat regardless of corpus size -- **state ops are O(1)** — key/value store backed by a B-tree primary key, constant at all scales - ---- - -## LongMemEval Benchmark - -`agent-memory-store` is benchmarked against the **LongMemEval** dataset (ICLR 2025), a standard for evaluating long-term memory in AI systems. The benchmark measures retrieval quality (Recall@5, Recall@10, NDCG@10) on 500 real conversation scenarios. - -> **Context**: `agent-memory-store` is designed for _agent-curated memory_ — agents decide what to store, writing structured chunks with topic, tags, and importance. LongMemEval instead dumps raw conversation turns verbatim, which is outside this system's intended use case. Despite that mismatch, the retrieval engine achieves 92.1% Recall@5 — validating the underlying BM25 + semantic search infrastructure. In real agent usage, where chunks are pre-filtered and structured by the agent before writing, retrieval quality would be higher still. - -### Results (500 questions) - -| Mode | Recall@5 | Recall@10 | NDCG@10 | Questions | -| --- | --- | --- | --- | --- | -| **hybrid** | 92.1% | 96.9% | 0.885 | 479 | -| **bm25** | 92.0% | 95.9% | 0.901 | 479 | -| **semantic** | 86.1% | 92.5% | 0.821 | 479 | - -### Performance by Question Type - -Breakdown of hybrid mode across the 5 LongMemEval categories: - -| Category | Count | Recall@5 | Recall@10 | NDCG@10 | -| --- | --- | --- | --- | --- | -| **single-session-assistant** | 56 | 96.4% | 98.2% | **0.970** | -| **knowledge-update** | 72 | 95.8% | 98.6% | 0.927 | -| **single-session-user** | 64 | 95.3% | 98.4% | 0.863 | -| **single-session-preference** | 30 | 93.3% | 96.7% | 0.784 | -| **multi-session** | 125 | 91.2% | 95.9% | 0.898 | -| **temporal-reasoning** | 132 | 87.4% | 95.7% | 0.847 | - -### Competitive Positioning - -Compared against published memory systems on LongMemEval Recall@5: - -| System | Recall@5 | LLM Required | -| --- | --- | --- | -| **MemPalace hybrid+LLM** | 100.0% | Haiku | -| **MemPalace raw** | 96.6% | None | -| Mastra (GPT-4o-mini) | 94.87% | Yes | -| **agent-memory-store (hybrid)** | **92.1%** | **None** | -| Hindsight (Gemini) | 91.4% | Yes | -| Stella (dense baseline) | ~85% | None | -| Contriever (dense baseline) | ~78% | None | -| BM25 (sparse baseline) | ~70% | None | - -**Key insight**: `agent-memory-store` achieves competitive retrieval quality **without any external LLM calls**, sitting between MemPalace raw and production systems like Mastra — all while using only local embeddings. - -### Run the Benchmark - -Test on a subset (quick validation): - -```bash -node benchmarks/longmemeval_bench.js --limit 50 -``` - -Full benchmark (500 questions, ~6 minutes with warm embedding cache): - -```bash -npm run bench:longmemeval -# or -node benchmarks/longmemeval_bench.js -``` - -**Options:** - -- `--limit N` — Run only first N questions (default: all 500) -- `--mode MODE` — Test specific mode: `hybrid`, `bm25`, `semantic`, or `all` (default: all) -- `--granularity GRAN` — Chunk strategy: `session` (default), `turn`, or `hybrid` -- `--top-k K` — Retrieval cutoff (default: 10) - -Results are saved to `benchmarks/.cache/longmemeval_results.json` for analysis. - ---- - -## Documentation - -Full reference documentation is available at [`docs/DOCUMENTATION.md`](./docs/DOCUMENTATION.md): - -- Complete tool reference with all parameters and return formats -- Search mode guide with examples and the RRF fusion formula -- SKILL.MD walkthrough — bootstrap protocol, handoff patterns, deduplication -- Multi-agent coordination patterns with code examples -- Architecture deep dive (each source file's role) -- Performance budgets and scaling guidance -- Anti-patterns and the quick-reference decision tree - ---- - -## Development - -```bash -git clone https://github.com/vbfs/agent-memory-store -cd agent-memory-store -npm install -npm start -``` - -Run tests: - -```bash -npm test -``` - -Run benchmark: - -```bash -node benchmark.js -``` - -See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines. - ---- - -## License - -MIT — see [LICENSE](./LICENSE). diff --git a/README.md b/README.md new file mode 100644 index 0000000..b58e85c --- /dev/null +++ b/README.md @@ -0,0 +1,262 @@ +# agent-memory-store + +[![npm version](https://img.shields.io/npm/v/agent-memory-store.svg)](https://www.npmjs.com/package/agent-memory-store) +[![CI](https://github.com/vbfs/agent-memory-store/actions/workflows/ci.yml/badge.svg)](https://github.com/vbfs/agent-memory-store/actions/workflows/ci.yml) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE) +[![Node.js](https://img.shields.io/badge/node-%3E%3D22.16-green.svg)](https://nodejs.org) + +**Shared, persistent memory for a team of AI agents, over MCP.** One SQLite file +per project, hybrid search (keyword + local multilingual embeddings), safe for +many agent processes at once. No API keys, no external services, no LLM calls. + +```bash +claude mcp add agent-memory -s project -- npx -y agent-memory-store +``` + +--- + +## Why + +Agents start every session from zero, and agents working in parallel don't +know what the others decided. `agent-memory-store` gives them one place to +**search before acting** and **write what others will need** — decisions with +their rationale, outputs and where they live, discoveries — plus a small +versioned key/value **state** for coordination (phase, owner, run id). + +What makes it suitable for a team: + +- **Multilingual retrieval** — a question in Portuguese finds a memory written in + English and vice versa; exact identifiers (`PAG-4821`, `orders.v1`, paths) + still match by keyword. +- **Many agents, one file** — WAL, busy timeouts and compare-and-set versions; + tested with concurrent processes, no lost writes. +- **Update, don't duplicate** — write with an `id` to update in place; every + write reports likely duplicates. +- **Safe by default** — natural-language queries can't break search, + expired memories disappear immediately, credentials are refused on write. +- **Measured, not claimed** — every number below comes from scripts in + `benchmarks/` that run the same code as the server. + +## Quick start + +Requires **Node.js ≥ 22.16**. The first start downloads the embedding model +(~310 MB) to `~/.cache/agent-memory-store/models`; until it is ready, +search runs in keyword mode. + +### Claude Code + +```bash +# shared by everyone who opens this repo (writes .mcp.json) +claude mcp add agent-memory -s project -- npx -y agent-memory-store +``` + +or in `.mcp.json`: + +```json +{ + "mcpServers": { + "agent-memory": { + "command": "npx", + "args": ["-y", "agent-memory-store"], + "env": { "AGENT_MEMORY_AGENT": "backend-agent" } + } + } +} +``` + +### opencode (`opencode.json`) + +```json +{ + "mcp": { + "agent-memory": { + "type": "local", + "command": ["npx", "-y", "agent-memory-store"], + "enabled": true + } + } +} +``` + +### Cursor / VS Code / other MCP clients + +```json +{ + "mcpServers": { + "agent-memory": { "command": "npx", "args": ["-y", "agent-memory-store"] } + } +} +``` + +The store lives in `.agent-memory-store/store.db` under the directory the +client starts the server from — one store per project. Add +`.agent-memory-store/` to `.gitignore`. To share one store across repositories, +set `AGENT_STORE_PATH` to an absolute path. + +### Teach your agents + +The server sends a short usage protocol to the client automatically (MCP +server instructions). For multi-agent pipelines, add +[`skills/SKILL.md`](./skills/SKILL.md) as a skill or paste this into +`CLAUDE.md` / `AGENTS.md`: + +```markdown +## Memory +- Before a task: `search_context` for prior decisions, conventions and outputs (any language). +- After a decision, output or discovery others need: `write_context` with a specific topic, + the content with its rationale, and 1–4 lowercase tags. +- To change a memory, pass its `id` to `write_context`. Merge reported duplicates. +- Shared mutable values (phase, owner, run id): `get_state` / `set_state` with `expected_version`. +- Never store secrets — store where they live. +``` + +## Tools + +| Tool | Purpose | +| --- | --- | +| `search_context` | Hybrid search. Filters: `tags`, `agent`, `since`/`until`. Returns snippets with score, similarity, version. | +| `write_context` | Create, or update in place with `id`. Optional `expected_version` (compare-and-set), `ttl_days`, `importance`. Reports likely duplicates. | +| `read_context` | Full text of one memory. | +| `list_context` | Newest first, metadata only, with total and paging. | +| `delete_context` | Delete one memory. | +| `get_state` / `set_state` | Versioned JSON values for coordination; `expected_version: 0` = claim if unset. | + +Full parameters, response formats and behavior: [docs/DOCUMENTATION.md](./docs/DOCUMENTATION.md). + +## How it works + +``` + agent A ─┐ ┌─ FTS5 BM25 (topic 3× · tags 2× · content) ─┐ + agent B ─┼─ MCP stdio servers ──┤ ├─ score fusion ─ results + agent C ─┘ (one per agent) └─ local embeddings → in-memory vector index ─┘ + │ + └── .agent-memory-store/store.db (SQLite, WAL, shared) +``` + +- **Keyword**: SQLite FTS5, accent-insensitive (`decisao` = `Decisão`); every + query term is quoted, so punctuation and operators can't cause syntax errors. +- **Semantic**: `Snowflake/snowflake-arctic-embed-m-v2.0` (multilingual, ONNX 8-bit, CPU) and exact cosine search over + an in-memory index that each process keeps in sync with the file. +- **Fusion**: weighted sum of per-query normalized scores, 70% semantic / + 30% keyword — chosen on held-out queries, see [Results](#results). + Importance and recency only break near-ties. + +## Results + +One command, one process, ~30 s, < 1 GB RAM: + +```bash +npm run bench +``` + +Measured on an Apple M2 (8 GB), Node 25.6. Raw outputs: +[`benchmarks/results/`](./benchmarks/results). Every benchmark runs the same +`MemoryStore` code as the MCP server; quality numbers are identical across +runs, and the metric code is unit-tested against hand-computed values. + +### Quality — bilingual agent memory (golden set) + +150 hand-written memories from a fictional product team (55% PT-BR, 45% EN), +120 queries: 35 cross-lingual, 35 paraphrases, 15 exact identifiers, 12 +knowledge updates, 10 filtered, 13 multi-memory +([`benchmarks/golden/dataset.json`](./benchmarks/golden/dataset.json)). +Synthetic and small: a regression test for the intended use, not a leaderboard. + +| Model (`AGENT_MEMORY_MODEL`) | Hit@1 | Recall@5 | MRR | Search p50 | Write p50 | RAM / process | +| --- | --- | --- | --- | --- | --- | --- | +| `none` (keyword only) | 50.8% | 70.0% | 0.587 | 0.7 ms | 0.1 ms | 64 MB | +| `minilm-l6-en` (0.0.x model) | 55.0% | 70.0% | 0.610 | 2.6 ms | 3.2 ms | 271 MB | +| `granite-97m-multilingual` | 66.7% | 88.3% | 0.770 | 4.5 ms | 5.8 ms | 453 MB | +| **`arctic-embed-m-v2` (default)** | **74.2%** | **95.8%** | **0.836** | **8.6 ms** | **13.9 ms** | **628 MB** | +| `embeddinggemma-300m` | 74.2% | 96.7% | 0.841 | 57.9 ms | 94.1 ms | 1372 MB | + +Hybrid mode. Search and write latency with 2,000 memories in an on-disk store +(write includes embedding and the duplicate check; reads are < 0.1 ms). +On Linux x64 (GitHub Actions) the default model scores 75.0% / 96.7% / 0.843 +(int8 kernels differ slightly between ARM and x86), searches in 12.8 ms and +uses about **1.3 GB RAM per process** — plan memory accordingly, or use +`granite-97m-multilingual` / `none` on small Linux machines. + +### LongMemEval-S (ICLR 2025), keyword engine + +Official retrieval protocol: session granularity, user turns only, abstention +and no-evidence questions excluded (**n = 419** of 500, cleaned release), +metrics from the official `eval_utils.py`. + +| Mode | R_any@5 | R_all@5 | R_any@10 | R_all@10 | NDCG@10 | +| --- | --- | --- | --- | --- | --- | +| keyword (BM25) | 95.5% | 84.2% | 96.4% | 89.3% | 0.882 | + +LongMemEval indexes raw chat logs, not curated memories, and embedding its +~16K long sessions takes about an hour and several GB of RAM on a laptop, so +the hybrid run is optional: `npm run bench:longmemeval` (`--sample 100` for a +stratified subset). The keyword run takes seconds: +`node benchmarks/longmemeval.js --model none`. + +### How the defaults were chosen + +- **Model** — `arctic-embed-m-v2` matches the best quality (EmbeddingGemma) + within 0.005 MRR at 7× lower latency and half the RAM, is Apache-2.0, and + separates near-duplicates well enough for the write-time duplicate warning. + The 0.0.x model (`all-MiniLM-L6-v2`, English-only) fails cross-lingual + queries: Recall@5 70.0% vs 95.8%. +- **Fusion** — equal-weight reciprocal rank fusion (0.0.x) scored *below* + semantic-only search on the golden set, because keyword hits dilute + cross-lingual and paraphrase queries. A grid over method × weight was run on + the odd-numbered queries only; the chosen setting (convex combination, 0.7 + semantic) was then confirmed on the even half (`npm run bench:tune-fusion`). + It keeps keyword strength for exact identifiers. +- **Duplicate warning** — the similarity threshold per model is set for a ~5% + false-positive rate on the golden set's superseded/superseding pairs. + +## Upgrading from 0.0.x + +Existing stores migrate automatically on first start (content, tags, +timestamps and state are kept; vectors are recomputed in the background). +Tool names are unchanged; new optional parameters only. Fixed along the way: + +- searches containing `? ' . - / ,` or `AND/OR/NOT` failed with FTS5 syntax errors; +- `min_score` was ignored; expired memories were returned until restart; +- updating meant delete + write; `INSERT OR REPLACE` left orphan index rows; +- concurrent processes could fail with `SQLITE_BUSY`; +- the previously published "92.1% Recall@5" came from a copy of the search + code that differed from production, a non-standard recall metric and a + competitor table mixing different metrics; it is replaced by the + reproducible results above. + +## Configuration + +| Variable | Default | | +| --- | --- | --- | +| `AGENT_STORE_PATH` | `./.agent-memory-store` | Store directory. | +| `AGENT_MEMORY_AGENT` | `global` | Default agent id recorded on writes from this process. | +| `AGENT_MEMORY_MODEL` | `arctic-embed-m-v2` | Or `granite-97m-multilingual` (lighter), `embeddinggemma-300m`, `minilm-l6-en`, `none` (keyword only, ~64 MB RAM). All agents sharing a store must use the same model. | +| `AGENT_MEMORY_CACHE` | `~/.cache/agent-memory-store/models` | Model cache. | + +## Limits + +- Each agent process loads its own model copy (~630 MB on macOS ARM, ~1.3 GB + on Linux x64 with the default). With + many agents on a small machine, use `granite-97m-multilingual` (~450 MB) or + `none` (~64 MB, keyword only). +- Exact vector search is linear: fine up to ~100K memories per store. +- Only the first ~2000 characters of a memory are embedded; keyword search + covers all of it. Prefer focused memories. +- Secret detection is pattern-based, not a DLP system. There is no access + control: whoever can read `store.db` can read every memory. + +## Development + +```bash +npm install +npm test # unit, end-to-end over stdio, multi-process — no model download +AMS_MODEL_TESTS=1 npm test # + end-to-end with the real model +npm run bench # quality + speed, ~30 s +npm run bench:longmemeval # optional, heavy (see above) +``` + +See [CONTRIBUTING.md](./CONTRIBUTING.md). Programmatic use (`import { MemoryStore } from "agent-memory-store"`) is documented in [docs/DOCUMENTATION.md](./docs/DOCUMENTATION.md#8-programmatic-use). + +## License + +MIT — see [LICENSE](./LICENSE). diff --git a/benchmark.js b/benchmark.js deleted file mode 100644 index 5f48c18..0000000 --- a/benchmark.js +++ /dev/null @@ -1,210 +0,0 @@ -#!/usr/bin/env node -/** - * Benchmark: agent-memory-store performance at scale. - * - * Tests write, read, search (BM25), list, and delete operations - * at 100, 1K, 5K, and 10K chunks to measure scalability. - * - * Usage: node benchmark.js - */ - -import { - initStore, - writeChunk, - readChunk, - searchChunks, - listChunks, - deleteChunk, - setState, - getState, -} from "./src/store.js"; - -const SIZES = [100, 1_000, 5_000, 10_000, 25_000, 50_000, 100_000, 250_000]; - -function randomWord() { - const words = [ - "auth", - "api", - "database", - "migration", - "deploy", - "cache", - "queue", - "webhook", - "middleware", - "router", - "schema", - "model", - "service", - "controller", - "handler", - "pipeline", - "worker", - "cron", - "batch", - "stream", - "socket", - "proxy", - "gateway", - "monitor", - "alert", - "config", - "secret", - "token", - "session", - "permission", - "role", - "tenant", - "billing", - "invoice", - "payment", - "subscription", - "notification", - "email", - "sms", - "push", - "template", - "render", - "search", - "index", - "vector", - "embedding", - "similarity", - "ranking", - ]; - return words[Math.floor(Math.random() * words.length)]; -} - -function randomSentence(n = 10) { - return Array.from({ length: n }, randomWord).join(" "); -} - -function randomTags() { - const count = 1 + Math.floor(Math.random() * 3); - return Array.from({ length: count }, randomWord); -} - -async function time(label, fn) { - const start = performance.now(); - const result = await fn(); - const ms = performance.now() - start; - return { label, ms, result }; -} - -async function bench(size) { - console.log(`\n${"=".repeat(60)}`); - console.log(` ${size.toLocaleString()} CHUNKS`); - console.log(`${"=".repeat(60)}`); - - // ── Write ── - const ids = []; - const { ms: writeTotal } = await time("write", async () => { - for (let i = 0; i < size; i++) { - const r = await writeChunk({ - topic: `${randomWord()} — ${randomSentence(4)}`, - content: randomSentence(50), - agent: ["architect", "dev", "qa", "pm"][i % 4], - tags: randomTags(), - importance: ["low", "medium", "high", "critical"][i % 4], - }); - ids.push(r.id); - } - }); - const writeAvg = writeTotal / size; - console.log( - ` write ${writeTotal.toFixed(0)}ms total | ${writeAvg.toFixed(2)}ms/op`, - ); - - // ── Read (random 100) ── - const readSample = 100; - const { ms: readTotal } = await time("read", async () => { - for (let i = 0; i < readSample; i++) { - const id = ids[Math.floor(Math.random() * ids.length)]; - await readChunk(id); - } - }); - console.log( - ` read ${readTotal.toFixed(0)}ms for ${readSample} reads | ${(readTotal / readSample).toFixed(2)}ms/op`, - ); - - // ── Search BM25 (10 queries) ── - const queries = Array.from({ length: 10 }, () => randomSentence(3)); - const { ms: searchBm25Total } = await time("search_bm25", async () => { - for (const q of queries) { - await searchChunks({ query: q, topK: 6, mode: "bm25" }); - } - }); - console.log( - ` search ${searchBm25Total.toFixed(0)}ms for 10 queries | ${(searchBm25Total / 10).toFixed(1)}ms/query (bm25)`, - ); - - // ── List ── - const { ms: listMs } = await time("list", async () => { - await listChunks(); - }); - console.log(` list ${listMs.toFixed(1)}ms`); - - // ── List with filter ── - const { ms: listFilterMs } = await time("list_filter", async () => { - await listChunks({ agent: "architect", tags: ["auth"] }); - }); - console.log(` list+filt ${listFilterMs.toFixed(1)}ms`); - - // ── State KV ── - const { ms: stateMs } = await time("state", async () => { - for (let i = 0; i < 100; i++) { - await setState(`bench_key_${i}`, { counter: i, data: randomSentence(5) }); - } - for (let i = 0; i < 100; i++) { - await getState(`bench_key_${i}`); - } - }); - console.log( - ` state ${stateMs.toFixed(0)}ms for 200 ops (100 set + 100 get)`, - ); - - // ── Delete all ── - const { ms: deleteTotal } = await time("delete", async () => { - for (const id of ids) { - await deleteChunk(id); - } - }); - console.log( - ` delete ${deleteTotal.toFixed(0)}ms total | ${(deleteTotal / size).toFixed(2)}ms/op`, - ); - - return { - size, - writeAvg, - readAvg: readTotal / readSample, - searchAvg: searchBm25Total / 10, - listMs, - stateAvg: stateMs / 200, - }; -} - -// ── Main ── - -console.log("agent-memory-store benchmark"); -console.log(`Node ${process.version} | ${process.platform} ${process.arch}`); - -await initStore(); - -const results = []; -for (const size of SIZES) { - results.push(await bench(size)); -} - -console.log(`\n${"=".repeat(60)}`); -console.log(" SUMMARY (ms)"); -console.log(`${"=".repeat(60)}`); -console.log(" chunks | write/op | read/op | search/q | list | state/op"); -console.log(" --------|----------|---------|----------|--------|--------"); -for (const r of results) { - console.log( - ` ${String(r.size).padStart(6)} | ${r.writeAvg.toFixed(2).padStart(8)} | ${r.readAvg.toFixed(2).padStart(7)} | ${r.searchAvg.toFixed(1).padStart(8)} | ${r.listMs.toFixed(1).padStart(6)} | ${r.stateAvg.toFixed(2).padStart(6)}`, - ); -} - -console.log("\nDone."); -process.exit(0); diff --git a/benchmarks/bench.js b/benchmarks/bench.js new file mode 100644 index 0000000..d691d39 --- /dev/null +++ b/benchmarks/bench.js @@ -0,0 +1,149 @@ +#!/usr/bin/env node +/** + * The benchmark: one command, one process, a couple of minutes, < 1 GB RAM. + * + * 1. Quality — golden set (150 bilingual agent memories, 120 queries), + * written and searched through the production MemoryStore. + * 2. Speed — 2,000 memories in an on-disk store with the real model: + * p50/p95 of search (hybrid, keyword), write and read, plus RSS. + * + * Usage: npm run bench [-- --model arctic-embed-m-v2] [-- --memories 2000] + */ + +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import path from "path"; +import { fileURLToPath } from "url"; +import { MemoryStore } from "../src/store/memory-store.js"; +import { createEmbedder, DEFAULT_MODEL } from "../src/embeddings.js"; +import { recallAny, reciprocalRank, mean, percentile } from "./lib/metrics.js"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const DAY = 86_400_000; +const RSS_LIMIT_MB = 1500; + +const args = process.argv.slice(2); +const arg = (name, dflt) => (args.includes(name) ? args[args.indexOf(name) + 1] : dflt); +const model = arg("--model", process.env.AGENT_MEMORY_MODEL || DEFAULT_MODEL); +const N = Number(arg("--memories", 2000)); + +const rssMB = () => Math.round(process.memoryUsage().rss / 1e6); +function guard() { + if (rssMB() > RSS_LIMIT_MB) { + console.error(`Aborting: RSS ${rssMB()} MB exceeds ${RSS_LIMIT_MB} MB safety limit.`); + process.exit(2); + } +} +async function timed(fn) { + const t = performance.now(); + await fn(); + return performance.now() - t; +} +const ms = (xs) => `${percentile(xs, 50).toFixed(1)} / ${percentile(xs, 95).toFixed(1)}`; +const pct = (v) => `${(v * 100).toFixed(1)}%`; + +const embedder = createEmbedder(model); +if (embedder && !(await embedder.load())) throw new Error(`Model ${model} failed to load`); +console.log(`agent-memory-store benchmark · model ${embedder?.id ?? "none (keyword only)"} · node ${process.version} · ${process.platform}-${process.arch}\n`); + +// ─── 1. Quality: golden set ───────────────────────────────────────────────── + +const data = JSON.parse(readFileSync(path.join(__dirname, "golden", "dataset.json"), "utf8")); +const NOW = Date.parse("2026-06-01T12:00:00Z"); +let now = NOW; +const g = MemoryStore.open(":memory:", { embedder, clock: () => now }); +for (const m of [...data.memories].sort((a, b) => b.created_days_ago - a.created_days_ago)) { + now = NOW - m.created_days_ago * DAY; + await g.write({ id: m.id, topic: m.topic, content: m.content, tags: m.tags, agent: m.agent, importance: m.importance }); +} +now = NOW; +await g.flushEmbeddings(); + +const modes = embedder ? ["hybrid", "bm25", "semantic"] : ["bm25"]; +const quality = {}; +console.log(`1) Quality — golden set: ${data.memories.length} memories (PT-BR/EN), ${data.queries.length} queries`); +console.log(" mode Hit@1 Recall@5 MRR"); +for (const mode of modes) { + const rows = []; + for (const q of data.queries) { + const { results } = await g.search({ query: q.query, limit: 10, mode, tags: q.filters?.tags, agent: q.filters?.agent }); + const ranked = results.map((r) => r.id); + const gold = new Set(q.relevant); + rows.push({ hit1: recallAny(ranked, gold, 1), r5: recallAny(ranked, gold, 5), rr: reciprocalRank(ranked, gold), type: q.type }); + } + quality[mode] = { + hit1: mean(rows.map((r) => r.hit1)), + recall5: mean(rows.map((r) => r.r5)), + mrr: mean(rows.map((r) => r.rr)), + crossLingualMrr: mean(rows.filter((r) => r.type === "cross_lingual").map((r) => r.rr)), + }; + const s = quality[mode]; + console.log(` ${mode.padEnd(9)} ${pct(s.hit1).padStart(6)} ${pct(s.recall5).padStart(6)} ${s.mrr.toFixed(3)}`); +} +g.close(); +guard(); + +// ─── 2. Speed: on-disk store ──────────────────────────────────────────────── + +const SUBJECTS = ["auth service", "payments API", "PIX webhook", "checkout", "orders worker", "Kafka consumer", "Postgres", "Redis cache", "CI pipeline", "staging deploy", "serviço de notificações", "fila de conciliação", "API de antifraude", "migração de banco"]; +const FACTS = ["uses JWT with RS256", "retries 3x with exponential backoff", "has a 20s timeout", "runs on ECS Fargate", "is partitioned by tenant", "usa cache com TTL de 5 minutos", "tem assinatura HMAC nos webhooks", "foi migrado para Aurora 16", "roda blue-green deploys", "exige idempotency keys"]; +const memory = (i) => ({ + id: `m${i}`, + topic: `${SUBJECTS[i % SUBJECTS.length]} — note ${i}`, + content: `${SUBJECTS[(i * 7) % SUBJECTS.length]} ${FACTS[(i * 3) % FACTS.length]}. Ticket PAG-${1000 + i}. ${FACTS[(i * 5 + 1) % FACTS.length]}.`, + tags: [["auth", "payments", "infra", "db", "data"][i % 5]], +}); +const QUERIES = ["What did we decide about auth tokens?", "como funciona o webhook do PIX?", "Postgres migration", "qual o timeout da API de antifraude?", "PAG-1234", "staging deploy strategy"]; + +const dir = mkdtempSync(path.join(tmpdir(), "ams-bench-")); +const store = MemoryStore.open(path.join(dir, "store.db"), { embedder }); +const tEmbed = performance.now(); +store.db.exec("BEGIN"); +for (let i = 0; i < N; i++) store.importMemory(memory(i)); +store.db.exec("COMMIT"); +await store.flushEmbeddings(); +const embedSec = (performance.now() - tEmbed) / 1000; +guard(); +await store.search({ query: "warmup" }); + +const t = { hybrid: [], bm25: [], write: [], read: [] }; +for (let round = 0; round < 10; round++) { + for (const q of QUERIES) { + if (embedder) t.hybrid.push(await timed(() => store.search({ query: q }))); + t.bm25.push(await timed(() => store.search({ query: q, mode: "bm25" }))); + } +} +for (let i = 0; i < 50; i++) { + const m = memory(N + i); + t.write.push(await timed(() => store.write({ topic: m.topic, content: m.content, tags: m.tags }))); + t.read.push(await timed(() => store.get(`m${(i * 37) % N}`))); +} +const peakRss = rssMB(); +store.close(); +rmSync(dir, { recursive: true, force: true }); + +console.log(`\n2) Speed — ${N.toLocaleString("en")} memories on disk (p50 / p95 ms)`); +if (embedder) console.log(` search hybrid ${ms(t.hybrid)}`); +console.log(` search keyword ${ms(t.bm25)}`); +console.log(` write ${ms(t.write)} (includes embedding + duplicate check)`); +console.log(` read ${ms(t.read)}`); +if (embedder) console.log(` embed backfill ${Math.round(N / embedSec)} memories/s`); +console.log(` process RSS ${peakRss} MB (model + index + runtime)`); + +const out = { + meta: { model: embedder?.id ?? null, node: process.version, platform: `${process.platform}-${process.arch}`, date: new Date().toISOString() }, + quality, + speed: { + memories: N, + searchHybridMs: embedder ? { p50: percentile(t.hybrid, 50), p95: percentile(t.hybrid, 95) } : null, + searchKeywordMs: { p50: percentile(t.bm25, 50), p95: percentile(t.bm25, 95) }, + writeMs: { p50: percentile(t.write, 50), p95: percentile(t.write, 95) }, + readMs: { p50: percentile(t.read, 50), p95: percentile(t.read, 95) }, + embedPerSec: embedder ? Math.round(N / embedSec) : null, + rssMB: peakRss, + }, +}; +mkdirSync(path.join(__dirname, "results"), { recursive: true }); +const file = path.join(__dirname, "results", `bench-${model}.json`); +writeFileSync(file, JSON.stringify(out, null, 2)); +console.log(`\nresults: ${path.relative(process.cwd(), file)}`); diff --git a/benchmarks/golden.js b/benchmarks/golden.js new file mode 100644 index 0000000..270d0cf --- /dev/null +++ b/benchmarks/golden.js @@ -0,0 +1,110 @@ +#!/usr/bin/env node +/** + * Golden-set benchmark: bilingual (PT-BR/EN) agent-curated memories, the + * workload this server is built for. Memories are written through the real + * write path and queried through the real search path. + * + * Usage: + * node benchmarks/golden.js [--model granite-97m-multilingual] [--modes hybrid,bm25,semantic] + */ + +import { mkdirSync, readFileSync, writeFileSync } from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; +import { MemoryStore } from "../src/store/memory-store.js"; +import { createEmbedder, DEFAULT_MODEL } from "../src/embeddings.js"; +import { withCache } from "./lib/cached-embedder.js"; +import { recallAny, recallAll, reciprocalRank, ndcgAny, mean } from "./lib/metrics.js"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const DAY = 86_400_000; + +function parseArgs(argv) { + const opts = { model: process.env.AGENT_MEMORY_MODEL || DEFAULT_MODEL, modes: null }; + for (let i = 0; i < argv.length; i++) { + if (argv[i] === "--model") opts.model = argv[++i]; + else if (argv[i] === "--modes") opts.modes = argv[++i].split(","); + else throw new Error(`Unknown argument ${argv[i]}`); + } + opts.modes ??= opts.model === "none" ? ["bm25"] : ["hybrid", "bm25", "semantic"]; + return opts; +} + +const opts = parseArgs(process.argv.slice(2)); +const data = JSON.parse(readFileSync(path.join(__dirname, "golden", "dataset.json"), "utf8")); +const embedder = withCache(createEmbedder(opts.model)); +if (embedder && !(await embedder.load())) throw new Error(`Model ${opts.model} failed to load`); + +const NOW = Date.parse("2026-06-01T12:00:00Z"); +let now = NOW; +const store = MemoryStore.open(":memory:", { embedder, clock: () => now }); + +// Oldest first, through the production write path. +const memories = [...data.memories].sort((a, b) => b.created_days_ago - a.created_days_ago); +for (const m of memories) { + now = NOW - m.created_days_ago * DAY; + await store.write({ id: m.id, topic: m.topic, content: m.content, tags: m.tags, agent: m.agent, importance: m.importance }); +} +now = NOW; +await store.flushEmbeddings(); + +const langOf = new Map(data.memories.map((m) => [m.id, m.lang])); +const rows = []; +for (const q of data.queries) { + const gold = new Set(q.relevant); + const row = { id: q.id, type: q.type, lang: q.lang, targetLang: langOf.get(q.relevant[0]), metrics: {} }; + for (const mode of opts.modes) { + const { results } = await store.search({ query: q.query, limit: 10, mode, tags: q.filters?.tags, agent: q.filters?.agent }); + const ranked = results.map((r) => r.id); + row.metrics[mode] = { + "recall_any@5": recallAny(ranked, gold, 5), + "recall_all@5": recallAll(ranked, gold, 5), + "recall_any@1": recallAny(ranked, gold, 1), + mrr: reciprocalRank(ranked, gold), + "ndcg@10": ndcgAny(ranked, gold, gold.size, 10), + }; + if (mode === opts.modes[0]) row.top = ranked.slice(0, 5); + } + rows.push(row); +} +store.close(); + +function summarize(subset, mode) { + const keys = Object.keys(subset[0].metrics[mode]); + return Object.fromEntries(keys.map((k) => [k, mean(subset.map((r) => r.metrics[mode][k]))])); +} +const pct = (v) => `${(v * 100).toFixed(1)}%`.padStart(7); + +console.log(`Golden set v${data.version}: ${data.memories.length} memories, ${data.queries.length} queries · model ${embedder?.id ?? "none"}\n`); +console.log("mode | Hit@1 | R_any@5 | R_all@5 | MRR | NDCG@10"); +console.log("----------|---------|---------|---------|-------|--------"); +const overall = {}; +for (const mode of opts.modes) { + const s = (overall[mode] = summarize(rows, mode)); + console.log(`${mode.padEnd(9)} | ${pct(s["recall_any@1"])} | ${pct(s["recall_any@5"])} | ${pct(s["recall_all@5"])} | ${s.mrr.toFixed(3)} | ${s["ndcg@10"].toFixed(3)}`); +} + +const groups = {}; +const addGroup = (name, subset) => { + if (!subset.length) return; + groups[name] = { n: subset.length, ...Object.fromEntries(opts.modes.map((m) => [m, summarize(subset, m)])) }; +}; +for (const type of [...new Set(rows.map((r) => r.type))].sort()) addGroup(`type:${type}`, rows.filter((r) => r.type === type)); +addGroup("lang:pt→pt", rows.filter((r) => r.lang === "pt" && r.targetLang === "pt")); +addGroup("lang:en→en", rows.filter((r) => r.lang === "en" && r.targetLang === "en")); +addGroup("lang:pt→en", rows.filter((r) => r.lang === "pt" && r.targetLang === "en")); +addGroup("lang:en→pt", rows.filter((r) => r.lang === "en" && r.targetLang === "pt")); + +console.log(`\nMRR by group (${opts.modes.join(" / ")}):`); +for (const [name, g] of Object.entries(groups)) { + console.log(` ${name.padEnd(20)} n=${String(g.n).padStart(3)} ${opts.modes.map((m) => g[m].mrr.toFixed(3)).join(" ")}`); +} + +const outDir = path.join(__dirname, "results"); +mkdirSync(outDir, { recursive: true }); +const outFile = path.join(outDir, `golden-${opts.model}.json`); +writeFileSync( + outFile, + JSON.stringify({ meta: { dataset: `golden v${data.version}`, model: embedder?.id ?? null, node: process.version, date: new Date().toISOString() }, overall, groups, perQuery: rows }, null, 1), +); +console.log(`\nresults: ${path.relative(process.cwd(), outFile)}`); diff --git a/benchmarks/golden/dataset.json b/benchmarks/golden/dataset.json new file mode 100644 index 0000000..b720760 --- /dev/null +++ b/benchmarks/golden/dataset.json @@ -0,0 +1,3188 @@ +{ + "version": 1, + "description": "Hand-authored retrieval evaluation set for agent-memory-store, modeled on a fictional Brazilian fintech/e-commerce team ('Pagaí') whose AI agents (pm, backend, frontend, infra, data, qa, security) write short memories in a mix of Brazilian Portuguese and English. The 150 memories span auth, PIX/payments, database, deploy/infra, CI, observability, frontend, mobile, data pipelines, testing, incident postmortems, product decisions, coding conventions, vendor quirks and process, with invented concrete specifics (versions, limits, paths, service names). The set deliberately contains confusable near-miss groups (e.g. two Redis instances with different eviction policies, charge vs refund PIX webhook timeouts, staging vs production deploys, day vs night PIX limits, inbound vs outbound webhooks) and 12 knowledge-update pairs where a newer memory explicitly supersedes an older one; for 'update' queries only the newer memory is relevant. The 120 queries were written as an agent would ask before a task and avoid reusing memory topics verbatim: cross_lingual queries are in the other language from their target, paraphrase queries reword with synonyms to minimize lexical overlap, keyword queries use exact identifiers, filter queries carry tag/agent filters needed to disambiguate, and multi_hop queries require 2–3 memories. created_days_ago is relative to dataset creation; no real secrets or real companies other than common technologies are referenced.", + "memories": [ + { + "id": "m001", + "topic": "Auth — JWT RS256 instead of server sessions", + "content": "Decided to issue JWT access tokens signed with RS256, private key in AWS KMS (alias pagai-auth-signing). Server-side sessions were rejected because the mobile app and 4 internal services must validate tokens without calling auth-svc on every request. Public keys are exposed at /.well-known/jwks.json.", + "tags": [ + "auth", + "jwt", + "decision" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 210 + }, + { + "id": "m002", + "topic": "Auth — rotação de refresh token", + "content": "Refresh tokens agora são rotacionados a cada uso (rotate-on-use) e guardados só como hash SHA-256 na tabela auth.refresh_tokens, TTL de 30 dias. Se um refresh token já usado for reapresentado, revogamos a família inteira de tokens daquele dispositivo — é o nosso sinal de roubo de token.", + "tags": [ + "auth", + "tokens" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 180 + }, + { + "id": "m003", + "topic": "Auth — validade do access token", + "content": "Access tokens JWT valem 60 minutos; o app renova via refresh token quando falta 1 min para expirar. Valor escolhido para reduzir chamadas ao auth-svc no horário de pico.", + "tags": [ + "auth", + "jwt", + "tokens" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 260 + }, + { + "id": "m004", + "topic": "Auth — access token TTL cut to 15 minutes", + "content": "Access token lifetime reduced from 60 to 15 minutes following the July pentest recommendation; clients refresh proactively at 80% of the TTL. This replaces the earlier 60-minute setting. Config: AUTH_ACCESS_TTL_SECONDS=900 in auth-svc.", + "tags": [ + "auth", + "jwt", + "tokens" + ], + "agent": "security-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 70 + }, + { + "id": "m005", + "topic": "Backoffice — TOTP MFA mandatory", + "content": "All backoffice users (admin.pagai.internal) must enroll TOTP MFA. SMS as a second factor was rejected due to SIM-swap risk. Enforcement lives in the auth-svc middleware requireMfa() in src/middleware/mfa.ts; there is no bypass flag, not even for staging.", + "tags": [ + "security", + "auth", + "mfa" + ], + "agent": "security-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 150 + }, + { + "id": "m006", + "topic": "Login — bloqueio por tentativas erradas", + "content": "Após 5 tentativas de senha errada em 10 minutos, a conta do cliente fica bloqueada por 30 minutos e enviamos e-mail de alerta. O contador fica no Redis com chave login_fail:{user_id} e expira sozinho.", + "tags": [ + "security", + "auth" + ], + "agent": "security-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 140 + }, + { + "id": "m007", + "topic": "Merchant dashboard — Google OIDC login", + "content": "The merchant dashboard supports 'Sign in with Google' via OIDC with PKCE. The consumer app does NOT — consumers only use CPF + password + device binding. Callback is /auth/oidc/callback; the state/nonce pair is stored in Redis for 5 minutes.", + "tags": [ + "auth", + "oauth", + "merchants" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 120 + }, + { + "id": "m008", + "topic": "Cache de configuração de lojistas no Redis", + "content": "O Redis cache-merchant (ElastiCache r6g.large) guarda a configuração dos lojistas com TTL de 10 min. Política de eviction allkeys-lru, porque tudo ali pode ser recomputado do Postgres; se encher, as chaves menos usadas são descartadas sem erro.", + "tags": [ + "redis", + "cache" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 200 + }, + { + "id": "m009", + "topic": "Rate limiting — dedicated Redis instance", + "content": "Rate limiting uses a dedicated Redis (redis-ratelimit, t4g.medium) with maxmemory-policy noeviction: we never want counters silently dropped, writes fail loudly instead. Sliding window implemented with sorted sets in lib/ratelimit/sliding.ts.", + "tags": [ + "redis", + "ratelimit" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 170 + }, + { + "id": "m010", + "topic": "API pública — limites de requisição por chave", + "content": "API pública de lojistas: 100 req/s por API key, burst de 200. Endpoints de criação de cobrança PIX têm limite próprio de 20 req/s. Quando excede, devolvemos HTTP 429 com header Retry-After em segundos.", + "tags": [ + "api", + "ratelimit" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 160 + }, + { + "id": "m011", + "topic": "Charges — idempotency keys persisted in Postgres", + "content": "Idempotency-Key values for POST /v1/charges are persisted in Postgres (payments.idempotency_keys, 24h retention), not Redis, because they must survive a Redis failover. Same key with a different request body returns 422 IDEMPOTENCY_MISMATCH.", + "tags": [ + "payments", + "idempotency" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 130 + }, + { + "id": "m012", + "topic": "PIX — webhook de confirmação de cobrança", + "content": "O webhook de confirmação de cobrança PIX (pix-charge-webhook) tem timeout de 5s para responder ao PSP. Se o processamento passar disso, publicamos no Kafka (tópico pix.charge.confirmed) e respondemos 200 na hora; o crédito é feito pelo consumer.", + "tags": [ + "pix", + "webhook" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 150 + }, + { + "id": "m013", + "topic": "PIX — webhook de devolução", + "content": "O fluxo de devolução usa timeout de 15s no pix-refund-webhook, porque precisamos consultar o ledger antes de confirmar. Retries do PSP: 3 tentativas com backoff de 1, 5 e 30 min. Não reaproveitar o handler da cobrança.", + "tags": [ + "pix", + "refund", + "webhook" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 110 + }, + { + "id": "m014", + "topic": "PIX — dynamic QR code expiration", + "content": "Dynamic PIX QR codes (cobv) expire after 30 minutes by default; merchants can override between 5 minutes and 24 hours via the expiresIn field. Static QR codes never expire and carry no amount lock.", + "tags": [ + "pix", + "qrcode" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 140 + }, + { + "id": "m015", + "topic": "PayBridge quirk — 200 on duplicate txid", + "content": "PayBridge's PUT /cob/{txid} returns 200 with the ORIGINAL charge body when the txid already exists, instead of 409. Always compare amount and expiresAt in the response; on mismatch raise PIX_TXID_CONFLICT and generate a new txid.", + "tags": [ + "vendor", + "pix", + "paybridge" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 100 + }, + { + "id": "m016", + "topic": "PIX — geração do txid", + "content": "txid é gerado como ULID sem hífens (26 caracteres) com prefixo 'PG', total de 28 caracteres — o limite do BACEN é 35. Gerado em src/pix/txid.ts; nunca reutilizar txid entre tentativas.", + "tags": [ + "pix", + "conventions" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 190 + }, + { + "id": "m017", + "topic": "PIX — conciliação diária com o PSP", + "content": "O job pix-recon roda às 03:15 BRT, compara o extrato do PSP com o ledger e grava divergências em recon.pix_mismatches. Divergência acima de R$ 1.000 abre alerta P2 no canal #fin-ops.", + "tags": [ + "pix", + "reconciliation", + "data" + ], + "agent": "data-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 90 + }, + { + "id": "m018", + "topic": "PIX — refund eligibility window", + "content": "PIX refunds are allowed up to 90 days after the original payment, per BACEN rules; older ones are rejected with REFUND_WINDOW_EXPIRED. Partial refunds are allowed, max 10 per original transaction, and their sum can't exceed the original amount.", + "tags": [ + "pix", + "refund" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 125 + }, + { + "id": "m019", + "topic": "PIX — PSP único PayBridge", + "content": "Toda cobrança e liquidação PIX passa pelo PayBridge, sem PSP secundário. Escolhido por custo (R$ 0,03 por transação) e por ser o único com API de cobv pronta. Integração em src/pix/paybridge/.", + "tags": [ + "pix", + "psp", + "paybridge" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 330 + }, + { + "id": "m020", + "topic": "PIX — dual PSP routing with Kobalt failover", + "content": "PIX now routes through PayBridge as primary and Kobalt Pay as automatic failover when PayBridge's error rate exceeds 5% over 2 minutes. This supersedes the earlier single-PSP (PayBridge only) decision. The router lives in src/pix/psp-router.ts.", + "tags": [ + "pix", + "psp", + "kobalt" + ], + "agent": "backend-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 45 + }, + { + "id": "m021", + "topic": "Cards — tokenization through CardVault", + "content": "Raw PANs never touch our services: the web/mobile SDK tokenizes directly against the CardVault provider and we only store the token, last4 and BIN. This keeps us in PCI SAQ A-EP scope; any change here needs security-agent review.", + "tags": [ + "payments", + "card", + "pci" + ], + "agent": "backend-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 220 + }, + { + "id": "m022", + "topic": "Convenção — dinheiro como inteiro", + "content": "Todo valor monetário é inteiro em centavos (BIGINT, campo amount_cents). Nunca usar float nem decimal no código de aplicação. Formatação para R$ só no frontend, via formatBRL().", + "tags": [ + "conventions", + "payments", + "money" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 280 + }, + { + "id": "m023", + "topic": "Boleto — vencimento e pagamento após o prazo", + "content": "Boletos são gerados com vencimento padrão de 3 dias úteis. Depois de vencido, o banco emissor ainda aceita pagamento por até 30 dias com multa de 2% e juros de 1% a.m.; após isso o boleto é baixado.", + "tags": [ + "boleto", + "payments" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 170 + }, + { + "id": "m024", + "topic": "Chargebacks — dispute response SLA", + "content": "Card chargeback disputes must be answered within 7 calendar days of the acquirer's notification. backend-agent opens a ticket in the DISPUTES queue and data-agent attaches delivery evidence from orders.shipments.", + "tags": [ + "payments", + "chargeback" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 115 + }, + { + "id": "m025", + "topic": "DB migrations — pre-deploy Kubernetes Job", + "content": "Production DB migrations run as a Kubernetes Job (migrate-job) before new pods roll out, using node-pg-migrate. Migrations must be backward compatible with the previous app version (expand/contract). Never run migrations from a laptop.", + "tags": [ + "database", + "migrations", + "deploy" + ], + "agent": "backend-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 160 + }, + { + "id": "m026", + "topic": "Postgres — índices em tabelas grandes", + "content": "Toda criação de índice em tabela com mais de 1M de linhas deve usar CREATE INDEX CONCURRENTLY numa migration separada com disableTransaction. Em março/2026 um índice criado sem isso travou a tabela orders por 4 minutos.", + "tags": [ + "database", + "postgres", + "migrations" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 130 + }, + { + "id": "m027", + "topic": "Postgres — main cluster on RDS 13", + "content": "Main database pagai-main runs on Amazon RDS for PostgreSQL 13.7, db.r5.xlarge Multi-AZ, 1 TB gp3. Good enough for current volume; revisit when we pass 5k TPS.", + "tags": [ + "database", + "postgres", + "infra" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 400 + }, + { + "id": "m028", + "topic": "Postgres — upgrade para Aurora PostgreSQL 16", + "content": "Migramos o cluster principal pagai-main de RDS Postgres 13 para Aurora PostgreSQL 16.2 (db.r7g.2xlarge, 1 writer + 2 readers). A decisão anterior de RDS 13 está obsoleta. Upgrade feito via blue/green com 40s de indisponibilidade.", + "tags": [ + "database", + "postgres", + "infra" + ], + "agent": "infra-agent", + "importance": "critical", + "lang": "pt", + "created_days_ago": 60 + }, + { + "id": "m029", + "topic": "Postgres — pooling com PgBouncer", + "content": "Todos os serviços conectam via PgBouncer em modo transaction (pgbouncer.pagai.internal:6432), pool_size 40 por serviço. Por isso não usar prepared statements nomeados nem SET de sessão, porque a conexão física muda entre transações.", + "tags": [ + "database", + "postgres", + "pgbouncer" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 150 + }, + { + "id": "m030", + "topic": "DB — when to use read replicas", + "content": "Read-only endpoints (statements, reports) may use the reader endpoint via the db.replica() helper. Replica lag can reach 2–3 s at peak, so never read-your-own-write from the replica right after creating a payment.", + "tags": [ + "database", + "replicas" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 55 + }, + { + "id": "m031", + "topic": "Backups do banco — retenção", + "content": "Snapshots automáticos do Aurora ficam 35 dias. Um snapshot mensal é copiado para a conta AWS pagai-backup (sa-east-1 → us-east-1) e retido por 5 anos por exigência regulatória.", + "tags": [ + "backup", + "database", + "compliance" + ], + "agent": "data-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 75 + }, + { + "id": "m032", + "topic": "Soft delete vs LGPD erasure", + "content": "Tables with customer data use soft delete (deleted_at timestamptz) EXCEPT when an LGPD erasure request applies: then PII columns are hard-deleted and an anonymized row is kept for accounting. See docs/adr/0021-lgpd-erasure.md.", + "tags": [ + "database", + "conventions", + "lgpd" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 240 + }, + { + "id": "m033", + "topic": "Deploy de produção — ArgoCD com aprovação", + "content": "Deploy em produção é feito pelo ArgoCD (app pagai-prod) com sync manual: precisa de aprovação de uma pessoa do on-call no Slack #deploys. Janela bloqueada na sexta após 16h e em véspera de feriado.", + "tags": [ + "deploy", + "production", + "argocd" + ], + "agent": "infra-agent", + "importance": "critical", + "lang": "pt", + "created_days_ago": 140 + }, + { + "id": "m034", + "topic": "Staging — auto-sync a cada merge", + "content": "Staging (pagai-staging) faz auto-sync no ArgoCD a cada merge na main; a tag da imagem é o SHA curto do commit. O banco de staging é resetado com dados sintéticos todo domingo às 02:00.", + "tags": [ + "deploy", + "staging", + "argocd" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 140 + }, + { + "id": "m035", + "topic": "Production rollouts — canary steps", + "content": "Production rollouts use Argo Rollouts canary: 5% → 25% → 50% → 100% with 10-minute pauses. Auto-abort if the 5xx rate goes above 1% or p99 latency above 800 ms (AnalysisTemplate http-health).", + "tags": [ + "deploy", + "canary", + "production" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 120 + }, + { + "id": "m036", + "topic": "Rolling back a bad release", + "content": "To roll back prod, run 'argo rollouts undo pagai-api -n prod' or click Rollback in ArgoCD. Do NOT revert the git commit first or ArgoCD will fight you. DB migrations are never rolled back automatically.", + "tags": [ + "deploy", + "rollback" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 100 + }, + { + "id": "m037", + "topic": "Kubernetes — clusters EKS", + "content": "Clusters EKS: pagai-prod (Kubernetes 1.30) e pagai-nonprod (1.31, staging + dev). Nós gerenciados pelo Karpenter, com consolidação ligada. Upgrade de versão sempre começa pelo nonprod e espera 2 semanas.", + "tags": [ + "k8s", + "infra" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 85 + }, + { + "id": "m038", + "topic": "Terraform — remote state and locking", + "content": "Terraform state lives in S3 bucket pagai-tfstate (versioned) with DynamoDB lock table tf-locks; one state per stack under infra/stacks/*. Never use -target in prod without a second reviewer.", + "tags": [ + "terraform", + "infra" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 200 + }, + { + "id": "m039", + "topic": "AWS — região principal e DR", + "content": "Região principal sa-east-1 (São Paulo). DR em warm standby em us-east-1 com RPO de 15 min e RTO de 2h. Teste de DR é semestral; o último foi em agosto/2026 e levou 1h40.", + "tags": [ + "aws", + "dr", + "infra" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 65 + }, + { + "id": "m040", + "topic": "Secrets — AWS Secrets Manager + External Secrets", + "content": "App secrets are stored in AWS Secrets Manager under /pagai/{env}/{service}/ and synced into Kubernetes by External Secrets Operator every 1h. Never put secrets in Helm values or committed .env files.", + "tags": [ + "secrets", + "security", + "infra" + ], + "agent": "infra-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 180 + }, + { + "id": "m041", + "topic": "CloudFront — assets do web app", + "content": "Assets estáticos do web app são servidos via CloudFront (distribuição E2PAGAIWEB) com cache de 1 ano para arquivos com hash no nome e no-cache para o index.html.", + "tags": [ + "cdn", + "frontend", + "infra" + ], + "agent": "infra-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 160 + }, + { + "id": "m042", + "topic": "DNS — domínios internos e públicos", + "content": "Serviços internos resolvem em *.pagai.internal via zona privada do Route53; APIs públicas ficam em api.pagai.com.br. Não fixar IPs no código: os IPs do NLB mudam quando ele é recriado.", + "tags": [ + "dns", + "infra" + ], + "agent": "infra-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 230 + }, + { + "id": "m043", + "topic": "Kafka — nomes de tópicos", + "content": "Tópicos seguem .., ex.: orders.order.created, pix.charge.confirmed. Partições padrão 12, retenção 7 dias; tópicos de ledger são compacted com retenção infinita.", + "tags": [ + "kafka", + "conventions" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 210 + }, + { + "id": "m044", + "topic": "Kafka consumers — retries and DLQ", + "content": "Consumers retry 3 times in-process with exponential backoff (200 ms base), then publish the message to .dlq. DLQ messages are replayed manually with scripts/kafka/replay-dlq.ts after the root cause is fixed.", + "tags": [ + "kafka", + "dlq", + "retries" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 95 + }, + { + "id": "m045", + "topic": "Kafka — cluster MSK", + "content": "Kafka roda no Amazon MSK 3.6 (3 brokers kafka.m7g.large, multi-AZ). O Schema Registry é o Glue Schema Registry com compatibilidade BACKWARD; schemas Avro em contracts/avro/.", + "tags": [ + "kafka", + "infra" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 175 + }, + { + "id": "m046", + "topic": "CI — self-hosted GitHub Actions runners", + "content": "CI runs on GitHub Actions with self-hosted runners on EKS (actions-runner-controller); builds use the label pagai-ci-large. Hosted runners are only used for the docs site. Average pipeline time is 11 minutes.", + "tags": [ + "ci", + "github-actions" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 130 + }, + { + "id": "m047", + "topic": "CI — quarentena de testes instáveis", + "content": "Teste marcado como flaky vai para quarentena com a tag @quarantine e deixa de bloquear o merge; tem 14 dias para ser corrigido, senão é apagado. A lista fica em test/quarantine.json.", + "tags": [ + "ci", + "testing", + "flaky" + ], + "agent": "qa-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 70 + }, + { + "id": "m048", + "topic": "CI — gate de cobertura de 70%", + "content": "O job de testes falha o PR se a cobertura de linhas do pacote alterado ficar abaixo de 70% (medida pelo c8). Exceções só com a label coverage-waiver aprovada pelo tech lead.", + "tags": [ + "ci", + "testing", + "coverage" + ], + "agent": "qa-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 250 + }, + { + "id": "m049", + "topic": "CI — diff coverage gate", + "content": "We replaced the 70% package line-coverage gate with an 80% diff-coverage gate: only lines touched by the PR count, enforced by diff-cover in the test job. Overall coverage is now report-only. This supersedes the old 70% rule and the coverage-waiver label.", + "tags": [ + "ci", + "testing", + "coverage" + ], + "agent": "qa-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 40 + }, + { + "id": "m050", + "topic": "CI — cache de build das imagens", + "content": "Builds Docker usam BuildKit com cache em registry no ECR (repo pagai/cache). Imagem base node:22.11-alpine fixada por digest; o Renovate atualiza toda semana. Isso derrubou o build de 9 para 3 min.", + "tags": [ + "ci", + "docker" + ], + "agent": "infra-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 145 + }, + { + "id": "m051", + "topic": "Git — proteção da branch main", + "content": "A main exige CI verde (jobs lint, test, build e sast) e branch atualizada antes do merge. Merge só via squash. Force-push bloqueado para todos, inclusive admins.", + "tags": [ + "ci", + "git", + "process" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 190 + }, + { + "id": "m052", + "topic": "Tracing — OpenTelemetry to Tempo", + "content": "All Node services use @opentelemetry/sdk-node with auto-instrumentation; traces go to Grafana Tempo via the otel-collector DaemonSet. Sampling: 10% head-based, plus 100% of errored traces via tail sampling.", + "tags": [ + "observability", + "tracing" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 110 + }, + { + "id": "m053", + "topic": "Logs — formato e campos obrigatórios", + "content": "Logs em JSON via pino com campos obrigatórios: service, env, trace_id, request_id e user_id (hash). Proibido logar CPF, PAN, chave PIX completa ou token. Retenção no Loki: 30 dias.", + "tags": [ + "logging", + "observability", + "lgpd" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 165 + }, + { + "id": "m054", + "topic": "Alerting — PagerDuty routing", + "content": "Alerts with severity=critical page the on-call through PagerDuty service PAGAI-CORE; severity=warning only posts to #alerts. Alertmanager config lives in infra/monitoring/alertmanager.yaml.", + "tags": [ + "alerting", + "oncall" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 100 + }, + { + "id": "m055", + "topic": "SLO — API de pagamentos", + "content": "SLO da API de pagamentos: 99,95% de disponibilidade mensal e p99 abaixo de 600 ms em POST /v1/charges. Error budget queimando 2x mais rápido que o normal em 1h dispara alerta crítico.", + "tags": [ + "slo", + "observability", + "payments" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 80 + }, + { + "id": "m056", + "topic": "Métricas de negócio no Metabase", + "content": "KPIs de negócio (GMV, taxa de aprovação, conversão de PIX) ficam na coleção 'Pagaí KPIs' do Metabase, lendo do ambiente analítico e nunca do Postgres de produção. Atualização a cada 1h.", + "tags": [ + "analytics", + "dashboards" + ], + "agent": "data-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 150 + }, + { + "id": "m057", + "topic": "Web app — stack", + "content": "Web app (apps/web) em Next.js 15 com App Router, React 19, TanStack Query para dados de servidor e Zustand só para estado de UI. Não usar Redux em código novo; o legado em apps/web/src/store/ está congelado.", + "tags": [ + "frontend", + "nextjs" + ], + "agent": "frontend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 200 + }, + { + "id": "m058", + "topic": "Frontend — styling approach", + "content": "Components are styled with styled-components v5 using the shared theme in apps/web/src/theme.ts; no global CSS except the reset. Chosen for colocated styles and easy theming.", + "tags": [ + "frontend", + "css" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 310 + }, + { + "id": "m059", + "topic": "Frontend — Tailwind CSS 4 no lugar de styled-components", + "content": "Abandonamos styled-components por incompatibilidade com React Server Components e custo de runtime; todo componente novo usa Tailwind CSS 4 com tokens em packages/ui/tokens.css. Componentes antigos migram quando forem tocados. Substitui a decisão anterior.", + "tags": [ + "frontend", + "css", + "decision" + ], + "agent": "frontend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 50 + }, + { + "id": "m060", + "topic": "Forms — shared zod schemas", + "content": "Forms use react-hook-form + zod schemas shared with the backend from packages/contracts. CPF/CNPJ checks use validateTaxId() in packages/contracts/src/br.ts — never write a custom regex for tax IDs.", + "tags": [ + "frontend", + "forms", + "validation" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 140 + }, + { + "id": "m061", + "topic": "Feature flags com Unleash", + "content": "Feature flags via Unleash (unleash.pagai.internal). No front, usar o hook useFlag('nome-da-flag'); flags temporárias precisam de dono e data de remoção no campo description, senão o lint de flags reclama.", + "tags": [ + "frontend", + "feature-flags" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 120 + }, + { + "id": "m062", + "topic": "Frontend — internacionalização", + "content": "Web e mobile são só pt-BR por enquanto, mas toda string passa pelos arquivos do next-intl (messages/pt-BR.json) para que adicionar es-AR depois seja barato. Nunca deixar texto de usuário hardcoded no JSX.", + "tags": [ + "frontend", + "i18n" + ], + "agent": "frontend-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 260 + }, + { + "id": "m063", + "topic": "Acessibilidade — meta WCAG", + "content": "Meta: WCAG 2.1 AA no checkout e no onboarding. axe-core roda dentro do Playwright em toda PR; contraste mínimo 4.5:1 e todo input precisa de label associado.", + "tags": [ + "frontend", + "a11y" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 90 + }, + { + "id": "m064", + "topic": "Checkout — waiting for PIX confirmation", + "content": "Web checkout polls GET /v1/charges/{id} every 3 s for up to 10 minutes while showing the PIX QR code, then switches to 'aguardando confirmação'. We tried SSE, but some merchants' corporate proxies killed long-lived connections.", + "tags": [ + "frontend", + "pix", + "checkout" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 85 + }, + { + "id": "m065", + "topic": "App mobile — React Native + Expo", + "content": "App do consumidor (apps/mobile) é React Native 0.76 com Expo SDK 52 e EAS Build. Atualizações OTA via EAS Update só para mudanças de JS; qualquer mudança nativa exige nova versão nas lojas.", + "tags": [ + "mobile", + "react-native" + ], + "agent": "frontend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 180 + }, + { + "id": "m066", + "topic": "Mobile — minimum OS versions", + "content": "Minimum supported versions: Android 9 (API 28) and iOS 15. Dropping older versions cut about 1.8% of MAU; approved by PM in July.", + "tags": [ + "mobile", + "compatibility" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 95 + }, + { + "id": "m067", + "topic": "App — vínculo de dispositivo e root", + "content": "Login no app vincula o dispositivo (device_id + chave no Secure Enclave/Keystore). Em aparelho com root ou jailbreak detectado, PIX acima de R$ 200 é bloqueado e o app fica só em modo consulta.", + "tags": [ + "mobile", + "security", + "pix" + ], + "agent": "security-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 130 + }, + { + "id": "m068", + "topic": "Push notifications — priorities and caps", + "content": "Push notifications are sent by notify-svc through Expo Push for both platforms. Transactional pushes (PIX received) use priority high; marketing pushes go through a separate queue capped at 1 per user per day.", + "tags": [ + "mobile", + "push", + "notifications" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 110 + }, + { + "id": "m069", + "topic": "Mobile — biweekly store releases", + "content": "The consumer app ships to the App Store and Play Store every other Thursday; the release branch is cut on Monday of release week. Out-of-band hotfixes only for SEV1/SEV2.", + "tags": [ + "mobile", + "release" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 280 + }, + { + "id": "m070", + "topic": "App — release semanal nas lojas", + "content": "A partir de setembro o app vai para as lojas toda terça (release semanal), substituindo a cadência quinzenal. Corte da branch release/* na segunda às 18h e rollout gradual 10% → 50% → 100% na Play Store.", + "tags": [ + "mobile", + "release" + ], + "agent": "frontend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 30 + }, + { + "id": "m071", + "topic": "Data — warehouse no Redshift", + "content": "Warehouse analítico em Amazon Redshift (2 nós ra3.xlplus); cargas diárias via COPY a partir do S3 às 04:00. O Metabase conecta direto no Redshift.", + "tags": [ + "data", + "warehouse" + ], + "agent": "data-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 360 + }, + { + "id": "m072", + "topic": "Analytics — Iceberg lakehouse queried with Trino", + "content": "Redshift was decommissioned in June 2026. Analytics tables now live as Apache Iceberg on s3://pagai-lake and are queried through Trino (trino.pagai.internal:8443); Metabase was repointed to Trino. This replaces the Redshift warehouse decision.", + "tags": [ + "data", + "warehouse", + "trino" + ], + "agent": "data-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 110 + }, + { + "id": "m073", + "topic": "CDC — Debezium on Kafka Connect", + "content": "Change data capture from pagai-main uses Debezium 2.7 on Kafka Connect, publishing to cdc.. topics. It relies on the logical replication slot debezium_main; a stuck connector makes WAL pile up on the writer.", + "tags": [ + "data", + "cdc", + "kafka" + ], + "agent": "data-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 140 + }, + { + "id": "m074", + "topic": "Airflow — convenções de DAG", + "content": "DAGs no Airflow 2.10 (MWAA) ficam em data/dags/. Convenção: um DAG por domínio, schedule em BRT usando pendulum, retries=2 e SLA de 2h para os DAGs de finanças.", + "tags": [ + "data", + "airflow" + ], + "agent": "data-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 160 + }, + { + "id": "m075", + "topic": "Lake — PII tokenization", + "content": "PII columns (cpf, email, phone) are tokenized with HMAC-SHA256 before landing in the lake (key in Secrets Manager at /pagai/prod/data/pii-hmac). Only the fraud team role can detokenize, through the pii-vault API.", + "tags": [ + "data", + "pii", + "lgpd" + ], + "agent": "data-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 120 + }, + { + "id": "m076", + "topic": "Modelo antifraude — features e re-treino", + "content": "O modelo fraud-score v3 (XGBoost) usa 42 features, entre elas velocidade de PIX por CPF em 1h/24h, idade da conta e troca recente de dispositivo. Re-treino mensal; threshold de bloqueio 0,87.", + "tags": [ + "fraud", + "ml", + "data" + ], + "agent": "data-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 60 + }, + { + "id": "m077", + "topic": "dbt — model layers and tests", + "content": "dbt models: staging (stg_), intermediate (int_), marts (fct_/dim_). Every mart needs unique + not_null tests on its primary key and an owner in meta. CI runs dbt build --select state:modified+.", + "tags": [ + "data", + "dbt", + "conventions" + ], + "agent": "data-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 105 + }, + { + "id": "m078", + "topic": "Testes — ferramentas por camada", + "content": "Backend: Vitest para unitário e Testcontainers (Postgres 16 + Redis 7) para integração. Front: Playwright para E2E, com 30 cenários críticos rodando em toda PR; o restante roda no nightly.", + "tags": [ + "testing", + "vitest", + "playwright" + ], + "agent": "qa-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 170 + }, + { + "id": "m079", + "topic": "PSP sandboxes — limitations", + "content": "The PayBridge sandbox never sends refund webhooks and always settles PIX in ~2 s, so refund flows must be tested with our local PSP simulator (tools/psp-sim, port 4010). The Kobalt sandbox does send them but rate-limits at 5 req/s.", + "tags": [ + "testing", + "pix", + "sandbox", + "vendor" + ], + "agent": "qa-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 75 + }, + { + "id": "m080", + "topic": "Testes — CPFs de teste", + "content": "Em testes usar apenas CPFs gerados por generateFakeCpf() (dígito verificador válido, sempre começando com 999). Nunca usar CPF real de funcionário, nem em staging.", + "tags": [ + "testing", + "lgpd" + ], + "agent": "qa-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 210 + }, + { + "id": "m081", + "topic": "Load test — charges baseline", + "content": "k6 load test (tests/load/charges.js) baseline from September: POST /v1/charges sustains 1,200 rps at p99 420 ms on 6 pods. Beyond ~1,500 rps PgBouncer saturates before the app does.", + "tags": [ + "testing", + "performance", + "k6" + ], + "agent": "qa-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 35 + }, + { + "id": "m082", + "topic": "QA — regressão antes do release do app", + "content": "Antes de cada release mobile, o qa-agent roda a suíte de regressão no BrowserStack (Android 9, 13, 15; iOS 15, 17, 18), cerca de 45 min. O release só sai com 0 falhas nos fluxos de PIX e login.", + "tags": [ + "qa", + "mobile", + "release" + ], + "agent": "qa-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 25 + }, + { + "id": "m083", + "topic": "INC-0412 — PIX double credit", + "content": "Incident INC-0412: ~180 customers received PIX credits twice because the charge-confirmed consumer was not idempotent across a Kafka rebalance. Fix: unique constraint on ledger.entries(e2e_id) plus consumer-side dedupe. Duration 47 min.", + "tags": [ + "incident", + "pix", + "postmortem" + ], + "agent": "backend-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 240 + }, + { + "id": "m084", + "topic": "INC-0467 — PgBouncer fora do ar", + "content": "INC-0467: o PgBouncer ficou sem file descriptors (ulimit 1024) no pico do Dia das Mães e derrubou a API por 22 min. Corrigido para ulimit 65536 e criamos alerta quando cl_waiting > 50.", + "tags": [ + "incident", + "pgbouncer", + "postmortem" + ], + "agent": "infra-agent", + "importance": "critical", + "lang": "pt", + "created_days_ago": 150 + }, + { + "id": "m085", + "topic": "INC-0489 — expired certificate on hooks endpoint", + "content": "INC-0489: the TLS certificate for hooks.pagai.com.br expired because it was the only cert not managed by cert-manager. PSP webhooks failed for 3h; the PSP retried, so no money was lost. All certs are now in cert-manager with a 21-day expiry alert.", + "tags": [ + "incident", + "tls", + "postmortem" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 110 + }, + { + "id": "m086", + "topic": "INC-0501 — fila de e-mail travada", + "content": "INC-0501: o worker de e-mail transacional travou por causa de um template Handlebars com loop infinito; 40 mil comprovantes atrasaram 6h. Agora os templates passam por teste de renderização no CI e o worker tem timeout de 10s por mensagem.", + "tags": [ + "incident", + "email", + "postmortem" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 55 + }, + { + "id": "m087", + "topic": "INC-0510 — leaked sandbox credential", + "content": "INC-0510: a contractor committed a PayBridge sandbox API key to a public gist. It was rotated within 20 minutes, no production impact. Follow-up: gitleaks added to pre-commit and to the CI sast job.", + "tags": [ + "incident", + "security", + "secrets" + ], + "agent": "security-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 40 + }, + { + "id": "m088", + "topic": "Roadmap — PIX Parcelado adiado", + "content": "PIX Parcelado ficou fora do roadmap do Q4/2026; a prioridade é PIX Automático (recorrência), que tem prazo regulatório. Revisitar em fevereiro/2027.", + "tags": [ + "product", + "roadmap", + "pix" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 50 + }, + { + "id": "m089", + "topic": "PIX Automático — v1 scope", + "content": "PIX Automático v1: only fixed-amount monthly subscriptions, max R$ 5,000, and the consumer can cancel anytime from the app. Variable amounts and retries outside the payment window are v2.", + "tags": [ + "product", + "pix", + "recurring" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 45 + }, + { + "id": "m090", + "topic": "Precificação — taxa do lojista por PIX", + "content": "Taxa padrão para o lojista: 0,99% por PIX recebido, mínimo R$ 0,05 e teto de R$ 9,90. Lojistas com GMV acima de R$ 1M/mês negociam caso a caso com o comercial.", + "tags": [ + "product", + "pricing", + "pix" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 130 + }, + { + "id": "m091", + "topic": "Pricing — free PIX allowance for new merchants", + "content": "New merchants get their first 100 PIX receipts per month free, with no end date, to compete with banks' free offers. The fee applies from the 101st PIX of the month.", + "tags": [ + "product", + "pricing" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 200 + }, + { + "id": "m092", + "topic": "Precificação — fim da cortesia de 100 PIX", + "content": "A cortesia de 100 PIX grátis por mês para lojistas novos foi descontinuada em out/2026. Agora o lojista novo tem 30 dias de taxa zero e depois paga a taxa padrão. Substitui a regra anterior dos 100 PIX/mês.", + "tags": [ + "product", + "pricing" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 20 + }, + { + "id": "m093", + "topic": "Merchant onboarding — KYC steps", + "content": "Merchant onboarding requires: CNPJ lookup, partner selfie + ID document via the KYC vendor IDCheck, and bank account validation with a R$ 0,01 PIX. Target: approval in under 10 minutes for 80% of merchants.", + "tags": [ + "product", + "onboarding", + "kyc" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 100 + }, + { + "id": "m094", + "topic": "Limite de PIX no período noturno", + "content": "Seguindo regra do BACEN, PIX entre 20h e 6h para pessoa física tem limite padrão de R$ 1.000. O cliente pode pedir aumento pelo app, com efetivação após 24h a 48h.", + "tags": [ + "product", + "pix", + "limits", + "compliance" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 160 + }, + { + "id": "m095", + "topic": "PIX — daytime limits for individuals", + "content": "Default daytime PIX limits (06:00–20:00) for individuals: R$ 5,000 per transaction and R$ 20,000 per day. Increases up to R$ 50,000 take effect immediately for KYC level 2 customers.", + "tags": [ + "product", + "pix", + "limits" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 160 + }, + { + "id": "m096", + "topic": "Checkout — métrica norte", + "content": "North star do checkout: conversão de PIX iniciado → pago, hoje em 78%. Meta do semestre: 85%. A maior perda é QR code que expira sem pagamento.", + "tags": [ + "product", + "metrics", + "checkout" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 65 + }, + { + "id": "m097", + "topic": "API error code format", + "content": "API error codes are UPPER_SNAKE_CASE, prefixed by domain (PIX_, AUTH_, CARD_), returned as {code, message, request_id}. Never reuse a code with a different meaning; the registry is packages/contracts/src/errors.ts.", + "tags": [ + "conventions", + "api", + "errors" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 230 + }, + { + "id": "m098", + "topic": "Backend — estrutura de pastas", + "content": "Serviços Node seguem src/{domain}/{handlers,services,repos}.ts. Regra: handler nunca acessa repo direto, sempre via service. O eslint-plugin-boundaries quebra o build se a regra for violada.", + "tags": [ + "conventions", + "architecture" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 250 + }, + { + "id": "m099", + "topic": "Convenção de mensagens de commit", + "content": "Commits seguem Conventional Commits (feat:, fix:, chore:) com a chave do Jira no escopo, ex.: fix(PAG-1234): corrige arredondamento. O release-please usa isso para gerar changelog e versão.", + "tags": [ + "conventions", + "git" + ], + "agent": "backend-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 270 + }, + { + "id": "m100", + "topic": "Datas — UTC no banco, BRT na borda", + "content": "O banco guarda tudo em timestamptz UTC; conversão para America/Sao_Paulo só na borda (API de extrato e frontend). O cut-off de liquidação é calculado em BRT usando date-fns-tz.", + "tags": [ + "conventions", + "timezone" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 185 + }, + { + "id": "m101", + "topic": "TypeScript — strict settings", + "content": "All packages use TypeScript 5.6 with strict: true and noUncheckedIndexedAccess. 'any' is banned by lint except in *.test.ts files; use unknown plus zod parsing at boundaries.", + "tags": [ + "conventions", + "typescript" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 175 + }, + { + "id": "m102", + "topic": "API pública — versionamento", + "content": "A API pública é versionada no path (/v1, /v2). Mudança breaking só em versão nova; a versão antiga é mantida por 12 meses após o anúncio, com header Sunset nas respostas.", + "tags": [ + "api", + "conventions", + "versioning" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 145 + }, + { + "id": "m103", + "topic": "Splitting amounts into installments", + "content": "When splitting amounts (fees, installments) we round half-up per cent and push the leftover cent(s) to the first installment, so the parts always sum to the total. Use splitCents() from packages/money; never Math.round on floats.", + "tags": [ + "conventions", + "payments", + "money" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 120 + }, + { + "id": "m104", + "topic": "IDCheck — comportamento da API de KYC", + "content": "A API do IDCheck às vezes devolve status PENDING por até 20 min em selfies; não tratar como reprovação. O webhook deles não tem assinatura HMAC, então sempre reconsultar GET /verifications/{id} antes de aprovar o lojista.", + "tags": [ + "vendor", + "kyc", + "idcheck" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 90 + }, + { + "id": "m105", + "topic": "Kobalt Pay — webhook signature check", + "content": "Kobalt signs webhooks with HMAC-SHA512 in header X-Kobalt-Signature, computed over the raw body bytes BEFORE JSON parsing; express.json() breaks verification. Use the rawBody middleware in src/pix/kobalt/webhook.ts.", + "tags": [ + "vendor", + "kobalt", + "webhook" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 40 + }, + { + "id": "m106", + "topic": "PayBridge — mTLS nos webhooks", + "content": "O PayBridge exige mTLS nos webhooks: nosso endpoint hooks.pagai.com.br precisa apresentar certificado cliente emitido pela CA deles, renovado anualmente (o próximo vence em março/2027).", + "tags": [ + "vendor", + "paybridge", + "tls", + "webhook" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 120 + }, + { + "id": "m107", + "topic": "OTP SMS — providers and fallback", + "content": "OTP SMS goes through TextaBR as primary and SMSFlux as fallback after 2 delivery failures within 60 s. TextaBR silently drops messages containing URLs, so OTP texts must never include links.", + "tags": [ + "vendor", + "sms", + "otp" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 135 + }, + { + "id": "m108", + "topic": "Consulta de CNPJ — ReceitaData", + "content": "Consulta de CNPJ via API ReceitaData com cache de 7 dias no Postgres (tabela kyc.cnpj_cache). Limite contratado de 3 req/s; acima disso eles devolvem 429 sem Retry-After, então usamos fila com token bucket.", + "tags": [ + "vendor", + "kyc", + "cnpj" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 80 + }, + { + "id": "m109", + "topic": "Transactional email — Amazon SES limits", + "content": "Transactional email goes through Amazon SES in sa-east-1 with a sending quota of 50 msg/s. Bounce rate must stay under 5% or AWS pauses the account; bounces arrive via SNS topic ses-bounces and feed the suppression list.", + "tags": [ + "email", + "ses", + "aws" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 160 + }, + { + "id": "m110", + "topic": "Plantão — escala e escalonamento", + "content": "On-call semanal, troca na segunda às 10h, com primário e secundário. O primário tem 15 min para dar ack no PagerDuty; depois escala para o secundário e então para o tech lead. Compensação: 1 day-off por semana de plantão.", + "tags": [ + "process", + "oncall" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 140 + }, + { + "id": "m111", + "topic": "Process — two approvals per PR", + "content": "Every pull request needs 2 approvals from engineers of the owning team before merge, regardless of size. Self-approval by agents doesn't count.", + "tags": [ + "process", + "review" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 290 + }, + { + "id": "m112", + "topic": "Review — 1 aprovação de CODEOWNER", + "content": "Mudamos a política de review: basta 1 aprovação, desde que seja de um CODEOWNER do diretório alterado. Mudanças em src/ledger/ e src/pix/ continuam exigindo 2 aprovações. Substitui a regra antiga de 2 aprovações para tudo.", + "tags": [ + "process", + "review" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 35 + }, + { + "id": "m113", + "topic": "Incident severity levels", + "content": "SEV1: money movement broken or data leak — all hands, status page update every 30 min. SEV2: degraded payments or one partner down. SEV3: internal tooling. Blameless postmortem mandatory for SEV1/SEV2 within 5 business days.", + "tags": [ + "process", + "incident" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 200 + }, + { + "id": "m114", + "topic": "Agentes — papéis e responsabilidades", + "content": "pm-agent prioriza o backlog e escreve specs; backend-agent e frontend-agent implementam; qa-agent aprova releases; security-agent revisa toda mudança em auth, pix e secrets antes do merge.", + "tags": [ + "process", + "agents" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 300 + }, + { + "id": "m115", + "topic": "Black Friday change freeze", + "content": "Change freeze from Nov 20 to Dec 2, 2026: only SEV1/SEV2 fixes, each approved by the CTO and the on-call lead. Feature flags may still be toggled during the freeze.", + "tags": [ + "process", + "freeze", + "deploy" + ], + "agent": "pm-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 15 + }, + { + "id": "m116", + "topic": "RFCs para decisões grandes", + "content": "Decisões que afetam mais de um time ou custam mais de US$ 2k/mês exigem RFC em docs/rfcs/ com 5 dias úteis de comentários. Template em docs/rfcs/0000-template.md.", + "tags": [ + "process", + "rfc" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 220 + }, + { + "id": "m117", + "topic": "Dependency vulnerability policy", + "content": "Dependabot plus osv-scanner run in CI. Critical CVEs must be patched within 72h, high within 14 days. Exceptions are tracked in security/exceptions.yaml with an expiry date.", + "tags": [ + "security", + "dependencies" + ], + "agent": "security-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 150 + }, + { + "id": "m118", + "topic": "Criptografia de dados sensíveis em coluna", + "content": "Chave PIX e telefone do cliente são criptografados em nível de coluna com envelope encryption (AWS KMS, chave pagai-pii-cmk) via packages/crypto. O CPF é guardado com hash HMAC para busca e uma versão criptografada.", + "tags": [ + "security", + "encryption", + "lgpd" + ], + "agent": "security-agent", + "importance": "critical", + "lang": "pt", + "created_days_ago": 190 + }, + { + "id": "m119", + "topic": "AWS WAF on the public API", + "content": "AWS WAF in front of api.pagai.com.br: managed rule sets Core + KnownBadInputs, geo-block outside BR/US/PT for the merchant API, and a rate-based rule of 2,000 requests per 5 minutes per IP.", + "tags": [ + "security", + "waf" + ], + "agent": "security-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 105 + }, + { + "id": "m120", + "topic": "Pentest externo de 2026", + "content": "O pentest externo anual, feito em julho/2026, encontrou 2 achados médios: IDOR em GET /v1/statements/{id} e falta de rate limit no reset de senha. Ambos corrigidos em 10 dias.", + "tags": [ + "security", + "pentest" + ], + "agent": "security-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 85 + }, + { + "id": "m121", + "topic": "Senhas — bcrypt", + "content": "Senhas de clientes são guardadas com bcrypt cost 10 (lib bcryptjs). Custo escolhido para manter o login abaixo de 100 ms nos pods atuais.", + "tags": [ + "security", + "passwords" + ], + "agent": "security-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 380 + }, + { + "id": "m122", + "topic": "Password storage — Argon2id", + "content": "New password hashes use Argon2id (m=64 MiB, t=3, p=1) via the argon2 npm package. Legacy bcrypt hashes are rehashed transparently on the next successful login. This replaces the bcrypt cost 10 decision.", + "tags": [ + "security", + "passwords" + ], + "agent": "security-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 90 + }, + { + "id": "m123", + "topic": "CORS policy for the public API", + "content": "The public API allows CORS only from merchant-registered origins (merchants.allowed_origins); the consumer web app is same-origin. Wildcard '*' is forbidden, even in staging.", + "tags": [ + "security", + "cors", + "api" + ], + "agent": "security-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 115 + }, + { + "id": "m124", + "topic": "Ledger — saldo calculado na hora", + "content": "O saldo da conta é calculado com SUM(amount_cents) sobre ledger.entries a cada consulta. Simples e sempre consistente; o volume atual (2M de linhas) não justifica cache.", + "tags": [ + "ledger", + "balance" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 340 + }, + { + "id": "m125", + "topic": "Ledger — balance snapshots", + "content": "Balances are now read from ledger.balance_snapshots, updated in the same transaction as each entry (SELECT ... FOR UPDATE on the account row). Summing entries per request stopped scaling past 40M rows; this replaces the on-the-fly sum. A nightly job checks snapshots against the full sum.", + "tags": [ + "ledger", + "balance" + ], + "agent": "backend-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 25 + }, + { + "id": "m126", + "topic": "Métricas de aplicação no CloudWatch", + "content": "Métricas customizadas dos serviços são enviadas ao CloudWatch via Embedded Metric Format no stdout; dashboards e alarmes ficam no console da AWS, namespace Pagai/App.", + "tags": [ + "observability", + "metrics" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 230 + }, + { + "id": "m127", + "topic": "App metrics — Prometheus + Mimir", + "content": "App metrics are now exposed on /metrics, scraped by the Prometheus agent and stored in Grafana Mimir with 13-month retention; dashboards at grafana.pagai.internal. CloudWatch EMF is deprecated for app metrics (kept only for AWS-managed services). Replaces the CloudWatch setup.", + "tags": [ + "observability", + "metrics" + ], + "agent": "infra-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 30 + }, + { + "id": "m128", + "topic": "Ledger — double-entry invariant", + "content": "Every money movement writes balanced entries in ledger.entries (sum of debits = sum of credits per transaction_id); a DEFERRABLE constraint trigger enforces it at commit. Never UPDATE an entry — corrections are new reversing entries.", + "tags": [ + "ledger", + "accounting" + ], + "agent": "backend-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 260 + }, + { + "id": "m129", + "topic": "Liquidação — prazos por meio de pagamento", + "content": "O lojista recebe PIX em D+0 (saldo disponível na hora) e cartão de crédito em D+30 por padrão, com antecipação opcional a 1,99% a.m. O cut-off diário é às 22h BRT.", + "tags": [ + "settlement", + "payments" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 150 + }, + { + "id": "m130", + "topic": "Outgoing merchant webhooks — retries", + "content": "Outgoing merchant webhooks retry up to 8 times over ~24h (1m, 5m, 15m, 1h, 3h, 6h, 12h, 24h) and are signed with HMAC-SHA256 in X-Pagai-Signature. After the final failure the event shows up in the dashboard for manual resend.", + "tags": [ + "webhook", + "merchants" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 125 + }, + { + "id": "m131", + "topic": "Mapa dos serviços core", + "content": "Serviços core: api-gateway (Kong), auth-svc, payments-svc, pix-svc, ledger-svc, notify-svc e kyc-svc. Comunicação síncrona interna via gRPC; eventos assíncronos via Kafka.", + "tags": [ + "architecture", + "services" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 280 + }, + { + "id": "m132", + "topic": "Kong gateway — plugins and config", + "content": "Kong 3.7 runs the api-gateway with plugins: jwt (RS256 validation using the JWKS from auth-svc), rate-limiting-advanced backed by redis-ratelimit, and correlation-id. Declarative config in infra/kong/kong.yaml, applied with deck sync.", + "tags": [ + "gateway", + "kong", + "infra" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 135 + }, + { + "id": "m133", + "topic": "Custos — orçamento AWS", + "content": "Orçamento AWS de US$ 48k/mês, com alerta no AWS Budgets em 80% e 100%. Maiores custos: Aurora (31%), EKS/EC2 (27%) e MSK (12%). Revisão de custos toda primeira quinta-feira do mês.", + "tags": [ + "aws", + "cost", + "finops" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 60 + }, + { + "id": "m134", + "topic": "Custos — política de instâncias spot", + "content": "Spot só é permitido no pagai-nonprod e nos workers do Airflow; node groups de produção são on-demand, com Compute Savings Plan de 1 ano cobrindo ~70% da carga base.", + "tags": [ + "aws", + "cost", + "k8s" + ], + "agent": "infra-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 90 + }, + { + "id": "m135", + "topic": "Lake — retenção por camada", + "content": "Eventos brutos no lake (camada bronze) ficam 13 meses; camadas silver e gold são mantidas por 5 anos. Dados de clientes com pedido de exclusão LGPD são removidos em até 15 dias pelo job lgpd-erasure.", + "tags": [ + "data", + "retention", + "lgpd" + ], + "agent": "data-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 70 + }, + { + "id": "m136", + "topic": "fraud-score — latency budget and fallback", + "content": "fraud-score inference must answer within 120 ms p99 because it sits in the PIX send path; it is served by a Python FastAPI on 3 c7g.xlarge pods with the model in memory. On timeout we fall back to rules only: fail-open below R$ 500, fail-closed above.", + "tags": [ + "fraud", + "ml", + "latency" + ], + "agent": "data-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 50 + }, + { + "id": "m137", + "topic": "Sandbox para integração dos lojistas", + "content": "Lojistas testam a integração em sandbox.pagai.com.br, que usa o simulador de PSP e nunca move dinheiro real. Chaves de sandbox começam com sk_test_ e as de produção com sk_live_.", + "tags": [ + "sandbox", + "merchants", + "api" + ], + "agent": "qa-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 145 + }, + { + "id": "m138", + "topic": "Checkout bundle size budget", + "content": "The checkout route JS budget is 180 KB gzipped; CI fails through size-limit if it's exceeded. Charting libraries must be lazy-loaded, and we dropped moment.js for date-fns to save ~60 KB.", + "tags": [ + "frontend", + "performance" + ], + "agent": "frontend-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 80 + }, + { + "id": "m139", + "topic": "Design system Ipê", + "content": "O design system interno 'Ipê' fica em packages/ui, documentado no Storybook (storybook.pagai.internal). Componente novo só entra no Ipê depois de review do designer e teste visual com screenshots do Playwright.", + "tags": [ + "frontend", + "design-system" + ], + "agent": "frontend-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 100 + }, + { + "id": "m140", + "topic": "Paginação nas APIs de listagem", + "content": "Endpoints de listagem usam paginação por cursor (?cursor=&limit=, limit máximo 100); o cursor é um base64 opaco de (created_at, id). Paginação por offset é proibida em tabelas com mais de 100 mil linhas.", + "tags": [ + "api", + "conventions", + "pagination" + ], + "agent": "backend-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 190 + }, + { + "id": "m141", + "topic": "Revisão de acessos à produção", + "content": "Revisão trimestral de acessos à AWS e ao banco de produção. Acesso de leitura ao prod é via SSO com sessão de 1h e aprovação no Slack #access-requests. Ninguém tem escrita direta; só pela role de break-glass.", + "tags": [ + "security", + "access", + "aws" + ], + "agent": "security-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 95 + }, + { + "id": "m142", + "topic": "Break-glass role procedure", + "content": "The break-glass IAM role pagai-breakglass requires MFA and two-person approval in #access-requests. Every assume-role fires a critical alert to security-agent and must be justified in the incident channel within 1h.", + "tags": [ + "security", + "access", + "incident" + ], + "agent": "infra-agent", + "importance": "critical", + "lang": "en", + "created_days_ago": 95 + }, + { + "id": "m143", + "topic": "Comprovante de PIX por e-mail e push", + "content": "O comprovante de PIX é enviado por e-mail e push em até 30s após a confirmação (template pix-receipt-v4). O cliente pode desativar o e-mail, mas o push transacional não pode ser desativado.", + "tags": [ + "notifications", + "pix", + "email" + ], + "agent": "backend-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 70 + }, + { + "id": "m144", + "topic": "Contract tests with merchant SDKs", + "content": "Public API contract tests use Pact: the Node and PHP merchant SDKs publish pacts to pact-broker.pagai.internal and payments-svc verifies them in CI. A breaking provider change fails the can-i-deploy step.", + "tags": [ + "testing", + "contracts", + "api" + ], + "agent": "qa-agent", + "importance": "medium", + "lang": "en", + "created_days_ago": 115 + }, + { + "id": "m145", + "topic": "Split de pagamento para marketplaces", + "content": "Split de pagamento lançado em agosto/2026: até 10 recebedores por transação, com a taxa cobrada do recebedor principal. Disponível para cartão e PIX, não para boleto.", + "tags": [ + "product", + "split", + "marketplace" + ], + "agent": "pm-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 55 + }, + { + "id": "m146", + "topic": "PIX Automático — mandate storage", + "content": "PIX Automático mandates are stored in recurring.mandates with the state machine PENDING → ACTIVE → CANCELLED | EXPIRED. Charges are scheduled 2–10 days before the due date per BACEN spec. Code in src/pix/automatico/.", + "tags": [ + "pix", + "recurring" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 30 + }, + { + "id": "m147", + "topic": "Redis — versão e topologia", + "content": "Os Redis gerenciados (cache-merchant e redis-ratelimit) usam ElastiCache Redis OSS 7.1, cluster mode desabilitado, 1 primário + 1 réplica em AZs diferentes e failover automático em ~30s.", + "tags": [ + "redis", + "infra" + ], + "agent": "infra-agent", + "importance": "medium", + "lang": "pt", + "created_days_ago": 120 + }, + { + "id": "m148", + "topic": "Cache HTTP nos endpoints de catálogo", + "content": "GET /v1/banks e GET /v1/mcc-codes respondem com Cache-Control: public, max-age=86400 e ficam cacheados no CloudFront; essas listas mudam no máximo uma vez por mês.", + "tags": [ + "cache", + "api" + ], + "agent": "backend-agent", + "importance": "low", + "lang": "pt", + "created_days_ago": 150 + }, + { + "id": "m149", + "topic": "Antifraude — regras estáticas no envio de PIX", + "content": "Regras estáticas antifraude: PIX acima de R$ 2.000 para chave cadastrada há menos de 24h exige confirmação biométrica; 3 PIX seguidos para a mesma chave nova em 10 min bloqueiam o envio temporariamente.", + "tags": [ + "fraud", + "pix", + "rules" + ], + "agent": "backend-agent", + "importance": "high", + "lang": "pt", + "created_days_ago": 45 + }, + { + "id": "m150", + "topic": "Debezium — heartbeats and slot-lag alert", + "content": "After INC-0498 (replication slot bloat to 80 GB), Debezium emits heartbeats every 10 s via heartbeat.action.query on table cdc.heartbeat, and infra-agent is paged when slot lag exceeds 2 GB.", + "tags": [ + "data", + "cdc", + "alerting" + ], + "agent": "data-agent", + "importance": "high", + "lang": "en", + "created_days_ago": 20 + } + ], + "queries": [ + { + "id": "q001", + "query": "What happens if someone presents a refresh token that was already rotated?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m002" + ] + }, + { + "id": "q002", + "query": "Por que não usamos sessão guardada no servidor para autenticar?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m001" + ] + }, + { + "id": "q003", + "query": "How many wrong password attempts before a customer gets locked out?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m006" + ] + }, + { + "id": "q004", + "query": "Usuários do painel administrativo podem usar SMS como segundo fator?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m005" + ] + }, + { + "id": "q005", + "query": "What happens when the merchant settings cache runs out of memory?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m008" + ] + }, + { + "id": "q006", + "query": "Os contadores de limite de requisições podem sumir se a memória do Redis lotar?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m009" + ] + }, + { + "id": "q007", + "query": "What timeout do we use when the PSP notifies us about a PIX refund?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m013" + ] + }, + { + "id": "q008", + "query": "How fast must we answer the PSP when a PIX charge is paid, and what if processing is slow?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m012" + ] + }, + { + "id": "q009", + "query": "Depois de quanto tempo um QR code de cobrança com valor deixa de valer?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m014" + ] + }, + { + "id": "q010", + "query": "O PayBridge retorna erro se eu criar uma cobrança com um txid repetido?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m015" + ] + }, + { + "id": "q011", + "query": "When does the daily job that matches the PSP statement against our books run, and where do mismatches go?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m017" + ] + }, + { + "id": "q012", + "query": "A gente armazena o número completo do cartão em algum lugar?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m021" + ] + }, + { + "id": "q013", + "query": "Should I use decimal or float for money amounts in backend code?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m022" + ] + }, + { + "id": "q014", + "query": "How do I add an index to a huge table without locking writes?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m026" + ] + }, + { + "id": "q015", + "query": "Como as migrations de banco rodam em produção?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m025" + ] + }, + { + "id": "q016", + "query": "Can I use named prepared statements on our Postgres connections?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m029" + ] + }, + { + "id": "q017", + "query": "Como desfaço um deploy ruim em produção?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m036" + ] + }, + { + "id": "q018", + "query": "What are our recovery point and recovery time objectives if São Paulo region goes down?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m039" + ] + }, + { + "id": "q019", + "query": "Onde eu cadastro uma credencial nova de um serviço pra ela chegar no pod?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m040" + ] + }, + { + "id": "q020", + "query": "What naming pattern should a new event stream topic follow?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m043" + ] + }, + { + "id": "q021", + "query": "O que acontece com uma mensagem que falha várias vezes no consumidor?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m044" + ] + }, + { + "id": "q022", + "query": "Which fields are mandatory in service logs and what must never be logged?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m053" + ] + }, + { + "id": "q023", + "query": "Quais alertas acordam o plantonista e quais só vão pro Slack?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m054" + ] + }, + { + "id": "q024", + "query": "Can I use Redux for state in new web pages?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m057" + ] + }, + { + "id": "q025", + "query": "Por que o checkout fica consultando o status em vez de usar SSE pra saber se o PIX foi pago?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m064" + ] + }, + { + "id": "q026", + "query": "What restrictions apply when the app runs on a jailbroken or rooted phone?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m067" + ] + }, + { + "id": "q027", + "query": "Como os CPFs são protegidos quando chegam no data lake?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m075" + ] + }, + { + "id": "q028", + "query": "What signals does the anti-fraud model use and how often is it retrained?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m076" + ] + }, + { + "id": "q029", + "query": "O que causou o crédito em dobro de PIX em fevereiro?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m083" + ] + }, + { + "id": "q030", + "query": "Why did the connection pooler go down during the Mother's Day peak?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m084" + ] + }, + { + "id": "q031", + "query": "O que entra na primeira versão da recorrência via PIX?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m089" + ] + }, + { + "id": "q032", + "query": "What's the night-time PIX cap for individual customers?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m094" + ] + }, + { + "id": "q033", + "query": "Por que a validação da assinatura do webhook do Kobalt falha quando uso express.json?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m105" + ] + }, + { + "id": "q034", + "query": "How does on-call escalation work if the primary doesn't acknowledge the page?", + "lang": "en", + "type": "cross_lingual", + "relevant": [ + "m110" + ] + }, + { + "id": "q035", + "query": "Posso dar UPDATE numa entrada contábil pra corrigir um valor errado?", + "lang": "pt", + "type": "cross_lingual", + "relevant": [ + "m128" + ] + }, + { + "id": "q036", + "query": "Quantas chamadas por segundo um lojista pode fazer com a mesma credencial de integração?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m010" + ] + }, + { + "id": "q037", + "query": "If a client retries charge creation with the same dedupe header but a different payload, what do we return?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m011" + ] + }, + { + "id": "q038", + "query": "Como é montado o identificador da transação que mandamos pro PSP?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m016" + ] + }, + { + "id": "q039", + "query": "How long after paying can a customer still get their money returned?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m018" + ] + }, + { + "id": "q040", + "query": "Se o cliente pagar o boleto atrasado, ainda aceita? Tem cobrança extra?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m023" + ] + }, + { + "id": "q041", + "query": "How many days do we have to contest a disputed card transaction?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m024" + ] + }, + { + "id": "q042", + "query": "Is it safe to query the secondary database right after inserting a payment?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m030" + ] + }, + { + "id": "q043", + "query": "Por quanto tempo guardamos as cópias de segurança do banco principal?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m031" + ] + }, + { + "id": "q044", + "query": "When a customer asks us to delete their personal data, do we remove the whole record?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m032" + ] + }, + { + "id": "q045", + "query": "O ambiente de homologação recebe as mudanças sozinho depois que eu faço merge?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m034" + ] + }, + { + "id": "q046", + "query": "What traffic steps does a prod release go through and when does it stop on its own?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m035" + ] + }, + { + "id": "q047", + "query": "Where is the infrastructure-as-code state kept and how do we prevent two applies at once?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m038" + ] + }, + { + "id": "q048", + "query": "Qual versão do broker de mensageria usamos e onde ficam os schemas dos eventos?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m045" + ] + }, + { + "id": "q049", + "query": "Um teste instável está quebrando meu PR, o que eu faço com ele?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m047" + ] + }, + { + "id": "q050", + "query": "What fraction of requests get distributed traces recorded?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m052" + ] + }, + { + "id": "q051", + "query": "Qual a meta de disponibilidade e de latência do endpoint de criar cobrança?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m055" + ] + }, + { + "id": "q052", + "query": "How do I check that a company tax ID typed in a web form is valid?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m060" + ] + }, + { + "id": "q053", + "query": "Como ligo ou desligo uma funcionalidade nova na tela sem fazer deploy?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m061" + ] + }, + { + "id": "q054", + "query": "Quais requisitos de inclusão para pessoas com deficiência o fluxo de pagamento precisa cumprir?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m063" + ] + }, + { + "id": "q055", + "query": "Dá pra mandar correção pro celular do cliente sem passar pela revisão da loja?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m065" + ] + }, + { + "id": "q056", + "query": "Is there a cap on promotional notifications per customer?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m068" + ] + }, + { + "id": "q057", + "query": "How do row changes in the main database get streamed into Kafka?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m073" + ] + }, + { + "id": "q058", + "query": "Quantas vezes uma tarefa do orquestrador de pipelines é repetida e qual o prazo pros fluxos financeiros?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m074" + ] + }, + { + "id": "q059", + "query": "What layers and name prefixes do our analytics transformation models use?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m077" + ] + }, + { + "id": "q060", + "query": "Que ferramenta usamos pra subir um banco de verdade nos testes de integração?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m078" + ] + }, + { + "id": "q061", + "query": "How much traffic can the charge creation endpoint take before something saturates?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m081" + ] + }, + { + "id": "q062", + "query": "Por que os recibos enviados por e-mail atrasaram horas naquele incidente?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m086" + ] + }, + { + "id": "q063", + "query": "What did we change after a test credential got exposed publicly?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m087" + ] + }, + { + "id": "q064", + "query": "Quanto o lojista paga por cada transferência instantânea recebida?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m090" + ] + }, + { + "id": "q065", + "query": "What does a seller have to go through before being approved on the platform?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m093" + ] + }, + { + "id": "q066", + "query": "Em que fuso horário as datas ficam gravadas no banco?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m100" + ] + }, + { + "id": "q067", + "query": "Am I allowed to use an untyped escape hatch in production TypeScript code?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m101" + ] + }, + { + "id": "q068", + "query": "A verificação de identidade do lojista ficou parada muito tempo, devo recusar o cadastro?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m104" + ] + }, + { + "id": "q069", + "query": "When is a postmortem required and how soon must it be written?", + "lang": "en", + "type": "paraphrase", + "relevant": [ + "m113" + ] + }, + { + "id": "q070", + "query": "Como protegemos o telefone e a chave PIX do cliente no banco de dados?", + "lang": "pt", + "type": "paraphrase", + "relevant": [ + "m118" + ] + }, + { + "id": "q071", + "query": "INC-0489", + "lang": "en", + "type": "keyword", + "relevant": [ + "m085" + ] + }, + { + "id": "q072", + "query": "X-Pagai-Signature header", + "lang": "en", + "type": "keyword", + "relevant": [ + "m130" + ] + }, + { + "id": "q073", + "query": "infra/kong/kong.yaml", + "lang": "en", + "type": "keyword", + "relevant": [ + "m132" + ] + }, + { + "id": "q074", + "query": "pagai-breakglass", + "lang": "en", + "type": "keyword", + "relevant": [ + "m142" + ] + }, + { + "id": "q075", + "query": "prefixo sk_test_", + "lang": "pt", + "type": "keyword", + "relevant": [ + "m137" + ] + }, + { + "id": "q076", + "query": "packages/contracts/src/errors.ts", + "lang": "en", + "type": "keyword", + "relevant": [ + "m097" + ] + }, + { + "id": "q077", + "query": "splitCents()", + "lang": "en", + "type": "keyword", + "relevant": [ + "m103" + ] + }, + { + "id": "q078", + "query": "eslint-plugin-boundaries", + "lang": "pt", + "type": "keyword", + "relevant": [ + "m098" + ] + }, + { + "id": "q079", + "query": "tools/psp-sim port 4010", + "lang": "en", + "type": "keyword", + "relevant": [ + "m079" + ] + }, + { + "id": "q080", + "query": "E2PAGAIWEB", + "lang": "en", + "type": "keyword", + "relevant": [ + "m041" + ] + }, + { + "id": "q081", + "query": "tabela kyc.cnpj_cache", + "lang": "pt", + "type": "keyword", + "relevant": [ + "m108" + ] + }, + { + "id": "q082", + "query": "security/exceptions.yaml", + "lang": "en", + "type": "keyword", + "relevant": [ + "m117" + ] + }, + { + "id": "q083", + "query": "release-please", + "lang": "pt", + "type": "keyword", + "relevant": [ + "m099" + ] + }, + { + "id": "q084", + "query": "ses-bounces SNS topic", + "lang": "en", + "type": "keyword", + "relevant": [ + "m109" + ] + }, + { + "id": "q085", + "query": "generateFakeCpf", + "lang": "pt", + "type": "keyword", + "relevant": [ + "m080" + ] + }, + { + "id": "q086", + "query": "Quanto tempo dura o access token hoje?", + "lang": "pt", + "type": "update", + "relevant": [ + "m004" + ] + }, + { + "id": "q087", + "query": "Which provider settles our PIX transactions and is there a backup?", + "lang": "en", + "type": "update", + "relevant": [ + "m020" + ] + }, + { + "id": "q088", + "query": "Qual versão do Postgres está rodando no cluster principal?", + "lang": "pt", + "type": "update", + "relevant": [ + "m028" + ] + }, + { + "id": "q089", + "query": "What test coverage threshold does CI enforce on pull requests?", + "lang": "en", + "type": "update", + "relevant": [ + "m049" + ] + }, + { + "id": "q090", + "query": "How should I style a new React component in the web app?", + "lang": "en", + "type": "update", + "relevant": [ + "m059" + ] + }, + { + "id": "q091", + "query": "How often do we ship the mobile app to the stores?", + "lang": "en", + "type": "update", + "relevant": [ + "m070" + ] + }, + { + "id": "q092", + "query": "Onde ficam as tabelas analíticas pra eu rodar uma consulta de GMV?", + "lang": "pt", + "type": "update", + "relevant": [ + "m072" + ] + }, + { + "id": "q093", + "query": "Do newly signed merchants get any free PIX transactions?", + "lang": "en", + "type": "update", + "relevant": [ + "m092" + ] + }, + { + "id": "q094", + "query": "Quantas aprovações um PR precisa pra ser mergeado?", + "lang": "pt", + "type": "update", + "relevant": [ + "m112" + ] + }, + { + "id": "q095", + "query": "Qual algoritmo usamos pra hashear a senha dos clientes?", + "lang": "pt", + "type": "update", + "relevant": [ + "m122" + ] + }, + { + "id": "q096", + "query": "How is an account balance computed when the statement API asks for it?", + "lang": "en", + "type": "update", + "relevant": [ + "m125" + ] + }, + { + "id": "q097", + "query": "Onde eu publico métricas customizadas de um serviço novo?", + "lang": "pt", + "type": "update", + "relevant": [ + "m127" + ] + }, + { + "id": "q098", + "query": "Redis version, replication and failover", + "lang": "en", + "type": "filter", + "relevant": [ + "m147" + ], + "filters": { + "agent": "infra-agent" + } + }, + { + "id": "q099", + "query": "Qual o timeout configurado no webhook?", + "lang": "pt", + "type": "filter", + "relevant": [ + "m013" + ], + "filters": { + "tags": [ + "refund" + ] + } + }, + { + "id": "q100", + "query": "Como funciona o deploy?", + "lang": "pt", + "type": "filter", + "relevant": [ + "m034" + ], + "filters": { + "tags": [ + "staging" + ] + } + }, + { + "id": "q101", + "query": "What happened in the incident and what did we change afterwards?", + "lang": "en", + "type": "filter", + "relevant": [ + "m087" + ], + "filters": { + "agent": "security-agent", + "tags": [ + "incident" + ] + } + }, + { + "id": "q102", + "query": "What PIX limits apply to individual customers?", + "lang": "en", + "type": "filter", + "relevant": [ + "m094", + "m095" + ], + "filters": { + "tags": [ + "limits" + ] + } + }, + { + "id": "q103", + "query": "Como funciona o acesso emergencial à conta AWS de produção?", + "lang": "pt", + "type": "filter", + "relevant": [ + "m142" + ], + "filters": { + "agent": "infra-agent" + } + }, + { + "id": "q104", + "query": "O que acontece quando o antifraude não responde a tempo?", + "lang": "pt", + "type": "filter", + "relevant": [ + "m136" + ], + "filters": { + "agent": "data-agent" + } + }, + { + "id": "q105", + "query": "How do we verify webhook signatures?", + "lang": "en", + "type": "filter", + "relevant": [ + "m105" + ], + "filters": { + "tags": [ + "kobalt" + ] + } + }, + { + "id": "q106", + "query": "What has to pass before the app goes to the stores?", + "lang": "en", + "type": "filter", + "relevant": [ + "m082" + ], + "filters": { + "agent": "qa-agent", + "tags": [ + "mobile" + ] + } + }, + { + "id": "q107", + "query": "Por quanto tempo os eventos brutos ficam guardados?", + "lang": "pt", + "type": "filter", + "relevant": [ + "m135" + ], + "filters": { + "tags": [ + "lgpd" + ] + } + }, + { + "id": "q108", + "query": "When the gateway throttles a merchant, where are the counters stored and what are the limits per key?", + "lang": "en", + "type": "multi_hop", + "relevant": [ + "m132", + "m009", + "m010" + ] + }, + { + "id": "q109", + "query": "Quais são todos os timeouts de webhook do PIX que configuramos?", + "lang": "pt", + "type": "multi_hop", + "relevant": [ + "m012", + "m013" + ] + }, + { + "id": "q110", + "query": "Before shipping a PIX change to production, what reviews, approvals and rollout steps apply?", + "lang": "en", + "type": "multi_hop", + "relevant": [ + "m033", + "m035", + "m114" + ] + }, + { + "id": "q111", + "query": "Como um pagamento PIX confirmado vira crédito sem duplicar, mesmo se o consumer rebalancear?", + "lang": "pt", + "type": "multi_hop", + "relevant": [ + "m012", + "m083" + ] + }, + { + "id": "q112", + "query": "Besides the ML score, what rules block or challenge a customer sending a PIX?", + "lang": "en", + "type": "multi_hop", + "relevant": [ + "m149", + "m067" + ] + }, + { + "id": "q113", + "query": "Me dá o panorama do PIX Automático: escopo do produto e como as autorizações são guardadas.", + "lang": "pt", + "type": "multi_hop", + "relevant": [ + "m089", + "m146" + ] + }, + { + "id": "q114", + "query": "Which core services exist and how does the edge gateway validate tokens before reaching them?", + "lang": "en", + "type": "multi_hop", + "relevant": [ + "m131", + "m132" + ] + }, + { + "id": "q115", + "query": "Onde devem ficar os segredos e o que mudou depois que uma chave vazou?", + "lang": "pt", + "type": "multi_hop", + "relevant": [ + "m040", + "m087" + ] + }, + { + "id": "q116", + "query": "How and when do merchants get paid for PIX, and how much do we charge them?", + "lang": "en", + "type": "multi_hop", + "relevant": [ + "m129", + "m090" + ] + }, + { + "id": "q117", + "query": "O que precisamos saber sobre certificados TLS do endpoint que recebe webhooks do PayBridge?", + "lang": "pt", + "type": "multi_hop", + "relevant": [ + "m106", + "m085" + ] + }, + { + "id": "q118", + "query": "Where can I test refund flows if the vendor sandbox never calls back, and what do merchants use for testing?", + "lang": "en", + "type": "multi_hop", + "relevant": [ + "m079", + "m137" + ] + }, + { + "id": "q119", + "query": "Quais são as regras de retenção que temos para logs, backups do banco e dados do lake?", + "lang": "pt", + "type": "multi_hop", + "relevant": [ + "m053", + "m031", + "m135" + ] + }, + { + "id": "q120", + "query": "How does a customer get notified about a received PIX — channels, delivery mechanism and opt-out rules?", + "lang": "en", + "type": "multi_hop", + "relevant": [ + "m068", + "m143" + ] + } + ] +} diff --git a/benchmarks/lib/bench-store.js b/benchmarks/lib/bench-store.js deleted file mode 100644 index 25883db..0000000 --- a/benchmarks/lib/bench-store.js +++ /dev/null @@ -1,213 +0,0 @@ -/** - * BenchStore — in-memory SQLite store for benchmark isolation. - * - * Replicates the same schema, FTS5, and hybrid search logic from - * src/db.js and src/search.js, but uses DatabaseSync(":memory:") - * so each question gets a fresh, isolated database with zero disk I/O. - */ - -import { DatabaseSync } from "node:sqlite"; - -// ─── Schema (mirrored from src/db.js) ─────────────────────────────────────── - -const SCHEMA_TABLES = ` -CREATE TABLE IF NOT EXISTS chunks ( - id TEXT PRIMARY KEY, - topic TEXT NOT NULL, - agent TEXT NOT NULL DEFAULT 'global', - tags TEXT NOT NULL DEFAULT '[]', - importance TEXT NOT NULL DEFAULT 'medium', - content TEXT NOT NULL, - embedding BLOB, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - expires_at TEXT -); -`; - -const SCHEMA_FTS = ` -CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( - id UNINDEXED, - topic, - tags, - agent, - content, - content='chunks', - content_rowid=rowid -); -`; - -const SCHEMA_TRIGGERS = ` -CREATE TRIGGER IF NOT EXISTS chunks_ai AFTER INSERT ON chunks BEGIN - INSERT INTO chunks_fts(rowid, id, topic, tags, agent, content) - VALUES (new.rowid, new.id, new.topic, new.tags, new.agent, new.content); -END; - -CREATE TRIGGER IF NOT EXISTS chunks_ad AFTER DELETE ON chunks BEGIN - INSERT INTO chunks_fts(chunks_fts, rowid, id, topic, tags, agent, content) - VALUES ('delete', old.rowid, old.id, old.topic, old.tags, old.agent, old.content); -END; - -CREATE TRIGGER IF NOT EXISTS chunks_au AFTER UPDATE ON chunks BEGIN - INSERT INTO chunks_fts(chunks_fts, rowid, id, topic, tags, agent, content) - VALUES ('delete', old.rowid, old.id, old.topic, old.tags, old.agent, old.content); - INSERT INTO chunks_fts(rowid, id, topic, tags, agent, content) - VALUES (new.rowid, new.id, new.topic, new.tags, new.agent, new.content); -END; -`; - -// ─── Search helpers (mirrored from src/search.js) ─────────────────────────── - -function cosineSimilarity(a, b) { - let dot = 0; - for (let i = 0; i < a.length; i++) dot += a[i] * b[i]; - return dot; -} - -function reciprocalRankFusion(bm25Hits, vecHits, wBM25 = 0.4, wVec = 0.6) { - const K = 60; - const scores = new Map(); - - bm25Hits.forEach(({ id }, rank) => { - scores.set(id, (scores.get(id) || 0) + wBM25 / (K + rank + 1)); - }); - - vecHits.forEach(({ id }, rank) => { - scores.set(id, (scores.get(id) || 0) + wVec / (K + rank + 1)); - }); - - return [...scores.entries()] - .map(([id, score]) => ({ id, score })) - .sort((a, b) => b.score - a.score); -} - -// ─── BenchStore class ─────────────────────────────────────────────────────── - -export class BenchStore { - constructor() { - this.db = new DatabaseSync(":memory:"); - this.db.exec("PRAGMA journal_mode = WAL"); - this.db.exec(SCHEMA_TABLES); - this.db.exec(SCHEMA_FTS); - this.db.exec(SCHEMA_TRIGGERS); - this._stmtCache = new Map(); - } - - _stmt(sql) { - let s = this._stmtCache.get(sql); - if (!s) { - s = this.db.prepare(sql); - this._stmtCache.set(sql, s); - } - return s; - } - - /** - * Insert a chunk with pre-computed embedding. - */ - insertChunk({ id, topic = "session", agent = "longmemeval", tags = [], importance = "medium", content, embedding }) { - const now = new Date().toISOString(); - this._stmt( - `INSERT OR REPLACE INTO chunks (id, topic, agent, tags, importance, content, embedding, created_at, updated_at, expires_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ).run( - id, - topic, - agent, - JSON.stringify(tags), - importance, - content, - embedding ? Buffer.from(embedding.buffer) : null, - now, - now, - null, - ); - } - - /** - * FTS5 BM25 search (mirrors src/db.js searchFTS). - */ - searchFTS(query, topK = 18) { - // Strip all non-alphanumeric chars to avoid FTS5 syntax errors - const ftsQuery = query - .replace(/[^a-zA-Z0-9\s]/g, " ") - .split(/\s+/) - .filter((t) => t.length > 1) - .join(" OR "); - - if (!ftsQuery) return []; - - const sql = ` - SELECT c.id, c.topic, c.content, rank - FROM chunks_fts - JOIN chunks c ON c.id = chunks_fts.id - WHERE chunks_fts MATCH ? - ORDER BY rank LIMIT ?`; - - const rows = this.db.prepare(sql).all(ftsQuery, topK); - return rows.map((r) => ({ - id: r.id, - score: -r.rank, - })); - } - - /** - * Vector search over all stored embeddings. - */ - vectorSearch(queryEmbedding, topK = 18) { - const rows = this.db - .prepare(`SELECT id, embedding FROM chunks WHERE embedding IS NOT NULL`) - .all(); - - if (!rows.length) return []; - - return rows - .map((r) => ({ - id: r.id, - score: cosineSimilarity( - queryEmbedding, - new Float32Array(r.embedding.buffer, r.embedding.byteOffset, r.embedding.byteLength / 4), - ), - })) - .filter((r) => r.score > 0) - .sort((a, b) => b.score - a.score) - .slice(0, topK); - } - - /** - * Hybrid search: BM25 + vector + RRF, or single mode. - * - * @param {string} query - Search query text - * @param {Float32Array|null} queryEmbedding - Pre-computed query embedding - * @param {number} topK - Number of results - * @param {string} mode - "hybrid" | "bm25" | "semantic" - * @returns {Array<{id: string, score: number}>} - */ - hybridSearch(query, queryEmbedding, topK = 10, mode = "hybrid") { - const candidateK = topK * 3; - - if (mode === "bm25") { - return this.searchFTS(query, candidateK).slice(0, topK); - } - - if (mode === "semantic") { - if (!queryEmbedding) return this.searchFTS(query, candidateK).slice(0, topK); - return this.vectorSearch(queryEmbedding, topK); - } - - // Hybrid - const bm25Hits = this.searchFTS(query, candidateK); - if (!queryEmbedding) return bm25Hits.slice(0, topK); - - const vecHits = this.vectorSearch(queryEmbedding, candidateK); - return reciprocalRankFusion(bm25Hits, vecHits).slice(0, topK); - } - - /** - * Close the in-memory database. - */ - destroy() { - this._stmtCache.clear(); - this.db.close(); - } -} diff --git a/benchmarks/lib/cached-embedder.js b/benchmarks/lib/cached-embedder.js new file mode 100644 index 0000000..9877eb6 --- /dev/null +++ b/benchmarks/lib/cached-embedder.js @@ -0,0 +1,87 @@ +/** + * Disk cache for benchmark embeddings. + * + * Wraps a real embedder and stores every vector it computes, keyed by a hash + * of the exact input text, in benchmarks/.cache/embeddings/.bin. + * Embeddings are deterministic, so cached and fresh vectors are identical; + * the store, ranking and fusion code under test are unchanged. Re-runs (other + * fusion settings, CI) then cost seconds instead of an hour. + */ + +import { createHash } from "crypto"; +import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; + +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".cache", "embeddings"); +const HASH_BYTES = 16; + +const key = (kind, text) => createHash("sha256").update(kind).update("\0").update(text).digest().subarray(0, HASH_BYTES); + +export class CachedEmbedder { + constructor(inner) { + this.inner = inner; + this.id = inner.id; + this.duplicateThreshold = inner.duplicateThreshold; + this.file = path.join(DIR, `${inner.id.replace(/[^\w.-]+/g, "_")}.bin`); + this.cache = new Map(); + this.hits = 0; + this.misses = 0; + } + + get dim() { + return this.inner.dim; + } + + isReady() { + return this.inner.isReady(); + } + + async load() { + if (!(await this.inner.load())) return false; + if (this.cache.size === 0 && existsSync(this.file)) { + const buf = readFileSync(this.file); + const rec = HASH_BYTES + this.inner.dim * 4; + for (let o = 0; o + rec <= buf.length; o += rec) { + const vec = new Float32Array(buf.buffer.slice(buf.byteOffset + o + HASH_BYTES, buf.byteOffset + o + rec)); + this.cache.set(buf.toString("hex", o, o + HASH_BYTES), vec); + } + } + return true; + } + + async _get(kind, texts, compute) { + const keys = texts.map((t) => key(kind, t)); + const out = keys.map((k) => this.cache.get(k.toString("hex")) ?? null); + const missing = out.map((v, i) => (v ? -1 : i)).filter((i) => i >= 0); + this.hits += texts.length - missing.length; + this.misses += missing.length; + if (missing.length) { + const vecs = await compute(missing.map((i) => texts[i])); + mkdirSync(DIR, { recursive: true }); + const chunks = []; + missing.forEach((i, j) => { + out[i] = vecs[j]; + this.cache.set(keys[i].toString("hex"), vecs[j]); + chunks.push(keys[i], Buffer.from(vecs[j].buffer, vecs[j].byteOffset, vecs[j].byteLength)); + }); + appendFileSync(this.file, Buffer.concat(chunks)); + } + return out; + } + + async embedQuery(text) { + const [v] = await this._get("q", [text], async ([t]) => [await this.inner.embedQuery(t)]); + return v; + } + + async embedDocuments(texts) { + return this._get("d", texts, (ts) => this.inner.embedDocuments(ts)); + } +} + +/** Wraps an embedder with the disk cache unless AMS_NO_EMBED_CACHE=1 (or no embedder). */ +export function withCache(embedder) { + if (!embedder || process.env.AMS_NO_EMBED_CACHE === "1") return embedder; + return new CachedEmbedder(embedder); +} diff --git a/benchmarks/lib/dataset.js b/benchmarks/lib/dataset.js index 4d8f63d..8687342 100644 --- a/benchmarks/lib/dataset.js +++ b/benchmarks/lib/dataset.js @@ -1,5 +1,6 @@ /** - * LongMemEval dataset loader with local caching. + * LongMemEval-S loader with local caching, plus the official corpus + * construction rules (src/retrieval/run_retrieval.py, process_item_flat_index). */ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; @@ -9,153 +10,55 @@ import { fileURLToPath } from "url"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const CACHE_DIR = path.join(__dirname, "..", ".cache"); const CACHE_FILE = path.join(CACHE_DIR, "longmemeval_s_cleaned.json"); - const DATASET_URL = "https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned/resolve/main/longmemeval_s_cleaned.json"; -/** - * Downloads and caches the LongMemEval-S dataset (500 questions). - * - * @returns {Promise} Array of question objects - */ export async function loadDataset() { - if (existsSync(CACHE_FILE)) { - process.stderr.write(`[bench] Loading cached dataset from ${CACHE_FILE}\n`); - return JSON.parse(readFileSync(CACHE_FILE, "utf-8")); - } - + if (existsSync(CACHE_FILE)) return JSON.parse(readFileSync(CACHE_FILE, "utf-8")); mkdirSync(CACHE_DIR, { recursive: true }); - - process.stderr.write( - `[bench] Downloading LongMemEval dataset from HuggingFace...\n`, - ); + process.stderr.write("[bench] Downloading LongMemEval-S (cleaned) from Hugging Face...\n"); const res = await fetch(DATASET_URL); - if (!res.ok) { - throw new Error(`Failed to download dataset: ${res.status} ${res.statusText}`); - } - + if (!res.ok) throw new Error(`Failed to download dataset: ${res.status} ${res.statusText}`); const text = await res.text(); writeFileSync(CACHE_FILE, text); - process.stderr.write(`[bench] Dataset cached at ${CACHE_FILE}\n`); - return JSON.parse(text); } /** - * Extracts ground-truth relevant session IDs for a question. - * A session is relevant if any of its turns has has_answer=true. - * - * @param {object} question - A question object from the dataset - * @returns {Set} Set of relevant session IDs (as string indices) - */ -export function getRelevantSessionIds(question) { - const relevant = new Set(); - const sessions = question.haystack_sessions || []; - - for (let i = 0; i < sessions.length; i++) { - const session = sessions[i]; - const turns = Array.isArray(session) ? session : session.turns || []; - for (const turn of turns) { - if (turn.has_answer === true) { - relevant.add(String(i)); - break; - } - } - } - - return relevant; -} - -/** - * Converts haystack sessions to ingestible chunks (session-level granularity). - * Each session becomes one chunk with all turns concatenated. - * - * @param {Array} sessions - haystack_sessions array - * @returns {Array<{id: string, content: string}>} + * Official exclusions: abstention questions and questions without any + * user-side evidence turn. */ -export function sessionsToChunks(sessions) { - return sessions.map((session, i) => { - const turns = Array.isArray(session) ? session : session.turns || []; - const content = turns - .map((t) => `${t.role === "user" ? "User" : "Assistant"}: ${t.content}`) - .join("\n"); - return { id: String(i), content }; - }); +export function isEvaluable(q) { + if (q.question_id.includes("_abs")) return false; + return q.haystack_sessions.some((s) => s.some((t) => t.role === "user" && t.has_answer)); } -/** - * Converts haystack sessions to ingestible chunks (hybrid granularity). - * Indexes BOTH the full session (for multi-turn context) AND each individual - * turn (for single-turn precision). IDs are prefixed: s_{i} for session - * chunks, t_{i}_{j} for turn chunks — both map back to session i. - * - * This gives BM25 and vector search two "views" of the same content: - * - Session view: finds answers that span multiple turns - * - Turn view: pinpoints exact turns with high-precision matches - * - * @param {Array} sessions - haystack_sessions array - * @returns {Array<{id: string, sessionId: string, granularity: string, content: string}>} - */ -export function sessionsToHybridChunks(sessions) { - const chunks = []; - for (let i = 0; i < sessions.length; i++) { - const session = sessions[i]; - const turns = Array.isArray(session) ? session : session.turns || []; - - // Session-level chunk — full conversation context - const fullContent = turns - .map((t) => `${t.role === "user" ? "User" : "Assistant"}: ${t.content}`) - .join("\n"); - if (fullContent.trim()) { - chunks.push({ - id: `s_${i}`, - sessionId: String(i), - granularity: "session", - role: null, - content: fullContent, - }); - } - - // Turn-level chunks — individual precision - for (let j = 0; j < turns.length; j++) { - const turn = turns[j]; - if (!turn.content?.trim()) continue; - chunks.push({ - id: `t_${i}_${j}`, - sessionId: String(i), - granularity: "turn", - role: turn.role, - content: turn.content, - }); - } - } - return chunks; +/** "2023/05/20 (Sat) 02:21" → ISO string */ +export function parseDate(s) { + const m = /^(\d{4})\/(\d{2})\/(\d{2})(?: \(\w+\))?(?: (\d{2}):(\d{2}))?/.exec(s || ""); + if (!m) return null; + return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0))).toISOString(); } /** - * Converts haystack sessions to ingestible chunks (turn-level granularity). - * Each turn (user AND assistant) becomes a separate chunk tagged with its - * session index. Including assistant turns is critical — they contain the - * actual facts that questions ask about. + * Session-granularity corpus. Official: user turns only, joined with spaces; + * a session is gold if its id contains "answer" and one of its user turns + * has has_answer=true. `withAssistant` adds assistant turns (non-official + * variant, reported separately). * - * @param {Array} sessions - haystack_sessions array - * @returns {Array<{id: string, sessionId: string, role: string, content: string}>} + * @returns {{ docs: Array<{id, text, date}>, gold: Set }} */ -export function sessionsToTurnChunks(sessions) { - const chunks = []; - for (let i = 0; i < sessions.length; i++) { - const session = sessions[i]; - const turns = Array.isArray(session) ? session : session.turns || []; - for (let turnIdx = 0; turnIdx < turns.length; turnIdx++) { - const turn = turns[turnIdx]; - if (!turn.content?.trim()) continue; - chunks.push({ - id: `${i}_${turnIdx}`, - sessionId: String(i), - role: turn.role, - content: turn.content, - }); - } - } - return chunks; +export function buildSessionCorpus(q, { withAssistant = false } = {}) { + const docs = []; + const gold = new Set(); + q.haystack_sessions.forEach((turns, i) => { + const id = q.haystack_session_ids[i]; + const text = turns + .filter((t) => withAssistant || t.role === "user") + .map((t) => t.content) + .join(" "); + docs.push({ id, text, date: parseDate(q.haystack_dates?.[i]) }); + if (id.includes("answer") && turns.some((t) => t.role === "user" && t.has_answer)) gold.add(id); + }); + return { docs, gold }; } diff --git a/benchmarks/lib/metrics.js b/benchmarks/lib/metrics.js index 8bd9597..fd21265 100644 --- a/benchmarks/lib/metrics.js +++ b/benchmarks/lib/metrics.js @@ -1,53 +1,57 @@ /** - * LongMemEval retrieval metrics: Recall@k and NDCG@k. - */ - -/** - * Recall@k — fraction of relevant items found in the top-k retrieved results. + * Retrieval metrics, ported 1:1 from LongMemEval's official evaluation + * (src/retrieval/eval_utils.py in github.com/xiaowu0162/LongMemEval): * - * @param {string[]} retrievedIds - Ranked list of retrieved IDs - * @param {Set} relevantIds - Set of ground-truth relevant IDs - * @param {number} k - Cutoff - * @returns {number|null} Recall value (0-1), or null if no relevant items exist + * recall_any@k — 1 if ANY gold doc is in the top k, else 0 + * recall_all@k — 1 if ALL gold docs are in the top k, else 0 + * ndcg_any@k — binary-relevance NDCG over the top k + * + * Plus MRR for the golden set. */ -export function recallAtK(retrievedIds, relevantIds, k) { - if (relevantIds.size === 0) return null; - const topK = retrievedIds.slice(0, k); - let found = 0; - for (const id of topK) { - if (relevantIds.has(id)) found++; - } - return found / relevantIds.size; + +function dcg(relevances, k) { + const rel = relevances.slice(0, k); + if (rel.length === 0) return 0; + let s = rel[0]; + for (let i = 1; i < rel.length; i++) s += rel[i] / Math.log2(i + 1); + return s; } /** - * NDCG@k — Normalized Discounted Cumulative Gain. - * - * @param {string[]} retrievedIds - Ranked list of retrieved IDs - * @param {Set} relevantIds - Set of ground-truth relevant IDs - * @param {number} k - Cutoff - * @returns {number|null} NDCG value (0-1), or null if no relevant items exist + * @param {string[]} ranked - retrieved doc ids, best first + * @param {Set} gold - relevant doc ids + * @param {number} corpusGold - number of relevant docs in the corpus (for the ideal ranking) + * @param {number} k */ -export function ndcgAtK(retrievedIds, relevantIds, k) { - if (relevantIds.size === 0) return null; +export function ndcgAny(ranked, gold, corpusGold, k) { + const actual = dcg(ranked.map((id) => (gold.has(id) ? 1 : 0)), k); + const ideal = dcg(Array.from({ length: corpusGold }, () => 1), k); + return ideal === 0 ? 0 : actual / ideal; +} + +export function recallAny(ranked, gold, k) { + const top = new Set(ranked.slice(0, k)); + return [...gold].some((id) => top.has(id)) ? 1 : 0; +} - const topK = retrievedIds.slice(0, k); +export function recallAll(ranked, gold, k) { + const top = new Set(ranked.slice(0, k)); + return [...gold].every((id) => top.has(id)) ? 1 : 0; +} - // DCG@k - let dcg = 0; - for (let i = 0; i < topK.length; i++) { - if (relevantIds.has(topK[i])) { - dcg += 1 / Math.log2(i + 2); // i+2 because log2(1) = 0 - } - } +/** Reciprocal rank of the first relevant result (0 if none). */ +export function reciprocalRank(ranked, gold) { + const i = ranked.findIndex((id) => gold.has(id)); + return i === -1 ? 0 : 1 / (i + 1); +} - // IDCG@k — ideal ranking: all relevant items first - const idealCount = Math.min(relevantIds.size, k); - let idcg = 0; - for (let i = 0; i < idealCount; i++) { - idcg += 1 / Math.log2(i + 2); - } +export function mean(xs) { + return xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0; +} - if (idcg === 0) return 0; - return dcg / idcg; +/** Nearest-rank percentile of a numeric array. */ +export function percentile(xs, p) { + if (!xs.length) return 0; + const s = [...xs].sort((a, b) => a - b); + return s[Math.min(s.length - 1, Math.ceil((p / 100) * s.length) - 1)]; } diff --git a/benchmarks/longmemeval.js b/benchmarks/longmemeval.js new file mode 100644 index 0000000..b207017 --- /dev/null +++ b/benchmarks/longmemeval.js @@ -0,0 +1,178 @@ +#!/usr/bin/env node +/** + * LongMemEval-S retrieval benchmark, run through the production MemoryStore + * (same FTS query builder, vector index, fusion and ranking as the MCP server). + * + * Protocol follows the official LongMemEval retrieval evaluation: + * - LongMemEval-S cleaned, session granularity, user turns only + * - 470 evaluable questions (abstention and no-evidence questions excluded) + * - recall_any@k, recall_all@k, ndcg_any@k + * + * Usage: + * node benchmarks/longmemeval.js [--model granite-97m-multilingual] [--limit N] + * [--modes hybrid,bm25,semantic] [--with-assistant] + * [--fusions rrf:0.5,convex:0.7] (extra hybrid variants) + * [--sample N] (deterministic sample, stratified by question type) + */ + +import { mkdirSync, writeFileSync } from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; +import { MemoryStore } from "../src/store/memory-store.js"; +import { createEmbedder, DEFAULT_MODEL } from "../src/embeddings.js"; +import { withCache } from "./lib/cached-embedder.js"; +import { loadDataset, isEvaluable, buildSessionCorpus, parseDate } from "./lib/dataset.js"; +import { recallAny, recallAll, ndcgAny, mean } from "./lib/metrics.js"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +function parseArgs(argv) { + const opts = { model: process.env.AGENT_MEMORY_MODEL || DEFAULT_MODEL, limit: null, sample: null, modes: null, withAssistant: false, fusions: [] }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--model") opts.model = argv[++i]; + else if (a === "--limit") opts.limit = parseInt(argv[++i], 10); + else if (a === "--sample") opts.sample = parseInt(argv[++i], 10); + else if (a === "--modes") opts.modes = argv[++i].split(","); + else if (a === "--with-assistant") opts.withAssistant = true; + else if (a === "--fusions") opts.fusions = argv[++i].split(","); + else throw new Error(`Unknown argument ${a}`); + } + opts.modes ??= opts.model === "none" ? ["bm25"] : ["hybrid", "bm25", "semantic"]; + // Each fusion variant is reported as its own row, e.g. "hybrid[convex:0.7]". + opts.runs = [ + ...opts.modes.map((mode) => ({ name: mode, mode })), + ...opts.fusions.map((f) => { + const [method, w] = f.split(":"); + return { name: `hybrid[${f}]`, mode: "hybrid", fusion: { method, semanticWeight: Number(w) } }; + }), + ]; + return opts; +} + +const KS = [5, 10]; +const opts = parseArgs(process.argv.slice(2)); +const embedder = withCache(createEmbedder(opts.model)); +if (embedder && !(await embedder.load())) throw new Error(`Model ${opts.model} failed to load`); + +let questions = await loadDataset(); +const total = questions.length; +questions = questions.filter(isEvaluable); +const evaluable = questions.length; +if (opts.limit) questions = questions.slice(0, opts.limit); +if (opts.sample) questions = stratifiedSample(questions, opts.sample); + +/** Evenly spaced picks within each question type, proportional to its share. */ +function stratifiedSample(qs, n) { + const byType = new Map(); + for (const q of qs) byType.set(q.question_type, [...(byType.get(q.question_type) ?? []), q]); + const picked = []; + for (const group of byType.values()) { + const k = Math.max(1, Math.round((group.length / qs.length) * n)); + for (let i = 0; i < k; i++) picked.push(group[Math.floor((i * group.length) / k)]); + } + return picked; +} + +console.log(`LongMemEval-S (cleaned) · session granularity · ${opts.withAssistant ? "user+assistant turns (NON-OFFICIAL variant)" : "user turns (official)"}`); +console.log(`model: ${embedder?.id ?? "none (keyword only)"} · questions: ${questions.length} of ${total} (excluded ${total - evaluable} abstention/no-evidence)\n`); + +const perQuestion = []; +const t0 = performance.now(); + +for (let qi = 0; qi < questions.length; qi++) { + const q = questions[qi]; + const { docs, gold } = buildSessionCorpus(q, { withAssistant: opts.withAssistant }); + const questionTime = Date.parse(parseDate(q.question_date) ?? new Date().toISOString()); + const store = MemoryStore.open(":memory:", { embedder, clock: () => questionTime }); + + for (const d of docs) { + store.importMemory({ + id: d.id, + topic: "conversation", + content: d.text || "(empty)", + createdAt: d.date ?? undefined, + updatedAt: d.date ?? undefined, + }); + } + await store.flushEmbeddings(); + + const row = { id: q.question_id, type: q.question_type, gold: gold.size, metrics: {} }; + for (const { name, mode, fusion } of opts.runs) { + const { results } = await store.search({ query: q.question, limit: 50, mode, ...(fusion && { fusion }) }); + const ranked = results.map((r) => r.id); + const m = {}; + for (const k of KS) { + m[`recall_any@${k}`] = recallAny(ranked, gold, k); + m[`recall_all@${k}`] = recallAll(ranked, gold, k); + m[`ndcg_any@${k}`] = ndcgAny(ranked, gold, gold.size, k); + } + row.metrics[name] = m; + } + perQuestion.push(row); + store.close(); + questions[qi] = null; // the dataset is ~1 GB in memory; release as we go + + const done = qi + 1; + const elapsed = (performance.now() - t0) / 1000; + process.stderr.write(`\r ${done}/${questions.length} · ${elapsed.toFixed(0)}s · ETA ${((elapsed / done) * (questions.length - done)).toFixed(0)}s `); +} +process.stderr.write("\n\n"); + +function summarize(rows, mode) { + const keys = Object.keys(rows[0].metrics[mode]); + return Object.fromEntries(keys.map((k) => [k, mean(rows.map((r) => r.metrics[mode][k]))])); +} + +const pct = (v) => `${(v * 100).toFixed(1)}%`.padStart(7); +const overall = {}; +console.log("mode | R_any@5 | R_all@5 | R_any@10 | R_all@10 | NDCG@10"); +console.log("----------|---------|---------|----------|----------|--------"); +for (const { name } of opts.runs) { + const s = (overall[name] = summarize(perQuestion, name)); + console.log( + `${name.padEnd(9)} | ${pct(s["recall_any@5"])} | ${pct(s["recall_all@5"])} | ${pct(s["recall_any@10"])} | ${pct(s["recall_all@10"])} | ${s["ndcg_any@10"].toFixed(3)}`, + ); +} + +const byType = {}; +const primary = opts.runs[0].name; +console.log(`\nby question type (${primary}):`); +for (const type of [...new Set(perQuestion.map((r) => r.type))].sort()) { + const rows = perQuestion.filter((r) => r.type === type); + const s = (byType[type] = { n: rows.length, ...summarize(rows, primary) }); + console.log(` ${type.padEnd(27)} n=${String(rows.length).padStart(3)} R_any@5 ${pct(s["recall_any@5"])} R_all@5 ${pct(s["recall_all@5"])} NDCG@10 ${s["ndcg_any@10"].toFixed(3)}`); +} + +const seconds = (performance.now() - t0) / 1000; +console.log(`\ncompleted in ${seconds.toFixed(0)}s${embedder?.misses != null ? ` (embedding cache: ${embedder.hits} hits, ${embedder.misses} computed)` : ""}`); + +const outDir = path.join(__dirname, "results"); +mkdirSync(outDir, { recursive: true }); +const suffix = `${opts.model}${opts.withAssistant ? "-with-assistant" : ""}${opts.limit ? `-limit${opts.limit}` : ""}${opts.sample ? `-sample${opts.sample}` : ""}`; +const outFile = path.join(outDir, `longmemeval-${suffix}.json`); +writeFileSync( + outFile, + JSON.stringify( + { + meta: { + dataset: "LongMemEval-S (cleaned)", + granularity: "session", + turns: opts.withAssistant ? "user+assistant (non-official)" : "user (official)", + model: embedder?.id ?? null, + questions: questions.length, + selection: opts.sample ? `stratified sample of ${opts.sample}` : opts.limit ? `first ${opts.limit}` : "all evaluable", + node: process.version, + platform: `${process.platform}-${process.arch}`, + date: new Date().toISOString(), + seconds: Math.round(seconds), + }, + overall, + byType, + perQuestion, + }, + null, + 1, + ), +); +console.log(`results: ${path.relative(process.cwd(), outFile)}`); diff --git a/benchmarks/results/bench-arctic-embed-m-v2.json b/benchmarks/results/bench-arctic-embed-m-v2.json new file mode 100644 index 0000000..69e49c0 --- /dev/null +++ b/benchmarks/results/bench-arctic-embed-m-v2.json @@ -0,0 +1,49 @@ +{ + "meta": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0@q8", + "node": "v25.6.1", + "platform": "darwin-arm64", + "date": "2026-10-13T00:50:49.940Z" + }, + "quality": { + "hybrid": { + "hit1": 0.7416666666666667, + "recall5": 0.9583333333333334, + "mrr": 0.8364219576719576, + "crossLingualMrr": 0.9 + }, + "bm25": { + "hit1": 0.5083333333333333, + "recall5": 0.7, + "mrr": 0.5873842592592593, + "crossLingualMrr": 0.4584126984126983 + }, + "semantic": { + "hit1": 0.725, + "recall5": 0.9583333333333334, + "mrr": 0.827662037037037, + "crossLingualMrr": 0.9285714285714286 + } + }, + "speed": { + "memories": 2000, + "searchHybridMs": { + "p50": 8.546290999998746, + "p95": 15.062041999997746 + }, + "searchKeywordMs": { + "p50": 0.734667000000627, + "p95": 1.7274579999975685 + }, + "writeMs": { + "p50": 13.917583999998897, + "p95": 17.168792000000394 + }, + "readMs": { + "p50": 0.015167000001383713, + "p95": 0.040166999999200925 + }, + "embedPerSec": 93, + "rssMB": 630 + } +} \ No newline at end of file diff --git a/benchmarks/results/bench-embeddinggemma-300m.json b/benchmarks/results/bench-embeddinggemma-300m.json new file mode 100644 index 0000000..c77bea2 --- /dev/null +++ b/benchmarks/results/bench-embeddinggemma-300m.json @@ -0,0 +1,49 @@ +{ + "meta": { + "model": "onnx-community/embeddinggemma-300m-ONNX@q8", + "node": "v25.6.1", + "platform": "darwin-arm64", + "date": "2026-10-13T00:54:07.529Z" + }, + "quality": { + "hybrid": { + "hit1": 0.7416666666666667, + "recall5": 0.9666666666666667, + "mrr": 0.8405555555555554, + "crossLingualMrr": 0.8416666666666667 + }, + "bm25": { + "hit1": 0.5083333333333333, + "recall5": 0.7, + "mrr": 0.5873842592592593, + "crossLingualMrr": 0.4584126984126983 + }, + "semantic": { + "hit1": 0.7666666666666667, + "recall5": 0.9583333333333334, + "mrr": 0.8542658730158728, + "crossLingualMrr": 0.8993197278911564 + } + }, + "speed": { + "memories": 2000, + "searchHybridMs": { + "p50": 57.92704199999571, + "p95": 95.33208400002331 + }, + "searchKeywordMs": { + "p50": 0.7761250000039581, + "p95": 1.8780409999890253 + }, + "writeMs": { + "p50": 94.07000000000698, + "p95": 124.3648749999993 + }, + "readMs": { + "p50": 0.020459000021219254, + "p95": 0.07658300001639873 + }, + "embedPerSec": 18, + "rssMB": 1372 + } +} \ No newline at end of file diff --git a/benchmarks/results/bench-granite-97m-multilingual.json b/benchmarks/results/bench-granite-97m-multilingual.json new file mode 100644 index 0000000..b7679fa --- /dev/null +++ b/benchmarks/results/bench-granite-97m-multilingual.json @@ -0,0 +1,49 @@ +{ + "meta": { + "model": "onnx-community/granite-embedding-97m-multilingual-r2-ONNX@q8", + "node": "v25.6.1", + "platform": "darwin-arm64", + "date": "2026-10-13T00:51:28.607Z" + }, + "quality": { + "hybrid": { + "hit1": 0.6666666666666666, + "recall5": 0.8833333333333333, + "mrr": 0.7695238095238094, + "crossLingualMrr": 0.8571428571428571 + }, + "bm25": { + "hit1": 0.5083333333333333, + "recall5": 0.7, + "mrr": 0.5873842592592593, + "crossLingualMrr": 0.4584126984126983 + }, + "semantic": { + "hit1": 0.6416666666666667, + "recall5": 0.8833333333333333, + "mrr": 0.7433068783068782, + "crossLingualMrr": 0.8904761904761905 + } + }, + "speed": { + "memories": 2000, + "searchHybridMs": { + "p50": 4.523917000000438, + "p95": 8.066584000000148 + }, + "searchKeywordMs": { + "p50": 0.7491250000002765, + "p95": 1.6696249999986321 + }, + "writeMs": { + "p50": 5.752249999999549, + "p95": 6.886540999999852 + }, + "readMs": { + "p50": 0.011500000000523869, + "p95": 0.02979100000084145 + }, + "embedPerSec": 287, + "rssMB": 453 + } +} \ No newline at end of file diff --git a/benchmarks/results/bench-minilm-l6-en.json b/benchmarks/results/bench-minilm-l6-en.json new file mode 100644 index 0000000..e6aa582 --- /dev/null +++ b/benchmarks/results/bench-minilm-l6-en.json @@ -0,0 +1,49 @@ +{ + "meta": { + "model": "Xenova/all-MiniLM-L6-v2@q8", + "node": "v25.6.1", + "platform": "darwin-arm64", + "date": "2026-10-13T00:51:17.107Z" + }, + "quality": { + "hybrid": { + "hit1": 0.55, + "recall5": 0.7, + "mrr": 0.6102314814814815, + "crossLingualMrr": 0.5166666666666666 + }, + "bm25": { + "hit1": 0.5083333333333333, + "recall5": 0.7, + "mrr": 0.5873842592592593, + "crossLingualMrr": 0.4584126984126983 + }, + "semantic": { + "hit1": 0.4583333333333333, + "recall5": 0.6333333333333333, + "mrr": 0.5379464285714287, + "crossLingualMrr": 0.43860544217687075 + } + }, + "speed": { + "memories": 2000, + "searchHybridMs": { + "p50": 2.5898340000003373, + "p95": 3.8565830000006827 + }, + "searchKeywordMs": { + "p50": 0.634291000000303, + "p95": 1.6149590000004537 + }, + "writeMs": { + "p50": 3.17541699999947, + "p95": 4.06970900000033 + }, + "readMs": { + "p50": 0.009750000000167347, + "p95": 0.016417000000728876 + }, + "embedPerSec": 579, + "rssMB": 271 + } +} \ No newline at end of file diff --git a/benchmarks/results/bench-none.json b/benchmarks/results/bench-none.json new file mode 100644 index 0000000..e806e59 --- /dev/null +++ b/benchmarks/results/bench-none.json @@ -0,0 +1,34 @@ +{ + "meta": { + "model": null, + "node": "v25.6.1", + "platform": "darwin-arm64", + "date": "2026-10-13T00:49:31.937Z" + }, + "quality": { + "bm25": { + "hit1": 0.5083333333333333, + "recall5": 0.7, + "mrr": 0.5873842592592593, + "crossLingualMrr": 0.4584126984126983 + } + }, + "speed": { + "memories": 2000, + "searchHybridMs": null, + "searchKeywordMs": { + "p50": 0.6992089999999962, + "p95": 1.6281660000000215 + }, + "writeMs": { + "p50": 0.13104199999997945, + "p95": 0.2563329999999837 + }, + "readMs": { + "p50": 0.0072920000000067375, + "p95": 0.009541999999981954 + }, + "embedPerSec": 36263, + "rssMB": 64 + } +} \ No newline at end of file diff --git a/benchmarks/results/longmemeval-none.json b/benchmarks/results/longmemeval-none.json new file mode 100644 index 0000000..7143d97 --- /dev/null +++ b/benchmarks/results/longmemeval-none.json @@ -0,0 +1,6366 @@ +{ + "meta": { + "dataset": "LongMemEval-S (cleaned)", + "granularity": "session", + "turns": "user (official)", + "model": null, + "questions": 419, + "node": "v25.6.1", + "platform": "darwin-arm64", + "date": "2026-10-12T21:48:24.764Z", + "seconds": 2 + }, + "overall": { + "bm25": { + "recall_any@5": 0.954653937947494, + "recall_all@5": 0.8424821002386634, + "ndcg_any@5": 0.8723491234274473, + "recall_any@10": 0.964200477326969, + "recall_all@10": 0.8926014319809069, + "ndcg_any@10": 0.8816528244375521 + } + }, + "byType": { + "knowledge-update": { + "n": 72, + "recall_any@5": 1, + "recall_all@5": 0.9722222222222222, + "ndcg_any@5": 0.9749499254216276, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9795140725242109 + }, + "multi-session": { + "n": 121, + "recall_any@5": 0.9669421487603306, + "recall_all@5": 0.7024793388429752, + "ndcg_any@5": 0.8122064111672764, + "recall_any@10": 0.9752066115702479, + "recall_all@10": 0.7933884297520661, + "ndcg_any@10": 0.8303707065454884 + }, + "single-session-assistant": { + "n": 5, + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + }, + "single-session-preference": { + "n": 30, + "recall_any@5": 0.8, + "recall_all@5": 0.8, + "ndcg_any@5": 0.6841239671428611, + "recall_any@10": 0.8333333333333334, + "recall_all@10": 0.8333333333333334, + "ndcg_any@10": 0.6941583003316604 + }, + "single-session-user": { + "n": 64, + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + }, + "temporal-reasoning": { + "n": 127, + "recall_any@5": 0.9291338582677166, + "recall_all@5": 0.8267716535433071, + "ndcg_any@5": 0.8465920733875345, + "recall_any@10": 0.9448818897637795, + "recall_all@10": 0.8818897637795275, + "ndcg_any@10": 0.8550229583908437 + } + }, + "perQuestion": [ + { + "id": "e47becba", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "118b2229", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "51a45a95", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "58bf7951", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1e043500", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c5e8278d", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6ade9755", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6f9b354f", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "58ef2f1c", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "f8c5f88b", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "5d3d2817", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "7527f7e2", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c960da58", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "3b6f954b", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "726462e0", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "94f70d80", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "66f24dbb", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "ad7109d1", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "af8d2e46", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "dccbc061", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c8c3f81d", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8ebdbe50", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6b168ec8", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "75499fd8", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "21436231", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "95bcc1c8", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0862e8bf", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "853b0a1d", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a06e4cfe", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "37d43f65", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b86304ba", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "d52b4f67", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "25e5aa4f", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "caf9ead2", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8550ddae", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "60d45044", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "3f1e9474", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "86b68151", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "577d4d32", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "ec81a493", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "15745da0", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e01b8e2f", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "bc8a6e93", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "ccb36322", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "001be529", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b320f3f8", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "19b5f2b3", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4fd1909e", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "545bd2b5", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8a137a7f", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "76d63226", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "86f00804", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8e9d538c", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "311778f1", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c19f7a0b", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4100d0a0", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "29f2956b", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1faac195", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "faba32e5", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "f4f1d8a4", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c14c00dd", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "36580ce8", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "3d86fd0a", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a82c026e", + "type": "single-session-user", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0a995998", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6d550036", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.10075757095025123 + } + } + }, + { + "id": "gpt4_59c863d7", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.47909091485969846, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6936189039107378 + } + } + }, + { + "id": "b5ef892d", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6934264036172708 + } + } + }, + { + "id": "e831120c", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "3a704032", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "gpt4_d84a3211", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "aae3761f", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_f2262a51", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "dd2973ad", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.75, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.75 + } + } + }, + { + "id": "c4a1ceb8", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.6166463990037038, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7231110467503035 + } + } + }, + { + "id": "gpt4_a56e767c", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.38009376671593426, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.38009376671593426 + } + } + }, + { + "id": "6cb6f249", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "46a3abf7", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.9502344167898356, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9502344167898356 + } + } + }, + { + "id": "36b9f61e", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.9502344167898356, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9502344167898356 + } + } + }, + { + "id": "28dc39ac", + "type": "multi-session", + "gold": 5, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_2f8be40d", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.16369747519436975, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.28360370847843547 + } + } + }, + { + "id": "2e6d26dc", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7763433706236033, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.7763433706236033 + } + } + }, + { + "id": "gpt4_15e38248", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.47909091485969846, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.47909091485969846 + } + } + }, + { + "id": "88432d0a", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.20151514190050246, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.3022727128507537 + } + } + }, + { + "id": "80ec1f4f", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.7153382790366966, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7153382790366966 + } + } + }, + { + "id": "d23cf73b", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.9360403422435027, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9360403422435027 + } + } + }, + { + "id": "gpt4_7fce9456", + "type": "multi-session", + "gold": 5, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7386919056633241, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.8322826352853723 + } + } + }, + { + "id": "d682f1a2", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.6199062332840657, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.6199062332840657 + } + } + }, + { + "id": "7024f17c", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "gpt4_5501fe77", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_2ba83207", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7984848580994974, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.7984848580994974 + } + } + }, + { + "id": "2318644b", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "2ce6a0f2", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.6584645692843067, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7820230128403328 + } + } + }, + { + "id": "gpt4_d12ceb0e", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.543791241910304, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.543791241910304 + } + } + }, + { + "id": "00ca467f", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b3c15d39", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_31ff4165", + "type": "multi-session", + "gold": 5, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7019304721653611, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.8105479816216159 + } + } + }, + { + "id": "eeda8a6d", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "2788b940", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.8403030283801005, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9467676761267002 + } + } + }, + { + "id": "60bf93ed", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "9d25d4e0", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "129d1232", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7601875334318685, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8955796649110442 + } + } + }, + { + "id": "60472f9c", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "gpt4_194be4b3", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.20151514190050246, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.20151514190050246 + } + } + }, + { + "id": "a9f6b44c", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.543791241910304, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.543791241910304 + } + } + }, + { + "id": "d851d5ba", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "5a7937c8", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_ab202e7f", + "type": "multi-session", + "gold": 5, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5788417167007833, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7719800769539802 + } + } + }, + { + "id": "gpt4_e05b82a6", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.6584645692843067, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7722349873850949 + } + } + }, + { + "id": "gpt4_731e37d7", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.543791241910304, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.543791241910304 + } + } + }, + { + "id": "edced276", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.75, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.75 + } + } + }, + { + "id": "10d9b85a", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.5654648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.5654648767857288 + } + } + }, + { + "id": "e3038f8c", + "type": "multi-session", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8181615409042062, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8181615409042062 + } + } + }, + { + "id": "2b8f3739", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.7338381252682711, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7338381252682711 + } + } + }, + { + "id": "1a8a66a6", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.4298593499260986, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.4298593499260986 + } + } + }, + { + "id": "c2ac3c61", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "bf659f65", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.543791241910304, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6908315825767142 + } + } + }, + { + "id": "gpt4_372c3eed", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7601875334318685, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9072278740982787 + } + } + }, + { + "id": "gpt4_2f91af09", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "81507db6", + "type": "multi-session", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8a2466db", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "06878be2", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "75832dbd", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0edc2aef", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "35a27287", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "32260d93", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "195a1a1b", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.6309297535714575, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6309297535714575 + } + } + }, + { + "id": "afdc33df", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "caf03d32", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "54026fce", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "06f04340", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "6b7dfb22", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1a1907b4", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "09d032c9", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "38146c39", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "d24813b1", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.3010299956639812 + } + } + }, + { + "id": "57f827a0", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "95228167", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.6309297535714575, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6309297535714575 + } + } + }, + { + "id": "505af2f5", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "75f70248", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "d6233ab6", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1da05512", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "fca70973", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.6309297535714575, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6309297535714575 + } + } + }, + { + "id": "b6025781", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a89d7624", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "b0479f84", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1d4e3b97", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "07b6f563", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1c0ddc50", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.6309297535714575, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6309297535714575 + } + } + }, + { + "id": "0a34ad58", + "type": "single-session-preference", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "d3ab962e", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "2311e44b", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "cc06de0d", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a11281a2", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4f54b7c9", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "85fa3a3f", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "9aaed6a3", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1f2b8d4f", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e6041065", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "51c32626", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "d905b33f", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "7405e8b1", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "f35224e0", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6456829e", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "a4996e51", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "3c1045c8", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6934264036172708 + } + } + }, + { + "id": "60036106", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "681a1674", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e25c3b8d", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4adc0475", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4bc144e2", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "ef66a6e5", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.75, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.75 + } + } + }, + { + "id": "5025383b", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a1cc6108", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "9ee3ecd6", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "3fdac837", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.75, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.75 + } + } + }, + { + "id": "91b15a6e", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "27016adc", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "720133ac", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "77eafa52", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8979f9ec", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0100672e", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a96c20ee", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "92a0aa75", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "3fe836c9", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1c549ce4", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6c49646a", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1192316e", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0ea62687", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "67e0d0f2", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "bb7c3b45", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "ba358f49", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "61f8c8f8", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "60159905", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "ef9cf60a", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "73d42213", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "bc149d6b", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "099778bb", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "09ba9854", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "d6062bb9", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "157a136e", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "c18a7dc8", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "a3332713", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "55241a1f", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a08a253f", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "f0e564bc", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "078150f1", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8cf4d046", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "a346bb18", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.75, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.75 + } + } + }, + { + "id": "37f165cf", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8e91e7d9", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "87f22b4a", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e56a43b9", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "efc3f7c2", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "21d02d0d", + "type": "multi-session", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_59149c77", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "gpt4_f49edff3", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "71017276", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b46e15ed", + "type": "temporal-reasoning", + "gold": 4, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.6387878864795979, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.6387878864795979 + } + } + }, + { + "id": "gpt4_fa19884c", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0bc8ad92", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.543791241910304, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.658210866856708 + } + } + }, + { + "id": "af082822", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_4929293a", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_b5700ca9", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "9a707b81", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_1d4ab0c9", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_e072b769", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0db4c65d", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_1d80365e", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_7f6b06db", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.23981246656813146, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.23981246656813146 + } + } + }, + { + "id": "gpt4_6dc9b45b", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_8279ba02", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_18c2b244", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_a1b77f9c", + "type": "temporal-reasoning", + "gold": 6, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9922385874580825 + } + } + }, + { + "id": "gpt4_1916e0ea", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_7a0daae1", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_468eb063", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.6309297535714575, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6309297535714575 + } + } + }, + { + "id": "gpt4_7abb270c", + "type": "temporal-reasoning", + "gold": 6, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.6824663776358925, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.7135769373515951 + } + } + }, + { + "id": "gpt4_1e4a8aeb", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_4fc4f797", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4dfccbf7", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_61e13b3c", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_45189cb4", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.7836037084784354, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7836037084784354 + } + } + }, + { + "id": "2ebe6c90", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_e061b84f", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.11990623328406573 + } + } + }, + { + "id": "370a8ff4", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_d6585ce8", + "type": "temporal-reasoning", + "gold": 5, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7386919056633241, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.7386919056633241 + } + } + }, + { + "id": "gpt4_4ef30696", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_ec93e27f", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6e984301", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8077ef71", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_f420262c", + "type": "temporal-reasoning", + "gold": 5, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.7386919056633241, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.932295706899544 + } + } + }, + { + "id": "gpt4_8e165409", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_74aed68e", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "bcbe585f", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_21adecb5", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "5e1b23de", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_98f46fc6", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_af6db32f", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "eac54adc", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "gpt4_7ddcf75f", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_a2d1d1f6", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_85da3956", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_b0863698", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_68e94287", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.7153382790366966, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.7153382790366966 + } + } + }, + { + "id": "gpt4_e414231e", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_7ca326fa", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.9502344167898356, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9502344167898356 + } + } + }, + { + "id": "gpt4_7bc6cf22", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "2ebe6c92", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.75, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.75 + } + } + }, + { + "id": "gpt4_e061b84g", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "71017277", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "b46e15ee", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_d6585ce9", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_1e4a8aec", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.43067655807339306, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.43067655807339306 + } + } + }, + { + "id": "gpt4_f420262d", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.25, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.25 + } + } + }, + { + "id": "gpt4_59149c78", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "gpt4_e414231f", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_4929293b", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "gpt4_468eb064", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_fa19884d", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.43067655807339306, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.43067655807339306 + } + } + }, + { + "id": "9a707b82", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.43067655807339306, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.43067655807339306 + } + } + }, + { + "id": "eac54add", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "4dfccbf8", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0bc8ad93", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.5 + } + } + }, + { + "id": "6e984302", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.3333333333333333 + } + } + }, + { + "id": "gpt4_8279ba03", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "gpt4_b5700ca0", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_68e94288", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 0, + "recall_all@5": 0, + "ndcg_any@5": 0, + "recall_any@10": 0, + "recall_all@10": 0, + "ndcg_any@10": 0 + } + } + }, + { + "id": "gpt4_2655b836", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_2487a7cb", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "gpt4_76048e76", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_2312f94c", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0bb5a684", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "08f4fc43", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "2c63a862", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "gpt4_385a5000", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "2a1811e2", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "bbf86515", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_5dcc0aab", + "type": "temporal-reasoning", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.43067655807339306, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.43067655807339306 + } + } + }, + { + "id": "gpt4_0b2f1d21", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "f0853d11", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_6ed717ea", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_70e84552", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a3838d2b", + "type": "temporal-reasoning", + "gold": 6, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.9782642268827851 + } + } + }, + { + "id": "gpt4_93159ced", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6934264036172708 + } + } + }, + { + "id": "gpt4_2d58bcd6", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_65aabe59", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "982b5123", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b9cfe692", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "gpt4_4edbafa2", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c8090214", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_483dd43c", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e4e14d04", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c9f37c46", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_2c50253f", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "dcfa8644", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_b4a80587", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_9a159967", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.543791241910304, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.658210866856708 + } + } + }, + { + "id": "cc6d1ec1", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_8c8961ae", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_d9af6064", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_7de946e7", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "d01c6aa8", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "993da5e2", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a3045048", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_d31cdae3", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_cd90e484", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_88806d6e", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_4cd9eba1", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_93f6379c", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b29f3365", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_2f56ae70", + "type": "temporal-reasoning", + "gold": 3, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.38009376671593426, + "recall_any@10": 1, + "recall_all@10": 0, + "ndcg_any@10": 0.38009376671593426 + } + } + }, + { + "id": "6613b389", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_78cf46a3", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_0a05b494", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_1a1dc16d", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_2f584639", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_213fd887", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_5438fa52", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "gpt4_c27434e8", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "gpt4_fe651585", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8c18457d", + "type": "temporal-reasoning", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6a1eabeb", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6aeb4375", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "830ce83f", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6781035935540111 + } + } + }, + { + "id": "852ce960", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "945e3d21", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "d7c942c3", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "71315a70", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "89941a93", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "ce6d2d27", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "9ea5eabc", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "07741c44", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a1eacc2a", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "184da446", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "031748ae", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4d6b87c8", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0f05491a", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "08e075c7", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "f9e8c073", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "41698283", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "2698e78f", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b6019101", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "45dc21b6", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "5a4f22c0", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6071bd76", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e493bb7c", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "618f13b2", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "72e3ee87", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c4ea545c", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.75, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.75 + } + } + }, + { + "id": "01493427", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "6a27ffc2", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "2133c1b5", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "18bc8abd", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "db467c8c", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "7a87bd0c", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e61a7584", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "1cea1afa", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "ed4ddc30", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "8fb83627", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "b01defab", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "22d2cb42", + "type": "knowledge-update", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0e4e4c46", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4b24c848", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "7e974930", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "603deb26", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "59524333", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "5831f84d", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "eace081b", + "type": "knowledge-update", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "affe2881", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "50635ada", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "e66b632c", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0ddfec37", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "f685340e", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "cc5ded98", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "dfde3500", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "69fee5aa", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "7401057b", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "cf22b7bf", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "a2f3aa27", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c7dc5443", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "06db6396", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "3ba21379", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "9bbe84a2", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "10e09553", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "dad224aa", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 0.8154648767857288, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.8154648767857288 + } + } + }, + { + "id": "ba61f0b9", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "42ec0761", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "5c40ec5b", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "c6853660", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "26bdc477", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "0977f2af", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 0, + "ndcg_any@5": 0.5, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 0.6505149978319906 + } + } + }, + { + "id": "89941a94", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "07741c45", + "type": "knowledge-update", + "gold": 2, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "f523d9fe", + "type": "single-session-assistant", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "dc439ea3", + "type": "single-session-assistant", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "5809eb10", + "type": "single-session-assistant", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "4388e9dd", + "type": "single-session-assistant", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + }, + { + "id": "561fabcd", + "type": "single-session-assistant", + "gold": 1, + "metrics": { + "bm25": { + "recall_any@5": 1, + "recall_all@5": 1, + "ndcg_any@5": 1, + "recall_any@10": 1, + "recall_all@10": 1, + "ndcg_any@10": 1 + } + } + } + ] +} \ No newline at end of file diff --git a/benchmarks/tune-fusion.js b/benchmarks/tune-fusion.js new file mode 100644 index 0000000..c8d3ccb --- /dev/null +++ b/benchmarks/tune-fusion.js @@ -0,0 +1,60 @@ +#!/usr/bin/env node +/** + * Reproduces how DEFAULT_FUSION was chosen: grid over fusion method and + * semantic weight on the golden set, split into a dev half (odd queries, + * used for the choice) and a test half (even queries, reported only). + * + * Usage: node benchmarks/tune-fusion.js [model ...] + */ + +import { readFileSync } from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; +import { MemoryStore } from "../src/store/memory-store.js"; +import { createEmbedder } from "../src/embeddings.js"; +import { withCache } from "./lib/cached-embedder.js"; +import { reciprocalRank, recallAny, mean } from "./lib/metrics.js"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const data = JSON.parse(readFileSync(path.join(__dirname, "golden", "dataset.json"), "utf8")); +const DAY = 86_400_000; +const NOW = Date.parse("2026-06-01T12:00:00Z"); + +const configs = []; +for (const method of ["rrf", "convex"]) { + for (const w of [0.3, 0.5, 0.6, 0.7, 0.8, 0.9]) configs.push({ method, semanticWeight: w }); +} +configs.push({ method: "rrf", semanticWeight: 1 }); // semantic only + +const models = process.argv.slice(2); +if (!models.length) models.push("granite-97m-multilingual", "arctic-embed-m-v2", "embeddinggemma-300m"); + +for (const model of models) { + const embedder = withCache(createEmbedder(model)); + if (!(await embedder.load())) throw new Error(`Model ${model} failed to load`); + let now = NOW; + const store = MemoryStore.open(":memory:", { embedder, clock: () => now }); + for (const m of [...data.memories].sort((a, b) => b.created_days_ago - a.created_days_ago)) { + now = NOW - m.created_days_ago * DAY; + await store.write({ id: m.id, topic: m.topic, content: m.content, tags: m.tags, agent: m.agent, importance: m.importance }); + } + now = NOW; + await store.flushEmbeddings(); + + console.log(`\n${embedder.id}`); + console.log("fusion | MRR dev | MRR test | R@5 dev | R@5 test"); + for (const fusion of configs) { + const split = { dev: [], test: [] }; + for (let i = 0; i < data.queries.length; i++) { + const q = data.queries[i]; + const { results } = await store.search({ query: q.query, limit: 10, tags: q.filters?.tags, agent: q.filters?.agent, fusion }); + const ranked = results.map((r) => r.id); + const gold = new Set(q.relevant); + (i % 2 ? split.dev : split.test).push([reciprocalRank(ranked, gold), recallAny(ranked, gold, 5)]); + } + const f = (xs, j) => mean(xs.map((x) => x[j])).toFixed(3); + const label = fusion.semanticWeight === 1 ? "semantic only" : `${fusion.method} w_sem=${fusion.semanticWeight}`; + console.log(`${label.padEnd(19)} | ${f(split.dev, 0)} | ${f(split.test, 0)} | ${f(split.dev, 1)} | ${f(split.test, 1)}`); + } + store.close(); +} diff --git a/docs/DOCUMENTATION.md b/docs/DOCUMENTATION.md index 5d126c1..b2f893e 100644 --- a/docs/DOCUMENTATION.md +++ b/docs/DOCUMENTATION.md @@ -1,1052 +1,314 @@ -# agent-memory-store — Documentation - -Full reference for all features, tools, search modes, the SKILL.MD governance skill, multi-agent coordination patterns, and architecture internals. - ---- - -## Table of Contents - -1. [Overview and Concepts](#1-overview-and-concepts) - - 1.1 [What is a chunk?](#11-what-is-a-chunk) - - 1.2 [What is state?](#12-what-is-state) - - 1.3 [The two-store model](#13-the-two-store-model) - - 1.4 [Project isolation](#14-project-isolation) -2. [Complete Tool Reference](#2-complete-tool-reference) - - 2.1 [search_context](#21-search_context) - - 2.2 [write_context](#22-write_context) - - 2.3 [read_context](#23-read_context) - - 2.4 [list_context](#24-list_context) - - 2.5 [delete_context](#25-delete_context) - - 2.6 [get_state](#26-get_state) - - 2.7 [set_state](#27-set_state) -3. [Search Modes](#3-search-modes) - - 3.1 [hybrid (default)](#31-hybrid-default) - - 3.2 [bm25](#32-bm25) - - 3.3 [semantic](#33-semantic) - - 3.4 [Choosing a mode](#34-choosing-a-mode) - - 3.5 [How RRF fusion works](#35-how-rrf-fusion-works) -4. [SKILL.MD Guide](#4-skillmd-guide) - - 4.1 [What SKILL.MD is](#41-what-skillmd-is) - - 4.2 [The read/write decision framework](#42-the-readwrite-decision-framework) - - 4.3 [When to READ](#43-when-to-read) - - 4.4 [When to WRITE](#44-when-to-write) - - 4.5 [How to install the skill](#45-how-to-install-the-skill) - - 4.6 [Compatibility](#46-compatibility) -5. [Multi-Agent Coordination](#5-multi-agent-coordination) - - 5.1 [Pipeline handoff protocol](#51-pipeline-handoff-protocol) - - 5.2 [Shared state conventions](#52-shared-state-conventions) - - 5.3 [Conflict resolution](#53-conflict-resolution) -6. [Bootstrap Protocol](#6-bootstrap-protocol) - - 6.1 [Detecting a virgin project](#61-detecting-a-virgin-project) - - 6.2 [The four bootstrap writes](#62-the-four-bootstrap-writes) - - 6.3 [Confirming with the user](#63-confirming-with-the-user) -7. [Deduplication](#7-deduplication) - - 7.1 [Why duplicates form](#71-why-duplicates-form) - - 7.2 [Search-before-write pattern](#72-search-before-write-pattern) - - 7.3 [Judging relevance](#73-judging-relevance) -8. [Tag Discipline](#8-tag-discipline) - - 8.1 [Tag rules](#81-tag-rules) - - 8.2 [Bad/good comparison](#82-badgood-comparison) - - 8.3 [Managing the vocabulary](#83-managing-the-vocabulary) -9. [Importance Levels](#9-importance-levels) -10. [TTL Guide](#10-ttl-guide) -11. [Performance Budgets](#11-performance-budgets) - - 11.1 [Operation benchmarks](#111-operation-benchmarks) - - 11.2 [Budget by corpus size](#112-budget-by-corpus-size) - - 11.3 [Scaling beyond 25K chunks](#113-scaling-beyond-25k-chunks) -12. [Architecture Deep Dive](#12-architecture-deep-dive) - - 12.1 [index.js — MCP server](#121-indexjs--mcp-server) - - 12.2 [store.js — Public API](#122-storejs--public-api) - - 12.3 [db.js — SQLite layer](#123-dbjs--sqlite-layer) - - 12.4 [search.js — Hybrid search engine](#124-searchjs--hybrid-search-engine) - - 12.5 [embeddings.js — Local embedding pipeline](#125-embeddingsjs--local-embedding-pipeline) - - 12.6 [bm25.js — Pure JS BM25 (reference)](#126-bm25js--pure-js-bm25-reference) - - 12.7 [migrate.js — Filesystem migration](#127-migratejs--filesystem-migration) -13. [Anti-Patterns](#13-anti-patterns) -14. [Quick Reference — Decision Tree](#14-quick-reference--decision-tree) - ---- - -## 1. Overview and Concepts - -### 1.1 What is a chunk? - -A chunk is the atomic unit of memory. Each chunk is a structured record stored in the `chunks` table: - -| Field | Type | Description | -| --- | --- | --- | -| `id` | string | 10-char hex (SHA-1 truncation of `agent:topic:timestamp:random`) | -| `topic` | string | Short, specific title — the primary search surface | -| `agent` | string | Agent ID that wrote this chunk (default: `"global"`) | -| `tags` | string[] | Canonical tags for filtering and retrieval | -| `importance` | string | `low` / `medium` / `high` / `critical` | -| `content` | string | Markdown body — the actual memory content | -| `embedding` | BLOB | 384-dim Float32 vector (may be `null` if not yet computed) | -| `created_at` | string | ISO 8601 timestamp | -| `updated_at` | string | ISO 8601 timestamp | -| `expires_at` | string | ISO 8601 timestamp, or `null` for permanent chunks | - -Chunks accumulate over time. They are written once and retrieved by search. To update a chunk, delete the old one and write a new version. - -### 1.2 What is state? - -State is a flat key-value store backed by the `state` table. Values are JSON-serialized — any JSON-serializable value is valid (string, number, boolean, object, array). - -State is designed for **mutable pipeline variables** that change frequently: current phase, active run ID, feature flags, counters. Unlike chunks, state is not searchable — it is retrieved only by exact key. - -`get_state` returns `null` (not an error) for keys that don't exist yet. - -### 1.3 The two-store model - -Understanding when to use each is critical for correct agent behavior: - -| | `write_context` / `search_context` | `set_state` / `get_state` | -| --- | --- | --- | -| **Model** | Accumulate over time | Point-in-time single value | -| **Retrieval** | Full-text + semantic search | Exact key lookup | -| **Use for** | Decisions, outputs, discoveries | Phase, run ID, flags, counters | -| **Overwrites?** | No — chunks accumulate (delete manually) | Yes — `set_state` overwrites | -| **Searchable?** | Yes | No | - -Never use `set_state` for data that should be searchable. Never use `write_context` for mutable counters or flags. - -### 1.4 Project isolation - -By default, the store is created at `.agent-memory-store/store.db` relative to `process.cwd()` — the directory where the MCP server starts. Each project directory gets its own isolated store automatically. - -To use a shared or global store, set `AGENT_STORE_PATH` to an absolute path: - -```bash -AGENT_STORE_PATH=/home/user/.global-agent-memory npx agent-memory-store -``` - -This is useful for agents that need to share memory across multiple repositories or for global project context. - ---- - -## 2. Complete Tool Reference - -### 2.1 `search_context` - -Search stored chunks using hybrid ranking (BM25 + semantic similarity). Call at the start of every task to retrieve relevant prior knowledge before acting. - -**Parameters:** - -| Name | Type | Required | Default | Constraints | Description | -| --- | --- | --- | --- | --- | --- | -| `query` | string | yes | — | — | Search query. Use specific, canonical terms. | -| `tags` | string[] | no | `[]` | — | Narrow to chunks matching any of these tags. | -| `agent` | string | no | — | — | Narrow to chunks written by a specific agent ID. | -| `top_k` | number | no | `6` | 1–20 | Maximum number of results to return. | -| `min_score` | number | no | `0.1` | ≥ 0 | Minimum relevance score. Lower = more permissive. | -| `search_mode` | string | no | `"hybrid"` | hybrid / bm25 / semantic | Search strategy. See [§3](#3-search-modes). | - -**Example call:** - -```json -{ - "query": "authentication decision JWT sessions", - "tags": ["auth", "decision"], - "top_k": 5, - "search_mode": "hybrid" -} -``` - -**Response format:** - -``` -### [score: 0.85] Auth service — JWT decision -**id:** `a1b2c3d4e5` | **agent:** pm-agent | **tags:** auth, decision | **importance:** critical | **updated:** 2025-06-01T14:00:00.000Z - -Chose stateless JWT. Rationale: no shared session store needed across services. -Refresh tokens stored in Redis with 7d TTL. Access tokens: 15min, RS256. +# agent-memory-store — Reference + +- [1. Concepts](#1-concepts) +- [2. Tools](#2-tools) +- [3. Search and ranking](#3-search-and-ranking) +- [4. Many agents, one store](#4-many-agents-one-store) +- [5. Embedding models](#5-embedding-models) +- [6. Configuration](#6-configuration) +- [7. Storage, schema and migrations](#7-storage-schema-and-migrations) +- [8. Programmatic use](#8-programmatic-use) +- [9. Benchmarks and how to reproduce them](#9-benchmarks-and-how-to-reproduce-them) +- [10. Limits and trade-offs](#10-limits-and-trade-offs) +- [11. Troubleshooting](#11-troubleshooting) --- -### [score: 0.71] Auth service — token refresh flow -... -``` - -Returns `"No matching chunks found."` when no results pass `min_score`. - ---- - -### 2.2 `write_context` - -Persist a memory chunk to the database. Call after completing a subtask, making a key decision, or producing output that downstream agents will need. - -**Parameters:** - -| Name | Type | Required | Default | Description | -| --- | --- | --- | --- | --- | -| `topic` | string | yes | — | Short, specific title. `"Auth — JWT decision"` not `"decision"`. | -| `content` | string | yes | — | Chunk body in markdown. Include rationale, not just conclusions. | -| `agent` | string | no | `"global"` | Agent ID writing this chunk (e.g. `"pm-agent"`, `"scraper-agent"`). | -| `tags` | string[] | no | `[]` | Canonical tags for future retrieval. Use consistent terms. | -| `importance` | string | no | `"medium"` | `low` / `medium` / `high` / `critical`. See [§9](#9-importance-levels). | -| `ttl_days` | number | no | — | Auto-expiry in days. Omit for permanent storage. See [§10](#10-ttl-guide). | - -**Example call:** - -```json -{ - "topic": "Auth service — chose JWT over sessions", - "content": "Chose stateless JWT. Rationale: no shared session store needed across services. Refresh tokens stored in Redis with 7d TTL. Access tokens: 15min, RS256.", - "agent": "pm-agent", - "tags": ["auth", "architecture", "decision"], - "importance": "critical" -} -``` - -**Response:** - -``` -Chunk saved: id=`a1b2c3d4e5` | topic="Auth service — chose JWT over sessions" | tags=[auth, architecture, decision] | importance=critical -``` - -**Important:** Embeddings are computed asynchronously. The chunk is immediately searchable via BM25; semantic search results may lag by ~200ms while the embedding model processes the content. - ---- - -### 2.3 `read_context` - -Retrieve the full content of a specific chunk by its ID. Use when you know the exact chunk ID (from a previous `search_context` or `list_context` result). - -**Parameters:** - -| Name | Type | Required | Description | -| --- | --- | --- | --- | -| `id` | string | yes | Chunk ID (10-char hex from `write_context` or `list_context`). | - -**Response:** - -``` -## Auth service — chose JWT over sessions -**id:** `a1b2c3d4e5` | **agent:** pm-agent | **tags:** auth, decision | **importance:** critical | **updated:** 2025-06-01T14:00:00.000Z - -Chose stateless JWT. Rationale: no shared session store needed across services... -``` - -Returns `"No chunk found with id \`{id}\`."` for unknown IDs. - ---- - -### 2.4 `list_context` - -List all stored chunks (metadata only, no body). Use for store inventory, curation, and finding chunks to delete. +## 1. Concepts -**Parameters:** +**Memory** — a short, self-contained piece of knowledge an agent wants others to +find later: a decision and its rationale, an output and where it lives, a +discovery. Fields: -| Name | Type | Required | Default | Constraints | Description | -| --- | --- | --- | --- | --- | --- | -| `agent` | string | no | — | — | Filter by agent ID. | -| `tags` | string[] | no | `[]` | — | Filter by tags (any match). | -| `limit` | number | no | `100` | 1–500 | Maximum results to return. | -| `offset` | number | no | `0` | ≥ 0 | Results to skip for pagination. | - -**Example — paginate through a large store:** - -```json -{ "limit": 100, "offset": 0 } // page 1 -{ "limit": 100, "offset": 100 } // page 2 -{ "limit": 100, "offset": 200 } // page 3 -``` - -**Response:** - -``` -3 chunk(s) found: - -- `a1b2c3d4e5` **Auth service — JWT decision** | agent:pm-agent | tags:[auth, decision] | critical | 2025-06-01T14:00:00.000Z -- `f6g7h8i9j0` **Scraper run 042 — output** | agent:scraper-agent | tags:[scraper, output] | high | 2025-06-01T15:30:00.000Z -- `k1l2m3n4o5` **Staging deploy config** | agent:global | tags:[config, infra] | medium | 2025-05-28T09:00:00.000Z -``` - ---- - -### 2.5 `delete_context` - -Permanently delete a chunk by ID. Use to remove outdated or incorrect memory before writing an updated version (see [§7 Deduplication](#7-deduplication)). - -**Parameters:** - -| Name | Type | Required | Description | -| --- | --- | --- | --- | -| `id` | string | yes | Chunk ID to permanently delete. | - -**Response:** `"Chunk \`{id}\` deleted."` or `"No chunk found with id \`{id}\`."`. - -Deletion is permanent. Expired chunks (TTL-based) are also non-recoverable. +| Field | Description | +| --- | --- | +| `id` | Generated 12-hex id, or a stable id you choose (`auth-decision`). | +| `topic` | Specific title. Weighted 3× in keyword search. | +| `content` | Markdown body. | +| `tags` | Lowercase labels, matched exactly. Weighted 2× in keyword search. | +| `agent` | Agent that created it. `updated_by` tracks the last writer. | +| `importance` | `low` / `medium` / `high` / `critical`. Breaks near-ties in ranking. | +| `version` | Starts at 1, +1 on every update. Used for compare-and-set. | +| `created_at`, `updated_at` | ISO 8601. | +| `expires_at` | Set by `ttl_days`. Expired memories are invisible immediately and deleted within a minute. | + +**State** — a key → JSON value map for small mutable coordination data (current +phase, run id, owner of a task, counters). Every key has a `version`. + +Rule of thumb: if another agent should *find* it, it is a memory; if another +agent should *read a known key*, it is state. --- -### 2.6 `get_state` +## 2. Tools -Read a pipeline state variable by key. Use to check progress, flags, and counters across agent turns. +All tools return plain text designed to be short and readable by a model. +Failures return `isError: true` with an actionable message (validation errors, +version conflicts, refused secrets, unknown ids) — never a stack trace. -**Parameters:** +### `search_context` (read-only) -| Name | Type | Required | Description | +| Param | Type | Default | Notes | | --- | --- | --- | --- | -| `key` | string | yes | State key to read (e.g. `"current_phase"`, `"project_tags"`). | - -**Response:** The stored value as a string or formatted JSON. Returns `"State key "{key}" not found."` for missing keys — this is not an error condition. +| `query` | string | — | Natural language, any language, or exact identifiers. Punctuation is safe. | +| `tags` | string[] | — | At least one must match (exact, case-insensitive). | +| `agent` | string | — | Creator agent id. | +| `since` / `until` | ISO date | — | Filter on `updated_at`. | +| `top_k` | 1–50 | 6 | | +| `min_score` | 0–1 | 0 | Drops results below this rank-based score. | +| `search_mode` | `hybrid` \| `bm25` \| `semantic` | `hybrid` | Falls back to `bm25` while the model loads or if it is unavailable; the response says which mode ran. | +| `max_chars` | 100–20000 | 1000 | Content shown per result; longer content is cut with a pointer to `read_context`. | -**Common state keys by convention:** - -| Key | Typical value | Description | -| --- | --- | --- | -| `project_tags` | `{ "vocabulary": [...], "updated": "..." }` | Tag vocabulary. Empty = virgin project. | -| `current_phase` | `"scraping"` / `"analysis"` | Pipeline phase tracker. | -| `pipeline_{run_id}` | `{ "phase": "...", "agent": "...", ... }` | Per-run state for multi-agent pipelines. | +Example response: ---- - -### 2.7 `set_state` - -Write a pipeline state variable. Overwrites any existing value for the same key. - -**Parameters:** - -| Name | Type | Required | Description | -| --- | --- | --- | --- | -| `key` | string | yes | State key (e.g. `"pipeline_status"`, `"current_phase"`). | -| `value` | any | yes | Any JSON-serializable value (string, number, boolean, object, array). | - -**Response:** `"State "{key}" written at {timestamp}."`. - -**Example:** - -```json -{ - "key": "pipeline_run_042", - "value": { - "phase": "notification", - "step": 3, - "input_file": "data/shortlist.json", - "agent": "notifier-agent", - "started_at": "2025-06-01T14:00:00Z" - } -} ``` +2 result(s), hybrid search: ---- - -## 3. Search Modes - -### 3.1 hybrid (default) - -Combines BM25 full-text search and semantic vector similarity, merged via Reciprocal Rank Fusion (RRF). This is the recommended mode for general use. - -The query is processed in two parallel paths: -1. FTS5 BM25 search (synchronous, uses the `chunks_fts` virtual table) -2. Query embedding computation (asynchronous, 384-dim vector) - -Results are then merged using RRF with weights BM25=0.4, semantic=0.6. See [§3.5](#35-how-rrf-fusion-works) for the formula. - -Falls back to BM25-only silently if the embedding model is unavailable. - -### 3.2 bm25 - -FTS5 keyword matching only. No embedding computation. Fast and deterministic. - -FTS5 query construction: special characters (`* ^ : ( ) { } [ ]`) are stripped, tokens are split on whitespace, joined with `OR`, minimum token length is 2 characters. This means `"JWT auth decision"` becomes `JWT OR auth OR decision`. - -**Best for:** exact tag lookups, canonical term searches, queries where you know the precise vocabulary used at write time. - -### 3.3 semantic - -Vector cosine similarity only. Brute-force: all stored embeddings are loaded into memory, cosine similarity is computed against the query embedding. - -Content is truncated to 800 characters before embedding (topic + tags + content concatenated). The model (`all-MiniLM-L6-v2`) produces 384-dim Float32 vectors, mean-pooled and L2-normalized. - -**Best for:** cross-lingual queries (e.g., searching "autenticação" when chunks say "auth"), conceptual similarity when exact terms differ. - -**Memory note:** at 50K chunks, all embeddings occupy ~75MB of RAM (50,000 × 384 × 4 bytes). For large stores, prefer `bm25` or `hybrid` (which still benefits from semantic scoring without the full in-memory load). - -### 3.4 Choosing a mode - -| Situation | Recommended mode | -| --- | --- | -| General use (unknown query type) | `hybrid` | -| Exact tag or term lookup | `bm25` | -| Query in different language than stored content | `semantic` | -| Chunk just written (<200ms ago), need immediate result | `bm25` | -| Very large stores where memory is constrained | `bm25` | -| Embeddings not yet computed (embedding model failed) | `bm25` | - -### 3.5 How RRF fusion works - -Reciprocal Rank Fusion assigns a score to each document based on its rank in each list, then sums weighted contributions: - -``` -score = w_bm25 / (K + rank_bm25 + 1) - + w_vec / (K + rank_vec + 1) +[1] Auth — chose JWT over sessions +id: 3f9a0c12be41 · score 0.98 · similarity 0.81 · tags: auth, decision · critical · by backend-agent · updated 2026-09-30 (v2) +Stateless JWT (RS256). Refresh tokens in Redis, 7d TTL. ... ``` -Where: -- `w_bm25 = 0.4`, `w_vec = 0.6` -- `K = 60` (smoothing constant — reduces sensitivity to top-rank differences) -- `rank_*` is 0-indexed position in each ranked list +### `write_context` -Documents appearing in **both** lists receive additive contributions from both terms, naturally boosting high-quality matches. Documents appearing in only one list receive a partial score. RRF is robust to score scale differences between BM25 and cosine similarity. - ---- - -## 4. SKILL.MD Guide - -### 4.1 What SKILL.MD is - -[`skills/SKILL.MD`](../skills/SKILL.MD) is a governance skill — a structured prompt file that agents load to govern when and how to interact with persistent memory. - -It is **tool-agnostic**: the patterns apply to any MCP server exposing `search_context`/`write_context`/`get_state`/`set_state` equivalents. The skill uses Claude Code's frontmatter format to declare a name and a natural-language trigger description, so agents that support skill loading know when to activate it automatically. - -**Two levels of memory instruction:** - -| Level | What it is | When to use | +| Param | Type | Notes | | --- | --- | --- | -| System prompt snippet (README) | 10-line quick-start guidance | Simple, single-agent use | -| `skills/SKILL.MD` | Full governance skill (12 sections) | Multi-agent pipelines, complex projects | - -### 4.2 The read/write decision framework - -Before taking any substantive action, ask two questions: - -1. **"Is there something in memory I should know before I act?"** - → If yes, or if uncertain: **read first**. - -2. **"Will the result of this action be needed later — by me or another agent?"** - → If yes: **write after**. - -If both are yes, the pattern is: **read → act → write**. - -If neither is yes, skip memory entirely and act normally. Memory is not a logging system — it stores decisions, outputs, and discoveries that affect future work. - -### 4.3 When to READ - -**Trigger 1 — Cold start (first action in a new session)** - -Before any work in a fresh session, bootstrap your context: - -``` -search_context({ query: "project conventions stack architecture", top_k: 5 }) -get_state("project_tags") -get_state("current_phase") -``` - -If all three return empty, you are in a virgin project. See [§6 Bootstrap Protocol](#6-bootstrap-protocol). - -**Trigger 2 — New task or instruction received** - -Search before doing anything else. You may have done related work before, or another agent may have left relevant context. - -``` -Incoming: "Set up the staging deployment pipeline" -→ search_context({ query: "staging deployment pipeline", top_k: 5 }) -→ search_context({ query: "infrastructure decisions", top_k: 3 }) -→ Incorporate findings, then proceed. -``` - -**Trigger 3 — A named entity appears** - -When input mentions a specific project, system, service, agent, or acronym you don't have full context on, search before assuming. - -``` -Incoming: "Continue the TAYA Jira integration" -→ search_context({ query: "TAYA Jira integration", tags: ["taya", "jira"] }) -``` - -Named entities are the strongest signal that prior work exists in memory. - -**Trigger 4 — Uncertainty about a fact** - -If you catch yourself about to write a value, URL, credential format, or decision you're not certain about — stop and search. Guessing when the answer exists in memory is the failure mode that makes multi-agent systems unreliable. - -``` -Internal signal: "I think the API endpoint was /v2/... but I'm not sure" -→ search_context({ query: "API endpoint config" }) -``` - -**Trigger 5 — Handoff received from another agent** - -Always read state and search for the sending agent's outputs before continuing. - -``` -Handoff: "HANDOFF Scraper→Analyzer | run-042 | ✅ | 87 items" -→ get_state("pipeline_run_042") -→ search_context({ query: "scraper output run 042", top_k: 4 }) -``` - -The handoff message is a pointer, not a full briefing. +| `topic` | string | Required. | +| `content` | string | Required. | +| `id` | string | Update this memory in place, or create it with this id. `[A-Za-z0-9][A-Za-z0-9._:-]{0,127}`. | +| `tags` | string[] | Normalized to lowercase, deduplicated. On update, omitted = keep. | +| `importance` | enum | On update, omitted = keep. Default `medium`. | +| `agent` | string | Defaults to `AGENT_MEMORY_AGENT` or `global`. | +| `ttl_days` | number \| null | Omitted = keep current expiry; `null` = never expire. | +| `expected_version` | integer | Write only if the current version matches (`0` = must not exist). | -**Trigger 6 — Resuming after a pause or session restart** +The response reports `Created`/`Updated`, the new version, and up to three +**possible duplicates**: memories with the same topic (case-insensitive) or +semantic similarity above the model's duplicate threshold. Content that looks +like a credential is refused (see [§10](#10-limits-and-trade-offs)). -If any signal suggests this task was interrupted, read state and search: +### `read_context` (read-only) -``` -→ get_state("current_phase") -→ search_context({ query: "phase 3 output decisions", top_k: 5 }) -``` +`id` → full content and metadata. Unknown or expired ids are errors. -### 4.4 When to WRITE +### `list_context` (read-only) -**Trigger 1 — Decision made with rationale** +Newest first, metadata only (with content length). Filters: `agent`, `tags`, +`since`, `until`. Paging: `limit` (1–500, default 50), `offset`. The response +states the total and the next offset. -Persist any non-trivial choice with the reasoning. Future agents need the *why*, not just the *what*. +### `delete_context` (destructive) -```json -{ - "topic": "Auth service — chose JWT over sessions", - "content": "Chose stateless JWT. Rationale: no shared session store needed across services. Refresh tokens stored in Redis with 7d TTL. Access tokens: 15min, RS256.", - "tags": ["auth", "architecture", "decision"], - "importance": "critical" -} -``` +`id` → deletes the memory, its vector and its index entries. Unknown ids are errors. -**Trigger 2 — Subtask completed with output** +### `get_state` (read-only) / `set_state` -When you finish a discrete unit of work that produces something another agent or future session will consume: +`get_state(key)` returns the value, version, time and writer (or "not set, +version 0"). `set_state(key, value, expected_version?, agent?)` stores any JSON +value; with `expected_version` it is a compare-and-set: -```json -{ - "topic": "Scraper run 042 — 87 listings collected", - "content": "Raw file at data/raw.json. Source: ZAP Imóveis. Filters: SP capital, 2+ bedrooms, < R$800k. Rate: 2 req/s, 0 blocks. Duration: 4m12s.", - "tags": ["scraper", "output"], - "importance": "high" -} ``` - -**Trigger 3 — Discovery that changes understanding** - -If you learn something that updates prior assumptions — an API changed, a config is different from documented, an edge case was found — write it immediately. - -```json -{ - "topic": "ZAP API — rate limit changed to 1 req/s", - "content": "As of 2025-06: rate limit tightened from 2 to 1 req/s. Previous setting causes 429s. Updated scraper config accordingly.", - "tags": ["scraper", "config", "discovery"], - "importance": "high", - "ttl_days": 30 -} -``` - -**Trigger 4 — Before ending your turn in a pipeline** - -Before passing control, **always in this order**: write output → update state → send handoff. - -If the handoff is sent before the write, the receiving agent may search memory before the chunk exists. - -``` -# 1. Persist output -write_context({ - topic: "Analyzer run 042 — shortlist produced", - content: "214 analyzed → 12 shortlisted at data/shortlist.json. ...", - tags: ["analyzer", "output"], - importance: "high" -}) - -# 2. Update pipeline state -set_state("pipeline_run_042", { - phase: "notification", - step: 3, - input_file: "data/shortlist.json", - agent: "notifier-agent", - started_at: "2025-06-01T14:00:00Z" -}) - -# 3. Send minimal handoff (detail is in memory) -# HANDOFF Analyzer→Notifier | run-042 | ✅ | 12 shortlisted -``` - -### 4.5 How to install the skill - -**Claude Code (recommended):** - -Copy `skills/SKILL.MD` to your Claude Code skills directory: - -```bash -# Project-level (only for this project) -cp skills/SKILL.MD .claude/skills/SKILL.MD - -# Global (available in all projects) -cp skills/SKILL.MD ~/.claude/skills/agent-memory.md -``` - -Claude Code reads the frontmatter `name:` and `description:` fields to decide when to activate the skill automatically. The description covers all the trigger conditions (new task, handoff, uncertainty, pipeline ending, etc.). - -**Other clients (Cursor, opencode, custom agents):** - -Paste the full content of `skills/SKILL.MD` into the system prompt or `CLAUDE.md`/`AGENTS.md`. Since the frontmatter metadata is used by Claude Code's skill loader, other clients treat it as plain markdown — the content is still fully effective as a system prompt. - -### 4.6 Compatibility - -The skill is tool-agnostic. The patterns apply to any MCP server exposing equivalent tool names. The frontmatter declares: - -```yaml -name: agent-memory -description: "Governs when and how agents read from and write to a persistent memory store..." +get_state("release_owner") → not set (version 0) +set_state("release_owner", "infra-agent", expected_version: 0) → version 1 (claimed) +set_state("release_owner", "qa-agent", expected_version: 0) → error: conflict (already claimed) ``` -If your MCP server uses different tool names (e.g., `memory_search` / `memory_save`), the skill still applies — the patterns are independent of tool naming. - --- -## 5. Multi-Agent Coordination - -### 5.1 Pipeline handoff protocol - -The canonical handoff sequence between two agents: - -**Agent A (finishing its turn):** - -``` -1. write_context({ topic: "...", tags: [..., "output"], importance: "high" }) -2. set_state("pipeline_phase", { phase: "next", agent: "B", input: "...", started_at: "..." }) -3. Send handoff message — lightweight, detail lives in memory - e.g. "HANDOFF AgentA→AgentB | run-042 | ✅ | summary of output" -``` - -**Agent B (starting its turn):** - -``` -1. get_state("pipeline_phase") ← get current context -2. search_context({ query: "agent A output", top_k: 5 }) ← retrieve output -3. Proceed with full context from memory -``` - -The handoff message should be **minimal** — just enough for Agent B to know which state key and search terms to use. All substantive context lives in the memory store. - -### 5.2 Shared state conventions - -**Use `set_state` for:** -- Current phase (`"scraping"`, `"analysis"`, `"notification"`) -- Active run ID -- Feature flags (`true` / `false`) -- Counters (items processed, retries remaining) - -**Use `write_context` for:** -- Decisions (with rationale) -- Completed task outputs (with file paths) -- Discoveries (with impact on future work) -- Configuration captured at a point in time - -**Never use `set_state` for searchable data.** State is a key-value store; context is a search engine. Use each for its strength. - -**Example pipeline state object:** - -```json -{ - "phase": "notification", - "step": 3, - "run_id": "042", - "input_file": "data/shortlist.json", - "agent": "notifier-agent", - "started_at": "2025-06-01T14:00:00Z", - "items_count": 12 -} -``` - -### 5.3 Conflict resolution - -When two agents write about the same topic concurrently (rare but possible in parallel pipelines), last write wins. To mitigate conflicts: - -- Include timestamps in chunk content: `"As of 2025-06-01T14:00Z: ..."` -- Use agent-specific tags to distinguish authorship: `["scraper", "output"]` vs `["analyzer", "output"]` -- On read, when duplicates appear, prefer the chunk with the most recent `updated` timestamp -- Use the deduplication pattern ([§7](#7-deduplication)) proactively — it also detects concurrent writes +## 3. Search and ranking + +1. **Keyword (BM25)** — SQLite FTS5 with the `unicode61 remove_diacritics 2` + tokenizer, so `decisao` matches `Decisão`. The query is split into terms + (Unicode-aware), common Portuguese/English stopwords are dropped, and each + term is quoted, so no input can produce an FTS syntax error. Columns are + weighted topic 3 : tags 2 : content 1. +2. **Semantic** — the query is embedded with the configured local model and + compared (cosine) with every memory vector in an in-memory index. Filters + (`agent`, `tags`, dates, expiry) are applied before ranking. +3. **Fusion** — Reciprocal Rank Fusion over the top 50 of each list + (`1 / (60 + rank)`, equal weights). `score` is that sum divided by its + maximum, so `1.0` means "first in both lists" and `0.5` "first in one list + only". It is a relative ranking signal, not a probability. +4. **Tie-breakers** — importance and recency (30-day half-life) add at most + ~2.5×10⁻⁴, less than one rank step at the top of the list, so they only + reorder results that are otherwise nearly tied. + +`similarity` (cosine) is reported for results found by semantic search. It is +absolute but model-specific: compare it across results of one query, not +across models. --- -## 6. Bootstrap Protocol - -### 6.1 Detecting a virgin project - -At the start of any session, run: - -``` -get_state("project_tags") -``` - -If the result is `null` (key not found), the project has no memory yet. Before doing any task work, write the foundational chunks. - -If the result exists, retrieve it and use the vocabulary for all writes in this session. - -### 6.2 The four bootstrap writes - -**Write 1 — Project identity:** - -```json -{ - "topic": "Project bootstrap — identity and stack", - "content": "Project: [name]. Stack: [languages, frameworks, databases]. Repo: [url]. Deploy: [target]. Architecture: [monolith/microservices/serverless].", - "tags": ["project", "config"], - "importance": "critical" -} -``` - -**Write 2 — Conventions:** - -```json -{ - "topic": "Project conventions — code and workflow", - "content": "Linter: [tool]. Formatter: [tool]. Test framework: [tool]. Branch strategy: [flow]. Commit format: [conventional/other]. PR policy: [review requirements].", - "tags": ["project", "config", "decision"], - "importance": "critical" -} -``` - -**Write 3 — Directory structure:** - -```json -{ - "topic": "Project structure — key directories", - "content": "src/ — application code. tests/ — test suites. docs/ — documentation. scripts/ — automation. config/ — environment configs.", - "tags": ["project", "config"], - "importance": "high" -} -``` - -**Write 4 — Tag vocabulary:** - -```json -{ - "key": "project_tags", - "value": { - "vocabulary": ["project", "config", "decision", "output", "discovery", "auth", "api", "infra"], - "updated": "2025-06-01" - } -} -``` - -(Use `set_state` for the vocabulary, not `write_context`.) - -### 6.3 Confirming with the user - -The bootstrap should capture reality, not assumptions. Ask the user to confirm or adjust the four bootstrap writes before proceeding with the actual task. This is especially important for conventions (linter, test framework, branch strategy) and the tag vocabulary, which all future agents will inherit. +## 4. Many agents, one store + +Each MCP client starts its own server process; all of them open the same +`store.db`. This is safe: + +- **WAL mode** — readers never block writers or each other. +- **`busy_timeout = 5000` and `BEGIN IMMEDIATE`** — concurrent writers queue + instead of failing with `SQLITE_BUSY`. +- **Versions** — `expected_version` on `write_context` and `set_state` gives + agents compare-and-set, so they never silently overwrite each other. +- **Vector index sync** — each process keeps its own in-memory index and + checks `PRAGMA data_version` before searching; changes from other processes + are loaded incrementally (new vectors by sequence number, deletions by + count reconciliation). +- **Embedding work** — vectors are computed on write when the model is ready, + otherwise in the background. Background and re-embedding work is guarded by + a lease so only one process does it, and a vector is stored only if the + memory's content hash still matches (an older embedding can never overwrite + a newer one). + +The test suite runs 4 processes × 500 writes plus a contended compare-and-set +counter against one file and checks that nothing is lost. + +Every process loads its own copy of the model (see the RAM figure in the +README's performance table). All agents sharing a store must use the same +`AGENT_MEMORY_MODEL`; otherwise they keep re-embedding each other's vectors. --- -## 7. Deduplication - -### 7.1 Why duplicates form - -Duplicates form when agents write without checking first. The result is multiple chunks covering the same topic with different (often contradictory) content. When another agent searches for that topic, it gets conflicting results and cannot determine which is authoritative. - -At 50 chunks, duplication is annoying. At 5,000 chunks, it makes the memory store unreliable. +## 5. Embedding models -### 7.2 Search-before-write pattern +Models run locally on CPU via ONNX Runtime (`@huggingface/transformers`), 8-bit +quantized. They are downloaded once to `~/.cache/agent-memory-store/models`. -Before every `write_context` call: - -``` -1. search_context({ query: "[topic you're about to write]", top_k: 3 }) - -2. If the top result is a clear match on the same topic: - a. delete_context(results[0].id) - b. write_context({ topic: "...", content: "updated version..." }) - -3. If no clear match: - a. write_context({ ... }) directly -``` - -**Example:** - -``` -results = search_context({ query: "Jira config endpoint token", top_k: 3 }) - -# Top result: "Jira integration — endpoint and API token" — clear match -→ delete_context("f6g7h8i9j0") -→ write_context({ topic: "Jira config — endpoint and token", content: "Updated: endpoint changed to https://..." }) -``` - -### 7.3 Judging relevance - -Do not use score thresholds to judge whether a chunk is a duplicate. BM25 scores vary with corpus size: a score of 0.8 in a 500-chunk store may be as strong as 2.0 in a 50K-chunk store. - -**Always judge by reading the top result's topic and content**, not its score. Ask: "Does this chunk cover the same topic I'm about to write?" If yes, it's a duplicate regardless of score. If no, write a new chunk. - -A score-based threshold that works at 500 chunks will produce false negatives at 50K chunks (real duplicates missed) and false positives in small stores (unrelated chunks flagged). - ---- - -## 8. Tag Discipline - -### 8.1 Tag rules - -- **Short and lowercase:** `auth`, `jira`, `scraper` — not `Authentication-Service` -- **No hyphens or spaces:** `ratelimit`, `apiquirk` — or use two separate tags: `api`, `quirk` -- **Use the canonical system name:** `taya`, `zap`, `postgres`, `redis` -- **Always include a type tag:** `decision`, `config`, `output`, `discovery` -- **Never invent a new tag when an existing one covers the concept** -- **At session start, always load** `get_state("project_tags")` and use that vocabulary - -Tags are how agents find each other's work. A tag written as `auth` and searched as `authentication` produces no match. Consistency is non-negotiable. - -### 8.2 Bad/good comparison - -| Bad | Good | Why | -| --- | --- | --- | -| `authentication-service` | `auth` | Short, no hyphens | -| `JiraIntegration` | `jira` | Lowercase, canonical name | -| `myDecision` | `decision` | Generic type tag | -| `taya-api-endpoint-config` | `taya`, `config` | Split into system + type | -| `UpdatedSetting` | `discovery` or `config` | Use standard type vocabulary | -| `2025-scraper-output` | `scraper`, `output` | No dates in tags — use content | - -### 8.3 Managing the vocabulary - -Adding a new tag requires updating the shared vocabulary so all agents adopt it: - -``` -current = get_state("project_tags") -current.vocabulary.push("redis") -current.updated = "2025-06-01" -set_state("project_tags", current) -``` - -Add the new tag to the vocabulary **before** using it in a `write_context` call. If another agent runs a cold start while you're mid-session, it will inherit the updated vocabulary. +| Key (`AGENT_MEMORY_MODEL`) | Model | Languages | Dims | Notes | +| --- | --- | --- | --- | --- | +| `arctic-embed-m-v2` | `Snowflake/snowflake-arctic-embed-m-v2.0` | multilingual | 768 | **Default.** Apache-2.0. ~310 MB download, ~630 MB RAM per process. | +| `granite-97m-multilingual` | `ibm-granite/granite-embedding-97m-multilingual-r2` | multilingual | 384 | Apache-2.0. Lighter (~450 MB RAM), lower quality. | +| `embeddinggemma-300m` | `google/embeddinggemma-300m` | multilingual | 768 | Gemma license. Same quality as the default, ~7× slower, ~1.4 GB RAM. | +| `minilm-l6-en` | `sentence-transformers/all-MiniLM-L6-v2` | English | 384 | The 0.0.x model. Fails cross-lingual queries. | +| `none` | — | — | — | Keyword search only, ~64 MB RAM. | + +The default was chosen by measurement — see the README's results table and +`benchmarks/results/`. Each model's query/document prefixes and pooling follow +its model card. Documents are embedded as `topic + tags + content`, truncated to +2000 characters (~512 tokens); keyword search always covers the full text. + +Switching models is automatic: vectors are stored with the model id, and on +start the server re-embeds every memory that has no vector for the current +model, in the background. Search falls back to keyword-only until that +finishes. --- -## 9. Importance Levels +## 6. Configuration -| Level | Use when | Example | +| Variable | Default | Description | | --- | --- | --- | -| `critical` | Another agent will fail or make wrong decisions without this | Architecture decision, API contract | -| `high` | Meaningfully changes how the next step runs | Task output with file paths, discovered rate limit | -| `medium` | Useful background, good to have — **this is the default** | General project context, tech stack notes | -| `low` | Ephemeral notes, debugging traces, things that may expire | Scratch notes, temporary workarounds | - -When in doubt, use `high`. Underdeclaring importance means critical chunks may be skipped during curation passes; overdeclaring has no mechanical downside — it just means more chunks are prioritized. +| `AGENT_STORE_PATH` | `./.agent-memory-store` (relative to the client's working directory) | Store directory. Use an absolute path to share one store across repositories. | +| `AGENT_MEMORY_MODEL` | `arctic-embed-m-v2` | Embedding model key (§5) or `none`. | +| `AGENT_MEMORY_AGENT` | `global` | Default agent id for writes from this server process. Set one per agent for provenance. | +| `AGENT_MEMORY_CACHE` | `$XDG_CACHE_HOME/agent-memory-store/models` or `~/.cache/agent-memory-store/models` | Model cache directory. | --- -## 10. TTL Guide +## 7. Storage, schema and migrations -Most chunks should be **permanent** (omit `ttl_days`). Use TTL only for time-bound information: +One SQLite file, `store.db` (plus `-wal`/`-shm` while open): -| TTL | Use case | +| Table | Purpose | | --- | --- | -| 1 day | Session-scoped scratch notes | -| 7–14 days | Rate limits, API quirks that change frequently | -| 30 days | A/B test results, time-bound experiment data | -| 90 days | Quarterly metrics snapshots | -| *(none)* | Everything else — permanent by default | +| `chunks` | Memories. `seq INTEGER PRIMARY KEY` keeps FTS rowids stable across `VACUUM`. | +| `chunks_fts` | FTS5 external-content index, kept in sync by triggers. | +| `vectors` | One vector per memory: model id, content hash, Float32 blob. Deleted with the memory (foreign key cascade). | +| `state` | Key → JSON value, version, writer. | +| `leases` | Short-lived locks for background embedding work. | -**Implementation detail:** expired chunks are purged automatically at server startup with: +The schema version lives in `PRAGMA user_version` (currently 2). On start the +server migrates older stores in a single transaction: -```sql -DELETE FROM chunks WHERE expires_at IS NOT NULL AND expires_at < datetime('now') -``` +- **0.0.6–0.0.9 SQLite stores (v1)** — rebuilds the tables and FTS index, + keeps every memory and state value with their timestamps, drops the old + MiniLM vectors (recomputed with the current model). +- **≤ 0.0.5 markdown stores** (`chunks/*.md`, `state/*.json`) — imported, then + the folders are renamed to `*_backup`. -Expired chunks cannot be recovered. When uncertain, omit `ttl_days` — permanent chunks can always be deleted manually with `delete_context`. +Backup: copy `store.db` while no agent is writing, or run +`sqlite3 store.db "VACUUM INTO 'backup.db'"` at any time. --- -## 11. Performance Budgets - -### 11.1 Operation benchmarks - -Measured on Apple Silicon (Node v25, darwin arm64, BM25 mode, isolated runs): - -| Operation | 1K chunks | 10K chunks | 50K chunks | 100K chunks | 250K chunks | -| --- | --- | --- | --- | --- | --- | -| **write** | 0.17 ms | 0.19 ms | 0.23 ms | 0.21 ms | 0.25 ms | -| **read** | 0.01 ms | 0.05 ms | 0.21 ms | 0.22 ms | 0.85 ms | -| **search (BM25)** | ~5 ms | ~10 ms | ~60 ms | ~110 ms | ~390 ms | -| **list** | 0.2 ms | 0.3 ms | 0.3 ms | 0.3 ms | 1.1 ms | -| **state get/set** | 0.03 ms | 0.03 ms | 0.07 ms | 0.05 ms | 0.03 ms | - -### 11.2 Budget by corpus size - -| Corpus size | Search latency | Reads | Writes | Recommendation | -| --- | --- | --- | --- | --- | -| < 5K chunks | < 15ms/query | 0.02ms | 0.17ms | No constraints | -| 5–25K | 15–35ms/query | 0.02ms | 0.18ms | Normal operation | -| 25–50K | 35–60ms/query | 0.02ms | 0.18ms | Consider partitioning by domain | -| 50–100K | 60–110ms/query | 0.10ms | 0.18ms | Partition recommended | -| > 100K | 110ms+/query | 1.0ms+ | 0.20ms | Split into separate stores | - -**Practical guidance:** - -- A typical project stays under 5K chunks. At this size, 3 searches per action add under 50ms total — invisible next to LLM latency of 1–3 seconds. -- `list_context` without filters is O(n). Always use tag/agent filters or pagination when listing at scale. -- Do 2–3 targeted searches per read trigger, not one broad search. Specific queries outperform vague ones on BM25. -- `write` stays constant at ~0.2ms regardless of corpus size — FTS5 triggers and embedding backfill are non-blocking. - -### 11.3 Scaling beyond 25K chunks - -At 25K+ chunks: - -**Semantic search memory:** At 50K chunks with 384-dim Float32 embeddings, brute-force cosine loads ~75MB of embedding data. Consider switching to `bm25` mode or partitioning. - -**Partitioning strategy:** Create separate stores per domain using `AGENT_STORE_PATH`: -- `/project/.agent-memory-store/` — project-level memory -- `/project/.agent-memory-auth/` — auth domain only -- `/project/.agent-memory-infra/` — infrastructure only - -Each store runs its own MCP server instance. Agents choose which server to query based on the task domain. - -**`list_context` at scale:** Pagination caps results at 500 rows maximum. Always filter by `agent` or `tags` when listing large stores to avoid full-table scans. - ---- - -## 12. Architecture Deep Dive - -### 12.1 `index.js` — MCP server - -Entry point. Registers all 7 tools via `@modelcontextprotocol/sdk`. Uses `zod/v4` for parameter validation with explicit `.describe()` strings that appear in the MCP tool manifest (these are what agents see when they inspect available tools). - -Calls `initStore()` at startup — this runs DB initialization, triggers filesystem migration if needed, and warms up the embedding model in the background. The server accepts connections via `StdioServerTransport`. +## 8. Programmatic use -### 12.2 `store.js` — Public API +```js +import { MemoryStore } from "agent-memory-store"; +import { createEmbedder } from "agent-memory-store/embeddings"; -The single export layer between `index.js` and the DB/search/embedding modules. All 7 MCP operations go through here. - -**Chunk ID generation:** `crypto.createHash('sha1').update(\`${agent}:${topic}:${Date.now()}:${Math.random()}\`).digest('hex').slice(0, 10)` — 10-char hex, collision-resistant for typical agent memory volumes. - -**Async embedding on write:** `writeChunk()` calls `insertChunk()` synchronously (chunk is immediately queryable via BM25), then calls `embed(text).then(embedding => updateEmbedding(id, embedding))` asynchronously. A `backfillEmbeddings()` function on startup processes any chunks that still have `null` embeddings (e.g., from a previous run where the embedding model failed). - -### 12.3 `db.js` — SQLite layer - -Uses `node:sqlite` — the SQLite module built into Node.js >= 22.5. No external database dependency. - -**Schema:** - -```sql -CREATE TABLE chunks ( - id TEXT PRIMARY KEY, - topic TEXT NOT NULL, - agent TEXT NOT NULL, - tags TEXT DEFAULT '[]', -- JSON array - importance TEXT DEFAULT 'medium', - content TEXT NOT NULL, - embedding BLOB, -- Float32Array, null until backfilled - created_at TEXT, - updated_at TEXT, - expires_at TEXT -); - -CREATE VIRTUAL TABLE chunks_fts USING fts5( - id UNINDEXED, topic, content, - content='chunks', content_rowid='rowid' -); +const store = MemoryStore.open("/path/to/store.db", { embedder: createEmbedder() }); +const m = await store.write({ topic: "Deploy", content: "Blue-green on ECS", tags: ["infra"] }); +const { mode, results } = await store.search({ query: "how do we deploy?", limit: 5 }); +store.setState("phase", "release", { expectedVersion: 0 }); +store.close(); ``` -FTS5 stays in sync via three triggers (INSERT, DELETE, UPDATE on `chunks`). WAL mode is set at connection time via `PRAGMA journal_mode = WAL`. A prepared statement cache (`stmtCache`) avoids re-preparing identical SQL. - -**Expiry cleanup** runs at startup: `DELETE FROM chunks WHERE expires_at IS NOT NULL AND expires_at < datetime('now')`. - -**STORE_PATH resolution:** `process.env.AGENT_STORE_PATH || path.join(process.cwd(), '.agent-memory-store')`. - -### 12.4 `search.js` — Hybrid search engine - -Three search modes, selected by the `mode` parameter: - -**`hybrid`:** Runs FTS5 BM25 search synchronously. Concurrently embeds the query. When both complete, applies RRF fusion. Uses a `bm25Map` cache to avoid redundant `getChunk()` DB reads for chunks that appear in both lists. - -**`bm25`:** Calls `searchFTS()` from `db.js` directly. Returns ranked results immediately. - -**`semantic`:** Embeds the query, loads all stored embeddings from DB (filtered by agent/tags if provided), computes cosine similarity for each, sorts by score. - -**Graceful fallback:** If `embed()` returns `null` (model unavailable), hybrid and semantic modes fall back to BM25 results transparently. - -### 12.5 `embeddings.js` — Local embedding pipeline - -Uses `@huggingface/transformers` with ONNX Runtime for inference. Model: `all-MiniLM-L6-v2`. - -**Lazy initialization:** The pipeline loads on the first `embed()` call, not at server start. A `loadingPromise` deduplicates concurrent load attempts — only one download/initialization happens even if multiple chunks are written simultaneously. - -**Input construction:** `[topic, tags.join(' '), content.slice(0, 800)]` joined with space. Content is truncated at 800 characters before embedding. - -**Post-processing:** Mean pooling across token embeddings, then L2 normalization to unit vector. - -**Graceful degradation:** If the model fails to load (network unavailable, disk error, Node.js version mismatch), `loadFailed = true` and all subsequent `embed()` calls return `null` without throwing. `search.js` detects `null` and falls back to BM25. - -### 12.6 `bm25.js` — Pure JS BM25 (reference) - -A pure JavaScript BM25 implementation with standard parameters (k1=1.5, b=0.75), Unicode-normalized tokenization (handles accents), and IDF weighting. - -**This module is not on the hot path.** It has no runtime callers in the current codebase. All live BM25 search goes through SQLite FTS5 in `db.js`. This file is kept as a reference implementation and fallback option if the SQLite FTS5 approach needs to be replaced. - -### 12.7 `migrate.js` — Filesystem migration - -Handles one-time migration from the legacy filesystem format (chunks as `.md` files with gray-matter YAML frontmatter, state as `.json` files) to the current SQLite format. - -**Trigger condition:** `chunks/` directory exists but `store.db` does not. - -**Process:** -1. Read all `.md` files from `chunks/` -2. Parse YAML frontmatter with `gray-matter` -3. Skip expired chunks (don't migrate stale data) -4. Insert valid chunks into the new `chunks` table -5. Rename `chunks/` → `chunks_backup/` and `state/` → `state_backup/` - -Migration is silent and automatic — no user action needed. Post-migration, the backup directories can be deleted once the new store is verified. +`createEmbedder("none")` gives a keyword-only store; `createEmbedder("hash")` +is a deterministic test embedder with no model download. --- -## 13. Anti-Patterns - -**Don't search reflexively.** Only search when you genuinely need external information. A mathematical question doesn't need a memory search. Save searches for facts that might exist in memory. - -**Don't write conversational exchanges.** Memory stores decisions, outputs, and discoveries — not chat history or intermediate reasoning. If it won't help a future agent, don't write it. +## 9. Benchmarks and how to reproduce them -**Don't use vague topics.** `"Update"`, `"Info"`, `"Note"` are unsearchable. A topic must be specific enough that a different agent can find it with a relevant query six months later: `"ZAP API — rate limit changed to 1 req/s"` not `"API update"`. +Every benchmark imports `MemoryStore` — the same code the MCP server runs. +Results are written to `benchmarks/results/*.json` with the machine, Node +version and date. -**Don't write without rationale.** A chunk that says `"Using Redis"` is much less useful than one explaining *why* Redis was chosen over alternatives. Future agents need context to decide whether a decision still applies. - -**Don't skip deduplication.** Writing without searching first is how memory fills with contradictory chunks. Always search before write. See [§7](#7-deduplication). - -**Don't threshold BM25 scores for dedup decisions.** Scores vary with corpus size. Read the top result's content to judge relevance, not its score. - -**Don't ignore low-score results.** A result with a low score might still be the only chunk on a topic. Read the top result even when scores are low — just weight it accordingly in your reasoning. - -**Don't store secrets in memory.** API keys, tokens, passwords, and connection strings with credentials belong in `.env` files or secret managers — not in a searchable text store. Write *references* to where secrets live: `"API key stored in .env as OPENAI_API_KEY"`. - -**Don't use `set_state` for searchable data.** State is not indexed by content — it can only be retrieved by exact key. If something needs to be found by search, use `write_context`. +```bash +npm run bench # golden-set quality + speed (2K memories), ~30 s, < 1 GB RAM +npm run bench:golden # golden set with per-type / per-language breakdown +npm run bench:tune-fusion # reproduces the fusion choice (dev/test split) +npm run bench:longmemeval # LongMemEval-S, official protocol — heavy (≈1 h, several GB) +node benchmarks/longmemeval.js --model none # keyword-only LongMemEval, seconds +``` + +Benchmarks cache embeddings in `benchmarks/.cache/embeddings/` (vectors are +deterministic, so results are identical); re-runs only pay for new texts. + +**Golden set** (`benchmarks/golden/dataset.json`): 150 hand-written memories +from a fictional product team (≈55% Portuguese, 45% English) and 120 queries: +cross-lingual, paraphrases, exact identifiers, knowledge updates (the newer +memory must win), filtered queries and multi-memory questions. It is synthetic +and small; treat it as a regression test for the intended workload, not as a +leaderboard. + +**LongMemEval-S** (Wu et al., ICLR 2025): ~50 chat sessions per question. +Protocol copied from the official retrieval code: session granularity, user +turns only, abstention questions and questions without user-side evidence +excluded (419 of 500 in the cleaned release), `recall_any@k`, `recall_all@k` +and `ndcg_any@k`. `--with-assistant` indexes assistant turns too and is +reported separately because it is not the official setting. LongMemEval +indexes raw conversations, not curated memories, so it measures the retrieval +engine, not the intended usage. -**Don't use `write_context` for mutable counters or flags.** Chunks accumulate — they don't overwrite. Using `write_context` for a counter creates a new chunk on every update. Use `set_state` instead. +--- -**Don't send the handoff message before `write_context`.** The receiving agent may search memory immediately on receiving the handoff. If the write hasn't happened yet, the agent proceeds without the context it needs. Always: write → state → handoff. +## 10. Limits and trade-offs + +- **Scale** — exact vector search is linear in the number of memories. It is + fast at agent-memory scale (see README); beyond ~100K memories per store, + split stores by domain or use keyword-only mode. +- **RAM per process** — each agent process holds the model and its own copy of + the vector index. +- **Long content** — only the first ~2000 characters are embedded. Keyword + search covers everything. Prefer several focused memories over one long one. +- **Secret detection** is pattern-based (private keys, cloud/API key formats, + JWTs, passwords inside connection strings). It catches common mistakes; it + is not a DLP system. +- **No access control** — anyone who can read `store.db` can read every memory. + The store is meant for one team on one machine. +- **Scores** — `score` is a relative rank signal; there is no universal "is + this relevant" threshold. Read the top results. --- -## 14. Quick Reference — Decision Tree +## 11. Troubleshooting -``` -┌─ New session? -│ └─ get_state("project_tags") -│ ├─ null → Bootstrap (§6), then proceed -│ └─ exists → search conventions + current phase, then proceed -│ -├─ New task arrives? -│ └─ search_context (2–3 queries) → incorporate → act -│ -├─ Named entity in input? -│ └─ search_context (entity name + tags) -│ -├─ Feeling uncertain? -│ └─ search_context (topic of uncertainty) -│ -├─ Handoff received? -│ └─ get_state (run/pipeline ID) + search_context (sending agent output) -│ -├─ Resuming after pause? -│ └─ get_state (current_phase) + search_context (last phase output) -│ -├─ Decision made? -│ └─ search (dedup) → write_context (topic + rationale + tags + importance) -│ -├─ Subtask complete? -│ └─ search (dedup) → write_context (output + file paths + key facts) -│ -├─ Discovery made? -│ └─ search (dedup) → write_context (what changed + impact, ttl if temporary) -│ -├─ Turn ending in pipeline? -│ └─ write_context → set_state → send handoff (always this order) -│ -└─ None of the above? - └─ Act normally. Memory is not needed for every action. -``` +| Symptom | Cause / fix | +| --- | --- | +| Responses say `bm25 search` right after start | The model is loading (first run downloads it). It switches to hybrid automatically. | +| `Embedding model failed to load` on stderr | No network on first run or a corrupt cache. Delete `~/.cache/agent-memory-store/models` and restart, or set `AGENT_MEMORY_MODEL=none`. | +| Memory missing from another project | `AGENT_STORE_PATH` defaults to the client's working directory, so each project has its own store. Set an absolute path to share one. | +| `Version conflict` | Another agent changed it first. Re-read (`read_context` / `get_state`) and retry with the new version. | +| `Refused: content looks like it contains a …` | Store where the secret lives, not its value. | +| `node:sqlite` not found, or "has no FTS5 full-text search" | Node.js older than 22.16 (earlier 22.x builds ship SQLite without FTS5). Upgrade. | diff --git a/package-lock.json b/package-lock.json index 226e1aa..c58c3df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "0.1.0", "license": "MIT", "dependencies": { - "@huggingface/transformers": "^3.0.0", + "@huggingface/transformers": "3.8.1", "@modelcontextprotocol/sdk": "^1.28.0", "gray-matter": "^4.0.3", "zod": "^4.3.6" @@ -18,7 +18,7 @@ "agent-memory-store": "src/index.js" }, "engines": { - "node": ">=22.5.0" + "node": ">=22.16.0" } }, "node_modules/@emnapi/runtime": { diff --git a/package.json b/package.json index 8c69bff..0e045d7 100644 --- a/package.json +++ b/package.json @@ -1,17 +1,23 @@ { "name": "agent-memory-store", - "version": "0.0.9", - "description": "Local-first MCP memory server for multi-agent systems. Hybrid search (BM25 + semantic embeddings), SQLite-backed, zero-config.", + "version": "0.1.0", + "description": "Shared, persistent memory for teams of AI agents over MCP. Hybrid search (SQLite FTS5 + local multilingual embeddings), safe for many agent processes, zero external services.", "type": "module", - "exports": "./src/index.js", + "exports": { + ".": "./src/store/memory-store.js", + "./embeddings": "./src/embeddings.js" + }, "bin": { "agent-memory-store": "./src/index.js" }, "scripts": { "start": "node src/index.js", - "test": "node --test src/__tests__/store.test.js", - "lint": "node --check src/bm25.js src/store.js src/index.js src/db.js src/embeddings.js src/search.js src/migrate.js", - "bench:longmemeval": "node benchmarks/longmemeval_bench.js" + "test": "node --no-warnings --test \"test/*.test.js\"", + "lint": "node --check src/index.js && node --check src/server.js && node --check src/embeddings.js && node --check src/migrate.js && node --check src/store/memory-store.js", + "bench": "node --no-warnings benchmarks/bench.js", + "bench:golden": "node --no-warnings benchmarks/golden.js", + "bench:tune-fusion": "node --no-warnings benchmarks/tune-fusion.js", + "bench:longmemeval": "node --no-warnings benchmarks/longmemeval.js" }, "keywords": [ "mcp", @@ -42,15 +48,16 @@ }, "homepage": "https://github.com/vbfs/agent-memory-store#readme", "engines": { - "node": ">=22.5.0" + "node": ">=22.16.0" }, "files": [ "src/", "README.md", - "LICENSE" + "LICENSE", + "skills/" ], "dependencies": { - "@huggingface/transformers": "^3.0.0", + "@huggingface/transformers": "3.8.1", "@modelcontextprotocol/sdk": "^1.28.0", "gray-matter": "^4.0.3", "zod": "^4.3.6" diff --git a/skills/SKILL.MD b/skills/SKILL.MD deleted file mode 100644 index 3dce3c3..0000000 --- a/skills/SKILL.MD +++ /dev/null @@ -1,452 +0,0 @@ ---- -name: agent-memory -description: "Governs when and how agents read from and write to a persistent memory store (agent-memory-store or any MCP server exposing search_context/write_context/get_state/set_state equivalents). Use this skill whenever an agent has access to persistent memory tools and needs to decide whether to read or write. Trigger on: starting a new task, receiving a handoff, resuming after interruption, encountering a named entity without full context, making a non-trivial decision, completing a subtask with output, discovering something that changes assumptions, or ending a turn in a multi-agent pipeline. Also trigger when the agent is about to guess something that might already exist in memory, or when building multi-agent pipelines that share context across sessions." ---- - -# Context Memory Skill - -This skill governs **when** and **how** an agent interacts with its persistent -memory store. It is tool-agnostic: the patterns apply whether the server -exposes `search_context`/`write_context`, `memory_search`/`memory_save`, -or any equivalent read/write pair. - -**Core principle:** an agent's context window is ephemeral; the memory store -is permanent. Every important decision, discovery, and output lives in the -store — not just in the current conversation. - ---- - -## 1. The read/write decision framework - -Before taking any substantive action, ask two questions: - -1. **"Is there something in memory I should know before I act?"** - → If yes, or if uncertain: **read first**. -2. **"Will the result of this action be needed later — by me or another agent?"** - → If yes: **write after**. - -If both are yes, the pattern is: **read → act → write**. - -If neither is yes, skip memory entirely and act normally. Memory is not a -logging system — it stores decisions, outputs, and discoveries that affect -future work. - ---- - -## 2. When to READ - -### 2.1 — Cold start (first action in a new session) - -Before any work in a fresh session, bootstrap your context: - -``` -search_context({ query: "project conventions stack architecture", topK: 5 }) -get_state("project_tags") -get_state("current_phase") -``` - -If all three return empty, you are in a **virgin project**. See §5 (Bootstrap -protocol) for what to write before proceeding. - -If results exist, incorporate them before acting on any user instruction. - -### 2.2 — New task or instruction received - -Any time a new task arrives that you haven't handled in this session, -search memory before doing anything else. You may have done related work -before, or another agent may have left relevant context. - -``` -Incoming: "Set up the staging deployment pipeline" -→ search_context({ query: "staging deployment pipeline", topK: 5 }) -→ search_context({ query: "infrastructure decisions", topK: 3 }) -→ Incorporate findings, then proceed. -``` - -**Why:** acting without checking memory risks duplicating work, contradicting -prior decisions, or missing configuration that already exists. - -### 2.3 — A named entity appears - -When input mentions a specific project name, system, service, agent, person, -or acronym you don't have full context on, search for it before assuming. - -``` -Incoming: "Continue the TAYA Jira integration" -→ search_context({ query: "TAYA Jira integration", tags: ["taya", "jira"] }) -``` - -Named entities are the strongest signal that prior work exists in memory. -Never assume you know the current state of a named system without checking. - -### 2.4 — Uncertainty about a fact - -If you catch yourself about to write a value, URL, credential format, decision, -or configuration detail that you're not 100% certain about — stop and search. -Uncertainty is a read trigger. Guessing when the answer exists in memory is -the failure mode that makes multi-agent systems unreliable. - -``` -Internal signal: "I think the API endpoint was /v2/... but I'm not sure" -→ search_context({ query: "API endpoint config" }) -``` - -### 2.5 — Handoff received from another agent - -Always read state and search for the sending agent's outputs before continuing. - -``` -Handoff: "HANDOFF Scraper→Analyzer | run-042 | ✅ | 87 items" -→ get_state("pipeline_run_042") -→ search_context({ query: "scraper output run 042", topK: 4 }) -``` - -The handoff message is a pointer, not a full briefing. - -### 2.6 — Resuming after a pause or session restart - -If any signal suggests this task was interrupted (references to phases, -run IDs, "continue from where we left off"), read state and search. - -``` -→ get_state("pipeline_current_phase") -→ search_context({ query: "phase 3 output decisions", topK: 5 }) -``` - ---- - -## 3. When to WRITE - -### 3.1 — Decision made with rationale - -Any time you make a non-trivial choice, persist it with the reasoning. -Future agents need the *why*, not just the *what*. - -``` -write_context({ - topic: "Auth service — chose JWT over sessions", - content: "Chose stateless JWT. Rationale: no shared session store needed across services. Refresh tokens stored in Redis with 7d TTL. Access tokens: 15min, RS256.", - tags: ["auth", "architecture", "decision"], - importance: "critical" -}) -``` - -### 3.2 — Subtask completed with output - -When you finish a discrete unit of work that produces something another agent -or future session will consume, persist it. - -``` -write_context({ - topic: "Scraper run 042 — 87 listings collected", - content: "Raw file at data/raw.json. Source: ZAP Imóveis. Filters: SP capital, 2+ bedrooms, < R$800k. Rate: 2 req/s, 0 blocks. Duration: 4m12s.", - tags: ["scraper", "output"], - importance: "high" -}) -``` - -### 3.3 — Discovery that changes understanding - -If you learn something that updates prior assumptions — an API changed, -a config is different from documented, an edge case was found — write it -immediately, even if no action follows yet. - -``` -write_context({ - topic: "ZAP API — rate limit changed to 1 req/s", - content: "As of 2025-06: rate limit tightened from 2 to 1 req/s. Previous setting causes 429s. Updated scraper config accordingly.", - tags: ["scraper", "config", "discovery"], - importance: "high", - ttl_days: 30 -}) -``` - -### 3.4 — Before ending your turn in a pipeline - -Before passing control, write your output, update state, then send handoff. -**Always in this order.** If the handoff is sent before the write, the -receiving agent may search memory before the chunk exists. - -``` -# 1. Persist output -write_context({ - topic: "Analyzer run 042 — shortlist produced", - content: "214 analyzed → 12 shortlisted at data/shortlist.json. Criteria: price/m² < median, transport > 7, no legal flags.", - tags: ["analyzer", "output"], - importance: "high" -}) - -# 2. Update pipeline state -set_state("pipeline_current_phase", { - phase: "notification", - step: 3, - input_file: "data/shortlist.json", - agent: "notifier-agent", - started_at: "2025-06-01T14:00:00Z" -}) - -# 3. Send minimal handoff (detail is in memory) -# HANDOFF Analyzer→Notifier | run-042 | ✅ | 12 shortlisted -``` - ---- - -## 4. Deduplication — search before every write - -Before writing a new chunk, search for an existing one on the same topic. -If a relevant chunk exists (top result with clear topic match), **delete it -and rewrite** rather than creating a duplicate. - -``` -results = search_context({ query: "Jira config endpoint token", topK: 3 }) - -if results[0] is a clear match on the same topic: - delete_context(results[0].id) - -write_context({ topic: "Jira config — endpoint and token", ... }) -``` - -**Why:** duplicate chunks fragment knowledge and produce contradictory search -results. One chunk per topic, kept current. - -**Judging relevance:** use the topic and content of the top result, not just -the score. BM25 scores vary with corpus size — a score of 0.8 in a 500-chunk -store may be as strong a match as 2.0 in a 50K-chunk store. Read the result -and decide whether it covers the same topic you're about to write. - ---- - -## 5. Bootstrap protocol (first session on a new project) - -When `get_state("project_tags")` returns empty, the project has no memory yet. -Before doing any task work, write these foundational chunks: - -### 5.1 — Project identity - -``` -write_context({ - topic: "Project bootstrap — identity and stack", - content: "Project: [name]. Stack: [languages, frameworks, databases]. Repo: [url]. Deploy: [target]. Architecture: [monolith/microservices/serverless].", - tags: ["project", "config"], - importance: "critical" -}) -``` - -### 5.2 — Conventions - -``` -write_context({ - topic: "Project conventions — code and workflow", - content: "Linter: [tool]. Formatter: [tool]. Test framework: [tool]. Branch strategy: [flow]. Commit format: [conventional/other]. PR policy: [review requirements].", - tags: ["project", "config", "decision"], - importance: "critical" -}) -``` - -### 5.3 — Directory structure - -``` -write_context({ - topic: "Project structure — key directories", - content: "src/ — application code. tests/ — test suites. docs/ — documentation. scripts/ — automation. config/ — environment configs.", - tags: ["project", "config"], - importance: "high" -}) -``` - -### 5.4 — Tag vocabulary - -``` -set_state("project_tags", { - vocabulary: ["project", "config", "decision", "output", "discovery", "auth", ...], - updated: "2025-06-01" -}) -``` - -Ask the user to confirm or adjust these before proceeding with the actual task. - ---- - -## 6. Tag discipline - -Tags are how agents find each other's work. A tag written as `auth` and -searched as `authentication` produces no match. Consistency is non-negotiable. - -**Rules:** - -- Short, lowercase, no hyphens: `auth`, `jira`, `scraper` — not `authentication-service` -- Use the canonical system name: `taya`, `zap`, `postgres` -- Include the chunk type: `decision`, `config`, `output`, `discovery` -- Never invent a new tag when an existing one covers the concept -- At session start, always run `get_state("project_tags")` and use that vocabulary - -**When you need a new tag:** add it to the vocabulary in state before using it. -This ensures all agents in the pipeline see and adopt it. - -``` -current = get_state("project_tags") -current.vocabulary.push("redis") -set_state("project_tags", current) -``` - ---- - -## 7. Importance levels - -| Level | Use when | -|------------|-----------------------------------------------------------------| -| `critical` | Another agent will fail or make wrong decisions without this | -| `high` | Meaningfully changes how the next step runs | -| `medium` | Useful background, good to have — **this is the default** | -| `low` | Ephemeral notes, debugging traces, things that may expire | - -When in doubt, use `high`. Underdeclaring means important chunks get ignored -during curation; overdeclaring is a much smaller problem. - ---- - -## 8. TTL — when to expire chunks - -Most chunks should be **permanent** (no `ttl_days`). Use TTL only for: - -| TTL | Use case | -|------------|----------------------------------------------------| -| 1 day | Session-scoped scratch notes | -| 7–14 days | Rate limits, API quirks that change frequently | -| 30 days | A/B test results, time-bound experiment data | -| 90 days | Quarterly metrics snapshots | -| *(none)* | Everything else — permanent by default | - -Permanent chunks can always be deleted manually. Expired chunks cannot be -recovered. When uncertain, omit TTL. - ---- - -## 9. Performance budget - -Based on benchmarks (Node.js, SQLite backend, Apple Silicon): - -| Corpus size | Search latency | Reads | Writes | Recommendation | -|-------------|----------------|----------|----------|---------------------------------| -| < 5K chunks | < 15ms/query | 0.02ms | 0.17ms | No constraints | -| 5–25K | 15–35ms/query | 0.02ms | 0.18ms | Normal operation | -| 25–50K | 35–60ms/query | 0.02ms | 0.18ms | Consider partitioning by domain | -| 50–100K | 60–110ms/query | 0.10ms | 0.18ms | Partition recommended | -| > 100K | 110ms+/query | 1.0ms+ | 0.20ms | Split into separate stores | - -**Practical guidance:** - -- A typical project stays under 5K chunks. At this size, 3 searches per action - add < 50ms total — invisible next to LLM latency (1–3 seconds). -- `list()` without filters is O(n) and becomes the bottleneck at > 25K chunks. - Always use tag filters or pagination when listing. -- Do 2–3 targeted searches per read trigger, not one broad search. Specific - queries outperform vague ones on BM25. - ---- - -## 10. Multi-agent coordination patterns - -### 10.1 — Pipeline handoff protocol - -``` -Agent A (finishing): - 1. write_context({ topic: "...", tags: [..., "output"] }) - 2. set_state("pipeline_phase", { phase: "next", agent: "B", ... }) - 3. Send handoff message (lightweight, detail lives in memory) - -Agent B (starting): - 1. get_state("pipeline_phase") - 2. search_context({ query: "agent A output", topK: 5 }) - 3. Proceed with full context -``` - -### 10.2 — Shared state conventions - -Use `set_state` for mutable, single-value data that changes frequently: -current phase, active run ID, feature flags, counters. - -Use `write_context` for immutable records: decisions, outputs, discoveries. -These accumulate over time and are retrieved by search. - -**Never use `set_state` for data that should be searchable.** State is a -key-value store; context is a search engine. Use each for its strength. - -### 10.3 — Conflict resolution - -When two agents write about the same topic concurrently (rare but possible -in parallel pipelines), the last write wins. To mitigate: - -- Include timestamps in chunk content -- Use agent-specific tags (`scraper`, `analyzer`) to distinguish authorship -- On read, prefer the most recent chunk when duplicates appear - ---- - -## 11. Anti-patterns - -**Don't search reflexively.** Searching is for information retrieval, not for -confirming your own responses. Only search when you genuinely need external -information to proceed correctly. A question like "what is 2+2" does not -warrant a memory search. - -**Don't write conversational exchanges.** Memory is for decisions, outputs, -and discoveries — not for logging chat history or intermediate reasoning. - -**Don't use vague topics.** `"Update"`, `"Info"`, `"Note"` are unsearchable. -A topic must be specific enough that a different agent can find it with a -relevant query six months later. - -**Don't write without rationale.** A chunk that says "Using Redis" is much -less useful than one explaining *why* Redis was chosen over alternatives. -Future agents need context to decide whether a decision still applies. - -**Don't ignore low-score results.** A result with a low score might still be -the only chunk on a topic. Read the top result even when scores are low — -just weight it accordingly. - -**Don't skip deduplication.** Writing without searching first is how memory -fills with contradictory chunks. Always search before write (§4). - -**Don't store secrets in memory.** API keys, tokens, passwords, and connection -strings with credentials belong in `.env` files or secret managers — not in -a searchable text store. Write *references* to where secrets live, not the -secrets themselves. - ---- - -## 12. Quick reference — decision tree - -``` -┌─ New session? -│ └─ get_state("project_tags") -│ ├─ Empty → Bootstrap (§5), then proceed -│ └─ Exists → search conventions + current phase, then proceed -│ -├─ New task arrives? -│ └─ search_context (2–3 queries) → incorporate → act -│ -├─ Named entity in input? -│ └─ search_context (entity name + tags) -│ -├─ Feeling uncertain? -│ └─ search_context (topic of uncertainty) -│ -├─ Handoff received? -│ └─ get_state (run/pipeline ID) + search_context -│ -├─ Decision made? -│ └─ search (dedup) → write_context (topic + rationale + tags + importance) -│ -├─ Subtask complete? -│ └─ search (dedup) → write_context (output + file paths + key facts) -│ -├─ Discovery made? -│ └─ search (dedup) → write_context (what changed + impact, ttl if temporary) -│ -├─ Turn ending in pipeline? -│ └─ write_context → set_state → send handoff (always this order) -│ -└─ None of the above? - └─ Act normally. Memory is not needed for every action. -``` \ No newline at end of file diff --git a/skills/SKILL.md b/skills/SKILL.md new file mode 100644 index 0000000..edd92ae --- /dev/null +++ b/skills/SKILL.md @@ -0,0 +1,92 @@ +--- +name: agent-memory +description: "How to use the shared agent memory (agent-memory-store MCP tools: search_context, write_context, read_context, list_context, delete_context, get_state, set_state). Use whenever these tools are available and you start a task, receive a handoff, are unsure about a project fact, make a decision, finish a piece of work others depend on, or discover something that changes prior assumptions." +--- + +# Shared agent memory + +Your context window is temporary; the memory store is shared by every agent on +this project and survives sessions. Use it so no agent re-decides, re-discovers +or contradicts what another already settled. + +## 1. Read before you act + +At the start of a task, after a handoff, or whenever you are about to assume a +project fact (a convention, a decision, a config value, where something lives): + +``` +search_context({ query: "how do we run database migrations in production?" }) +``` + +- Ask in natural language, in Portuguese or English — search is multilingual + and also matches exact identifiers (`PAG-4821`, `orders.v1`, file paths). +- Run 1–3 focused queries rather than one vague one. +- Results show a snippet; call `read_context(id)` for the full text. +- `score` is relative ranking (1.0 = top for both keyword and semantic search); + `similarity` is semantic closeness. Read the result before trusting it. +- Narrow with `tags`, `agent`, `since`/`until` when you know the scope. + +## 2. Write what others will need + +Write after a **decision** (with the why), an **output** (what and where), or a +**discovery** that changes assumptions. Do not write chat logs, plans you have +not executed, or anything only you need right now. + +``` +write_context({ + topic: "Payments — PIX refund webhook timeout set to 20s", + content: "Raised from 10s to 20s: the bank's sandbox p99 is 14s (load test PAG-4821). Retries: 3, exponential backoff. Config: services/payments/config/pix.yaml.", + tags: ["payments", "pix", "decision"], + importance: "high" +}) +``` + +- **Topic**: specific enough to be found six months from now by another agent. +- **Content**: facts, numbers, paths, and the reason. Under ~2000 characters + (longer text is still keyword-searchable, but split it if you can). +- **Tags**: 1–4 short lowercase words. Check existing ones with `list_context`. +- **Importance**: `critical` = others will break things without it; + `high` = changes how the next step runs; `medium` default; `low` = ephemeral. +- **Temporary facts** (rate limits, incident workarounds): set `ttl_days`. + +## 3. Update, don't duplicate + +When something changes, update the existing memory instead of adding a new one: + +``` +write_context({ id: "", topic: "...", content: "" }) +``` + +`write_context` warns about possible duplicates (same topic or very similar +content). When it does, merge them: update one with the combined content and +`delete_context` the other. Use `delete_context` only for memories that are +wrong or obsolete. + +When several agents may edit the same memory, pass `expected_version` (from +the `vN` shown in search/read results). On a conflict, re-read and retry. + +## 4. Coordinate with state + +`get_state` / `set_state` hold small mutable values: current phase, run id, +who owns what, counters. Not searchable — use `write_context` for knowledge. + +To change shared state safely: + +``` +s = get_state({ key: "release_phase" }) // → version 3 +set_state({ key: "release_phase", value: {...}, expected_version: 3 }) +``` + +`expected_version: 0` means "only if nobody has set it yet" (claiming a task). + +## 5. Handoffs + +Finish in this order: `write_context` (your output) → `set_state` (next phase) +→ hand off with a short pointer. The receiving agent starts with `get_state` and +`search_context`, so the details live in memory, not in the message. + +## 6. Never store secrets + +The server rejects API keys, tokens, private keys and passwords in connection +strings. Write where the secret lives instead ("DATABASE_URL in Vault at +prod/payments"). diff --git a/src/bm25.js b/src/bm25.js deleted file mode 100644 index d399b16..0000000 --- a/src/bm25.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * BM25 (Best Match 25) ranking algorithm — pure JavaScript implementation. - * - * BM25 is a bag-of-words retrieval function that ranks documents by relevance - * to a given query. It is the default ranking algorithm in Elasticsearch and - * Apache Lucene, and works exceptionally well for short, well-labeled text - * chunks without requiring any external APIs or embedding models. - * - * Tuning parameters: - * k1 (1.5) — term frequency saturation. Higher = more weight on rare terms. - * b (0.75) — length normalization. 1.0 = full normalization, 0 = none. - */ - -const k1 = 1.5; -const b = 0.75; - -/** - * Tokenizes a string into lowercase terms, stripping punctuation. - * Handles Latin extended characters (Portuguese, Spanish, French, etc.). - * - * @param {string} text - * @returns {string[]} - */ -function tokenize(text) { - return text - .toLowerCase() - .normalize("NFD") - .replace(/[\u0300-\u036f]/g, "") - .replace(/[^\w\s]/g, " ") - .split(/\s+/) - .filter((t) => t.length > 1); -} - -export class BM25 { - constructor() { - /** @type {Array<{ id: string, len: number, metadata: object }>} */ - this.documents = []; - /** @type {Array>} */ - this.termFreqs = []; - /** @type {Map} term → document frequency */ - this.docFreqs = new Map(); - this.avgLen = 0; - } - - /** - * Adds a document to the index. - * - * @param {string} id - Unique document identifier - * @param {string} text - Searchable text content - * @param {object} metadata - Arbitrary metadata attached to results - */ - addDocument(id, text, metadata = {}) { - const tokens = tokenize(text); - const tf = new Map(); - for (const t of tokens) tf.set(t, (tf.get(t) || 0) + 1); - - this.documents.push({ id, len: tokens.length, metadata }); - this.termFreqs.push(tf); - - for (const term of tf.keys()) { - this.docFreqs.set(term, (this.docFreqs.get(term) || 0) + 1); - } - - const total = this.documents.reduce((s, d) => s + d.len, 0); - this.avgLen = total / this.documents.length; - } - - /** - * Computes the BM25 score for a single document against query terms. - * - * @param {number} docIdx - * @param {string[]} queryTerms - * @returns {number} - */ - _score(docIdx, queryTerms) { - const doc = this.documents[docIdx]; - const tf = this.termFreqs[docIdx]; - const N = this.documents.length; - let score = 0; - - for (const term of queryTerms) { - const freq = tf.get(term) || 0; - if (freq === 0) continue; - const df = this.docFreqs.get(term) || 0; - const idf = Math.log((N - df + 0.5) / (df + 0.5) + 1); - const tfNorm = - (freq * (k1 + 1)) / (freq + k1 * (1 - b + b * (doc.len / this.avgLen))); - score += idf * tfNorm; - } - return score; - } - - /** - * Searches the index and returns the top-K most relevant documents. - * - * @param {string} query - Natural language search query - * @param {number} [topK=5] - Maximum results to return - * @param {Function} [filter=null] - Optional predicate fn(metadata) => boolean - * @returns {Array<{ id: string, score: number, metadata: object }>} - */ - search(query, topK = 5, filter = null) { - const queryTerms = tokenize(query); - const results = []; - - for (let i = 0; i < this.documents.length; i++) { - const doc = this.documents[i]; - if (filter && !filter(doc.metadata)) continue; - const score = this._score(i, queryTerms); - if (score > 0) - results.push({ id: doc.id, score, metadata: doc.metadata }); - } - - return results.sort((a, b) => b.score - a.score).slice(0, topK); - } -} diff --git a/src/db.js b/src/db.js deleted file mode 100644 index c4b15d1..0000000 --- a/src/db.js +++ /dev/null @@ -1,367 +0,0 @@ -/** - * SQLite database layer powered by node:sqlite (built-in). - * - * Single-file database at /store.db with WAL mode. - * FTS5 for full-text BM25 search, BLOB columns for vector embeddings. - * Zero external dependencies — uses Node.js native SQLite (>=22.5). - */ - -import { DatabaseSync } from "node:sqlite"; -import { mkdirSync } from "fs"; -import path from "path"; - -const STORE_PATH = process.env.AGENT_STORE_PATH - ? path.resolve(process.env.AGENT_STORE_PATH) - : path.join(process.cwd(), ".agent-memory-store"); - -const DB_PATH = path.join(STORE_PATH, "store.db"); - -let db = null; -const stmtCache = new Map(); - -/** - * Returns a cached prepared statement for static SQL. - * Avoids re-preparing the same SQL on every call. - */ -function stmt(sql) { - let s = stmtCache.get(sql); - if (!s) { - s = getDb().prepare(sql); - stmtCache.set(sql, s); - } - return s; -} - -// ─── Schema ───────────────────────────────────────────────────────────────── - -const SCHEMA_TABLES = ` -CREATE TABLE IF NOT EXISTS chunks ( - id TEXT PRIMARY KEY, - topic TEXT NOT NULL, - agent TEXT NOT NULL DEFAULT 'global', - tags TEXT NOT NULL DEFAULT '[]', - importance TEXT NOT NULL DEFAULT 'medium', - content TEXT NOT NULL, - embedding BLOB, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - expires_at TEXT -); - -CREATE INDEX IF NOT EXISTS idx_chunks_agent ON chunks(agent); -CREATE INDEX IF NOT EXISTS idx_chunks_updated ON chunks(updated_at); -CREATE INDEX IF NOT EXISTS idx_chunks_expires ON chunks(expires_at); - -CREATE TABLE IF NOT EXISTS state ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at TEXT NOT NULL -); -`; - -const SCHEMA_FTS = ` -CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( - id UNINDEXED, - topic, - tags, - agent, - content, - content='chunks', - content_rowid=rowid -); -`; - -const SCHEMA_TRIGGERS = ` -CREATE TRIGGER IF NOT EXISTS chunks_ai AFTER INSERT ON chunks BEGIN - INSERT INTO chunks_fts(rowid, id, topic, tags, agent, content) - VALUES (new.rowid, new.id, new.topic, new.tags, new.agent, new.content); -END; - -CREATE TRIGGER IF NOT EXISTS chunks_ad AFTER DELETE ON chunks BEGIN - INSERT INTO chunks_fts(chunks_fts, rowid, id, topic, tags, agent, content) - VALUES ('delete', old.rowid, old.id, old.topic, old.tags, old.agent, old.content); -END; - -CREATE TRIGGER IF NOT EXISTS chunks_au AFTER UPDATE ON chunks BEGIN - INSERT INTO chunks_fts(chunks_fts, rowid, id, topic, tags, agent, content) - VALUES ('delete', old.rowid, old.id, old.topic, old.tags, old.agent, old.content); - INSERT INTO chunks_fts(rowid, id, topic, tags, agent, content) - VALUES (new.rowid, new.id, new.topic, new.tags, new.agent, new.content); -END; -`; - -// ─── Initialization ───────────────────────────────────────────────────────── - -/** - * Returns the database instance. Creates it on first call. - * Synchronous — node:sqlite DatabaseSync is synchronous by design. - */ -export function getDb() { - if (db) return db; - - mkdirSync(STORE_PATH, { recursive: true }); - - db = new DatabaseSync(DB_PATH); - - // WAL mode for better concurrent read performance - db.exec("PRAGMA journal_mode = WAL"); - - // Run schema - db.exec(SCHEMA_TABLES); - db.exec(SCHEMA_FTS); - db.exec(SCHEMA_TRIGGERS); - - // Purge expired chunks - db.exec( - `DELETE FROM chunks WHERE expires_at IS NOT NULL AND expires_at < datetime('now')`, - ); - - // Graceful shutdown - const shutdown = () => { - if (db) db.close(); - process.exit(0); - }; - process.on("SIGINT", shutdown); - process.on("SIGTERM", shutdown); - - return db; -} - -// ─── CRUD Operations ──────────────────────────────────────────────────────── - -/** - * Inserts or replaces a chunk in the database. - */ -export function insertChunk({ - id, - topic, - agent, - tags, - importance, - content, - embedding, - createdAt, - updatedAt, - expiresAt, -}) { - stmt( - `INSERT OR REPLACE INTO chunks (id, topic, agent, tags, importance, content, embedding, created_at, updated_at, expires_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ).run( - id, - topic, - agent, - JSON.stringify(tags), - importance, - content, - embedding ? Buffer.from(embedding.buffer) : null, - createdAt, - updatedAt, - expiresAt, - ); -} - -/** - * Retrieves a single chunk by ID. - * @returns {object|null} - */ -export function getChunk(id) { - const row = stmt(`SELECT * FROM chunks WHERE id = ?`).get(id); - if (!row) return null; - return parseChunkRow(row); -} - -/** - * Deletes a chunk by ID. - * @returns {boolean} true if a row was deleted - */ -export function deleteChunkById(id) { - const result = stmt(`DELETE FROM chunks WHERE id = ?`).run(id); - return result.changes > 0; -} - -/** - * Lists chunk metadata, with optional agent/tags filters. - * Sorted by updated_at descending. - */ -export function listChunksDb({ agent, tags = [], limit = 100, offset = 0 } = {}) { - const d = getDb(); - let sql = `SELECT id, topic, agent, tags, importance, updated_at FROM chunks`; - const conditions = []; - const params = []; - - if (agent) { - conditions.push(`agent = ?`); - params.push(agent); - } - - if (tags.length > 0) { - const tagConditions = tags.map(() => `tags LIKE ?`); - conditions.push(`(${tagConditions.join(" OR ")})`); - params.push(...tags.map((t) => `%"${t}"%`)); - } - - if (conditions.length) sql += ` WHERE ${conditions.join(" AND ")}`; - sql += ` ORDER BY updated_at DESC LIMIT ? OFFSET ?`; - params.push(limit, offset); - - const rows = d.prepare(sql).all(...params); - return rows.map((r) => ({ - id: r.id, - topic: r.topic, - agent: r.agent, - tags: JSON.parse(r.tags), - importance: r.importance, - updated: r.updated_at, - })); -} - -/** - * Full-text search via FTS5 (BM25). - * Returns ranked results with full chunk data (avoids separate lookups). - */ -export function searchFTS({ query, agent, tags = [], topK = 18 }) { - const d = getDb(); - - // Escape FTS5 special chars and build query - const ftsQuery = query - .replace(/["*^:(){}[\]]/g, " ") - .split(/\s+/) - .filter((t) => t.length > 1) - .join(" OR "); - - if (!ftsQuery) return []; - - let sql = ` - SELECT c.id, c.topic, c.agent, c.tags, c.importance, c.content, c.updated_at, rank - FROM chunks_fts - JOIN chunks c ON c.id = chunks_fts.id - WHERE chunks_fts MATCH ?`; - const params = [ftsQuery]; - - if (agent) { - sql += ` AND c.agent = ?`; - params.push(agent); - } - - if (tags.length > 0) { - const tagConditions = tags.map(() => `c.tags LIKE ?`); - sql += ` AND (${tagConditions.join(" OR ")})`; - params.push(...tags.map((t) => `%"${t}"%`)); - } - - sql += ` ORDER BY rank LIMIT ?`; - params.push(topK); - - const rows = d.prepare(sql).all(...params); - return rows.map((r) => ({ - id: r.id, - topic: r.topic, - agent: r.agent, - tags: JSON.parse(r.tags), - importance: r.importance, - content: r.content, - updated: r.updated_at, - score: -r.rank, - })); -} - -/** - * Retrieves all embeddings for vector search. - * @returns {Array<{ id: string, embedding: Float32Array }>} - */ -export function getAllEmbeddings({ agent, tags = [] } = {}) { - const d = getDb(); - let sql = `SELECT id, embedding FROM chunks WHERE embedding IS NOT NULL`; - const params = []; - - if (agent) { - sql += ` AND agent = ?`; - params.push(agent); - } - - if (tags.length > 0) { - const tagConditions = tags.map(() => `tags LIKE ?`); - sql += ` AND (${tagConditions.join(" OR ")})`; - params.push(...tags.map((t) => `%"${t}"%`)); - } - - const rows = d.prepare(sql).all(...params); - return rows - .filter((r) => r.embedding !== null) - .map((r) => ({ - id: r.id, - embedding: new Float32Array( - r.embedding.buffer, - r.embedding.byteOffset, - r.embedding.byteLength / 4, - ), - })); -} - -/** - * Updates only the embedding for a chunk. - */ -export function updateEmbedding(id, embedding) { - stmt(`UPDATE chunks SET embedding = ? WHERE id = ?`).run( - Buffer.from(embedding.buffer), - id, - ); -} - -/** - * Returns chunks that have no embedding yet. - */ -export function getChunksWithoutEmbedding() { - return stmt( - `SELECT id, topic, tags, content FROM chunks WHERE embedding IS NULL`, - ) - .all() - .map((r) => ({ - id: r.id, - topic: r.topic, - tags: r.tags, - content: r.content, - })); -} - -// ─── State Operations ─────────────────────────────────────────────────────── - -export function getStateDb(key) { - const row = stmt(`SELECT value FROM state WHERE key = ?`).get(key); - if (!row) return null; - return JSON.parse(row.value); -} - -export function setStateDb(key, value) { - const updatedAt = new Date().toISOString(); - stmt( - `INSERT OR REPLACE INTO state (key, value, updated_at) VALUES (?, ?, ?)`, - ).run(key, JSON.stringify(value), updatedAt); - return { key, updated: updatedAt }; -} - -// ─── Helpers ──────────────────────────────────────────────────────────────── - -function parseChunkRow(row) { - return { - id: row.id, - topic: row.topic, - agent: row.agent, - tags: JSON.parse(row.tags), - importance: row.importance, - content: row.content, - embedding: row.embedding - ? new Float32Array( - row.embedding.buffer, - row.embedding.byteOffset, - row.embedding.byteLength / 4, - ) - : null, - createdAt: row.created_at, - updatedAt: row.updated_at, - expiresAt: row.expires_at, - }; -} - -export { STORE_PATH }; diff --git a/src/embeddings.js b/src/embeddings.js index 568fb7c..6ace591 100644 --- a/src/embeddings.js +++ b/src/embeddings.js @@ -1,124 +1,247 @@ /** - * Local embedding generation via @huggingface/transformers. + * Embedding providers. * - * Uses the all-MiniLM-L6-v2 model (384 dimensions) running locally via ONNX Runtime. - * Model is auto-downloaded (~23MB) on first use and cached in ~/.cache/huggingface/. + * An Embedder turns text into L2-normalized Float32Array vectors: * - * Graceful degradation: if the model fails to load, all functions return null - * and the system falls back to BM25-only search. + * interface Embedder { + * id: string // stored next to each vector; a change triggers re-embedding + * dim: number | null // known after load + * load(): Promise // idempotent; false when unavailable + * isReady(): boolean + * embedQuery(text): Promise + * embedDocuments(texts): Promise + * } + * + * TransformersEmbedder runs an ONNX model locally via @huggingface/transformers. + * HashEmbedder is a deterministic, dependency-free embedder used by tests and CI. */ -let pipelineInstance = null; -let loadFailed = false; -let loadingPromise = null; +import { createHash } from "crypto"; +import os from "os"; +import path from "path"; +import { extractTerms } from "./store/fts-query.js"; /** - * Lazily initializes the feature-extraction pipeline. - * Returns null if the model cannot be loaded. - * Ensures only one load attempt runs at a time. + * Supported local models. Prefixes and pooling follow each model card; using + * the wrong ones silently degrades retrieval quality. + * + * duplicateThreshold: cosine above which write_context reports a "possible + * duplicate". Calibrated on the golden set (12 superseded/superseding pairs vs + * each memory's nearest unrelated neighbour) for a ~5% false-positive rate. */ -async function getPipeline() { - if (pipelineInstance) return pipelineInstance; - if (loadFailed) return null; +export const MODELS = { + "granite-97m-multilingual": { + repo: "onnx-community/granite-embedding-97m-multilingual-r2-ONNX", + pooling: "cls", + queryPrefix: "", + docPrefix: "", + dtype: "q8", + duplicateThreshold: 0.89, + }, + "embeddinggemma-300m": { + repo: "onnx-community/embeddinggemma-300m-ONNX", + pooling: "mean", + queryPrefix: "task: search result | query: ", + docPrefix: "title: none | text: ", + dtype: "q8", + duplicateThreshold: 0.8, + }, + "arctic-embed-m-v2": { + repo: "Snowflake/snowflake-arctic-embed-m-v2.0", + pooling: "cls", + queryPrefix: "query: ", + docPrefix: "", + dtype: "q8", + duplicateThreshold: 0.65, + }, + "minilm-l6-en": { + repo: "Xenova/all-MiniLM-L6-v2", + pooling: "mean", + queryPrefix: "", + docPrefix: "", + dtype: "q8", + duplicateThreshold: 0.75, + }, +}; - // Deduplicate concurrent load attempts - if (loadingPromise) return loadingPromise; +export const DEFAULT_MODEL = "arctic-embed-m-v2"; - loadingPromise = (async () => { - try { - process.stderr.write( - "[agent-memory-store] Loading embedding model (first run downloads ~23MB)...\n", - ); - const { pipeline } = await import("@huggingface/transformers"); - pipelineInstance = await pipeline( - "feature-extraction", - "Xenova/all-MiniLM-L6-v2", - { dtype: "fp32" }, - ); - process.stderr.write( - "[agent-memory-store] Embedding model loaded successfully.\n", +/** Max characters of a document sent to the model (~512 tokens). */ +export const MAX_EMBED_CHARS = 2000; + +const BATCH_SIZE = 16; + +/** + * Where models are cached. transformers.js defaults to a folder inside + * node_modules, which npx and `npm ci` throw away — so pin a user cache. + */ +export function modelCacheDir() { + if (process.env.AGENT_MEMORY_CACHE) return path.resolve(process.env.AGENT_MEMORY_CACHE); + const base = process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"); + return path.join(base, "agent-memory-store", "models"); +} + +function log(msg) { + process.stderr.write(`[agent-memory-store] ${msg}\n`); +} + +export class TransformersEmbedder { + /** + * @param {string} name - key of MODELS + */ + constructor(name) { + const spec = MODELS[name]; + if (!spec) { + throw new Error( + `Unknown embedding model "${name}". Available: ${Object.keys(MODELS).join(", ")}, none`, ); - return pipelineInstance; - } catch (err) { - loadFailed = true; - process.stderr.write( - `[agent-memory-store] Embedding model failed to load: ${err.message}\n` + - `[agent-memory-store] Falling back to BM25-only search.\n`, + } + this.name = name; + this.spec = spec; + this.id = `${spec.repo}@${spec.dtype}`; + this.dim = null; + this.duplicateThreshold = spec.duplicateThreshold; + this._extractor = null; + this._loading = null; + this._failed = false; + } + + isReady() { + return this._extractor !== null; + } + + async load() { + if (this._extractor) return true; + if (this._failed) return false; + if (!this._loading) { + this._loading = (async () => { + try { + log(`Loading embedding model ${this.spec.repo} (downloaded once, then cached)...`); + const { pipeline, env } = await import("@huggingface/transformers"); + env.cacheDir = modelCacheDir(); + // transformers.js warns that arctic's "gte" architecture is loaded via + // the base class; that is the intended path, so hide only that line. + const warn = console.warn; + console.warn = (...a) => (String(a[0]).startsWith("Unknown model class") ? undefined : warn(...a)); + let extractor; + try { + extractor = await pipeline("feature-extraction", this.spec.repo, { dtype: this.spec.dtype }); + } finally { + console.warn = warn; + } + const probe = await extractor(["probe"], { + pooling: this.spec.pooling, + normalize: true, + }); + this.dim = probe.dims.at(-1); + this._extractor = extractor; + log(`Embedding model ready (${this.dim} dims).`); + return true; + } catch (err) { + this._failed = true; + log(`Embedding model failed to load: ${err.message}. Using keyword search only.`); + return false; + } + })(); + } + return this._loading; + } + + async _run(texts) { + if (!(await this.load())) throw new Error("Embedding model unavailable"); + // Batch texts of similar length together: each batch is padded to its + // longest text, so mixing short and long ones wastes most of the compute. + const order = texts.map((t, i) => i).sort((a, b) => texts[a].length - texts[b].length); + const out = new Array(texts.length); + for (let i = 0; i < order.length; i += BATCH_SIZE) { + const idx = order.slice(i, i + BATCH_SIZE); + const tensor = await this._extractor( + idx.map((k) => texts[k]), + { pooling: this.spec.pooling, normalize: true }, ); - return null; - } finally { - loadingPromise = null; + const dim = tensor.dims.at(-1); + idx.forEach((k, j) => { + out[k] = Float32Array.from(tensor.data.subarray(j * dim, (j + 1) * dim)); + }); } - })(); + return out; + } - return loadingPromise; -} + async embedQuery(text) { + const [v] = await this._run([this.spec.queryPrefix + text.slice(0, MAX_EMBED_CHARS)]); + return v; + } -/** - * Generates an embedding for a single text string. - * - * @param {string} text - Text to embed (topic + tags + content) - * @returns {Promise} 384-dim embedding or null if unavailable - */ -export async function embed(text) { - const extractor = await getPipeline(); - if (!extractor) return null; - - try { - const output = await extractor(text, { - pooling: "mean", - normalize: true, - }); - return new Float32Array(output.data); - } catch (err) { - process.stderr.write( - `[agent-memory-store] Embedding error: ${err.message}\n`, - ); - return null; + async embedDocuments(texts) { + return this._run(texts.map((t) => this.spec.docPrefix + t.slice(0, MAX_EMBED_CHARS))); } } /** - * Generates embeddings for multiple texts. - * - * @param {string[]} texts - * @returns {Promise>} + * Deterministic hashing-trick embedder (terms + character trigrams). + * Captures lexical overlap only — it exists so tests exercise the full + * vector path without downloading a model. Not for production use. */ -export async function embedBatch(texts) { - const results = []; - for (const text of texts) { - results.push(await embed(text)); +export class HashEmbedder { + constructor(dim = 256) { + this.id = `hash-v1-${dim}`; + this.dim = dim; + this.duplicateThreshold = 0.8; } - return results; -} -/** - * Prepares searchable text from chunk fields for embedding. - * - * @param {object} chunk - * @param {string} chunk.topic - * @param {string[]|string} chunk.tags - * @param {string} chunk.content - * @returns {string} - */ -export function prepareText({ topic, tags, content }) { - const tagStr = Array.isArray(tags) ? tags.join(" ") : tags || ""; - // Truncate content to ~800 chars to stay within model token limit - const truncated = content.length > 800 ? content.slice(0, 800) : content; - return `${topic} ${tagStr} ${truncated}`.trim(); + isReady() { + return true; + } + + async load() { + return true; + } + + _vec(text) { + const v = new Float32Array(this.dim); + const add = (feature, weight) => { + const h = createHash("md5").update(feature).digest(); + const idx = h.readUInt32LE(0) % this.dim; + v[idx] += (h[4] & 1 ? 1 : -1) * weight; + }; + for (const term of extractTerms(text)) { + add(`t:${term}`, 1); + const padded = `#${term}#`; + for (let i = 0; i + 3 <= padded.length; i++) add(`g:${padded.slice(i, i + 3)}`, 0.3); + } + let norm = 0; + for (const x of v) norm += x * x; + norm = Math.sqrt(norm) || 1; + for (let i = 0; i < v.length; i++) v[i] /= norm; + return v; + } + + async embedQuery(text) { + return this._vec(text); + } + + async embedDocuments(texts) { + return texts.map((t) => this._vec(t)); + } } /** - * Returns whether the embedding model is available. + * Creates the embedder named by `name` (or AGENT_MEMORY_MODEL). + * "none" disables semantic search; "hash" is the test embedder. + * + * @param {string} [name] + * @returns {object|null} */ -export function isEmbeddingAvailable() { - return pipelineInstance !== null && !loadFailed; +export function createEmbedder(name = process.env.AGENT_MEMORY_MODEL || DEFAULT_MODEL) { + if (name === "none") return null; + if (name === "hash") return new HashEmbedder(); + return new TransformersEmbedder(name); } /** - * Pre-warms the embedding model (call during startup). - * Non-blocking — failures are silently handled. + * Text that represents a memory for embedding purposes. */ -export async function warmup() { - await getPipeline(); +export function documentText({ topic, tags = [], content }) { + const tagLine = tags.length ? `\n${tags.join(", ")}` : ""; + return `${topic}${tagLine}\n${content}`; } diff --git a/src/index.js b/src/index.js index 5093df8..1efdd63 100644 --- a/src/index.js +++ b/src/index.js @@ -1,347 +1,19 @@ #!/usr/bin/env node /** - * agent-memory-store MCP server entry point. - * - * Exposes 7 tools to any MCP-compatible client (Claude Code, opencode, etc.): - * search_context — Hybrid search (BM25 + semantic) over stored chunks - * write_context — persist a new memory chunk - * read_context — retrieve a chunk by ID - * list_context — list chunk metadata (no body) - * delete_context — remove a chunk by ID - * get_state — read a session state variable - * set_state — write a session state variable - * - * Usage: - * npx agent-memory-store - * AGENT_STORE_PATH=/your/project/.agent-memory-store npx agent-memory-store + * Entry point. node:sqlite is stable in practice but still prints an + * ExperimentalWarning on start, which MCP clients surface as server errors. + * Filter only that warning, then load the server (dynamically, so the filter + * is in place before node:sqlite is loaded). */ - -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; -import { z } from "zod/v4"; -import { - searchChunks, - writeChunk, - readChunk, - deleteChunk, - listChunks, - getState, - setState, - initStore, -} from "./store.js"; - -const { version } = JSON.parse( - await import("fs").then((fs) => - fs.promises.readFile(new URL("../package.json", import.meta.url), "utf8"), - ), -); - -// Initialize database, run migration, warm up embeddings -await initStore(); - -const server = new McpServer({ - name: "context-store", - version, -}); - -// ─── search_context ─────────────────────────────────────────────────────────── - -server.tool( - "search_context", - [ - "Search stored memory chunks using hybrid ranking (BM25 + semantic similarity).", - "Call this at the start of any task to retrieve relevant prior knowledge,", - "decisions, and outputs before generating a response.", - "Supports three modes: 'hybrid' (default, best quality), 'bm25' (keyword-only), 'semantic' (meaning-only).", - ].join(" "), - { - query: z - .string() - .describe( - "Search query. Be specific — use canonical terms your team agreed on.", - ), - tags: z - .array(z.string()) - .optional() - .describe("Narrow results to chunks matching any of these tags."), - agent: z - .string() - .optional() - .describe("Narrow results to chunks written by a specific agent ID."), - top_k: z - .number() - .int() - .min(1) - .max(20) - .optional() - .describe("Maximum number of results to return (default: 6)."), - min_score: z - .number() - .min(0) - .optional() - .describe( - "Minimum relevance score. Lower = more permissive (default: 0.1).", - ), - search_mode: z - .enum(["hybrid", "bm25", "semantic"]) - .optional() - .describe( - "Search strategy: 'hybrid' (BM25 + semantic, default), 'bm25' (keyword only), 'semantic' (embedding similarity only).", - ), - }, - async ({ query, tags, agent, top_k, min_score, search_mode }) => { - const results = await searchChunks({ - query, - tags: tags ?? [], - agent, - topK: top_k ?? 6, - minScore: min_score ?? 0.1, - mode: search_mode ?? "hybrid", - }); - - if (results.length === 0) { - return { content: [{ type: "text", text: "No matching chunks found." }] }; - } - - const body = results - .map((r) => - [ - `### [score: ${r.score}] ${r.topic}`, - `**id:** \`${r.id}\` | **agent:** ${r.agent} | **tags:** ${r.tags.join(", ")} | **importance:** ${r.importance} | **updated:** ${r.updated}`, - "", - r.content, - ].join("\n"), - ) - .join("\n\n---\n\n"); - - return { content: [{ type: "text", text: body }] }; - }, -); - -// ─── write_context ──────────────────────────────────────────────────────────── - -server.tool( - "write_context", - [ - "Persist a memory chunk to the database.", - "Call this after completing a subtask, making a key decision,", - "or producing output that downstream agents will need.", - "Embeddings are computed automatically in the background for semantic search.", - ].join(" "), - { - topic: z - .string() - .describe( - 'Short, specific title. e.g. "Auth service — JWT decision" not "decision".', - ), - content: z - .string() - .describe( - "Chunk body in markdown. Include rationale, not just conclusions.", - ), - agent: z - .string() - .optional() - .describe( - 'Agent ID writing this chunk (e.g. "pm-agent", "scraper-agent").', - ), - tags: z - .array(z.string()) - .optional() - .describe( - "Canonical tags for future retrieval. Use consistent terms across agents.", - ), - importance: z - .enum(["low", "medium", "high", "critical"]) - .optional() - .describe( - "Importance level — affects future curation decisions (default: medium).", - ), - ttl_days: z - .number() - .positive() - .optional() - .describe("Auto-expiry in days. Omit for permanent storage."), - }, - async ({ topic, content, agent, tags, importance, ttl_days }) => { - const result = await writeChunk({ - topic, - content, - agent: agent ?? "global", - tags: tags ?? [], - importance: importance ?? "medium", - ttlDays: ttl_days, - }); - - return { - content: [ - { - type: "text", - text: `Chunk saved: id=\`${result.id}\` | topic="${result.topic}" | tags=[${result.tags.join(", ")}] | importance=${result.importance}`, - }, - ], - }; - }, -); - -// ─── read_context ───────────────────────────────────────────────────────────── - -server.tool( - "read_context", - "Retrieve the full content of a specific chunk by its ID.", - { - id: z - .string() - .describe( - "Chunk ID (10-char hex string from write_context or list_context).", - ), - }, - async ({ id }) => { - const chunk = await readChunk(id); - - if (!chunk) { - return { - content: [{ type: "text", text: `No chunk found with id \`${id}\`.` }], - }; - } - - const { meta, content } = chunk; - const header = [ - `## ${meta.topic}`, - `**id:** \`${meta.id}\` | **agent:** ${meta.agent} | **tags:** ${(meta.tags || []).join(", ")} | **importance:** ${meta.importance} | **updated:** ${meta.updated}`, - ].join("\n"); - - return { content: [{ type: "text", text: `${header}\n\n${content}` }] }; - }, -); - -// ─── list_context ───────────────────────────────────────────────────────────── - -server.tool( - "list_context", - "List all stored chunks (metadata only, no body). Useful for inventory and curation.", - { - agent: z.string().optional().describe("Filter by agent ID."), - tags: z.array(z.string()).optional().describe("Filter by tags."), - limit: z - .number() - .int() - .min(1) - .max(500) - .optional() - .describe("Maximum number of results to return (default: 100)."), - offset: z - .number() - .int() - .min(0) - .optional() - .describe("Number of results to skip for pagination (default: 0)."), - }, - async ({ agent, tags, limit, offset }) => { - const chunks = await listChunks({ - agent, - tags: tags ?? [], - limit: limit ?? 100, - offset: offset ?? 0, - }); - - if (chunks.length === 0) { - return { content: [{ type: "text", text: "Memory store is empty." }] }; - } - - const lines = chunks.map( - (c) => - `- \`${c.id}\` **${c.topic}** | agent:${c.agent} | tags:[${c.tags.join(", ")}] | ${c.importance} | ${c.updated}`, - ); - - return { - content: [ - { - type: "text", - text: `${chunks.length} chunk(s) found:\n\n${lines.join("\n")}`, - }, - ], - }; - }, -); - -// ─── delete_context ─────────────────────────────────────────────────────────── - -server.tool( - "delete_context", - "Permanently delete a chunk by ID. Use to remove outdated or incorrect memory.", - { - id: z.string().describe("Chunk ID to delete."), - }, - async ({ id }) => { - const deleted = await deleteChunk(id); - return { - content: [ - { - type: "text", - text: deleted - ? `Chunk \`${id}\` deleted.` - : `No chunk found with id \`${id}\`.`, - }, - ], - }; - }, -); - -// ─── get_state ──────────────────────────────────────────────────────────────── - -server.tool( - "get_state", - "Read a pipeline state variable by key. Use to check progress, flags, and counters across agent turns.", - { - key: z.string().describe("State key to read."), - }, - async ({ key }) => { - const value = await getState(key); - - if (value === null) { - return { - content: [{ type: "text", text: `State key "${key}" not found.` }], - }; - } - - return { - content: [ - { - type: "text", - text: - typeof value === "string" ? value : JSON.stringify(value, null, 2), - }, - ], - }; - }, -); - -// ─── set_state ──────────────────────────────────────────────────────────────── - -server.tool( - "set_state", - "Write a pipeline state variable (any JSON-serializable value). Use to track progress, store flags, or pass structured data between agent turns.", - { - key: z - .string() - .describe('State key (e.g. "pipeline_status", "current_phase").'), - value: z.any().describe("Any JSON-serializable value."), - }, - async ({ key, value }) => { - const result = await setState(key, value); - return { - content: [ - { - type: "text", - text: `State "${key}" written at ${result.updated}.`, - }, - ], - }; - }, -); - -// ─── Start server ───────────────────────────────────────────────────────────── - -const transport = new StdioServerTransport(); -await server.connect(transport); +const emitWarning = process.emitWarning; +process.emitWarning = function (warning, ...args) { + const type = typeof args[0] === "string" ? args[0] : args[0]?.type; + if (type === "ExperimentalWarning" && String(warning?.message ?? warning).includes("SQLite")) return; + return emitWarning.call(this, warning, ...args); +}; + +// stdout carries the MCP protocol; a stray console.log from any dependency +// would corrupt it. Route general logging to stderr. +console.log = console.info = console.debug = console.error; + +await import("./server.js"); diff --git a/src/migrate.js b/src/migrate.js index 2f0f158..09b291c 100644 --- a/src/migrate.js +++ b/src/migrate.js @@ -1,124 +1,75 @@ /** - * Migration: filesystem-based storage → SQLite database. + * Migration: legacy filesystem storage (<= 0.0.5, markdown files) → SQLite. * - * Runs automatically on first startup if the legacy chunks/ directory exists - * but store.db does not. Migrates all chunks and state, then renames the - * legacy directories to *_backup/. + * Runs on startup when /chunks/ exists. Imports every chunk and + * state entry into the store, then renames the legacy directories to + * *_backup/ so the import never runs twice. */ import fs from "fs/promises"; import path from "path"; -import matter from "gray-matter"; -import { insertChunk, setStateDb, STORE_PATH } from "./db.js"; -const CHUNKS_DIR = path.join(STORE_PATH, "chunks"); -const STATE_DIR = path.join(STORE_PATH, "state"); -const DB_PATH = path.join(STORE_PATH, "store.db"); +async function isDir(p) { + return fs.stat(p).then((s) => s.isDirectory()).catch(() => false); +} /** - * Checks if migration is needed and runs it. - * @returns {Promise} true if migration was performed + * @param {import("./store/memory-store.js").MemoryStore} store + * @param {string} storeDir + * @returns {Promise} true if a migration ran */ -export async function migrateIfNeeded() { - // Check if legacy chunks dir exists - const chunksExist = await fs - .stat(CHUNKS_DIR) - .then((s) => s.isDirectory()) - .catch(() => false); - - if (!chunksExist) return false; - - // Check if DB already exists (already migrated) - const dbExists = await fs - .stat(DB_PATH) - .then((s) => s.isFile()) - .catch(() => false); - - if (dbExists) return false; - - process.stderr.write( - "[agent-memory-store] Migrating filesystem storage to SQLite...\n", - ); +export async function migrateLegacyFiles(store, storeDir) { + const chunksDir = path.join(storeDir, "chunks"); + const stateDir = path.join(storeDir, "state"); + if (!(await isDir(chunksDir))) return false; + process.stderr.write("[agent-memory-store] Migrating legacy file storage to SQLite...\n"); + const { default: matter } = await import("gray-matter"); let chunkCount = 0; let stateCount = 0; - // Migrate chunks - try { - const files = await fs.readdir(CHUNKS_DIR); - for (const file of files) { - if (!file.endsWith(".md")) continue; - try { - const raw = await fs.readFile(path.join(CHUNKS_DIR, file), "utf8"); - const { data: meta, content } = matter(raw); - - // Skip expired chunks - if (meta.expires && new Date(meta.expires) < new Date()) continue; - - const now = new Date().toISOString(); - await insertChunk({ - id: meta.id || file.replace(".md", ""), - topic: meta.topic || "Untitled", - agent: meta.agent || "global", - tags: meta.tags || [], - importance: meta.importance || "medium", - content: content.trim(), - embedding: null, // Will be computed in background - createdAt: meta.updated || now, - updatedAt: meta.updated || now, - expiresAt: meta.expires || null, - }); - chunkCount++; - } catch { - // Skip unreadable files - } + for (const file of await fs.readdir(chunksDir)) { + if (!file.endsWith(".md")) continue; + try { + const raw = await fs.readFile(path.join(chunksDir, file), "utf8"); + const { data: meta, content } = matter(raw); + if (meta.expires && new Date(meta.expires) < new Date()) continue; + store.importMemory({ + id: String(meta.id || file.replace(/\.md$/, "")), + topic: meta.topic || "Untitled", + content: content.trim() || "(empty)", + agent: meta.agent || "global", + tags: Array.isArray(meta.tags) ? meta.tags.map(String) : [], + importance: meta.importance, + createdAt: meta.updated ? new Date(meta.updated).toISOString() : undefined, + updatedAt: meta.updated ? new Date(meta.updated).toISOString() : undefined, + expiresAt: meta.expires || null, + }); + chunkCount++; + } catch (err) { + process.stderr.write(`[agent-memory-store] Skipped ${file}: ${err.message}\n`); } - } catch { - // chunks dir not readable } - // Migrate state - try { - const files = await fs.readdir(STATE_DIR); - for (const file of files) { + if (await isDir(stateDir)) { + for (const file of await fs.readdir(stateDir)) { if (!file.endsWith(".json")) continue; try { - const raw = await fs.readFile(path.join(STATE_DIR, file), "utf8"); - const { key, value } = JSON.parse(raw); - if (key) { - await setStateDb(key, value); + const { key, value } = JSON.parse(await fs.readFile(path.join(stateDir, file), "utf8")); + if (key && store.getState(key) === null) { + store.setState(key, value); stateCount++; } - } catch { - // Skip unreadable files + } catch (err) { + process.stderr.write(`[agent-memory-store] Skipped state ${file}: ${err.message}\n`); } } - } catch { - // state dir not readable - } - - // Rename legacy directories to backups - try { - await fs.rename(CHUNKS_DIR, CHUNKS_DIR + "_backup"); - } catch { - // Rename failed — not critical - } - - try { - const stateExists = await fs - .stat(STATE_DIR) - .then((s) => s.isDirectory()) - .catch(() => false); - if (stateExists) { - await fs.rename(STATE_DIR, STATE_DIR + "_backup"); - } - } catch { - // Rename failed — not critical + await fs.rename(stateDir, `${stateDir}_backup`).catch(() => {}); } + await fs.rename(chunksDir, `${chunksDir}_backup`).catch(() => {}); process.stderr.write( - `[agent-memory-store] Migration complete: ${chunkCount} chunks, ${stateCount} state entries.\n`, + `[agent-memory-store] Migration complete: ${chunkCount} memories, ${stateCount} state entries.\n`, ); - return true; } diff --git a/src/search.js b/src/search.js deleted file mode 100644 index c935d12..0000000 --- a/src/search.js +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Hybrid search engine combining FTS5 BM25 (native SQLite) and vector similarity. - * - * Search modes: - * - "hybrid" — FTS5 BM25 + vector cosine similarity merged via Reciprocal Rank Fusion - * - "bm25" — FTS5 only (no embeddings needed) - * - "semantic" — Vector similarity only - * - * Falls back to BM25-only if embeddings are not available. - */ - -import { searchFTS, getAllEmbeddings, getChunk } from "./db.js"; -import { embed, isEmbeddingAvailable } from "./embeddings.js"; - -/** - * Converts a full FTS result into the enriched output format. - */ -function ftsResultToEnriched(r) { - return { - id: r.id, - topic: r.topic, - agent: r.agent, - tags: r.tags, - importance: r.importance, - score: Math.round(r.score * 100) / 100, - content: r.content, - updated: r.updated, - }; -} - -// ─── Vector Search ────────────────────────────────────────────────────────── - -/** - * Computes cosine similarity between two Float32Arrays. - * Assumes both vectors are already L2-normalized (dot product = cosine sim). - */ -function cosineSimilarity(a, b) { - let dot = 0; - for (let i = 0; i < a.length; i++) dot += a[i] * b[i]; - return dot; -} - -/** - * Brute-force vector search over all chunk embeddings. - */ -function vectorSearch(queryEmbedding, { agent, tags = [], topK = 18 }) { - const embeddings = getAllEmbeddings({ agent, tags }); - if (!embeddings.length) return []; - - return embeddings - .map(({ id, embedding }) => ({ - id, - score: cosineSimilarity(queryEmbedding, embedding), - })) - .filter((r) => r.score > 0) - .sort((a, b) => b.score - a.score) - .slice(0, topK); -} - -// ─── Fusion ───────────────────────────────────────────────────────────────── - -/** - * Reciprocal Rank Fusion — merges two ranked lists into one. - */ -function reciprocalRankFusion(bm25Hits, vecHits, wBM25 = 0.4, wVec = 0.6) { - const K = 60; - const scores = new Map(); - - bm25Hits.forEach(({ id }, rank) => { - scores.set(id, (scores.get(id) || 0) + wBM25 / (K + rank + 1)); - }); - - vecHits.forEach(({ id }, rank) => { - scores.set(id, (scores.get(id) || 0) + wVec / (K + rank + 1)); - }); - - return [...scores.entries()] - .map(([id, score]) => ({ id, score })) - .sort((a, b) => b.score - a.score); -} - -// ─── Main Search ──────────────────────────────────────────────────────────── - -/** - * Main search function — performs hybrid, BM25, or semantic search. - * - * @param {object} opts - * @param {string} opts.query - * @param {string[]} [opts.tags] - * @param {string} [opts.agent] - * @param {number} [opts.topK] - * @param {number} [opts.minScore] - * @param {string} [opts.mode] - "hybrid" | "bm25" | "semantic" - * @returns {Promise} - */ -export async function hybridSearch({ - query, - tags = [], - agent, - topK = 6, - minScore = 0.1, - mode = "hybrid", -}) { - const candidateK = topK * 3; - const embeddingsReady = isEmbeddingAvailable(); - - // Determine effective mode - let effectiveMode = mode; - if ((mode === "hybrid" || mode === "semantic") && !embeddingsReady) { - effectiveMode = "bm25"; - } - - // BM25-only: searchFTS already returns full chunk data, no enrichment needed - if (effectiveMode === "bm25") { - const results = searchFTS({ query, agent, tags, topK: candidateK }); - return results.slice(0, topK).map(ftsResultToEnriched); - } - - // Semantic-only - if (effectiveMode === "semantic") { - const queryEmbedding = await embed(query); - if (!queryEmbedding) { - const results = searchFTS({ query, agent, tags, topK: candidateK }); - return results.slice(0, topK).map(ftsResultToEnriched); - } - const vecHits = vectorSearch(queryEmbedding, { agent, tags, topK: candidateK }); - return enrichVectorResults(vecHits.slice(0, topK)); - } - - // Hybrid: run FTS5 (sync) and embed query (async) in parallel - const queryEmbeddingPromise = embed(query); - const bm25Hits = searchFTS({ query, agent, tags, topK: candidateK }); - const queryEmbedding = await queryEmbeddingPromise; - - if (!queryEmbedding) { - return bm25Hits.slice(0, topK).map(ftsResultToEnriched); - } - - const vecHits = vectorSearch(queryEmbedding, { agent, tags, topK: candidateK }); - const fused = reciprocalRankFusion(bm25Hits, vecHits); - - // Enrich fused results: build lookup from BM25 data, only fetch missing from DB - const bm25Map = new Map(bm25Hits.map((r) => [r.id, r])); - const topResults = fused.slice(0, topK); - const enriched = []; - - for (const { id, score } of topResults) { - const cached = bm25Map.get(id); - if (cached) { - enriched.push({ - id: cached.id, - topic: cached.topic, - agent: cached.agent, - tags: cached.tags, - importance: cached.importance, - score: Math.round(score * 100) / 100, - content: cached.content, - updated: cached.updated, - }); - } else { - const chunk = getChunk(id); - if (!chunk) continue; - enriched.push({ - id: chunk.id, - topic: chunk.topic, - agent: chunk.agent, - tags: chunk.tags, - importance: chunk.importance, - score: Math.round(score * 100) / 100, - content: chunk.content, - updated: chunk.updatedAt, - }); - } - } - - return enriched; -} - -/** - * Enriches vector-only results by fetching full chunk data from DB. - */ -function enrichVectorResults(vecHits) { - const enriched = []; - for (const { id, score } of vecHits) { - const chunk = getChunk(id); - if (!chunk) continue; - enriched.push({ - id: chunk.id, - topic: chunk.topic, - agent: chunk.agent, - tags: chunk.tags, - importance: chunk.importance, - score: Math.round(score * 100) / 100, - content: chunk.content, - updated: chunk.updatedAt, - }); - } - return enriched; -} diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..fb8ab7f --- /dev/null +++ b/src/server.js @@ -0,0 +1,324 @@ +/** + * agent-memory-store MCP server (stdio). + * + * Tools: + * search_context — hybrid search (keyword + semantic) over memories + * write_context — create or update a memory + * read_context — full text of one memory + * list_context — inventory (metadata only) + * delete_context — remove a memory + * get_state — read a shared state value (+ version) + * set_state — write a shared state value (optional compare-and-set) + * + * Environment: + * AGENT_STORE_PATH store directory (default: ./.agent-memory-store) + * AGENT_MEMORY_MODEL embedding model key, or "none" for keyword-only + * AGENT_MEMORY_AGENT default agent id for writes (default: "global") + */ + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { readFileSync } from "fs"; +import path from "path"; +import { z } from "zod/v4"; +import { MemoryStore, MemoryError, IMPORTANCE } from "./store/memory-store.js"; +import { createEmbedder } from "./embeddings.js"; +import { migrateLegacyFiles } from "./migrate.js"; + +const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); + +const STORE_DIR = path.resolve(process.env.AGENT_STORE_PATH || path.join(process.cwd(), ".agent-memory-store")); +const DEFAULT_AGENT = process.env.AGENT_MEMORY_AGENT || "global"; + +const INSTRUCTIONS = `Persistent memory shared by every agent working in this project. +- Before acting on a task, call search_context with what you need to know (decisions, conventions, prior outputs). Queries can be in any language. +- After a decision, discovery or output others will need, call write_context with a specific topic, the content with its rationale, and a few lowercase tags. +- To change an existing memory, pass its id to write_context (updates in place). If write_context reports possible duplicates, update one of them instead of keeping both. +- Use get_state/set_state for small mutable values (phase, run id, flags). Pass expected_version to set_state when several agents may write the same key. +- Never store secrets; store where they live instead.`; + +const store = MemoryStore.open(path.join(STORE_DIR, "store.db"), { embedder: createEmbedder() }); +await migrateLegacyFiles(store, STORE_DIR); + +const server = new McpServer({ name: "agent-memory-store", version }, { instructions: INSTRUCTIONS }); + +// ─── Formatting helpers ───────────────────────────────────────────────────── + +function text(body) { + return { content: [{ type: "text", text: body }] }; +} + +function errorResult(err) { + const msg = err instanceof MemoryError ? err.message : `Internal error: ${err.message}`; + return { content: [{ type: "text", text: msg }], isError: true }; +} + +/** Wraps a handler so failures become actionable tool errors, never crashes. */ +function safe(handler) { + return async (args) => { + try { + return await handler(args); + } catch (err) { + if (!(err instanceof MemoryError)) { + process.stderr.write(`[agent-memory-store] ${err.stack || err.message}\n`); + } + return errorResult(err); + } + }; +} + +function day(iso) { + return iso ? iso.slice(0, 10) : ""; +} + +function metaLine(m, extra = []) { + const parts = [`id: ${m.id}`, ...extra]; + if (m.tags.length) parts.push(`tags: ${m.tags.join(", ")}`); + parts.push(m.importance); + parts.push(`by ${m.updatedBy}`); + parts.push(`updated ${day(m.updatedAt)} (v${m.version})`); + if (m.expiresAt) parts.push(`expires ${day(m.expiresAt)}`); + return parts.join(" · "); +} + +function snippet(content, maxChars) { + if (content.length <= maxChars) return content; + return `${content.slice(0, maxChars).trimEnd()}… [+${content.length - maxChars} chars — read_context for full text]`; +} + +// ─── Schemas ──────────────────────────────────────────────────────────────── + +const tagsSchema = z.array(z.string()).optional(); +const dateSchema = (what) => z.string().optional().describe(`ISO 8601 date/time; ${what}`); + +// ─── search_context ───────────────────────────────────────────────────────── + +server.registerTool( + "search_context", + { + title: "Search memory", + description: + "Search shared memory with hybrid ranking (keyword BM25 + multilingual semantic similarity). " + + "Call at the start of a task to find prior decisions, conventions and outputs. " + + "Results show a snippet; use read_context for the full text.", + inputSchema: { + query: z.string().min(1).describe("What you need to know, in natural language (any language)."), + tags: tagsSchema.describe("Only memories with at least one of these tags."), + agent: z.string().optional().describe("Only memories created by this agent id."), + since: dateSchema("only memories updated at or after this time"), + until: dateSchema("only memories updated at or before this time"), + top_k: z.number().int().min(1).max(50).optional().describe("Max results (default 6)."), + min_score: z + .number() + .min(0) + .max(1) + .optional() + .describe("Drop results below this rank-based score (0–1, default 0)."), + search_mode: z + .enum(["hybrid", "bm25", "semantic"]) + .optional() + .describe("hybrid (default), bm25 (exact keywords only) or semantic (meaning only)."), + max_chars: z + .number() + .int() + .min(100) + .max(20000) + .optional() + .describe("Max characters of content shown per result (default 1000)."), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + safe(async ({ query, tags, agent, since, until, top_k, min_score, search_mode, max_chars }) => { + const { mode, results } = await store.search({ + query, + tags, + agent, + since, + until, + limit: top_k ?? 6, + minScore: min_score ?? 0, + mode: search_mode ?? "hybrid", + }); + if (results.length === 0) return text(`No memories found (${mode} search).`); + const limit = max_chars ?? 1000; + const blocks = results.map((r, i) => { + const scores = [`score ${r.score.toFixed(2)}`]; + if (r.similarity != null) scores.push(`similarity ${r.similarity.toFixed(2)}`); + return `[${i + 1}] ${r.topic}\n${metaLine(r, scores)}\n${snippet(r.content, limit)}`; + }); + return text(`${results.length} result(s), ${mode} search:\n\n${blocks.join("\n\n")}`); + }), +); + +// ─── write_context ────────────────────────────────────────────────────────── + +server.registerTool( + "write_context", + { + title: "Write memory", + description: + "Save a memory other agents (and future sessions) will need: a decision with its rationale, an output and where it lives, or a discovery. " + + "Without id it creates a new memory; with id it updates that memory in place (fields you omit keep their values). " + + "The response lists possible duplicates — prefer updating them over creating near-copies.", + inputSchema: { + topic: z.string().min(1).describe('Short, specific title, e.g. "Auth — chose JWT over sessions".'), + content: z.string().min(1).describe("The memory in markdown. Include the why, not just the what."), + id: z + .string() + .optional() + .describe("Id of the memory to update. You may also choose a stable id (e.g. \"auth-decision\") to create one."), + tags: tagsSchema.describe("A few short lowercase tags, e.g. [\"auth\", \"decision\"]. Replaces existing tags on update."), + importance: z.enum(IMPORTANCE).optional().describe("low | medium (default) | high | critical."), + agent: z.string().optional().describe("Your agent id (e.g. \"backend-agent\")."), + ttl_days: z + .number() + .positive() + .nullable() + .optional() + .describe("Expire after this many days. Omit for permanent; null removes an existing expiry."), + expected_version: z + .number() + .int() + .min(0) + .optional() + .describe("Only write if the memory's current version matches (0 = must not exist). Prevents overwriting another agent's change."), + }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, + }, + safe(async ({ topic, content, id, tags, importance, agent, ttl_days, expected_version }) => { + const m = await store.write({ + id, + topic, + content, + tags, + importance, + agent: agent ?? DEFAULT_AGENT, + ttlDays: ttl_days, + expectedVersion: expected_version, + }); + const lines = [`${m.created ? "Created" : "Updated"} memory ${m.id} (v${m.version}): "${m.topic}"`]; + if (m.duplicates.length) { + lines.push("", "Possible duplicates — consider updating one of these (write_context with its id) and deleting the other:"); + for (const d of m.duplicates) lines.push(`- ${d.id}: "${d.topic}" (${d.reason})`); + } + if (m.content.length > 2000) { + lines.push("", "Note: only the first ~2000 characters are used for semantic search; keyword search covers the full text. Consider splitting long content."); + } + return text(lines.join("\n")); + }), +); + +// ─── read_context ─────────────────────────────────────────────────────────── + +server.registerTool( + "read_context", + { + title: "Read memory", + description: "Return the full content and metadata of one memory by id.", + inputSchema: { id: z.string().min(1).describe("Memory id from search_context or list_context.") }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + safe(async ({ id }) => { + const m = store.get(id); + if (!m) return errorResult(new MemoryError("NOT_FOUND", `No memory with id "${id}".`)); + return text(`# ${m.topic}\n${metaLine(m, [`created ${day(m.createdAt)}`])}\n\n${m.content}`); + }), +); + +// ─── list_context ─────────────────────────────────────────────────────────── + +server.registerTool( + "list_context", + { + title: "List memories", + description: "List memories newest first (metadata only, no content). Use for inventory and cleanup.", + inputSchema: { + agent: z.string().optional().describe("Only memories created by this agent id."), + tags: tagsSchema.describe("Only memories with at least one of these tags."), + since: dateSchema("only memories updated at or after this time"), + until: dateSchema("only memories updated at or before this time"), + limit: z.number().int().min(1).max(500).optional().describe("Page size (default 50)."), + offset: z.number().int().min(0).optional().describe("Items to skip (default 0)."), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + safe(async ({ agent, tags, since, until, limit, offset }) => { + const off = offset ?? 0; + const { total, items } = store.list({ agent, tags, since, until, limit: limit ?? 50, offset: off }); + if (total === 0) return text("No memories found."); + const lines = items.map((m) => `- ${m.topic}\n ${metaLine(m, [`${m.chars} chars`])}`); + const end = off + items.length; + const more = end < total ? `\n\nMore available: call again with offset ${end}.` : ""; + return text(`Memories ${items.length ? off + 1 : 0}–${end} of ${total}:\n${lines.join("\n")}${more}`); + }), +); + +// ─── delete_context ───────────────────────────────────────────────────────── + +server.registerTool( + "delete_context", + { + title: "Delete memory", + description: "Permanently delete a memory by id. Use for wrong or obsolete memories (prefer updating when it is merely outdated).", + inputSchema: { id: z.string().min(1).describe("Memory id to delete.") }, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, + }, + safe(async ({ id }) => { + if (!store.delete(id)) return errorResult(new MemoryError("NOT_FOUND", `No memory with id "${id}".`)); + return text(`Deleted memory ${id}.`); + }), +); + +// ─── get_state ────────────────────────────────────────────────────────────── + +server.registerTool( + "get_state", + { + title: "Get state", + description: "Read a shared state value (phase, run id, flags, counters) and its version.", + inputSchema: { key: z.string().min(1).describe("State key.") }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + safe(async ({ key }) => { + const s = store.getState(key); + if (!s) return text(`State "${key}" is not set (version 0).`); + return text( + `State "${key}" (version ${s.version}, updated ${s.updatedAt}${s.updatedBy ? ` by ${s.updatedBy}` : ""}):\n${JSON.stringify(s.value, null, 2)}`, + ); + }), +); + +// ─── set_state ────────────────────────────────────────────────────────────── + +server.registerTool( + "set_state", + { + title: "Set state", + description: + "Write a shared state value (any JSON). Pass expected_version (from get_state; 0 = must not exist) to update only if nobody changed it meanwhile.", + inputSchema: { + key: z.string().min(1).describe('State key, e.g. "current_phase".'), + value: z.any().describe("Any JSON value."), + expected_version: z.number().int().min(0).optional().describe("Compare-and-set guard."), + agent: z.string().optional().describe("Your agent id."), + }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + }, + safe(async ({ key, value, expected_version, agent }) => { + const r = store.setState(key, value ?? null, { expectedVersion: expected_version, agent: agent ?? DEFAULT_AGENT }); + return text(`State "${key}" written (version ${r.version}).`); + }), +); + +// ─── Start ────────────────────────────────────────────────────────────────── + +const shutdown = () => { + store.close(); + process.exit(0); +}; +process.on("SIGINT", shutdown); +process.on("SIGTERM", shutdown); +process.stdin.on("close", shutdown); + +await server.connect(new StdioServerTransport()); +store.warmup(); diff --git a/src/store.js b/src/store.js deleted file mode 100644 index fdbe2cc..0000000 --- a/src/store.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * context-store: SQLite-backed persistent memory for multi-agent systems. - * - * Storage: single SQLite database at /store.db - * Search: hybrid (BM25 via FTS5 + vector cosine similarity + RRF) - * Embeddings: local via @huggingface/transformers (graceful fallback to BM25-only) - */ - -import { createHash } from "crypto"; -import { - getDb, - insertChunk, - getChunk, - deleteChunkById, - listChunksDb, - getStateDb, - setStateDb, - updateEmbedding, - getChunksWithoutEmbedding, -} from "./db.js"; -import { hybridSearch } from "./search.js"; -import { embed, prepareText, warmup } from "./embeddings.js"; -import { migrateIfNeeded } from "./migrate.js"; - -/** - * Initializes the store: runs migration if needed, warms up DB and embeddings. - * Called once at startup. - */ -export async function initStore() { - // Ensure DB is ready (also runs schema + expiry purge) - getDb(); - - // Migrate from filesystem if needed - await migrateIfNeeded(); - - // Warm up embedding model in background (non-blocking) - warmup().then(() => backfillEmbeddings()); -} - -/** - * Background task: computes embeddings for chunks that don't have one yet. - */ -async function backfillEmbeddings() { - const chunks = getChunksWithoutEmbedding(); - if (!chunks.length) return; - - process.stderr.write( - `[agent-memory-store] Backfilling embeddings for ${chunks.length} chunks...\n`, - ); - - for (const chunk of chunks) { - const text = prepareText({ - topic: chunk.topic, - tags: chunk.tags, - content: chunk.content, - }); - const embedding = await embed(text); - if (embedding) { - updateEmbedding(chunk.id, embedding); - } - } - - process.stderr.write( - `[agent-memory-store] Embedding backfill complete.\n`, - ); -} - -/** - * Generates a stable short ID from agent + topic + current timestamp. - * @param {string} agentId - * @param {string} topic - * @returns {string} 10-char hex string - */ -function generateId(agentId, topic) { - const seed = `${agentId}:${topic}:${Date.now()}:${Math.random()}`; - return createHash("sha1").update(seed).digest("hex").slice(0, 10); -} - -// ─── Public API ─────────────────────────────────────────────────────────────── - -/** - * Searches chunks using hybrid search (BM25 + vector + RRF). - * - * @param {object} opts - * @param {string} opts.query - * @param {string[]} [opts.tags] - * @param {string} [opts.agent] - * @param {number} [opts.topK] - * @param {number} [opts.minScore] - * @param {string} [opts.mode] - "hybrid" | "bm25" | "semantic" - * @returns {Promise} - */ -export async function searchChunks({ - query, - tags = [], - agent, - topK = 6, - minScore = 0.1, - mode = "hybrid", -}) { - return hybridSearch({ query, tags, agent, topK, minScore, mode }); -} - -/** - * Writes a new chunk to the database. - * Embedding is computed asynchronously in the background. - * - * @param {object} opts - * @param {string} opts.topic - * @param {string} opts.content - * @param {string} [opts.agent] - * @param {string[]} [opts.tags] - * @param {string} [opts.importance] - * @param {number} [opts.ttlDays] - * @returns {Promise<{ id, topic, tags, importance }>} - */ -export async function writeChunk({ - topic, - content, - agent = "global", - tags = [], - importance = "medium", - ttlDays = null, -}) { - const id = generateId(agent, topic); - const now = new Date().toISOString(); - const expiresAt = ttlDays - ? new Date(Date.now() + ttlDays * 86_400_000).toISOString() - : null; - - insertChunk({ - id, - topic, - agent, - tags, - importance, - content, - embedding: null, // Computed in background - createdAt: now, - updatedAt: now, - expiresAt, - }); - - // Compute embedding in background (non-blocking) - const text = prepareText({ topic, tags, content }); - embed(text).then((embedding) => { - if (embedding) updateEmbedding(id, embedding); - }); - - return { id, topic, tags, importance }; -} - -/** - * Reads a single chunk by its ID. - * - * @param {string} id - * @returns {Promise<{ meta: object, content: string } | null>} - */ -export async function readChunk(id) { - const chunk = getChunk(id); - if (!chunk) return null; - - return { - meta: { - id: chunk.id, - topic: chunk.topic, - agent: chunk.agent, - tags: chunk.tags, - importance: chunk.importance, - updated: chunk.updatedAt, - ...(chunk.expiresAt ? { expires: chunk.expiresAt } : {}), - }, - content: chunk.content, - }; -} - -/** - * Deletes a chunk by ID. - * - * @param {string} id - * @returns {Promise} - */ -export async function deleteChunk(id) { - return deleteChunkById(id); -} - -/** - * Lists chunk metadata without loading full content. - * Sorted by most recently updated. - * - * @param {object} opts - * @param {string} [opts.agent] - * @param {string[]} [opts.tags] - * @returns {Promise} - */ -export async function listChunks({ agent, tags = [], limit = 100, offset = 0 } = {}) { - return listChunksDb({ agent, tags, limit, offset }); -} - -/** - * Reads a session state variable. - * - * @param {string} key - * @returns {Promise} - */ -export async function getState(key) { - return getStateDb(key); -} - -/** - * Writes a session state variable. - * - * @param {string} key - * @param {any} value - * @returns {Promise<{ key: string, updated: string }>} - */ -export async function setState(key, value) { - return setStateDb(key, value); -} diff --git a/src/store/fts-query.js b/src/store/fts-query.js new file mode 100644 index 0000000..2d26baf --- /dev/null +++ b/src/store/fts-query.js @@ -0,0 +1,78 @@ +/** + * Safe FTS5 query builder. + * + * Agents send natural-language queries ("What did we decide about auth?", + * "staging-deploy config", "decisão de autenticação"). Passing those to + * FTS5 MATCH verbatim throws syntax errors on punctuation and treats + * AND/OR/NOT/NEAR and "col:" as operators. Here every term is extracted + * with a Unicode-aware splitter and emitted as a quoted string, so the + * resulting expression can never be a syntax error. + */ + +const MAX_TERMS = 32; + +// Short, high-frequency function words in English and Portuguese. Kept small +// on purpose: BM25's IDF already discounts common words, this only removes +// the ones that add noise to OR queries. +const STOPWORDS = new Set( + `a an and are as at be but by do does did for from had has have how i if in + into is it its me my of on or our so than that the their them then there + these they this to was we were what when where which who why will with + you your about can could should would just also not no yes + o os as um uma uns umas de do da dos das em no na nos nas por pelo pela + pelos pelas para pra com sem sob sobre e ou mas que se ao aos qual quais + quem como onde quando porque por que eu tu ele ela nos vos eles elas meu + minha seu sua nosso nossa isso isto esse essa este esta aquele aquela foi + ser sao era sera tem ter ha nao sim mais menos muito ja ainda` + .split(/\s+/) + .filter(Boolean), +); + +/** + * Strips diacritics for stopword comparison only (FTS5's tokenizer does its + * own folding with remove_diacritics=2). + */ +function fold(term) { + return term.normalize("NFD").replace(/\p{M}+/gu, ""); +} + +/** + * Extracts search terms from free text. + * + * @param {string} text + * @returns {string[]} lowercase terms, stopwords removed (unless that would + * leave nothing), deduplicated, capped at MAX_TERMS + */ +export function extractTerms(text) { + if (typeof text !== "string") return []; + const raw = text + .toLowerCase() + .split(/[^\p{L}\p{N}\p{M}]+/u) + .filter((t) => t.length > 0); + + const seen = new Set(); + const all = []; + for (const t of raw) { + if (seen.has(t)) continue; + seen.add(t); + all.push(t); + } + + // Single letters are noise, but single digits ("phase 3", "run 7") are not. + const content = all.filter((t) => (t.length > 1 || /\p{N}/u.test(t)) && !STOPWORDS.has(fold(t))); + const terms = content.length > 0 ? content : all; + return terms.slice(0, MAX_TERMS); +} + +/** + * Builds an FTS5 MATCH expression that ORs every term as a quoted string. + * + * @param {string} text + * @returns {string|null} MATCH expression, or null when the query has no + * searchable terms (callers should then skip FTS entirely) + */ +export function buildFtsQuery(text) { + const terms = extractTerms(text); + if (terms.length === 0) return null; + return terms.map((t) => `"${t.replace(/"/g, '""')}"`).join(" OR "); +} diff --git a/src/store/memory-store.js b/src/store/memory-store.js new file mode 100644 index 0000000..1feb96b --- /dev/null +++ b/src/store/memory-store.js @@ -0,0 +1,917 @@ +/** + * MemoryStore — the single implementation used by the MCP server, the tests + * and the benchmarks. + * + * Storage: one SQLite file (node:sqlite), WAL mode, safe for several agent + * processes sharing it. Search: FTS5 BM25 + exact vector similarity fused + * with Reciprocal Rank Fusion. + */ + +import { DatabaseSync } from "node:sqlite"; +import { createHash, randomBytes } from "crypto"; +import { mkdirSync } from "fs"; +import path from "path"; +import { buildFtsQuery } from "./fts-query.js"; +import { VectorIndex } from "./vector-index.js"; +import { findSecret } from "./secrets.js"; +import { documentText } from "../embeddings.js"; + +export const SCHEMA_VERSION = 2; +export const IMPORTANCE = ["low", "medium", "high", "critical"]; + +const RRF_K = 60; +const PURGE_INTERVAL_MS = 60_000; +const BACKFILL_BATCH = 32; +const LEASE_MS = 120_000; +const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; + +/** + * How keyword and semantic rankings are combined. + * rrf: weighted Reciprocal Rank Fusion, w / (60 + rank) + * convex: weighted sum of per-query min-max normalized scores + * semanticWeight is the semantic share (keyword gets 1 - semanticWeight). + */ +export const DEFAULT_FUSION = { method: "convex", semanticWeight: 0.7 }; + +// Tie-breakers, in units of the normalized 0–1 score. They are smaller than +// the gap between neighbouring results in almost every query, so they only +// reorder results whose relevance is already nearly equal. +const IMPORTANCE_BONUS = { low: 0, medium: 0.001, high: 0.002, critical: 0.003 }; +const RECENCY_BONUS = 0.002; +const RECENCY_HALF_LIFE_DAYS = 30; + +export class MemoryError extends Error { + /** + * @param {"INVALID"|"NOT_FOUND"|"CONFLICT"|"SECRET"} code + * @param {string} message + */ + constructor(code, message) { + super(message); + this.code = code; + } +} + +// ─── Schema ───────────────────────────────────────────────────────────────── + +const SCHEMA_V2 = ` +CREATE TABLE chunks ( + seq INTEGER PRIMARY KEY, + id TEXT NOT NULL UNIQUE, + topic TEXT NOT NULL, + content TEXT NOT NULL, + tags TEXT NOT NULL DEFAULT '[]', + agent TEXT NOT NULL DEFAULT 'global', + updated_by TEXT, + importance TEXT NOT NULL DEFAULT 'medium', + content_hash TEXT NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + expires_at TEXT +); +CREATE INDEX idx_chunks_agent ON chunks(agent); +CREATE INDEX idx_chunks_updated ON chunks(updated_at); +CREATE INDEX idx_chunks_expires ON chunks(expires_at) WHERE expires_at IS NOT NULL; +CREATE INDEX idx_chunks_topic ON chunks(lower(topic)); + +CREATE VIRTUAL TABLE chunks_fts USING fts5( + topic, tags, content, + content='chunks', content_rowid='seq', + tokenize='unicode61 remove_diacritics 2' +); + +CREATE TRIGGER chunks_ai AFTER INSERT ON chunks BEGIN + INSERT INTO chunks_fts(rowid, topic, tags, content) + VALUES (new.seq, new.topic, new.tags, new.content); +END; +CREATE TRIGGER chunks_ad AFTER DELETE ON chunks BEGIN + INSERT INTO chunks_fts(chunks_fts, rowid, topic, tags, content) + VALUES ('delete', old.seq, old.topic, old.tags, old.content); +END; +CREATE TRIGGER chunks_au AFTER UPDATE OF topic, tags, content ON chunks BEGIN + INSERT INTO chunks_fts(chunks_fts, rowid, topic, tags, content) + VALUES ('delete', old.seq, old.topic, old.tags, old.content); + INSERT INTO chunks_fts(rowid, topic, tags, content) + VALUES (new.seq, new.topic, new.tags, new.content); +END; + +CREATE TABLE vectors ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + chunk_id TEXT NOT NULL UNIQUE REFERENCES chunks(id) ON DELETE CASCADE ON UPDATE CASCADE, + model TEXT NOT NULL, + content_hash TEXT NOT NULL, + vec BLOB NOT NULL +); +CREATE INDEX idx_vectors_model ON vectors(model, seq); + +CREATE TABLE IF NOT EXISTS state ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + updated_at TEXT NOT NULL, + updated_by TEXT +); + +CREATE TABLE leases ( + name TEXT PRIMARY KEY, + owner TEXT NOT NULL, + expires_at INTEGER NOT NULL +); +`; + +// ─── Helpers ──────────────────────────────────────────────────────────────── + +function hashText(text) { + return createHash("sha256").update(text).digest("hex").slice(0, 32); +} + +function toBlob(vec) { + return new Uint8Array(vec.buffer, vec.byteOffset, vec.byteLength); +} + +function fromBlob(blob) { + // Copy: the blob's buffer may be reused by SQLite bindings. + return new Float32Array(blob.buffer.slice(blob.byteOffset, blob.byteOffset + blob.byteLength)); +} + +function normalizeTags(tags) { + if (tags == null) return []; + if (!Array.isArray(tags)) throw new MemoryError("INVALID", "tags must be an array of strings"); + const out = []; + for (const t of tags) { + if (typeof t !== "string") throw new MemoryError("INVALID", "tags must be an array of strings"); + const n = t.trim().toLowerCase(); + if (n && !out.includes(n)) out.push(n); + } + return out; +} + +function normalizeDate(value, name) { + if (value == null || value === "") return null; + const d = new Date(value); + if (Number.isNaN(d.getTime())) { + throw new MemoryError("INVALID", `${name} must be an ISO 8601 date, got "${value}"`); + } + return d.toISOString(); +} + +function rowToMemory(r) { + return { + id: r.id, + topic: r.topic, + content: r.content, + tags: JSON.parse(r.tags), + agent: r.agent, + updatedBy: r.updated_by ?? r.agent, + importance: r.importance, + version: r.version, + createdAt: r.created_at, + updatedAt: r.updated_at, + expiresAt: r.expires_at ?? null, + }; +} + +// ─── MemoryStore ──────────────────────────────────────────────────────────── + +export class MemoryStore { + /** + * Opens (and creates or migrates) a store. + * + * @param {string} dbPath - path to the SQLite file, or ":memory:" + * @param {object} [opts] + * @param {object|null} [opts.embedder] - see src/embeddings.js; null = keyword only + * @param {() => number} [opts.clock] - ms timestamp source (tests) + * @param {{ method: "rrf"|"convex", semanticWeight: number }} [opts.fusion] + * @returns {MemoryStore} + */ + static open(dbPath, opts = {}) { + if (dbPath !== ":memory:") mkdirSync(path.dirname(path.resolve(dbPath)), { recursive: true }); + return new MemoryStore(new DatabaseSync(dbPath), opts); + } + + constructor(db, { embedder = null, clock = Date.now, fusion = DEFAULT_FUSION } = {}) { + this.db = db; + this.embedder = embedder; + this.fusion = fusion; + this.clock = clock; + this.owner = `${process.pid}:${randomBytes(4).toString("hex")}`; + this._stmts = new Map(); + this._index = new VectorIndex(); + this._indexModel = null; + this._indexSeq = 0; + this._dataVersion = -1; + this._indexDirty = true; + this._lastPurge = 0; + this._drainPromise = null; + this._closed = false; + + db.exec("PRAGMA busy_timeout = 5000"); + db.exec("PRAGMA journal_mode = WAL"); + db.exec("PRAGMA synchronous = NORMAL"); + db.exec("PRAGMA foreign_keys = ON"); + try { + db.exec("CREATE VIRTUAL TABLE temp.fts5_probe USING fts5(x); DROP TABLE temp.fts5_probe;"); + } catch { + throw new Error( + `The SQLite bundled with Node.js ${process.version} has no FTS5 full-text search. agent-memory-store needs Node.js >= 22.16.`, + ); + } + this._migrate(); + } + + close() { + if (this._closed) return; + this._closed = true; + this._stmts.clear(); + this.db.close(); + } + + _stmt(sql) { + let s = this._stmts.get(sql); + if (!s) { + s = this.db.prepare(sql); + this._stmts.set(sql, s); + } + return s; + } + + _now() { + return new Date(this.clock()).toISOString(); + } + + /** Runs fn inside BEGIN IMMEDIATE (takes the write lock up front, so the busy timeout applies). */ + _tx(fn) { + this.db.exec("BEGIN IMMEDIATE"); + try { + const result = fn(); + this.db.exec("COMMIT"); + return result; + } catch (err) { + this.db.exec("ROLLBACK"); + throw err; + } + } + + // ─── Schema migrations ────────────────────────────────────────────────── + + _migrate() { + const version = () => this.db.prepare("PRAGMA user_version").get().user_version; + if (version() >= SCHEMA_VERSION) return; + + this._tx(() => { + // Re-check under the write lock: another process may have migrated. + const v = version(); + if (v >= SCHEMA_VERSION) return; + const hasLegacy = this.db + .prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='chunks'") + .get(); + + if (v === 0 && hasLegacy) this._migrateV1toV2(); + else this.db.exec(SCHEMA_V2); + this.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`); + }); + } + + /** + * v1 (<= 0.0.9): chunks with inline embedding, FTS without diacritic + * folding, state without version. Content is preserved; embeddings are + * dropped and recomputed by the backfill with the current model. + */ + _migrateV1toV2() { + const d = this.db; + d.exec(` + DROP TRIGGER IF EXISTS chunks_ai; + DROP TRIGGER IF EXISTS chunks_ad; + DROP TRIGGER IF EXISTS chunks_au; + DROP TABLE IF EXISTS chunks_fts; + ALTER TABLE chunks RENAME TO chunks_v1; + `); + const hasState = d.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='state'").get(); + if (hasState) d.exec("ALTER TABLE state RENAME TO state_v1"); + d.exec("DROP INDEX IF EXISTS idx_chunks_agent; DROP INDEX IF EXISTS idx_chunks_updated; DROP INDEX IF EXISTS idx_chunks_expires;"); + d.exec(SCHEMA_V2); + + const insert = d.prepare(` + INSERT INTO chunks (id, topic, content, tags, agent, importance, content_hash, created_at, updated_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`); + for (const r of d.prepare("SELECT * FROM chunks_v1").iterate()) { + let tags; + try { + tags = normalizeTags(JSON.parse(r.tags)); + } catch { + tags = []; + } + const importance = IMPORTANCE.includes(r.importance) ? r.importance : "medium"; + const expires = r.expires_at ? normalizeDate(r.expires_at, "expires_at") : null; + insert.run( + r.id, + r.topic, + r.content, + JSON.stringify(tags), + r.agent || "global", + importance, + hashText(documentText({ topic: r.topic, tags, content: r.content })), + r.created_at, + r.updated_at, + expires, + ); + } + d.exec("DROP TABLE chunks_v1"); + + if (hasState) { + d.exec(`INSERT INTO state (key, value, version, updated_at) + SELECT key, value, 1, updated_at FROM state_v1`); + d.exec("DROP TABLE state_v1"); + } + } + + // ─── Filters ──────────────────────────────────────────────────────────── + + /** + * Builds the WHERE clause shared by search, list and the vector allow-list. + * Expired chunks are always excluded. + */ + _filters({ agent, tags, since, until } = {}) { + const clauses = ["(c.expires_at IS NULL OR c.expires_at > ?)"]; + const params = [this._now()]; + let narrowed = false; + if (agent) { + clauses.push("c.agent = ?"); + params.push(agent); + narrowed = true; + } + const t = normalizeTags(tags); + if (t.length) { + clauses.push(`EXISTS (SELECT 1 FROM json_each(c.tags) j WHERE j.value IN (${t.map(() => "?").join(",")}))`); + params.push(...t); + narrowed = true; + } + const s = normalizeDate(since, "since"); + if (s) { + clauses.push("c.updated_at >= ?"); + params.push(s); + narrowed = true; + } + const u = normalizeDate(until, "until"); + if (u) { + clauses.push("c.updated_at <= ?"); + params.push(u); + narrowed = true; + } + return { where: clauses.join(" AND "), params, narrowed }; + } + + _maybePurge() { + const nowMs = this.clock(); + if (nowMs - this._lastPurge < PURGE_INTERVAL_MS) return; + this._lastPurge = nowMs; + const res = this._stmt( + "DELETE FROM chunks WHERE expires_at IS NOT NULL AND expires_at <= ?", + ).run(this._now()); + if (res.changes > 0) this._indexDirty = true; + } + + // ─── Write ────────────────────────────────────────────────────────────── + + /** + * Creates or updates a memory. + * + * Without `id` a new memory is created. With `id`, the memory is updated in + * place (or created with that id if it does not exist). Omitted optional + * fields keep their current values on update. + * + * @param {object} input + * @param {string} input.topic + * @param {string} input.content + * @param {string} [input.id] + * @param {string} [input.agent] + * @param {string[]} [input.tags] + * @param {string} [input.importance] + * @param {number|null} [input.ttlDays] - null removes an existing expiry + * @param {number} [input.expectedVersion] - compare-and-set; 0 = must not exist + * @returns {Promise} + */ + async write(input) { + const { id: givenId, topic, content, agent, importance, ttlDays, expectedVersion } = input; + if (typeof topic !== "string" || !topic.trim()) throw new MemoryError("INVALID", "topic is required"); + if (typeof content !== "string" || !content.trim()) throw new MemoryError("INVALID", "content is required"); + if (givenId != null && !ID_RE.test(givenId)) { + throw new MemoryError("INVALID", "id must be 1-128 chars of letters, digits, '.', '_', ':' or '-'"); + } + if (importance != null && !IMPORTANCE.includes(importance)) { + throw new MemoryError("INVALID", `importance must be one of ${IMPORTANCE.join(", ")}`); + } + if (ttlDays != null && !(ttlDays > 0)) throw new MemoryError("INVALID", "ttl_days must be positive"); + const secret = findSecret(`${topic}\n${content}`); + if (secret) { + throw new MemoryError( + "SECRET", + `Refused: content looks like it contains a ${secret}. Store where the secret lives (e.g. "in 1Password: Prod/DB" or "env var DATABASE_URL"), never the value.`, + ); + } + + const tagsInput = input.tags == null ? null : normalizeTags(input.tags); + const existing = givenId ? this._getRow(givenId) : null; + const tags = tagsInput ?? (existing ? JSON.parse(existing.tags) : []); + const text = documentText({ topic: topic.trim(), tags, content }); + const contentHash = hashText(text); + + // Embed outside the transaction (it is the slow part) when the model is ready. + let vec = null; + const contentChanged = !existing || existing.content_hash !== contentHash; + if (this.embedder?.isReady() && contentChanged) { + try { + [vec] = await this.embedder.embedDocuments([text]); + } catch { + vec = null; // backfill will retry + } + } + + const result = this._tx(() => { + const now = this._now(); + let current = givenId ? this._getRow(givenId) : null; + if (current?.expires_at && current.expires_at <= now) { + // An expired memory no longer exists for readers; reuse of its id is a create. + this._stmt("DELETE FROM chunks WHERE id = ?").run(givenId); + current = null; + } + if (expectedVersion != null) { + const currentVersion = current ? current.version : 0; + if (currentVersion !== expectedVersion) { + throw new MemoryError( + "CONFLICT", + `Version conflict on "${givenId}": expected ${expectedVersion}, current is ${currentVersion}. Re-read and retry.`, + ); + } + } + + const expiresAt = + ttlDays === undefined + ? current?.expires_at ?? null + : ttlDays === null + ? null + : new Date(this.clock() + ttlDays * 86_400_000).toISOString(); + + let id = givenId; + if (current) { + this._stmt(` + UPDATE chunks SET topic = ?, content = ?, tags = ?, updated_by = ?, importance = ?, + content_hash = ?, version = version + 1, updated_at = ?, expires_at = ? + WHERE id = ?`).run( + topic.trim(), + content, + JSON.stringify(tags), + agent ?? current.updated_by ?? current.agent, + importance ?? current.importance, + contentHash, + now, + expiresAt, + id, + ); + } else { + if (!id) { + do id = randomBytes(6).toString("hex"); + while (this._getRow(id)); + } + this._stmt(` + INSERT INTO chunks (id, topic, content, tags, agent, updated_by, importance, content_hash, created_at, updated_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run( + id, + topic.trim(), + content, + JSON.stringify(tags), + agent ?? "global", + agent ?? "global", + importance ?? "medium", + contentHash, + now, + now, + expiresAt, + ); + } + if (vec) this._putVector(id, contentHash, vec); + // No vector for the new content yet: drop the old one rather than search with stale meaning. + else if (contentChanged) this._stmt("DELETE FROM vectors WHERE chunk_id = ?").run(id); + return { id, created: !current }; + }); + + if (vec || contentChanged) this._indexDirty = true; + if (!vec && contentChanged && this.embedder) this._scheduleDrain(); + + const memory = rowToMemory(this._getRow(result.id)); + return { + ...memory, + created: result.created, + duplicates: await this._findDuplicates(memory, vec), + }; + } + + /** + * Imports a memory verbatim (used by the legacy filesystem migration). + */ + importMemory({ id, topic, content, agent = "global", tags = [], importance = "medium", createdAt, updatedAt, expiresAt = null }) { + const t = normalizeTags(tags); + const now = this._now(); + this._stmt(` + INSERT INTO chunks (id, topic, content, tags, agent, updated_by, importance, content_hash, created_at, updated_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO NOTHING`).run( + id, + topic, + content, + JSON.stringify(t), + agent, + agent, + IMPORTANCE.includes(importance) ? importance : "medium", + hashText(documentText({ topic, tags: t, content })), + createdAt || now, + updatedAt || createdAt || now, + expiresAt ? normalizeDate(expiresAt, "expires") : null, + ); + this._indexDirty = true; + } + + _putVector(id, contentHash, vec) { + this._stmt("DELETE FROM vectors WHERE chunk_id = ?").run(id); + this._stmt( + "INSERT INTO vectors (chunk_id, model, content_hash, vec) VALUES (?, ?, ?, ?)", + ).run(id, this.embedder.id, contentHash, toBlob(vec)); + } + + async _findDuplicates(memory, vec) { + const found = new Map(); + const sameTopic = this._stmt(` + SELECT id, topic FROM chunks c + WHERE lower(c.topic) = lower(?) AND c.id != ? AND (c.expires_at IS NULL OR c.expires_at > ?) + LIMIT 3`).all(memory.topic, memory.id, this._now()); + for (const r of sameTopic) found.set(r.id, { id: r.id, topic: r.topic, reason: "same topic" }); + + if (vec && this._refreshIndex()) { + const threshold = this.embedder.duplicateThreshold ?? 0.9; + for (const hit of this._index.search(vec, 4)) { + if (hit.id === memory.id || found.has(hit.id) || hit.score < threshold) continue; + const r = this._getRow(hit.id); + if (!r || (r.expires_at && r.expires_at <= this._now())) continue; + found.set(hit.id, { id: hit.id, topic: r.topic, reason: `similar content (${hit.score.toFixed(2)})` }); + } + } + return [...found.values()].slice(0, 3); + } + + // ─── Embedding backfill ───────────────────────────────────────────────── + + _scheduleDrain() { + if (this._drainPromise || !this.embedder || this._closed) return this._drainPromise; + this._drainPromise = this._drain() + .catch((err) => process.stderr.write(`[agent-memory-store] Embedding backfill error: ${err.message}\n`)) + .finally(() => { + this._drainPromise = null; + }); + return this._drainPromise; + } + + _acquireLease(name) { + const nowMs = this.clock(); + const res = this._stmt(` + INSERT INTO leases (name, owner, expires_at) VALUES (?, ?, ?) + ON CONFLICT(name) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at + WHERE leases.expires_at < ? OR leases.owner = excluded.owner`).run(name, this.owner, nowMs + LEASE_MS, nowMs); + return res.changes > 0; + } + + _releaseLease(name) { + this._stmt("DELETE FROM leases WHERE name = ? AND owner = ?").run(name, this.owner); + } + + /** Embeds every chunk whose vector is missing, stale, or from another model. */ + async _drain() { + if (!(await this.embedder.load())) return; + if (this._closed || !this._acquireLease("embed")) return; + try { + for (;;) { + if (this._closed) return; + const rows = this._stmt(` + SELECT c.id, c.topic, c.tags, c.content, c.content_hash + FROM chunks c + LEFT JOIN vectors v ON v.chunk_id = c.id AND v.model = ? AND v.content_hash = c.content_hash + WHERE v.chunk_id IS NULL + LIMIT ${BACKFILL_BATCH}`).all(this.embedder.id); + if (rows.length === 0) return; + const texts = rows.map((r) => documentText({ topic: r.topic, tags: JSON.parse(r.tags), content: r.content })); + const vecs = await this.embedder.embedDocuments(texts); + if (this._closed) return; + this._tx(() => { + for (let i = 0; i < rows.length; i++) { + // Guard: skip if the chunk changed or vanished while we were embedding. + const cur = this._stmt("SELECT content_hash FROM chunks WHERE id = ?").get(rows[i].id); + if (cur && cur.content_hash === rows[i].content_hash) { + this._putVector(rows[i].id, rows[i].content_hash, vecs[i]); + } + } + }); + this._indexDirty = true; + this._acquireLease("embed"); // renew + } + } finally { + if (!this._closed) this._releaseLease("embed"); + } + } + + /** + * Starts loading the embedding model and backfilling missing vectors in + * the background. Safe to call repeatedly. + */ + warmup() { + if (!this.embedder) return Promise.resolve(); + return this._scheduleDrain() ?? Promise.resolve(); + } + + /** Waits until every chunk has a vector for the current model (tests, benchmarks). */ + async flushEmbeddings() { + if (!this.embedder) return; + for (;;) { + await this._scheduleDrain(); + const pending = this._stmt(` + SELECT count(*) AS n FROM chunks c + LEFT JOIN vectors v ON v.chunk_id = c.id AND v.model = ? AND v.content_hash = c.content_hash + WHERE v.chunk_id IS NULL`).get(this.embedder.id).n; + if (pending === 0 || !this.embedder.isReady()) return; + // Another process holds the lease; give it a moment. + await new Promise((r) => setTimeout(r, 50)); + } + } + + // ─── Vector index sync ────────────────────────────────────────────────── + + /** + * Brings the in-memory index up to date with the vectors table. Cheap when + * nothing changed: PRAGMA data_version only moves on other connections' + * commits, and our own writes set _indexDirty. + * + * @returns {boolean} true if the index is usable + */ + _refreshIndex() { + if (!this.embedder?.isReady()) return false; + const model = this.embedder.id; + const dv = this._stmt("PRAGMA data_version").get().data_version; + if (this._indexModel === model && !this._indexDirty && dv === this._dataVersion) return true; + + if (this._indexModel !== model) { + this._index = new VectorIndex(); + this._indexModel = model; + this._indexSeq = 0; + } + for (const r of this._stmt( + "SELECT seq, chunk_id, vec FROM vectors WHERE model = ? AND seq > ? ORDER BY seq", + ).iterate(model, this._indexSeq)) { + this._index.upsert(r.chunk_id, fromBlob(r.vec)); + this._indexSeq = r.seq; + } + const count = this._stmt("SELECT count(*) AS n FROM vectors WHERE model = ?").get(model).n; + if (count !== this._index.size) { + const live = new Set( + this._stmt("SELECT chunk_id FROM vectors WHERE model = ?").all(model).map((r) => r.chunk_id), + ); + for (const id of [...this._index.ids]) if (!live.has(id)) this._index.remove(id); + } + this._dataVersion = dv; + this._indexDirty = false; + return true; + } + + // ─── Read / delete / list ─────────────────────────────────────────────── + + _getRow(id) { + return this._stmt("SELECT * FROM chunks WHERE id = ?").get(id); + } + + /** + * @param {string} id + * @returns {object|null} the memory, or null if missing or expired + */ + get(id) { + const r = this._getRow(id); + if (!r || (r.expires_at && r.expires_at <= this._now())) return null; + return rowToMemory(r); + } + + /** + * @param {string} id + * @returns {boolean} true if a memory was deleted + */ + delete(id) { + const res = this._stmt("DELETE FROM chunks WHERE id = ?").run(id); + if (res.changes > 0) { + this._index.remove(id); + this._indexDirty = true; + } + return res.changes > 0; + } + + /** + * Lists memories (newest first) without their content. + * @returns {{ total: number, items: object[] }} + */ + list({ agent, tags, since, until, limit = 50, offset = 0 } = {}) { + this._maybePurge(); + const f = this._filters({ agent, tags, since, until }); + const total = this.db.prepare(`SELECT count(*) AS n FROM chunks c WHERE ${f.where}`).get(...f.params).n; + const rows = this.db + .prepare(`SELECT * FROM chunks c WHERE ${f.where} ORDER BY c.updated_at DESC, c.seq DESC LIMIT ? OFFSET ?`) + .all(...f.params, limit, offset); + return { + total, + items: rows.map((r) => { + const { content, ...meta } = rowToMemory(r); + return { ...meta, chars: content.length }; + }), + }; + } + + // ─── Search ───────────────────────────────────────────────────────────── + + /** + * Hybrid search. + * + * score: fused relevance in [0, 1] (see DEFAULT_FUSION), normalized so + * 1.0 means "top result of every retriever used". It is relative to the + * other results of the same query, not an absolute probability. + * similarity: cosine similarity to the query (absolute, model-specific), + * present when the memory was found by semantic search. + * + * @returns {Promise<{ mode: string, results: object[] }>} + */ + async search({ query, tags, agent, since, until, limit = 6, minScore = 0, mode = "hybrid", fusion = this.fusion }) { + if (typeof query !== "string" || !query.trim()) throw new MemoryError("INVALID", "query is required"); + if (!["hybrid", "bm25", "semantic"].includes(mode)) { + throw new MemoryError("INVALID", 'mode must be "hybrid", "bm25" or "semantic"'); + } + this._maybePurge(); + const f = this._filters({ agent, tags, since, until }); + const candidates = Math.max(50, limit * 5); + const lists = []; + + // Semantic first (async) so we know whether the keyword list stands alone. + let semantic = null; + if (mode !== "bm25" && this.embedder) { + if (this.embedder.isReady()) { + let qv = null; + try { + qv = await this.embedder.embedQuery(query); + } catch { + qv = null; // fall back to keyword search + } + if (qv && this._refreshIndex()) { + const allowed = f.narrowed + ? new Set(this.db.prepare(`SELECT c.id FROM chunks c WHERE ${f.where}`).all(...f.params).map((r) => r.id)) + : null; + semantic = this._index.search(qv, candidates, allowed).filter((h) => h.score > 0); + } + } else { + this.warmup(); + } + } + if (semantic) lists.push({ name: "semantic", hits: semantic }); + + if (mode !== "semantic" || !semantic) { + const match = buildFtsQuery(query); + if (match) { + const hits = this.db + .prepare(` + SELECT c.id, bm25(chunks_fts, 3.0, 2.0, 1.0) AS rank FROM chunks_fts + JOIN chunks c ON c.seq = chunks_fts.rowid + WHERE chunks_fts MATCH ? AND ${f.where} + ORDER BY rank + LIMIT ?`) + .all(match, ...f.params, candidates) + .map((r) => ({ id: r.id, score: -r.rank })); + lists.push({ name: "keyword", hits }); + } + } + + const effectiveMode = + lists.length === 2 ? "hybrid" : lists[0]?.name === "semantic" ? "semantic" : "bm25"; + if (lists.length === 0) return { mode: effectiveMode, results: [] }; + + const fused = this._fuse(lists, fusion); + const ids = [...fused.keys()]; + const rows = new Map(); + for (let i = 0; i < ids.length; i += 500) { + const chunk = ids.slice(i, i + 500); + for (const r of this.db + .prepare(`SELECT * FROM chunks c WHERE c.id IN (${chunk.map(() => "?").join(",")}) AND ${f.where}`) + .all(...chunk, ...f.params)) { + rows.set(r.id, r); + } + } + + const nowMs = this.clock(); + const results = []; + for (const [id, e] of fused) { + const r = rows.get(id); + if (!r) continue; + const score = e.score; + if (score < minScore) continue; + const ageDays = Math.max(0, (nowMs - Date.parse(r.updated_at)) / 86_400_000); + const rankKey = + score + + (IMPORTANCE_BONUS[r.importance] ?? 0) + + RECENCY_BONUS * Math.pow(0.5, ageDays / RECENCY_HALF_LIFE_DAYS); + results.push({ + ...rowToMemory(r), + score: Math.round(score * 1000) / 1000, + similarity: e.similarity == null ? null : Math.round(e.similarity * 1000) / 1000, + matched: e.matched, + _rankKey: rankKey, + }); + } + results.sort((a, b) => b._rankKey - a._rankKey); + return { + mode: effectiveMode, + results: results.slice(0, limit).map(({ _rankKey, ...r }) => r), + }; + } + + /** + * Combines ranked lists into id → { score (0–1), matched, similarity }. + */ + _fuse(lists, { method, semanticWeight }) { + const weightOf = (name) => (name === "semantic" ? semanticWeight : 1 - semanticWeight); + const totalWeight = lists.reduce((s, l) => s + weightOf(l.name), 0) || 1; + const fused = new Map(); + for (const { name, hits } of lists) { + const w = weightOf(name) / totalWeight; + let lo = Infinity; + let hi = -Infinity; + for (const h of hits) { + lo = Math.min(lo, h.score); + hi = Math.max(hi, h.score); + } + hits.forEach((h, rank) => { + let e = fused.get(h.id); + if (!e) fused.set(h.id, (e = { score: 0, matched: [], similarity: null })); + const part = + method === "convex" + ? hi > lo ? (h.score - lo) / (hi - lo) : 1 + : (RRF_K + 1) / (RRF_K + rank + 1); + e.score += w * part; + e.matched.push(name); + if (name === "semantic") e.similarity = h.score; + }); + } + return fused; + } + + // ─── State ────────────────────────────────────────────────────────────── + + /** + * @param {string} key + * @returns {{ key, value, version, updatedAt, updatedBy } | null} + */ + getState(key) { + const r = this._stmt("SELECT * FROM state WHERE key = ?").get(key); + if (!r) return null; + return { key: r.key, value: JSON.parse(r.value), version: r.version, updatedAt: r.updated_at, updatedBy: r.updated_by }; + } + + /** + * Sets a state value. With expectedVersion it is a compare-and-set + * (0 = key must not exist yet), which lets agents coordinate safely. + */ + setState(key, value, { expectedVersion, agent } = {}) { + if (typeof key !== "string" || !key.trim()) throw new MemoryError("INVALID", "key is required"); + if (value === undefined) throw new MemoryError("INVALID", "value is required (use null to clear)"); + const json = JSON.stringify(value); + const secret = findSecret(json); + if (secret) throw new MemoryError("SECRET", `Refused: value looks like it contains a ${secret}.`); + return this._tx(() => { + const cur = this._stmt("SELECT version FROM state WHERE key = ?").get(key); + const currentVersion = cur ? cur.version : 0; + if (expectedVersion != null && expectedVersion !== currentVersion) { + throw new MemoryError( + "CONFLICT", + `Version conflict on state "${key}": expected ${expectedVersion}, current is ${currentVersion}. Re-read and retry.`, + ); + } + const now = this._now(); + this._stmt(` + INSERT INTO state (key, value, version, updated_at, updated_by) VALUES (?, ?, 1, ?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, version = state.version + 1, + updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(key, json, now, agent ?? null); + return { key, version: currentVersion + 1, updatedAt: now }; + }); + } + + /** Counts for diagnostics. */ + stats() { + const now = this._now(); + const chunks = this._stmt( + "SELECT count(*) AS n FROM chunks WHERE expires_at IS NULL OR expires_at > ?", + ).get(now).n; + const vectors = this.embedder + ? this._stmt(`SELECT count(*) AS n FROM vectors v JOIN chunks c ON c.id = v.chunk_id + WHERE v.model = ? AND v.content_hash = c.content_hash`).get(this.embedder.id).n + : 0; + return { memories: chunks, embedded: vectors, model: this.embedder?.id ?? null }; + } +} diff --git a/src/store/secrets.js b/src/store/secrets.js new file mode 100644 index 0000000..66f8967 --- /dev/null +++ b/src/store/secrets.js @@ -0,0 +1,31 @@ +/** + * Detects credentials that should never be written to shared memory. + * + * Memory is plain text, shared by every agent and copied into prompts, so a + * leaked key spreads quickly. Patterns are deliberately specific (known + * prefixes and formats) to avoid rejecting ordinary prose. + */ + +const PATTERNS = [ + ["private key", /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/], + ["AWS access key", /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/], + ["Anthropic/OpenAI API key", /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/], + ["GitHub token", /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})\b/], + ["Slack token", /\bxox[abprs]-[A-Za-z0-9-]{10,}/], + ["Google API key", /\bAIza[0-9A-Za-z_-]{35}\b/], + ["Stripe secret key", /\b[sr]k_live_[0-9A-Za-z]{20,}\b/], + ["JSON Web Token", /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/], + // user:password@host — placeholders like ${DB_PASS}, or *** are allowed + ["connection string with password", /\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:[^\s:@/$<{*][^\s@/]{2,}@[^\s]+/i], +]; + +/** + * @param {string} text + * @returns {string|null} name of the first credential type found, or null + */ +export function findSecret(text) { + for (const [name, re] of PATTERNS) { + if (re.test(text)) return name; + } + return null; +} diff --git a/src/store/vector-index.js b/src/store/vector-index.js new file mode 100644 index 0000000..8ed264f --- /dev/null +++ b/src/store/vector-index.js @@ -0,0 +1,130 @@ +/** + * In-memory exact vector index. + * + * Vectors live in one contiguous Float32Array so a query is a single tight + * loop of dot products (vectors are L2-normalized, so dot = cosine). Exact + * search over 100K × 384 dims takes tens of milliseconds and needs no native + * extension; agent memory stores rarely get near that size. + */ + +export class VectorIndex { + constructor() { + this.dim = 0; + this.size = 0; + this.matrix = new Float32Array(0); + /** @type {string[]} position → chunk id */ + this.ids = []; + /** @type {Map} chunk id → position */ + this.pos = new Map(); + } + + clear() { + this.size = 0; + this.ids = []; + this.pos = new Map(); + this.matrix = new Float32Array(this.dim * 64); + } + + _ensureCapacity(n) { + const needed = n * this.dim; + if (this.matrix.length >= needed) return; + let cap = Math.max(64 * this.dim, this.matrix.length); + while (cap < needed) cap *= 2; + const next = new Float32Array(cap); + next.set(this.matrix.subarray(0, this.size * this.dim)); + this.matrix = next; + } + + /** + * Inserts or replaces the vector for a chunk. + * @param {string} id + * @param {Float32Array} vec + */ + upsert(id, vec) { + if (this.dim === 0) { + this.dim = vec.length; + this.clear(); + } + if (vec.length !== this.dim) { + throw new Error(`Vector dim ${vec.length} does not match index dim ${this.dim}`); + } + let p = this.pos.get(id); + if (p === undefined) { + this._ensureCapacity(this.size + 1); + p = this.size++; + this.ids[p] = id; + this.pos.set(id, p); + } + this.matrix.set(vec, p * this.dim); + } + + /** + * Removes a chunk's vector (swap-with-last, O(dim)). + * @param {string} id + */ + remove(id) { + const p = this.pos.get(id); + if (p === undefined) return; + const last = this.size - 1; + if (p !== last) { + const lastId = this.ids[last]; + this.matrix.copyWithin(p * this.dim, last * this.dim, (last + 1) * this.dim); + this.ids[p] = lastId; + this.pos.set(lastId, p); + } + this.ids.length = last; + this.pos.delete(id); + this.size = last; + } + + has(id) { + return this.pos.has(id); + } + + /** + * Returns the k most similar chunks. + * + * @param {Float32Array} query - normalized query vector + * @param {number} k + * @param {Set|null} [allowed] - restrict to these chunk ids + * @returns {Array<{ id: string, score: number }>} sorted by score desc + */ + search(query, k, allowed = null) { + if (this.size === 0 || k <= 0) return []; + if (query.length !== this.dim) { + throw new Error(`Query dim ${query.length} does not match index dim ${this.dim}`); + } + const dim = this.dim; + const m = this.matrix; + // Top-k kept as a small array sorted ascending by score (k is ≤ ~100). + const topScores = []; + const topPos = []; + + for (let p = 0; p < this.size; p++) { + if (allowed && !allowed.has(this.ids[p])) continue; + let dot = 0; + const base = p * dim; + for (let i = 0; i < dim; i++) dot += query[i] * m[base + i]; + + if (topScores.length < k) { + let j = topScores.length; + while (j > 0 && topScores[j - 1] > dot) j--; + topScores.splice(j, 0, dot); + topPos.splice(j, 0, p); + } else if (dot > topScores[0]) { + let j = 1; + while (j < k && topScores[j] < dot) j++; + topScores.splice(j, 0, dot); + topPos.splice(j, 0, p); + topScores.shift(); + topPos.shift(); + } + } + + const out = []; + for (let j = topScores.length - 1; j >= 0; j--) { + out.push({ id: this.ids[topPos[j]], score: topScores[j] }); + } + return out; + } +} diff --git a/test/concurrency.test.js b/test/concurrency.test.js new file mode 100644 index 0000000..5734dd9 --- /dev/null +++ b/test/concurrency.test.js @@ -0,0 +1,47 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "child_process"; +import path from "path"; +import { MemoryStore } from "../src/store/memory-store.js"; +import { HashEmbedder } from "../src/embeddings.js"; +import { tempDir, ROOT } from "./helpers.js"; + +const WORKERS = 4; +const PER_WORKER = 500; + +function runWorker(file, agent) { + return new Promise((resolve, reject) => { + const child = spawn( + process.execPath, + ["--no-warnings", path.join(ROOT, "test/fixtures/concurrent-worker.js"), file, agent, String(PER_WORKER)], + { stdio: ["ignore", "pipe", "pipe"] }, + ); + let out = ""; + let err = ""; + child.stdout.on("data", (d) => (out += d)); + child.stderr.on("data", (d) => (err += d)); + child.on("exit", (code) => (code === 0 ? resolve(JSON.parse(out)) : reject(new Error(`exit ${code}: ${err}`)))); + }); +} + +test(`${WORKERS} processes writing to one store: no lost writes, no SQLITE_BUSY`, { timeout: 120_000 }, async () => { + const [dir, cleanup] = tempDir(); + try { + const file = path.join(dir, "store.db"); + MemoryStore.open(file).close(); // create schema once, like the first agent would + const results = await Promise.all(Array.from({ length: WORKERS }, (_, i) => runWorker(file, `agent-${i}`))); + + for (const r of results) assert.equal(r.errors, 0, `${r.agent} had errors`); + assert.ok(results.some((r) => r.seenOthers > 0), "agents see each other's writes"); + + const s = MemoryStore.open(file, { embedder: new HashEmbedder() }); + assert.equal(s.list().total, WORKERS * PER_WORKER); + for (let i = 0; i < WORKERS; i++) assert.equal(s.list({ agent: `agent-${i}` }).total, PER_WORKER); + assert.equal(s.getState("counter").value, WORKERS * (PER_WORKER / 10), "CAS counter lost no increments"); + assert.doesNotThrow(() => s.db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('integrity-check')")); + assert.equal(s.db.prepare("PRAGMA integrity_check").get().integrity_check, "ok"); + s.close(); + } finally { + cleanup(); + } +}); diff --git a/test/e2e-model.test.js b/test/e2e-model.test.js new file mode 100644 index 0000000..d58000a --- /dev/null +++ b/test/e2e-model.test.js @@ -0,0 +1,58 @@ +// End-to-end with the real embedding model (downloads it on first run). +// Opt-in: AMS_MODEL_TESTS=1 npm test (runs in CI's retrieval-quality job) +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import path from "path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { tempDir, ROOT } from "./helpers.js"; + +const enabled = process.env.AMS_MODEL_TESTS === "1"; +let client; +let cleanup; + +before(async () => { + if (!enabled) return; + let dir; + [dir, cleanup] = tempDir(); + // No AGENT_MEMORY_MODEL: exercises the default model, as users get it. + const env = { ...process.env, AGENT_STORE_PATH: dir }; + delete env.AGENT_MEMORY_MODEL; + client = new Client({ name: "e2e-model", version: "1.0.0" }); + await client.connect(new StdioClientTransport({ command: process.execPath, args: [path.join(ROOT, "src/index.js")], env, stderr: "ignore" })); +}); + +after(async () => { + await client?.close(); + cleanup?.(); +}); + +async function call(name, args) { + const res = await client.callTool({ name, arguments: args }); + return res.content[0].text; +} + +test("cross-lingual hybrid search through the MCP server with the default model", { skip: !enabled, timeout: 600_000 }, async () => { + await call("write_context", { + topic: "Pagamentos — timeout do webhook de devolução PIX", + content: "Aumentamos o timeout do webhook de devolução PIX de 10s para 20s porque o p99 do banco no sandbox é 14s.", + tags: ["pix", "decision"], + }); + await call("write_context", { topic: "Staging deploy", content: "Staging auto-syncs in ArgoCD on every merge to main." }); + + // The model loads in the background; wait until searches run in hybrid mode. + let text = ""; + for (let i = 0; i < 600 && !text.includes("hybrid search"); i++) { + text = await call("search_context", { query: "How long do we wait for the PIX refund webhook?" }); + if (!text.includes("hybrid search")) await new Promise((r) => setTimeout(r, 1000)); + } + assert.match(text, /hybrid search/); + assert.match(text.split("\n\n")[1], /webhook de devolução PIX/, "Portuguese memory ranks first for an English question"); + assert.match(text, /similarity 0\.\d\d/); + + const dup = await call("write_context", { + topic: "PIX refund webhook timeout", + content: "The PIX refund webhook timeout was raised from 10s to 20s because the bank sandbox p99 is 14s.", + }); + assert.match(dup, /Possible duplicates/, "cross-lingual near-duplicate is reported"); +}); diff --git a/test/e2e-stdio.test.js b/test/e2e-stdio.test.js new file mode 100644 index 0000000..e00939e --- /dev/null +++ b/test/e2e-stdio.test.js @@ -0,0 +1,109 @@ +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import path from "path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { tempDir, ROOT } from "./helpers.js"; + +let client; +let cleanup; + +before(async () => { + let dir; + [dir, cleanup] = tempDir(); + const transport = new StdioClientTransport({ + command: process.execPath, + args: ["--no-warnings", path.join(ROOT, "src/index.js")], + env: { ...process.env, AGENT_STORE_PATH: dir, AGENT_MEMORY_MODEL: "hash", AGENT_MEMORY_AGENT: "e2e-agent" }, + stderr: "ignore", + }); + client = new Client({ name: "e2e", version: "1.0.0" }); + await client.connect(transport); +}); + +after(async () => { + await client?.close(); + cleanup?.(); +}); + +async function call(name, args) { + const res = await client.callTool({ name, arguments: args }); + return { text: res.content[0].text, isError: res.isError === true }; +} + +test("exposes the 7 tools with annotations and server instructions", async () => { + const { tools } = await client.listTools(); + assert.deepEqual( + tools.map((t) => t.name).sort(), + ["delete_context", "get_state", "list_context", "read_context", "search_context", "set_state", "write_context"], + ); + const byName = Object.fromEntries(tools.map((t) => [t.name, t])); + assert.equal(byName.search_context.annotations.readOnlyHint, true); + assert.equal(byName.delete_context.annotations.destructiveHint, true); + assert.match(client.getInstructions(), /search_context/); +}); + +test("full memory workflow over MCP", async () => { + const w = await call("write_context", { + topic: "Auth — chose JWT over sessions", + content: "Stateless JWT (RS256). Refresh tokens in Redis, 7d TTL.", + tags: ["auth", "decision"], + importance: "critical", + }); + assert.equal(w.isError, false); + const id = w.text.match(/memory (\S+) \(v1\)/)[1]; + + // The exact query that crashed 0.0.9 with an FTS5 syntax error. + const s = await call("search_context", { query: "What did we decide about auth?" }); + assert.equal(s.isError, false); + assert.match(s.text, /Auth — chose JWT over sessions/); + assert.match(s.text, new RegExp(`id: ${id}`)); + assert.match(s.text, /by e2e-agent/); + + for (const query of ["staging-deploy?", "node.js", "AND OR NOT", "what's the user's token", "\"unterminated"]) { + assert.equal((await call("search_context", { query })).isError, false, query); + } + + const dup = await call("write_context", { topic: "auth — chose jwt over sessions", content: "copy" }); + assert.match(dup.text, /Possible duplicates/); + assert.match(dup.text, new RegExp(id)); + + const upd = await call("write_context", { id, topic: "Auth — chose JWT over sessions", content: "Now PASETO v4.", expected_version: 1 }); + assert.match(upd.text, /Updated memory .* \(v2\)/); + const conflict = await call("write_context", { id, topic: "x", content: "y", expected_version: 1 }); + assert.equal(conflict.isError, true); + assert.match(conflict.text, /Version conflict/); + + const r = await call("read_context", { id }); + assert.match(r.text, /Now PASETO v4\./); + assert.match(r.text, /\(v2\)/); + + const l = await call("list_context", { tags: ["auth"] }); + assert.match(l.text, /of 1/); + + const secret = await call("write_context", { topic: "keys", content: "OPENAI sk-proj-abcdefghijklmnopqrstuvwxyz123456" }); + assert.equal(secret.isError, true); + assert.match(secret.text, /Refused/); + + assert.equal((await call("delete_context", { id })).isError, false); + assert.equal((await call("read_context", { id })).isError, true); + assert.equal((await call("delete_context", { id })).isError, true); +}); + +test("state with compare-and-set over MCP", async () => { + assert.match((await call("get_state", { key: "phase" })).text, /not set \(version 0\)/); + assert.match((await call("set_state", { key: "phase", value: { step: 1 }, expected_version: 0 })).text, /version 1/); + const conflict = await call("set_state", { key: "phase", value: { step: 9 }, expected_version: 0 }); + assert.equal(conflict.isError, true); + const g = await call("get_state", { key: "phase" }); + assert.match(g.text, /version 1/); + assert.match(g.text, /"step": 1/); +}); + +test("invalid arguments return tool errors, not crashes", async () => { + const bad = await call("search_context", { query: "x", since: "yesterday-ish" }); + assert.equal(bad.isError, true); + assert.match(bad.text, /ISO 8601/); + const ok = await call("search_context", { query: "still alive?" }); + assert.equal(ok.isError, false); +}); diff --git a/test/fixtures/concurrent-worker.js b/test/fixtures/concurrent-worker.js new file mode 100644 index 0000000..824454d --- /dev/null +++ b/test/fixtures/concurrent-worker.js @@ -0,0 +1,34 @@ +// Child process for test/concurrency.test.js: one "agent" hammering a shared store. +import { MemoryStore } from "../../src/store/memory-store.js"; +import { HashEmbedder } from "../../src/embeddings.js"; + +const [file, agent, countArg] = process.argv.slice(2); +const count = Number(countArg); +const store = MemoryStore.open(file, { embedder: new HashEmbedder() }); +let errors = 0; +let seenOthers = 0; + +for (let i = 0; i < count; i++) { + try { + await store.write({ topic: `${agent} note ${i}`, content: `Shared fact ${i} from ${agent}`, agent, tags: [agent] }); + if (i % 10 === 0) { + const { results } = await store.search({ query: `shared fact ${i}`, limit: 10 }); + if (results.some((r) => r.agent !== agent)) seenOthers++; + // Contended counter: CAS retry loop. + for (;;) { + const cur = store.getState("counter"); + try { + store.setState("counter", (cur?.value ?? 0) + 1, { expectedVersion: cur?.version ?? 0 }); + break; + } catch (e) { + if (e.code !== "CONFLICT") throw e; + } + } + } + } catch (e) { + errors++; + process.stderr.write(`${agent}: ${e.message}\n`); + } +} +store.close(); +process.stdout.write(JSON.stringify({ agent, errors, seenOthers })); diff --git a/test/fts-query.test.js b/test/fts-query.test.js new file mode 100644 index 0000000..6656a36 --- /dev/null +++ b/test/fts-query.test.js @@ -0,0 +1,69 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import { buildFtsQuery, extractTerms } from "../src/store/fts-query.js"; + +// Queries that broke the 0.0.x sanitizer (FTS5 syntax errors) plus edge cases. +const NASTY = [ + "What did we decide about auth?", + "what's the user's token", + "staging-deploy config", + "node.js version", + "api/v2 endpoint", + "AND OR NOT", + "NEAR(a b)", + "topic:auth", + 'say "hello', + "decisão de autenticação, JWT", + "C++ / C# * ^ ( ) { } [ ] : ; ! @ # $ % & = + ~ ` |", + "🚀 deploy 🔥", + "日本語のテキスト", + "-leading dash", + "a", + "", + " ", + "???", +]; + +function ftsDb() { + const db = new DatabaseSync(":memory:"); + db.exec(`CREATE VIRTUAL TABLE t USING fts5(body, tokenize='unicode61 remove_diacritics 2');`); + db.prepare("INSERT INTO t(body) VALUES (?)").run("Decisão de autenticação: usamos JWT. The staging deploy uses node.js 22."); + return db; +} + +test("buildFtsQuery never produces an FTS5 syntax error", () => { + const db = ftsDb(); + for (const q of NASTY) { + const match = buildFtsQuery(q); + if (match === null) continue; + assert.doesNotThrow(() => db.prepare("SELECT * FROM t WHERE t MATCH ?").all(match), `query: ${q}`); + } +}); + +test("natural-language queries still match the right document", () => { + const db = ftsDb(); + for (const q of ["What did we decide about autenticação?", "staging-deploy", "node.js", "decisao autenticacao", "DECISÃO"]) { + const rows = db.prepare("SELECT * FROM t WHERE t MATCH ?").all(buildFtsQuery(q)); + assert.equal(rows.length, 1, `query: ${q}`); + } +}); + +test("stopwords are removed unless nothing else remains", () => { + assert.deepEqual(extractTerms("What did we decide about the auth?"), ["decide", "auth"]); + assert.deepEqual(extractTerms("qual é a decisão sobre o banco?"), ["decisão", "banco"]); + assert.deepEqual(extractTerms("the and or"), ["the", "and", "or"]); + assert.deepEqual(extractTerms("phase 3 of run 7 a"), ["phase", "3", "run", "7"]); +}); + +test("empty or symbol-only queries return null", () => { + assert.equal(buildFtsQuery(""), null); + assert.equal(buildFtsQuery(" "), null); + assert.equal(buildFtsQuery("???"), null); + assert.equal(buildFtsQuery(undefined), null); +}); + +test("terms are deduplicated and capped", () => { + const q = Array.from({ length: 100 }, (_, i) => `term${i} term${i}`).join(" "); + assert.equal(extractTerms(q).length, 32); +}); diff --git a/test/helpers.js b/test/helpers.js new file mode 100644 index 0000000..5346fe4 --- /dev/null +++ b/test/helpers.js @@ -0,0 +1,12 @@ +import { mkdtempSync, rmSync } from "fs"; +import { tmpdir } from "os"; +import path from "path"; +import { fileURLToPath } from "url"; + +/** Creates a temp directory and returns [dir, cleanup]. */ +export function tempDir(prefix = "ams-test-") { + const dir = mkdtempSync(path.join(tmpdir(), prefix)); + return [dir, () => rmSync(dir, { recursive: true, force: true })]; +} + +export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); diff --git a/test/memory-store.test.js b/test/memory-store.test.js new file mode 100644 index 0000000..cd503f4 --- /dev/null +++ b/test/memory-store.test.js @@ -0,0 +1,439 @@ +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import { mkdirSync, writeFileSync, existsSync } from "fs"; +import path from "path"; +import { MemoryStore, SCHEMA_VERSION } from "../src/store/memory-store.js"; +import { HashEmbedder } from "../src/embeddings.js"; +import { migrateLegacyFiles } from "../src/migrate.js"; +import { tempDir } from "./helpers.js"; + +const DAY = 86_400_000; + +function memStore(opts = {}) { + return MemoryStore.open(":memory:", { embedder: new HashEmbedder(), ...opts }); +} + +function fakeClock(start = Date.parse("2026-01-01T00:00:00Z")) { + let t = start; + const clock = () => t; + clock.advance = (ms) => (t += ms); + return clock; +} + +async function codeOf(promiseOrFn) { + try { + await (typeof promiseOrFn === "function" ? promiseOrFn() : promiseOrFn); + } catch (e) { + return e.code; + } + return null; +} + +describe("write / read / delete", () => { + test("creates with generated id and reads back", async () => { + const s = memStore(); + const m = await s.write({ topic: " Auth decision ", content: "JWT", tags: ["Auth", " auth ", "Decision"], agent: "pm" }); + assert.match(m.id, /^[0-9a-f]{12}$/); + assert.equal(m.created, true); + assert.equal(m.version, 1); + assert.equal(m.topic, "Auth decision"); + assert.deepEqual(m.tags, ["auth", "decision"]); + const r = s.get(m.id); + assert.equal(r.content, "JWT"); + assert.equal(r.agent, "pm"); + assert.equal(s.delete(m.id), true); + assert.equal(s.get(m.id), null); + assert.equal(s.delete(m.id), false); + }); + + test("custom id creates then updates in place", async () => { + const s = memStore(); + const a = await s.write({ id: "db-choice", topic: "DB", content: "Postgres 15", tags: ["db"], importance: "high" }); + assert.equal(a.created, true); + const b = await s.write({ id: "db-choice", topic: "DB", content: "Postgres 16", agent: "dba" }); + assert.equal(b.created, false); + assert.equal(b.version, 2); + assert.equal(b.createdAt, a.createdAt); + assert.deepEqual(b.tags, ["db"], "omitted tags are kept"); + assert.equal(b.importance, "high", "omitted importance is kept"); + assert.equal(b.updatedBy, "dba"); + assert.equal(s.list().total, 1); + }); + + test("update keeps the FTS index consistent (no orphan rows)", async () => { + const s = memStore(); + const m = await s.write({ topic: "Cache", content: "We use memcached" }); + await s.write({ id: m.id, topic: "Cache", content: "We use redis" }); + assert.doesNotThrow(() => s.db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('integrity-check')")); + assert.equal((await s.search({ query: "memcached", mode: "bm25" })).results.length, 0); + assert.equal((await s.search({ query: "redis", mode: "bm25" })).results.length, 1); + s.delete(m.id); + assert.doesNotThrow(() => s.db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('integrity-check')")); + }); + + test("validates input", async () => { + const s = memStore(); + assert.equal(await codeOf(s.write({ topic: "", content: "x" })), "INVALID"); + assert.equal(await codeOf(s.write({ topic: "x", content: " " })), "INVALID"); + assert.equal(await codeOf(s.write({ topic: "x", content: "y", importance: "urgent" })), "INVALID"); + assert.equal(await codeOf(s.write({ topic: "x", content: "y", id: "has space" })), "INVALID"); + assert.equal(await codeOf(s.write({ topic: "x", content: "y", ttlDays: -1 })), "INVALID"); + assert.equal(await codeOf(s.write({ topic: "x", content: "y", tags: "auth" })), "INVALID"); + assert.equal(await codeOf(s.search({ query: "x", since: "not a date" })), "INVALID"); + assert.equal(await codeOf(s.search({ query: "" })), "INVALID"); + }); + + test("refuses secrets but allows references and placeholders", async () => { + const s = memStore(); + for (const content of [ + "key: sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz012345", + "AKIAIOSFODNN7EXAMPLE", + "-----BEGIN OPENSSH PRIVATE KEY-----\nabc", + "token ghp_0123456789abcdefghijklmnopqrstuvwxyzAB", + "postgres://app:hunter2secret@db.internal:5432/app", + ]) { + assert.equal(await codeOf(s.write({ topic: "creds", content })), "SECRET", content); + } + for (const content of [ + "DB password lives in 1Password: Prod/Postgres", + "postgres://app:${DB_PASSWORD}@db.internal:5432/app", + "postgres://app:@db/app", + "The task asks to rotate the API key every 90 days", + ]) { + assert.equal(await codeOf(s.write({ topic: "creds ref", content })), null, content); + } + assert.equal(await codeOf(() => s.setState("k", { token: "xoxb-1234567890-abcdefghij" })), "SECRET"); + }); +}); + +describe("compare-and-set", () => { + test("write with expected_version", async () => { + const s = memStore(); + assert.equal(await codeOf(s.write({ id: "x", topic: "t", content: "c", expectedVersion: 1 })), "CONFLICT"); + await s.write({ id: "x", topic: "t", content: "c", expectedVersion: 0 }); + assert.equal(await codeOf(s.write({ id: "x", topic: "t", content: "c2", expectedVersion: 0 })), "CONFLICT"); + const m = await s.write({ id: "x", topic: "t", content: "c2", expectedVersion: 1 }); + assert.equal(m.version, 2); + assert.equal(s.get("x").content, "c2"); + }); + + test("state with expected_version", () => { + const s = memStore(); + assert.equal(s.getState("phase"), null); + assert.equal(s.setState("phase", "plan", { expectedVersion: 0, agent: "a" }).version, 1); + assert.equal(codeOfSync(() => s.setState("phase", "build", { expectedVersion: 0 })), "CONFLICT"); + assert.equal(s.setState("phase", "build", { expectedVersion: 1 }).version, 2); + assert.equal(s.setState("phase", { n: 1 }).version, 3, "unguarded write always succeeds"); + const st = s.getState("phase"); + assert.deepEqual(st.value, { n: 1 }); + assert.equal(st.version, 3); + }); +}); + +function codeOfSync(fn) { + try { + fn(); + } catch (e) { + return e.code; + } + return null; +} + +describe("expiry", () => { + test("expired memories disappear from get, list and search without a restart", async () => { + const clock = fakeClock(); + const s = memStore({ clock }); + const tmp = await s.write({ topic: "Rate limit", content: "ZAP API allows 1 req/s", ttlDays: 1 }); + await s.write({ topic: "Rate policy", content: "Always respect API limits" }); + assert.equal(s.list().total, 2); + clock.advance(2 * DAY); + assert.equal(s.get(tmp.id), null); + assert.equal(s.list().total, 1); + const { results } = await s.search({ query: "ZAP rate limit" }); + assert.ok(results.every((r) => r.id !== tmp.id)); + }); + + test("an expired id counts as non-existent for writes", async () => { + const clock = fakeClock(); + const s = memStore({ clock }); + await s.write({ id: "tmp", topic: "t", content: "old", ttlDays: 1 }); + clock.advance(2 * DAY); + const m = await s.write({ id: "tmp", topic: "t", content: "new", expectedVersion: 0 }); + assert.equal(m.created, true); + assert.equal(m.version, 1); + assert.equal(m.expiresAt, null); + }); + + test("ttl null removes an expiry; omitted ttl keeps it", async () => { + const clock = fakeClock(); + const s = memStore({ clock }); + const m = await s.write({ id: "t", topic: "t", content: "c", ttlDays: 1 }); + assert.ok(m.expiresAt); + assert.ok((await s.write({ id: "t", topic: "t", content: "c2" })).expiresAt, "kept"); + assert.equal((await s.write({ id: "t", topic: "t", content: "c3", ttlDays: null })).expiresAt, null); + clock.advance(5 * DAY); + assert.ok(s.get("t")); + }); +}); + +describe("filters", () => { + test("tags match exactly (no LIKE wildcards)", async () => { + const s = memStore(); + await s.write({ topic: "OAuth flow", content: "PKCE", tags: ["oauth"] }); + await s.write({ topic: "Auth", content: "JWT", tags: ["auth"] }); + assert.equal(s.list({ tags: ["auth"] }).total, 1); + assert.equal(s.list({ tags: ["a_th"] }).total, 0); + assert.equal(s.list({ tags: ["%"] }).total, 0); + assert.equal(s.list({ tags: ["AUTH", "oauth"] }).total, 2); + const { results } = await s.search({ query: "flow JWT PKCE", tags: ["auth"] }); + assert.deepEqual(results.map((r) => r.topic), ["Auth"]); + }); + + test("agent and date filters apply to both retrievers", async () => { + const clock = fakeClock(); + const s = memStore({ clock }); + await s.write({ topic: "Deploy notes", content: "staging on ECS", agent: "infra" }); + clock.advance(10 * DAY); + await s.write({ topic: "Deploy notes 2", content: "staging on ECS fargate", agent: "backend" }); + for (const mode of ["hybrid", "bm25", "semantic"]) { + const byAgent = await s.search({ query: "staging deploy", agent: "infra", mode }); + assert.deepEqual(byAgent.results.map((r) => r.agent), ["infra"], mode); + const recent = await s.search({ query: "staging deploy", since: new Date(clock() - DAY).toISOString(), mode }); + assert.deepEqual(recent.results.map((r) => r.agent), ["backend"], mode); + } + assert.equal(s.list({ until: new Date(clock() - DAY).toISOString() }).total, 1); + }); + + test("list paginates newest first with total", async () => { + const clock = fakeClock(); + const s = memStore({ clock }); + for (let i = 0; i < 5; i++) { + await s.write({ topic: `m${i}`, content: "x" }); + clock.advance(1000); + } + const p1 = s.list({ limit: 2 }); + assert.equal(p1.total, 5); + assert.deepEqual(p1.items.map((m) => m.topic), ["m4", "m3"]); + assert.equal(p1.items[0].content, undefined); + assert.deepEqual(s.list({ limit: 2, offset: 4 }).items.map((m) => m.topic), ["m0"]); + }); +}); + +describe("search", () => { + test("modes, scores and top_k", async () => { + const s = memStore(); + const auth = await s.write({ topic: "Auth — JWT decision", content: "Stateless JWT with RS256 keys", tags: ["auth"] }); + await s.write({ topic: "Staging deploy", content: "ECS Fargate, node 22" }); + await s.write({ topic: "Database", content: "Postgres 16 with pgvector" }); + + const hybrid = await s.search({ query: "What did we decide about JWT auth?" }); + assert.equal(hybrid.mode, "hybrid"); + assert.equal(hybrid.results[0].id, auth.id); + assert.ok(hybrid.results[0].score > 0.9 && hybrid.results[0].score <= 1); + assert.deepEqual(hybrid.results[0].matched.sort(), ["keyword", "semantic"]); + assert.ok(hybrid.results[0].similarity > 0); + + const bm25 = await s.search({ query: "JWT", mode: "bm25" }); + assert.equal(bm25.mode, "bm25"); + assert.equal(bm25.results.length, 1); + assert.equal(bm25.results[0].similarity, null); + + const sem = await s.search({ query: "JWT tokens", mode: "semantic" }); + assert.equal(sem.mode, "semantic"); + assert.equal(sem.results[0].id, auth.id); + + assert.equal((await s.search({ query: "deploy database auth", limit: 2 })).results.length, 2); + const strict = await s.search({ query: "JWT auth", minScore: 0.9 }); + assert.ok(strict.results.length >= 1 && strict.results.every((r) => r.score >= 0.9)); + }); + + test("keyword-only store (no embedder) still works", async () => { + const s = MemoryStore.open(":memory:", { embedder: null }); + await s.write({ topic: "Auth", content: "JWT" }); + const r = await s.search({ query: "auth?", mode: "semantic" }); + assert.equal(r.mode, "bm25"); + assert.equal(r.results.length, 1); + }); + + test("importance and recency only break near-ties", async () => { + const clock = fakeClock(); + const s = memStore({ clock }); + const strong = await s.write({ topic: "Redis cache eviction policy", content: "allkeys-lru for redis cache", importance: "low" }); + clock.advance(400 * DAY); + await s.write({ topic: "Misc", content: "the cache is warm", importance: "critical" }); + const { results } = await s.search({ query: "redis cache eviction policy" }); + assert.equal(results[0].id, strong.id); + }); + + test("reports likely duplicates on write", async () => { + const s = memStore(); + const a = await s.write({ topic: "Auth decision", content: "We chose JWT with RS256 for the API gateway" }); + const b = await s.write({ topic: "auth decision", content: "something else" }); + assert.deepEqual(b.duplicates.map((d) => d.id), [a.id]); + const c = await s.write({ topic: "API gateway auth", content: "We chose JWT with RS256 for the API gateway" }); + assert.ok(c.duplicates.some((d) => d.id === a.id && d.reason.startsWith("similar"))); + const d = await s.write({ topic: "Unrelated", content: "Lunch is at noon" }); + assert.deepEqual(d.duplicates, []); + }); +}); + +describe("embeddings lifecycle", () => { + class SlowEmbedder extends HashEmbedder { + constructor() { + super(); + this.ready = false; + } + isReady() { + return this.ready; + } + async load() { + await new Promise((r) => setTimeout(r, 20)); + this.ready = true; + return true; + } + async embedDocuments(texts) { + await new Promise((r) => setTimeout(r, 30)); + return super.embedDocuments(texts); + } + } + + test("background embedding never stores a vector for stale content", async () => { + const s = MemoryStore.open(":memory:", { embedder: new SlowEmbedder() }); + const m = await s.write({ id: "x", topic: "t", content: "first version" }); + s.warmup(); + await new Promise((r) => setTimeout(r, 35)); // drain is now embedding "first version" + await s.write({ id: m.id, topic: "t", content: "second version" }); + await s.flushEmbeddings(); + const v = s.db.prepare("SELECT v.content_hash AS vh, c.content_hash AS ch FROM vectors v JOIN chunks c ON c.id = v.chunk_id").get(); + assert.equal(v.vh, v.ch); + assert.equal(s.stats().embedded, 1); + }); + + test("updating content while the model is not ready drops the stale vector", async () => { + const e = new SlowEmbedder(); + const s = MemoryStore.open(":memory:", { embedder: e }); + e.ready = true; + await s.write({ id: "x", topic: "Queue", content: "We use RabbitMQ for jobs" }); + assert.equal(s.stats().embedded, 1); + e.ready = false; // e.g. another process without the model, or model reloading + e.load = async () => false; + await s.write({ id: "x", topic: "Queue", content: "We moved jobs to SQS" }); + assert.equal(s.db.prepare("SELECT count(*) AS n FROM vectors").get().n, 0); + }); + + test("changing the model re-embeds everything", async () => { + const [dir, cleanup] = tempDir(); + try { + const file = path.join(dir, "store.db"); + const s1 = MemoryStore.open(file, { embedder: new HashEmbedder(256) }); + for (let i = 0; i < 40; i++) await s1.write({ topic: `topic ${i}`, content: `content number ${i}` }); + s1.close(); + const s2 = MemoryStore.open(file, { embedder: new HashEmbedder(128) }); + assert.equal(s2.stats().embedded, 0); + await s2.flushEmbeddings(); + assert.deepEqual(s2.stats(), { memories: 40, embedded: 40, model: "hash-v1-128" }); + const r = await s2.search({ query: "content number 7", mode: "semantic" }); + assert.equal(r.results[0].topic, "topic 7"); + s2.close(); + } finally { + cleanup(); + } + }); + + test("index picks up writes and deletes from another connection", async () => { + const [dir, cleanup] = tempDir(); + try { + const file = path.join(dir, "store.db"); + const a = MemoryStore.open(file, { embedder: new HashEmbedder() }); + const b = MemoryStore.open(file, { embedder: new HashEmbedder() }); + await a.write({ topic: "warmup", content: "warm the index" }); + await a.search({ query: "warm", mode: "semantic" }); + const m = await b.write({ topic: "Kafka topics", content: "orders.v1 partitioned by tenant" }); + const found = await a.search({ query: "kafka orders partitioned", mode: "semantic" }); + assert.equal(found.results[0].id, m.id); + b.delete(m.id); + const gone = await a.search({ query: "kafka orders partitioned", mode: "semantic" }); + assert.ok(gone.results.every((r) => r.id !== m.id)); + a.close(); + b.close(); + } finally { + cleanup(); + } + }); +}); + +describe("migrations", () => { + test("upgrades a v0.0.9 database in place", async () => { + const [dir, cleanup] = tempDir(); + try { + const file = path.join(dir, "store.db"); + const old = new DatabaseSync(file); + // Exact schema shipped in agent-memory-store <= 0.0.9 (src/db.js). + old.exec(` + CREATE TABLE chunks (id TEXT PRIMARY KEY, topic TEXT NOT NULL, agent TEXT NOT NULL DEFAULT 'global', + tags TEXT NOT NULL DEFAULT '[]', importance TEXT NOT NULL DEFAULT 'medium', content TEXT NOT NULL, + embedding BLOB, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, expires_at TEXT); + CREATE INDEX idx_chunks_agent ON chunks(agent); + CREATE INDEX idx_chunks_updated ON chunks(updated_at); + CREATE INDEX idx_chunks_expires ON chunks(expires_at); + CREATE TABLE state (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL); + CREATE VIRTUAL TABLE chunks_fts USING fts5(id UNINDEXED, topic, tags, agent, content, content='chunks', content_rowid=rowid); + CREATE TRIGGER chunks_ai AFTER INSERT ON chunks BEGIN + INSERT INTO chunks_fts(rowid, id, topic, tags, agent, content) VALUES (new.rowid, new.id, new.topic, new.tags, new.agent, new.content); + END;`); + const ins = old.prepare("INSERT INTO chunks VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + ins.run("a1b2c3d4e5", "Auth — JWT decision", "pm", '["auth","decision"]', "critical", "Chose JWT. Decisão final.", Buffer.alloc(16), "2025-01-01T00:00:00.000Z", "2025-02-01T00:00:00.000Z", null); + ins.run("f6e5d4c3b2", "Deploy", "infra", "[]", "medium", "ECS", null, "2025-01-01T00:00:00.000Z", "2025-01-01T00:00:00.000Z", null); + old.prepare("INSERT INTO state VALUES (?, ?, ?)").run("phase", JSON.stringify({ step: 3 }), "2025-01-01T00:00:00.000Z"); + old.close(); + + const s = MemoryStore.open(file, { embedder: new HashEmbedder() }); + assert.equal(s.db.prepare("PRAGMA user_version").get().user_version, SCHEMA_VERSION); + const m = s.get("a1b2c3d4e5"); + assert.equal(m.topic, "Auth — JWT decision"); + assert.equal(m.agent, "pm"); + assert.deepEqual(m.tags, ["auth", "decision"]); + assert.equal(m.importance, "critical"); + assert.equal(m.createdAt, "2025-01-01T00:00:00.000Z"); + assert.deepEqual(s.getState("phase"), { key: "phase", value: { step: 3 }, version: 1, updatedAt: "2025-01-01T00:00:00.000Z", updatedBy: null }); + assert.equal((await s.search({ query: "What did we decide about auth?", mode: "bm25" })).results[0].id, "a1b2c3d4e5"); + assert.equal((await s.search({ query: "decisao", mode: "bm25" })).results.length, 1); + await s.flushEmbeddings(); + assert.equal(s.stats().embedded, 2); + s.close(); + + // Re-opening is a no-op. + const again = MemoryStore.open(file, { embedder: new HashEmbedder() }); + assert.equal(again.list().total, 2); + again.close(); + } finally { + cleanup(); + } + }); + + test("imports the legacy markdown file store", async () => { + const [dir, cleanup] = tempDir(); + try { + mkdirSync(path.join(dir, "chunks")); + mkdirSync(path.join(dir, "state")); + writeFileSync( + path.join(dir, "chunks", "abc123.md"), + "---\nid: abc123\ntopic: Legacy topic\nagent: old-agent\ntags: [legacy, auth]\nimportance: high\nupdated: 2024-05-01T00:00:00.000Z\n---\n\nLegacy content body\n", + ); + writeFileSync(path.join(dir, "state", "phase.json"), JSON.stringify({ key: "phase", value: "done" })); + const s = MemoryStore.open(path.join(dir, "store.db"), { embedder: null }); + assert.equal(await migrateLegacyFiles(s, dir), true); + const m = s.get("abc123"); + assert.equal(m.content, "Legacy content body"); + assert.deepEqual(m.tags, ["legacy", "auth"]); + assert.equal(m.importance, "high"); + assert.equal(s.getState("phase").value, "done"); + assert.ok(existsSync(path.join(dir, "chunks_backup"))); + assert.equal(await migrateLegacyFiles(s, dir), false); + s.close(); + } finally { + cleanup(); + } + }); +}); diff --git a/test/metrics.test.js b/test/metrics.test.js new file mode 100644 index 0000000..9b91ef7 --- /dev/null +++ b/test/metrics.test.js @@ -0,0 +1,42 @@ +// Metrics checked against values computed by hand (and, for NDCG, against +// the formula in LongMemEval's official eval_utils.py). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { recallAny, recallAll, ndcgAny, reciprocalRank, mean, percentile } from "../benchmarks/lib/metrics.js"; + +const close = (a, b) => assert.ok(Math.abs(a - b) < 1e-9, `${a} ≈ ${b}`); + +test("recall_any / recall_all", () => { + const ranked = ["a", "b", "c", "d", "e", "f"]; + assert.equal(recallAny(ranked, new Set(["c"]), 5), 1); + assert.equal(recallAny(ranked, new Set(["f"]), 5), 0); + assert.equal(recallAll(ranked, new Set(["a", "e"]), 5), 1); + assert.equal(recallAll(ranked, new Set(["a", "f"]), 5), 0, "f is rank 6"); + assert.equal(recallAny([], new Set(["a"]), 5), 0); +}); + +test("reciprocal rank", () => { + assert.equal(reciprocalRank(["x", "a"], new Set(["a"])), 1 / 2); + assert.equal(reciprocalRank(["a"], new Set(["a"])), 1); + assert.equal(reciprocalRank(["x", "y"], new Set(["a"])), 0); + assert.equal(reciprocalRank(["x", "b", "a"], new Set(["a", "b"])), 1 / 2, "first relevant counts"); +}); + +test("ndcg_any matches the official formula", () => { + // official dcg: rel[0] + sum_{i>=1} rel[i] / log2(i + 1) + // one gold doc at rank 3 → DCG = 1/log2(3); ideal = 1 + close(ndcgAny(["x", "y", "a"], new Set(["a"]), 1, 10), 1 / Math.log2(3)); + // two gold at ranks 1 and 3 → (1 + 1/log2(3)) / (1 + 1/log2(2)) + close(ndcgAny(["a", "x", "b"], new Set(["a", "b"]), 2, 10), (1 + 1 / Math.log2(3)) / 2); + // gold outside the cutoff + close(ndcgAny(["x", "y", "a"], new Set(["a"]), 1, 2), 0); + close(ndcgAny(["a"], new Set(["a"]), 1, 10), 1); +}); + +test("mean and nearest-rank percentile", () => { + assert.equal(mean([1, 2, 3, 4]), 2.5); + assert.equal(mean([]), 0); + assert.equal(percentile([5, 1, 4, 2, 3], 50), 3); + assert.equal(percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 95), 10); + assert.equal(percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 90), 9); +});